text:
Q: If Button clicked - do animation to image Swift Playgrounds My goal is simple. When a button is clicked, the button should fade out and so should another image on the screen. I am using Swift Playgrounds. I have already got the button to fade out when clicked working. The main problem is getting the image on the screen to fade out once the button is clicked.
import PlaygroundSupport
import AVFoundation
class MyViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let title = UIImage(named: "Picture1")
        let imageView = UIImageView(image: title) //this is the image I want to fade out when the button is clicked
        imageView.image = title
        imageView.frame.size.width = 570
        imageView.frame.size.height = 140
        imageView.frame.origin.x = 100
        imageView.frame.origin.y = 0
        imageView.alpha = 0

        let button = UIButton(type: UIButton.ButtonType.custom) as UIButton
        let image = UIImage(named: "startbutton4.png") as UIImage?
        button.frame = CGRect(x: 265, y: 300, width: 249, height: 85)
        button.setImage(image, for: [])
        button.contentMode = .center
        button.imageView?.contentMode = .scaleAspectFit

        button.imageView?.contentMode = .scaleAspectFit
        button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
        self.view.addSubview(button)
        view.addSubview(imageView)
    }

    @objc func buttonAction(sender: UIButton) {
        sender.isHighlighted = false
        UIView.animate(withDuration: 1, delay: 1, options: .curveEaseOut, animations: {
           sender.alpha = 0
        }, completion: nil) // <--- this right here is the button fading out
    }

}
let master = MyViewController()
PlaygroundPage.current.liveView = master

If anyone has any idea how to do this, please let me know.

A: What i understand is you want to hide button ... once button is hidden you want to show image .. here is the code for that.. i hope it will help
func buttonAction(sender: UIButton) {
    sender.isHighlighted = false
    UIView.animate(withDuration: 1, delay: 1, options: .curveEaseOut, animations: {
       sender.alpha = 0
    }, completion: { success in
        if success {
        UIView.animate(withDuration: 1, delay: 1, options: .curveEaseOut, animations: {
           imageView.alpha = 1
            })
        }
    })
}


text:
Q: Solution of vector equation in alpha Is there a closed solution for $\alpha$ in the following vector equation?
$$(\vec\alpha^T\Sigma\vec\alpha)\vec\mu - (\vec\alpha^T\vec\mu)\Sigma\vec\alpha = \vec0$$
$\Sigma$ is an $n$ by $n$ symmetric correlation matrix.
$\vec\alpha$ is an $n$ by $1$ variable column vector.
$\vec\mu$ is an $n$ by $1$ column vector.

A: I assume that $\Sigma$ is invertible, $\mu$ is non-zero, and the equation has a non-zero solution.
We begin with
$$
(\alpha^T\Sigma \alpha) \mu  = (\alpha^T \mu) \Sigma\alpha
$$
We see that this equation can only have a solution if $\Sigma \alpha$ is a multiple of $\mu$.  That is, there exists a scalar $k$ for which
$$
k\mu = \Sigma \alpha \implies \alpha = k\Sigma^{-1}\mu.
$$
It suffices to plug this into the original equation and solve for $k$. We have
$$
(\alpha^T\Sigma \alpha) \mu  = (\alpha^T \mu) \Sigma\alpha \implies\\
k^2(\mu^T\Sigma^{-1} \mu) \mu = k^2 (\mu^T\Sigma^{-1} \mu) \mu.
$$
Both sides are the same. In other words, the equation holds for all $k$.
So, if $\Sigma$ is invertible and a non-zero solution exists, then $\alpha$ is a solution iff it has the form
$$
\alpha = k \Sigma^{-1}\mu
$$
for any $k \in \Bbb R$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Fix location of stippling for subplots I have been trying to stipple contour plots to show locations where values are statistically significant. However, when I do this in subplots where the significance is the same, the stippling looks different based on the random location of the filled stipples. I have reproduced the problem below. Is there a way to fix the location of the stipples so that they look the same when plotted? Or is there a better way to stipple plots?
These 2 subplots are plotting the exact same data, but the stipples look different.
import numpy as np
from matplotlib import pyplot as plt

#Create some random data
x = np.arange(0,100,1)
x,y = np.meshgrid(x,x)
stipp = 10*np.random.rand(len(x),len(x))

fig =plt.figure(figsize=(12,8))
ax1 = plt.subplot(121)
ax2 = plt.subplot(122)

#Plot stippling
ax1.contourf(x,y,stipp,[0,4],colors='none',hatches='.')
ax2.contourf(x,y,stipp,[0,4],colors='none',hatches='.')
plt.show()

A: So in case anyone wants to know, the best way to stipple multiple subplots with similar statistical significance is to use a scatter plot as recommended above instead of contouring. Just make sure to sample the data sparingly so you don't have a high density of dots next to each other.
import numpy as np
from matplotlib  import pyplot as plt

#Create some random data
x = np.arange(0,100,1)
x,y = np.meshgrid(x,x)
stipp = 10*np.random.rand(len(x),len(x))

fig =plt.figure(figsize=(12,8))
ax1 = plt.subplot(121)
ax2 = plt.subplot(122)

#Plot stippling
ax1.scatter(x[(stipp<=4) & (stipp>=0)][::5],y[(stipp<=4) & (stipp>=0)][::5])
ax2.scatter(x[(stipp<=4) & (stipp>=0)][::5],y[(stipp<=4) & (stipp>=0)][::5])

plt.show()


text:
Q: Postgres: how can I subtract value at one query? I think I can only get value, subtract value (at Java) and update value. Is it possible to subtract value at cell at one query?

A: Yes, but you got the syntax a bit wrong:
UPDATE table SET number_of_people = number_of_people - 3 WHERE id = 487364

This assumes that number_of_people is an integer value.


text:
Q: how to use fadeTo and fadeIn properly here I am trying to fade out 1 div out of two joined divs but not able to do so.Please help me out
$(document).ready(function(){
    $(window).scroll(function(){
        if($(window).scrollTop() > 0){
            $("#hide").fadeTo(slow, 0);
        }
        if($(window).scrollTop() == 0){
            $("#hide").fadeIn(slow, 0.7);
        }
    });
});

and my html code for  divs which are are

how to get the fade effect?

A: Your slow speed should be 'slow', but I think that it's better do this simple animation with CSS transitions, it's very easy:
CSS:
#hide{
    transition: 0.5s;
}

JS:
$(document).ready(function(){
    $(window).scroll(function(){
        if($(this).scrollTop() > 0){
            $("#hide").css('opacity', 0);
        }else{
            $("#hide").css('opacity', 0.7);
        }
    });
});

DEMO: https://jsfiddle.net/lmgonzalves/gxgjdhb1/


text:
Q: Crystal Report Load Report Failed in VS2010 I trying to create an application in c# with Crystal Report and then I create setup file using publish wizard and delivery to my client.
Now I use following code to bind crystal report in c#.
          ReportDocument doc = new ReportDocument();
          doc.Load("D//CrystalReport1.rpt",CrystalDecisions.Shared.OpenReportMethod.OpenReportByTempCopy);

            doc.SetDataSource(dt);
            crystalReportViewer1.ReportSource = doc;
            crystalReportViewer1.Refresh();

At client Side generate following error.

A: 'Load report failed.' exception occurs when the path specified for the .rpt file is incorrect. Please check the file path again. Also try the below code.
When working for web
doc.Load(Server.MapPath("\\CrystalReport1.rpt")",CrystalDecisions.Shared.OpenReportMethod.OpenReportByTempCopy)

Prefer to put the .rpt file in a folder and also specify the folder location.For eg.
Make a Folder Reports inside solution and consolidate all the .rpt files inside the folder
doc.Load(Server.MapPath("\\Reports\\CrystalReport1.rpt")",CrystalDecisions.Shared.OpenReportMethod.OpenReportByTempCopy)

When working for window
doc.Load(@"D//CrystalReport1.rpt",CrystalDecisions.Shared.OpenReportMethod.OpenReportByTempCopy)

trying using with a sign '@'. Hope it helps!


text:
Q: Could coq derive this solution automatically? Can coq manipulate algebraic expressions when performing the search for a proof? This problem is taken from a Corporate Finance course, but the financial details aren't what matters.
The problem was that given this formula:

and values for:
,
one had obtain r_wacc. (I'm simplifying the problem a little)
The solution was to divide the numerator and denominator of each fraction by E to obtain:

Which equals to:

Now obtaining r_wacc is easily done by substituing with the known values.
Could coq derive the solutions automatically given only the initial formula and the same known values? Or in other words, can coq manipulate algebraic expressions when performing the search for a proof?


text:
Q: cypress runner ignoring charset="windows-1252" html tag I'm testing a page which is windows-1252 encoded, it has the following meta tags in the html:
<html>
<head>
  <title>Meta-SSC</title>
  <meta http-equiv="Content-Type" content="text/html">
  <meta charset="windows-1252">

But cypress runner won't catch it, and can't correctly display characters like á, é, etc., like this:

My test are failing because of this.
On the other hand, when testing it on chrome (Version 72.0.3626.121 Official Build 32-bit running on windows 10) or firefox (65.0.2 64bits) it works ok:

Any idea how could I troubleshoot it?

Found this issue at Cypress' github that might be related.

A: It is indeed a known issue
this is the workaround I developed:
Cypress.Commands.add('containsLike', {
  prevSubject: true
}, (subject, search, chars) => {

  chars = chars || 'áéíóúñÁÉÍÓÚÑ'
  if (!Array.isArray(chars)) chars = chars.toString().split('')

  chars.forEach( char => {
    const repAllChars = new RegExp(char, 'g') // see: https://stackoverflow.com/a/17606289/47633
    search = search.replace(repAllChars, '.')
  })

  const regExp = new RegExp('^' + search + '$')
  return cy.wrap(subject).contains(regExp)
})

and I use it like this:
describe('my first test', () => {
  it.only('should pass', () => {
    cy.visit('http://localhost/xxxx/yyy.asp')
      .get('div.flash_error span')
      .containsLike('El código de la aplicacion no puede estar vacío.')
// it runs .contains(/^El c.digo de la aplicacion no puede estar vac.o\.$/)
  })
})


text:
Q: How to pass machine input and Lambda function output to map states Current Setup:
I currently have a Step Functions state machine that kicks off a Task state (which calls a Lambda function), followed by a map state (which submits a job to Batch), defined as follows
State Machine Definition
(note: region and account id have been omitted and substituted for dummy variable ACCOUNT_INFO)
{
  "StartAt": "Populate EFS",
  "States": {
    "Populate EFS": {
      "Next": "MapState",
      "Type": "Task",
      "InputPath": "$",
      "ResultPath": "$.populate_efs_result",
      "Resource": "arn:aws:states:::lambda:invoke",
      "Parameters": {
        "FunctionName": "arn:aws:lambda:{ACCOUNT_INFO}:function:PopulateEFSLambda",
        "Payload.$": "$"
      }
    },
    "MapState": {
      "Type": "Map",
      "End": true,
      "ResultPath": "$.metadata.run_info",
      "InputPath": "$",
      "Iterator": {
        "StartAt": "TaskState",
        "States": {
          "TaskState": {
            "Type": "Task",
            "End": true,
            "InputPath": "$",
            "ResultPath": null,
            "Resource": "arn:aws:states:::batch:submitJob.sync",
            "Parameters": {
              "JobDefinition": "arn:aws:batch:{ACCOUNT_INFO}:job-definition/BatchJobDefCfn:1",
              "JobName": "test",
              "JobQueue": "arn:aws:batch:{ACCOUNT_INFO}:job-queue/BatchQueue123",
              "ContainerOverrides": {
                "Command": [
                  "sh",
                  "-c",
                  "entrypoint.pl -i /NGS/${sequencer}/${run_id}/ -s ${sample_name}"
                ],
                "Environment": [
                  {
                    "Name": "run_id",
                    "Value.$": "$.run_id"
                  },
                  {
                    "Name": "sample_name",
                    "Value.$": "$.sample_name"
                  },
                  {
                    "Name": "sequencer",
                    "Value.$": "$.sequencer"
                  }
                ]
              }
            }
          }
        }
      }
    }
  }
}

State machine input
{
  "metadata": {
    "run_info": [
      {
        "sample_name": "SAMPLE_X",
        "sequencer": "Nextseq"
      },
      {
        "sample_name": "SAMPLE_Y",
        "sequencer": "Nextseq"
      },
      {
        "sample_name": "SAMPLE_Z",
        "sequencer": "Nextseq"
      }
    ]
  }
}

Lambda output (shortened for simplicity)
{"populate_efs_result": {
    "ExecutedVersion": "$LATEST",
    "Payload": "RUN_1"}

Expected Outcome:
The second step (MapState) needs information from the machine input (sample_name and sequencer), as well as what the Lambda function returns in populate_efs_result.Payload (run_id), therefore both need to be included in the event object for the Map state input. However, in my attempts so far, the input for the map state has been either the machine input or the Lambda output, not both.
I've tried changing the InputPath and ItemsPath parameters in the Map state definition and have also tried including the following in the Map state definition, but none of these methods work: Parameters: {"new_run_id.$": "$.populate_efs_result.Payload"}.

A: A simple but not so elegant solution could be to move your lambda step within the Map state. The advantage would be that the response from the lambda would be in the context of the map state (this might be needed if your lambda response if specific to each iteration of the map state). The disadvantage is that your lambda function would need to be executed for each iteration of the map, while lambda function are fast and cheap it is still not a perfect solution.
Another approach would be to pass the execution input to that lambda and then extend the lambda to modify the run_info array to include the required data. Then pass this modified array to the map state as the InputPath


text:
Q: Where is the http api for eventstore 3.6? Is there a link to the http endpoints for eventstore 3.6?
I was looking through the documentation provided on the site, bu I can't seem to find it.

A: Not sure what you mean by http endpoints, but the API does not change that much from version to version as everything is the same as before there, looking at http://docs.geteventstore.com/http-api/3.6.0/


text:
Q: java.io.InvalidClassException: org.jetbrains.kotlin.incremental.IncrementalModuleInfo I am getting below exception while running my project-
> Task :app:kaptGenerateStubsDebugKotlin
Compilation with Kotlin compile daemon was not successful
java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
    java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
    java.io.InvalidClassException: org.jetbrains.kotlin.incremental.IncrementalModuleInfo; local class incompatible: stream classdesc serialVersionUID = 0, local class serialVersionUID = 1
    at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:389)
    at sun.rmi.transport.Transport$1.run(Transport.java:200)
    at sun.rmi.transport.Transport$1.run(Transport.java:197)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
    at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:573)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:834)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:688)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:687)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
    at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(StreamRemoteCall.java:303)
    at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:279)
    at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:164)
    at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:235)
    at java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:180)
    at com.sun.proxy.$Proxy209.compile(Unknown Source)
    at org.jetbrains.kotlin.compilerRunner.GradleKotlinCompilerWork.incrementalCompilationWithDaemon(GradleKotlinCompilerWork.kt:289)
    at org.jetbrains.kotlin.compilerRunner.GradleKotlinCompilerWork.compileWithDaemon(GradleKotlinCompilerWork.kt:202)
    at org.jetbrains.kotlin.compilerRunner.GradleKotlinCompilerWork.compileWithDaemonOrFallbackImpl(GradleKotlinCompilerWork.kt:141)
    at org.jetbrains.kotlin.compilerRunner.GradleKotlinCompilerWork.run(GradleKotlinCompilerWork.kt:124)
    at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.runCompilerAsync(GradleKotlinCompilerRunner.kt:173)
    at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.runCompilerAsync(GradleKotlinCompilerRunner.kt:168)
    at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.runJvmCompilerAsync(GradleKotlinCompilerRunner.kt:87)
    at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.callCompilerAsync$kotlin_gradle_plugin(Tasks.kt:530)
    at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.callCompilerAsync$kotlin_gradle_plugin(Tasks.kt:455)
    at org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompile.executeImpl(Tasks.kt:376)
    at org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompile.execute(Tasks.kt:340)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:104)
    at org.gradle.api.internal.project.taskfactory.IncrementalTaskInputsTaskAction.doExecute(IncrementalTaskInputsTaskAction.java:47)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:51)
    at org.gradle.api.internal.project.taskfactory.AbstractIncrementalTaskAction.execute(AbstractIncrementalTaskAction.java:25)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:29)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$3.run(ExecuteActionsTaskExecuter.java:555)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$1.execute(DefaultBuildOperationRunner.java:29)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$1.execute(DefaultBuildOperationRunner.java:26)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$3.execute(DefaultBuildOperationRunner.java:75)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$3.execute(DefaultBuildOperationRunner.java:68)
    at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:153)
    at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:68)
    at org.gradle.internal.operations.DefaultBuildOperationRunner.run(DefaultBuildOperationRunner.java:56)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.lambda$run$1(DefaultBuildOperationExecutor.java:71)
    at org.gradle.internal.operations.UnmanagedBuildOperationWrapper.runWithUnmanagedSupport(UnmanagedBuildOperationWrapper.java:45)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:71)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:540)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:523)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.access$300(ExecuteActionsTaskExecuter.java:108)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$TaskExecution.executeWithPreviousOutputFiles(ExecuteActionsTaskExecuter.java:271)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$TaskExecution.execute(ExecuteActionsTaskExecuter.java:260)
    at org.gradle.internal.execution.steps.ExecuteStep.lambda$execute$0(ExecuteStep.java:33)
    at java.util.Optional.map(Optional.java:215)
    at org.gradle.internal.execution.steps.ExecuteStep.execute(ExecuteStep.java:33)
    at org.gradle.internal.execution.steps.ExecuteStep.execute(ExecuteStep.java:26)
    at org.gradle.internal.execution.steps.CleanupOutputsStep.execute(CleanupOutputsStep.java:67)
    at org.gradle.internal.execution.steps.CleanupOutputsStep.execute(CleanupOutputsStep.java:36)
    at org.gradle.internal.execution.steps.ResolveInputChangesStep.execute(ResolveInputChangesStep.java:49)
    at org.gradle.internal.execution.steps.ResolveInputChangesStep.execute(ResolveInputChangesStep.java:34)
    at org.gradle.internal.execution.steps.CancelExecutionStep.execute(CancelExecutionStep.java:43)
    at org.gradle.internal.execution.steps.TimeoutStep.executeWithoutTimeout(TimeoutStep.java:73)
    at org.gradle.internal.execution.steps.TimeoutStep.execute(TimeoutStep.java:54)
    at org.gradle.internal.execution.steps.CreateOutputsStep.execute(CreateOutputsStep.java:44)
    at org.gradle.internal.execution.steps.SnapshotOutputsStep.execute(SnapshotOutputsStep.java:54)
    at org.gradle.internal.execution.steps.SnapshotOutputsStep.execute(SnapshotOutputsStep.java:38)
    at org.gradle.internal.execution.steps.BroadcastChangingOutputsStep.execute(BroadcastChangingOutputsStep.java:42)
    at org.gradle.internal.execution.steps.CacheStep.executeWithoutCache(CacheStep.java:159)
    at org.gradle.internal.execution.steps.CacheStep.execute(CacheStep.java:72)
    at org.gradle.internal.execution.steps.CacheStep.execute(CacheStep.java:43)
    at org.gradle.internal.execution.steps.StoreExecutionStateStep.execute(StoreExecutionStateStep.java:44)
    at org.gradle.internal.execution.steps.StoreExecutionStateStep.execute(StoreExecutionStateStep.java:33)
    at org.gradle.internal.execution.steps.RecordOutputsStep.execute(RecordOutputsStep.java:38)
    at org.gradle.internal.execution.steps.RecordOutputsStep.execute(RecordOutputsStep.java:24)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.executeBecause(SkipUpToDateStep.java:92)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.lambda$execute$0(SkipUpToDateStep.java:85)
    at java.util.Optional.map(Optional.java:215)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:55)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:39)
    at org.gradle.internal.execution.steps.ResolveChangesStep.execute(ResolveChangesStep.java:76)
    at org.gradle.internal.execution.steps.ResolveChangesStep.execute(ResolveChangesStep.java:37)
    at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsFinishedStep.execute(MarkSnapshottingInputsFinishedStep.java:36)
    at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsFinishedStep.execute(MarkSnapshottingInputsFinishedStep.java:26)
    at org.gradle.internal.execution.steps.ResolveCachingStateStep.execute(ResolveCachingStateStep.java:94)
    at org.gradle.internal.execution.steps.ResolveCachingStateStep.execute(ResolveCachingStateStep.java:49)
    at org.gradle.internal.execution.steps.CaptureStateBeforeExecutionStep.execute(CaptureStateBeforeExecutionStep.java:79)
    at org.gradle.internal.execution.steps.CaptureStateBeforeExecutionStep.execute(CaptureStateBeforeExecutionStep.java:53)
    at org.gradle.internal.execution.steps.ValidateStep.execute(ValidateStep.java:74)
    at org.gradle.internal.execution.steps.SkipEmptyWorkStep.lambda$execute$2(SkipEmptyWorkStep.java:78)
    at java.util.Optional.orElseGet(Optional.java:267)
    at org.gradle.internal.execution.steps.SkipEmptyWorkStep.execute(SkipEmptyWorkStep.java:78)
    at org.gradle.internal.execution.steps.SkipEmptyWorkStep.execute(SkipEmptyWorkStep.java:34)
    at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsStartedStep.execute(MarkSnapshottingInputsStartedStep.java:39)
    at org.gradle.internal.execution.steps.LoadExecutionStateStep.execute(LoadExecutionStateStep.java:40)
    at org.gradle.internal.execution.steps.LoadExecutionStateStep.execute(LoadExecutionStateStep.java:28)
    at org.gradle.internal.execution.impl.DefaultWorkExecutor.execute(DefaultWorkExecutor.java:33)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeIfValid(ExecuteActionsTaskExecuter.java:187)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:179)
    at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:109)
    at org.gradle.api.internal.tasks.execution.FinalizePropertiesTaskExecuter.execute(FinalizePropertiesTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.ResolveTaskExecutionModeExecuter.execute(ResolveTaskExecutionModeExecuter.java:62)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:57)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:56)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:36)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.executeTask(EventFiringTaskExecuter.java:77)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:55)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:52)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:200)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:195)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$3.execute(DefaultBuildOperationRunner.java:75)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$3.execute(DefaultBuildOperationRunner.java:68)
    at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:153)
    at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:68)
    at org.gradle.internal.operations.DefaultBuildOperationRunner.call(DefaultBuildOperationRunner.java:62)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.lambda$call$2(DefaultBuildOperationExecutor.java:76)
    at org.gradle.internal.operations.UnmanagedBuildOperationWrapper.callWithUnmanagedSupport(UnmanagedBuildOperationWrapper.java:54)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:76)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:52)
    at org.gradle.execution.plan.LocalTaskNodeExecutor.execute(LocalTaskNodeExecutor.java:41)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:372)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:359)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:352)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:338)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.lambda$run$0(DefaultPlanExecutor.java:127)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.execute(DefaultPlanExecutor.java:191)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.executeNextNode(DefaultPlanExecutor.java:182)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.run(DefaultPlanExecutor.java:124)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
Caused by: java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:

    java.io.InvalidClassException: org.jetbrains.kotlin.incremental.IncrementalModuleInfo; local class incompatible: stream classdesc serialVersionUID = 0, local class serialVersionUID = 1
    at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:348)
    at sun.rmi.transport.Transport$1.run(Transport.java:200)
    at sun.rmi.transport.Transport$1.run(Transport.java:197)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
    at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:573)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:834)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:688)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:687)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    ... 1 more
Caused by: java.io.InvalidClassException: org.jetbrains.kotlin.incremental.IncrementalModuleInfo; local class incompatible: stream classdesc serialVersionUID = 0, local class serialVersionUID = 1
    at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:699)
    at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:2003)
    at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1850)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2160)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1667)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2405)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2329)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2187)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1667)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:503)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:461)
    at sun.rmi.server.UnicastRef.unmarshalValue(UnicastRef.java:327)
    at sun.rmi.server.UnicastServerRef.unmarshalParametersUnchecked(UnicastServerRef.java:629)
    at sun.rmi.server.UnicastServerRef.unmarshalParameters(UnicastServerRef.java:617)
    at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:338)
    ... 12 more

Could not connect to kotlin daemon. Using fallback strategy.
Caused by: java.io.InvalidClassException: org.jetbrains.kotlin.incremental.IncrementalModuleInfo; local class incompatible: stream classdesc serialVersionUID = 0, local class serialVersionUID = 1

warning: runtime JAR files in the classpath should have the same version. These files were found in the classpath:
runtime JAR files in the classpath should have the same version. These files were found in the classpath:

    C:/Users/bhuvn/.gradle/caches/transforms-2/files-2.1/cdc59ab6a7ee1c195fb72a3f01dc0739/jetified-kotlin-stdlib-jdk8-1.5.0.jar (version 1.5)
    C:/Users/bhuvn/.gradle/caches/transforms-2/files-2.1/34457c4434ad852ea060ee782f5e8323/jetified-kotlin-stdlib-jdk7-1.5.0.jar (version 1.5)
    C:/Users/bhuvn/.gradle/caches/transforms-2/files-2.1/d9343e9497e026cdfe06ff026aeb19fc/jetified-kotlin-reflect-1.4.20.jar (version 1.4)
    C:/Users/bhuvn/.gradle/caches/transforms-2/files-2.1/804f48f2d7dad2bfc8769d092e8ec65f/jetified-kotlin-stdlib-1.5.10.jar (version 1.5)
    C:/Users/bhuvn/.gradle/caches/transforms-2/files-2.1/47f384f6aa44e4e3b7645022cceff4d0/jetified-kotlin-stdlib-common-1.5.10.jar (version 1.5)
warning: some runtime JAR files in the classpath have an incompatible version. Consider removing them from the classpath
some runtime JAR files in the classpath have an incompatible version. Consider removing them from the classpath

exception: java.lang.NoSuchMethodError: org.jetbrains.kotlin.types.TypeSubstitutionKt.replace$default(Lorg/jetbrains/kotlin/types/KotlinType;Ljava/util/List;Lorg/jetbrains/kotlin/descriptors/annotations/Annotations;ILjava/lang/Object;)Lorg/jetbrains/kotlin/types/KotlinType;
    at org.jetbrains.kotlin.kapt3.KaptAnonymousTypeTransformerKt.convertPossiblyAnonymousType(KaptAnonymousTypeTransformer.kt:73)
    at org.jetbrains.kotlin.kapt3.KaptAnonymousTypeTransformerKt.convertPossiblyAnonymousType(KaptAnonymousTypeTransformer.kt:70)
    at org.jetbrains.kotlin.kapt3.KaptAnonymousTypeTransformer.transformAnonymousType(KaptAnonymousTypeTransformer.kt:32)
    at org.jetbrains.kotlin.resolve.DescriptorResolver.transformAnonymousTypeIfNeeded(DescriptorResolver.java:1037)
    at org.jetbrains.kotlin.resolve.VariableTypeAndInitializerResolver$resolveTypeNullable$1.invoke(VariableTypeAndInitializerResolver.kt:94)
    at org.jetbrains.kotlin.resolve.VariableTypeAndInitializerResolver$resolveTypeNullable$1.invoke(VariableTypeAndInitializerResolver.kt:86)
    at org.jetbrains.kotlin.storage.LockBasedStorageManager$LockBasedLazyValue.invoke(LockBasedStorageManager.java:408)
    at org.jetbrains.kotlin.storage.LockBasedStorageManager$LockBasedNotNullLazyValue.invoke(LockBasedStorageManager.java:527)
    at org.jetbrains.kotlin.types.DeferredType.getDelegate(DeferredType.java:107)
    at org.jetbrains.kotlin.types.WrappedType.getAnnotations(KotlinType.kt:127)
    at org.jetbrains.kotlin.resolve.lazy.ForceResolveUtil.forceResolveAllContents(ForceResolveUtil.java:108)
    at org.jetbrains.kotlin.resolve.lazy.ForceResolveUtil.doForceResolveAllContents(ForceResolveUtil.java:95)
    at org.jetbrains.kotlin.resolve.lazy.ForceResolveUtil.forceResolveAllContents(ForceResolveUtil.java:42)
    at org.jetbrains.kotlin.resolve.lazy.ForceResolveUtil.forceResolveAllContents(ForceResolveUtil.java:52)
    at org.jetbrains.kotlin.resolve.lazy.ForceResolveUtil.forceResolveAllContents(ForceResolveUtil.java:47)
    at org.jetbrains.kotlin.resolve.lazy.descriptors.LazyClassDescriptor.doForceResolveAllContents(LazyClassDescriptor.java:604)
    at org.jetbrains.kotlin.resolve.lazy.descriptors.LazyClassDescriptor.lambda$new$4(LazyClassDescriptor.java:220)
    at org.jetbrains.kotlin.storage.LockBasedStorageManager$LockBasedLazyValue.invoke(LockBasedStorageManager.java:408)
    at org.jetbrains.kotlin.resolve.lazy.descriptors.LazyClassDescriptor.forceResolveAllContents(LazyClassDescriptor.java:592)
    at org.jetbrains.kotlin.resolve.lazy.ForceResolveUtil.doForceResolveAllContents(ForceResolveUtil.java:78)
    at org.jetbrains.kotlin.resolve.lazy.ForceResolveUtil.forceResolveAllContents(ForceResolveUtil.java:42)
    at org.jetbrains.kotlin.resolve.jvm.extensions.PartialAnalysisHandlerExtension$doAnalysis$1.invoke(PartialAnalysisHandlerExtension.kt:72)
    at org.jetbrains.kotlin.resolve.jvm.extensions.PartialAnalysisHandlerExtension$doAnalysis$1.invoke(PartialAnalysisHandlerExtension.kt:67)
    at org.jetbrains.kotlin.resolve.jvm.extensions.PartialAnalysisHandlerExtension.doForEachDeclaration(PartialAnalysisHandlerExtension.kt:123)
    at org.jetbrains.kotlin.resolve.jvm.extensions.PartialAnalysisHandlerExtension.doForEachDeclaration(PartialAnalysisHandlerExtension.kt:138)
    at org.jetbrains.kotlin.resolve.jvm.extensions.PartialAnalysisHandlerExtension.doAnalysis(PartialAnalysisHandlerExtension.kt:67)
    at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.doAnalysis(Kapt3Extension.kt:150)
    at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(TopDownAnalyzerFacadeForJVM.kt:119)
    at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration$default(TopDownAnalyzerFacadeForJVM.kt:85)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:514)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:505)
    at org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport.analyzeAndReport(AnalyzerWithCompilerReport.kt:112)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.analyze(KotlinToJVMBytecodeCompiler.kt:505)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules$cli(KotlinToJVMBytecodeCompiler.kt:189)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules$cli$default(KotlinToJVMBytecodeCompiler.kt:155)
    at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:169)
    at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:52)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:88)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:44)
    at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:98)
    at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:76)
    at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:45)
    at org.jetbrains.kotlin.cli.common.CLITool$Companion.doMainNoExit(CLITool.kt:227)
    at org.jetbrains.kotlin.cli.common.CLITool$Companion.doMainNoExit$default(CLITool.kt:222)
    at org.jetbrains.kotlin.cli.common.CLITool$Companion.doMain(CLITool.kt:214)
    at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler$Companion.main(K2JVMCompiler.kt:271)
    at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.main(K2JVMCompiler.kt)

> Task :app:kaptGenerateStubsDebugKotlin FAILED
Execution failed for task ':app:kaptGenerateStubsDebugKotlin'.
> Internal compiler error. See log for more details

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

gradle-wrapper.properties
#Mon Jul 05 21:01:26 IST 2021
distributionBase=GRADLE_USER_HOME
distributionUrl=https\://services.gradle.org/distributions/gradle-6.7.1-all.zip
distributionPath=wrapper/dists
zipStorePath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME

Versions
build_tools_gradle = "4.2.0"
compilesdk = 30
minsdk = 21
targetsdk = 30

Based on this solution i tried adding many things to my gradle.properties file,but it didn't worked-
org.gradle.jvmargs=-Xmx4096m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app"s APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Automatically convert third-party libraries to use AndroidX
android.enableJetifier=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official
MaxPermSize=1024m
+HeapDumpOnOutOfMemoryError
Dfile.encoding=UTF-8
org.gradle.parallel=true
-Xmx1536m -XX:+HeapDumpOnOutOfMemoryError
-Dorg.gradle.caching=true
-Dorg.gradle.configureondemand=true
-Dkotlin.compiler.execution.strategy=in-process
-Dkotlin.incremental=false

A: The issue is in the package kotlin-reflect-1.4.20  - it is of the wrong version - the general kotlin plugin version you are using is kotlin-stdlib-jdk8-1.5.0 and kotlin-stdlib-1.5.10.
While minor versions sometimes may be cross-compatible middle and major versions of kotlin plugins are not compatible and can't be compiled into a single file.
Just use a more up-to-date version of kotlin-reflect and allign the version of kotlin with the version of its libs, and it should do the job.


text:
Q: How to import fonts in CSS? I want to use some fonts and I want it to work without having this font on the client computer. I have done this but it doesn't work:
@font-face {
    font-family: EntezareZohoor2;
    src: url(Entezar2.ttf) format("truetype");
}

.EntezarFont {
    font-family: EntezareZohoor2, B Nazanin, Tahoma !important;
}

A: When I went to Google fonts all they gave me were true type font files .ttf and didn't explain at all how to use the @font-face to include them into my document. I tried the web font generator from font squirrel too, which just kept running the loading gif and not working... I then found this site -
https://transfonter.org/
I had great success using the following method:
I selected the Add Fonts button, leaving the default options, added all of my .ttf that Google gave me for Open Sans (which was like 10, I chose a lot of options...).
Then I selected the Convert button.
Heres the best part!
They gave me a zip file with all the font format files I selected, .ttf, .woff and .eot. Inside that zip file they had a demo.html file that I just double clicked on and it opened up a web page in my browser showing me example usages of all the different css font options, how to implement them, and what they looked like etc.
@font-face
I still didn't know at this point how to include the fonts into my stylesheet properly using @font-face but then I noticed that this demo.html came with it's own stylesheet in the zip as well. I opened the stylesheet and it showed how to bring in all of the fonts using @font-face so I was able to quickly, and easily, copy paste this into my project -
@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-BoldItalic.eot');
    src: url('fonts/Open_Sans/OpenSans-BoldItalic.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-BoldItalic.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-BoldItalic.ttf') format('truetype');
    font-weight: bold;
    font-style: italic;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-LightItalic.eot');
    src: url('fonts/Open_Sans/OpenSans-LightItalic.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-LightItalic.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-LightItalic.ttf') format('truetype');
    font-weight: 300;
    font-style: italic;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-SemiBold.eot');
    src: url('fonts/Open_Sans/OpenSans-SemiBold.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-SemiBold.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-SemiBold.ttf') format('truetype');
    font-weight: 600;
    font-style: normal;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-Regular.eot');
    src: url('fonts/Open_Sans/OpenSans-Regular.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-Regular.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-Regular.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-Light.eot');
    src: url('fonts/Open_Sans/OpenSans-Light.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-Light.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-Light.ttf') format('truetype');
    font-weight: 300;
    font-style: normal;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-Italic.eot');
    src: url('fonts/Open_Sans/OpenSans-Italic.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-Italic.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-Italic.ttf') format('truetype');
    font-weight: normal;
    font-style: italic;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-SemiBoldItalic.eot');
    src: url('fonts/Open_Sans/OpenSans-SemiBoldItalic.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-SemiBoldItalic.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-SemiBoldItalic.ttf') format('truetype');
    font-weight: 600;
    font-style: italic;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-ExtraBold.eot');
    src: url('fonts/Open_Sans/OpenSans-ExtraBold.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-ExtraBold.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-ExtraBold.ttf') format('truetype');
    font-weight: 800;
    font-style: normal;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-ExtraBoldItalic.eot');
    src: url('fonts/Open_Sans/OpenSans-ExtraBoldItalic.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-ExtraBoldItalic.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-ExtraBoldItalic.ttf') format('truetype');
    font-weight: 800;
    font-style: italic;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-Bold.eot');
    src: url('fonts/Open_Sans/OpenSans-Bold.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-Bold.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-Bold.ttf') format('truetype');
    font-weight: bold;
    font-style: normal;
}

The demo.html also had it's own inline stylesheet that was interesting to take a look at, though I am familiar with working with font weights and styles once they are included so I didn't need it much. For an example of how to implement a font style onto an html element for reference purposes you could use the following method in a similar case to mine after @font-face has been used properly -
html, body{
    margin: 0;
    font-family: 'Open Sans';
}
.banner h1{
    font-size: 43px;
    font-weight: 700;
}
.banner p{
    font-size: 24px;
    font-weight: 300;
    font-style: italic;
}

A: Following lines are used to define a font in css
@font-face {
    font-family: 'EntezareZohoor2';
    src: url('fonts/EntezareZohoor2.eot'), url('fonts/EntezareZohoor2.ttf') format('truetype'), url('fonts/EntezareZohoor2.svg') format('svg');
    font-weight: normal;
    font-style: normal;
}

Following lines to define/use the font in css
#newfont{
    font-family:'EntezareZohoor2';
}

A: Go through http://www.w3.org/TR/css3-fonts/
Try this:
  @font-face {
        font-family: 'EntezareZohoor2';
        src: url('EntezareZohoor2.eot');
        src: local('EntezareZohoor2'), local('EntezareZohoor2'), url('EntezareZohoor2.ttf') format('svg');
       font-weight: normal;
       font-style: normal;
    }

A: One of the best source of information on this topic is Paul Irish's Bulletproof @font-face syntax article.
Read it and you will end with something like:
/* definition */
@font-face {
  font-family: EntezareZohoor2;
  src: url('fonts/EntezareZohoor2.eot');
  src: url('fonts/EntezareZohoor2.eot?') format('☺'),
       url('fonts/EntezareZohoor2.woff') format('woff'),
       url('fonts/EntezareZohoor2.ttf') format('truetype');
  font-weight: normal;
  font-style: normal;
}

/* use */
body {
    font-family: EntezareZohoor2, Tahoma, serif;
}

A: Try this link1,link2
@font-face {
        font-family: 'RieslingRegular';
        src: url('fonts/riesling.eot');
        src: local('Riesling Regular'), local('Riesling'), url('fonts/riesling.ttf')                       format('truetype');
    }

A: I used Ataturk's font like this. I didn't use "TTF" version. I translated orginal font version ("otf" version) to "eot" and "woof" version.
Then It works in local but not working when I uploaded the files to server.
So I added "TTF" version too like this. Now, It's working on Chrome and Firefox but Internet Explorer still defence.
When you installed on your computer "Ataturk" font, then working IE too. But I wanted to use this font without installing.
@font-face {
    font-family: 'Ataturk';
    font-style: normal;
    font-weight: normal;
    src: url('font/ataturk.eot');
    src: local('Ataturk Regular'), url('font/ataturk.ttf') format('truetype'),
    url('font/ataturk.woff') format('woff');
}

You can see it on my website here: http://www.canotur.com


text:
Q: Touch/drag motion to select multiple cells in a lazyvgrid? I'm trying to use a LazyVGrid in SwiftUI where you can touch and drag your finger to select multiple adjacent cells in a specific order. This is not a drag and drop and I don't want to move the cells (maybe drag isn't the right term here, but couldn't think of another term to describe it). Also, you would be able to reverse the selection (ie: each cell can only be selected once and reversing direction would un-select the cell). How can I accomplish this? Thanks!
For example:
struct ContentView: View {

    @EnvironmentObject private var cellsArray: CellsArray

    var body: some View {
        VStack {
            LazyVGrid(columns: gridItems, spacing: spacing) {
                ForEach(0..<(rows * columns), id: \.self){index in
                    VStack(spacing: 0) {
                        CellsView(index: index)
                    }
                }
            }
        }
    }
}
struct CellsView: View {

    @State var index: Int
    @EnvironmentObject var cellsArray: CellsArray

    var body: some View {
       ZStack {
           Text("\(self.cellsArray[index].cellValue)") //cellValue is a string
               .foregroundColor(Color.yellow)
               .frame(width: getWidth(), height: getWidth())
               .background(Color.gray)
       }
       //.onTapGesture ???
    }
    func getWidth()->CGFloat{

        let width = UIScreen.main.bounds.width - 10

        return width / CGFloat(columns)

    }
}

A: Something like this might help, the only issue here is the coordinate space. Overlay is not drawing the rectangle in the correct coordinate space.
struct ImagesView: View {
    var columnSize: CGFloat
    @Binding var projectImages: [ProjectImage]
    @State var selectedImages: [ImageSelection] = []
    @State var dragWidth: CGFloat = 1.0
    @State var dragHeight: CGFloat = 1.0
    @State var dragStart: CGPoint = CGPoint(x:0, y:0)
    let columns = [
        GridItem(.adaptive(minimum: 200), spacing: 0)
    ]

    var body: some View {
        GeometryReader() { geometry in
            ZStack{
                ScrollView{
                    LazyVGrid(columns: [
                        GridItem(.adaptive(minimum: columnSize), spacing: 2)
                    ], spacing: 2){
                        ForEach(projectImages, id: \.imageUUID){ image in
                            Image(nsImage: NSImage(data: image.imageData)!)
                                .resizable()
                                .scaledToFit()
                                .border(selectedImages.contains(where: {imageSelection in imageSelection.uuid == image.imageUUID}) ? Color.blue : .primary, width: selectedImages.contains(where: {imageSelection in imageSelection.uuid == image.imageUUID}) ? 5.0 : 1.0)

                                .gesture(TapGesture(count: 2).onEnded{
                                    print("Double tap finished")
                                })
                                .gesture(TapGesture(count: 1).onEnded{
                                    if selectedImages.contains(where: {imageSelection in imageSelection.uuid == image.imageUUID}) {
                                        print("Image is already selected")
                                        if let index = selectedImages.firstIndex(where: {imageSelection in imageSelection.uuid == image.imageUUID}){
                                            selectedImages.remove(at: index)
                                        }

                                    } else {
                                        selectedImages.append(ImageSelection(imageUUID: image.imageUUID))
                                        print("Image has been selected")
                                    }
                                })
                        }
                    }
                    .frame(minHeight: 50)
                    .padding(.horizontal, 1)
                }
                .simultaneousGesture(
                    DragGesture(minimumDistance: 2)
                        .onChanged({ value in
                            print("Drag Start: \(value.startLocation.x)")
                            self.dragStart = value.startLocation
                            self.dragWidth = value.translation.width
                            self.dragHeight = value.translation.height
                        })
                )
                .overlay{
                    Rectangle()
                        .frame(width: dragWidth, height: dragHeight)
                        .offset(x:dragStart.x, y:dragStart.y)
                }

            }
        }
    }
}


text:
Q: How to change img data to img url while drag and drop to TinyMCE? I've TinyMCE in my Wordpress blog (like all). When i drag and drop image from my computer disc to the TinyMCE window it is uploaded and embedded as img with data field. The effect of this is that after putting some images this way size of post is too big to be handled properly and saved by Wordpress.
Of course i know i can open the image upload window and drop image there but it would be so much easier if i could just drop the image like now: directly to the TinyMCE window and it would work like the drop box.
So basically what i imagine it should work like this: when i drop image to TinyMCE it gets the data of image, saves it to image folder of Wordpress and replace the img data to img url.
So... yeah... do you know any plugin that works that way?

A: There is no plugin that i know of.
You will need this code to intercept the drop event
$(ed.getDoc()).bind('drop', function(event){

    // you can read out different flavours (html, plain, file, etc....)
     var drag_content_html = event.originalEvent.dataTransfer.getData('text/html');
     var drag_content_plain1 = event.originalEvent.dataTransfer.getData('text/plain');

}


text:
Q: how to get parameter value when I use htaccess url rewrite with '-' in value I used htaccess for url rewrite in my gallery page and I used below code in htaccess.
RewriteRule ^gallery/(\w+)/(\w+) gallery_image.php?query=gallery&imgid=$1&slug=$2 [QSA,L]

Here slug values should be like firstname-lastname-imagetitle;
When I use $_REQUEST['slug'] to get parameter value, it returns only firstname.
Ex: if slug = 'jum-hague-art-gallery-brown-box' $_REQUEST['slug'] returns only jum. But I need entire value.
Please help me to find what I am doing wrong here.

A: minus (-) is word delimeter so \w gets only the 1st part of new slug. Write so to take all text after the slash
RewriteRule ^gallery/(\w+)/(.+)$ gallery_image.php?query=gallery&imgid=$1&slug=$2 [QSA,L]


text:
Q: How Run A Stored Procedure (with Parameters - Has A return Value) From Code Behind? How can I use a stored procedure (with parameters - has a return value of type int) from code behind?
My stored procedure looks like this :
ALTER Procedure [dbo].[sp_Noskheh_SumOfTotalPay]
    @Co_ID int
AS
-----------------
Declare @Sum bigint
-----------------
BEGIN
    SELECT
       @Sum = SUM(TotalPay)
    FROM Noskheh
    WHERE
       (Co_ID = @Co_ID)

    RETURN @Sum
END

I want to use @Sum in code behind ...
Would you please show me a way for doing that ?
Thanks in advance
best regards

A: You need to set up a SqlConnection and a SqlCommand. If you have your code with the RETURN @Sum statement in the end, you need to do this (define a parameter of type RETURN_VALUE):
using(SqlConnection _conn = new SqlConnection(-your-connection-string-here))
using(SqlCommand _cmd = new SqlCommand("dbo.sp_Noskheh_SumOfTotalPay", _conn))
{
   _cmd.CommandType = CommandType.StoredProcedure;

   _cmd.Parameters.Add(new SqlParameter("@CO_ID", SqlDbType.Int));
   _cmd.Parameters["@CO_ID"].Value = 5; // whatever value you want

   _cmd.Parameters.Add(new SqlParameter("@RETURN_VALUE", SqlDbType.BigInt));
   _cmd.Parameters["@RETURN_VALUE"].Direction = ParameterDirection.ReturnValue;

   _conn.Open();
   _cmd.ExecuteNonQuery();

   Int64 result = Int64.Parse(_cmd.Parameters["@RETURN_VALUE"].Value);

   _conn.Close();
}

It would be a lot easier if you would replace that RETURN statement with a simple SELECT:
SELECT @Sum

In that case, you can use the simplified version I had before - using .ExecuteScalar() to retrieve the single value of the single row being returned from the stored proc:
using(SqlConnection _conn = new SqlConnection(-your-connection-string-here))
using(SqlCommand _cmd = new SqlCommand("dbo.sp_Noskheh_SumOfTotalPay", _conn))
{
   _cmd.CommandType = CommandType.StoredProcedure;

   _cmd.Parameters.Add(new SqlParameter("@CO_ID", SqlDbType.Int));
   _cmd.Parameters["@CO_ID"].Value = 5; // whatever value you want

   _conn.Open();
   object result = _cmd.ExecuteScalar();
   _conn.Close();

   Int64 sum = Int64.Parse(result);
}

That should call your stored proc, read the single value you're returning, and converting it into an int variable called sum.

A: There is no shortage of tutorials on this subject.

A: You can add an SqlParameter @Sum with Direction set to ReturnValue
Example:
SqlCommand cmd = new SqlCommand():

cmd.Connection = // place your SqlConnection object;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "StoreProcedureName";

cmd.Parameters.Add("@Sum", SqlDbType.BigInt).Direction = ParameterDirection.ReturnValue


text:
Q: Critical point of $f(x)=(x^2-1)^2(x-3)^2$
Determine the critical point of $$f(x)=(x^2-1)^2(x-3)^2$$

Firstly, I get the derivative of $f(x)$. I got $=4x(x^2-1)(x-3)^2+2(x-3)(x^2-1)^2$. Any help will be appreciated.

A: Hint:
As
$$f(x)=((x^2-1)(x-3))^2=(g(x))^2,$$ the critical points of $f$ will be

*

*the roots of $g$, $x=\pm1$ and $x=3$;

*the critical points of $g$, which are the zeroes of $g'(x)=2x(x-3)+x^2-1=3x^2-6x-1$.

A: Now, note that\begin{align}4x(x^2-1)(x-3)^2+2(x-3)(x^2-1)^2&=2(x^2-1)(x-3)\bigl(2x(x-3)+x^2-1\bigr)\\&=2(x^2-1)(x-3)(3x^2-6x-1).\end{align}Can you take it from here?

A: If you are allowed to use critical points calculator, here is solution at
Wolfram|Alpha service.


text:
Q: how to filter JSON data in Flutter? I have 2 methods to read radio station data: _readStations and _getStationsRemoteJson
I can filter stations within Firestore data in _readStations method as shown in the following code snippet.
But I cannot do the same filtering with JSON data.
How can I filter JSON data?
Future<List<Station50K>> _getStationsRemoteJson() async {
  const url = 'JSON URL';

  final response = await http.get(Uri.parse(url));
  final body = json.decode(response.body);
  final stations = body['data'];

  return stations.map<Station50K>(Station50K.fromJson2).toList();
}

Stream<List<Station>> _readStations() {
  return FirebaseFirestore.instance.collection('stations').snapshots().map(
      (snapshot) => snapshot.docs
          .where((d) =>
              (_favorites.contains(d.data()['id'].toString())) &&
              (d
                      .data()['title']
                      .toString()
                      .toLowerCase()
                      .contains(_searchText.toLowerCase()) ||
                  d
                      .data()['city']
                      .toString()
                      .toLowerCase()
                      .contains(_searchText.toLowerCase()) ||
                  List.from(d.data()['genre']).any((pattern) {
                    return pattern
                        .toString()
                        .toLowerCase()
                        .contains(_searchText.toLowerCase());
                  })))
          .map((doc) => Station.fromJson2(doc.data()))
          .toList());
}

A: In _getStationsRemoteJson() when returning a list of objects you can first filter it (same as what you have for Firestore snapshot.docs.where(...)).
It would look like stations.map<Station50K>(Station50K.fromJson2).where((object) => object.property == 'searchSomething'). Probably what's confusing you is that from Firestore, the data you get back is a Map, while here you have already converted it to an object so you can use the object's properties.
Also, for filtering Firestore data there are specific built in methods so you get less data back from server and it costs you a lot less money if used often.Check it out here.

A: I think I solved it.
Future<List<Station50K>> _getStationsRemoteJson() async {
const url = 'JSON URL';

final response = await http.get(Uri.parse(url));
final body = json.decode(response.body);
final stations = body['data'];

List<Station50K> list = stations.map<Station50K>(Station50K.fromJson2).toList();

return list
    .where((d) =>
        (_favorites.contains(d.id)) &&
        (d.name.toLowerCase().contains(_searchText.toLowerCase()) ||
            d.city.toLowerCase().contains(_searchText.toLowerCase()) ||
            List.from(d.genres).any((pattern) {
              return pattern
                  .toString()
                  .toLowerCase()
                  .contains(_searchText.toLowerCase());
            })))
    .toList();
}


text:
Q: Microsoft IIS Server & Angular - Adding SSL parameter We have a Microsoft IIS Server that runs a .NET App with Angular, but requires https now to make use of browser push notifications. It works on localhost, but not when releasing it for testing.
I have added the appropriate parameter inside the package.json file:
"scripts": {
"ng": "ng",
"start": "ng serve -- --ssl=true",

when I run "npm run start" locally, it processes the parameter as expected and serves the page over https.
Any ideas why it doesn't work with the build pipeline? The page is only accessible with normal http and results in a timeout if I try https. Are there any other settings that I forgot to change?


text:
Q: Set background color of TableRow I try to set the background color of a TableRow.
Currently I have this in my XML file:
android:background="@color/buttonBackground"

and i work great. But when it run
row.setBackgroundColor(R.color.red);

the row disappears. Can someone explain why that is?

A: I believe you need to do:
Resources resource = context.getResources();
row.setBackgroundColor(resource.getColor(R.color.red)

A: You can also try :
row.setBackgroundColor(Color.RED);

This works for me in Android Studio 2.2.3.

A: You must be missing the alpha value in your color definition. Verify it has 4 bytes, like #FFFFFFFF.

A: row.setBackgroundColor(ContextCompat.getColor(this,R.color.colorAccent))

A: Just write: android:background="@android:color/buttonBackground"


text:
Q: floating-point promotion : stroustrup vs compiler - who is right? In section 10.5.1 of Stroustrup's new book "The C++ Programming Language - Fourth Edition" he says, that before an arithmetic operation is performed, integral promotion is used to create ints out of shorter integer types, and similarly, floating-point promotion is used to create doubles out of floats.
I confirmed the first claim with the following code:
#include <iostream>
#include <typeinfo>

int main()
{
    short a;
    short b;
    std::cout << typeid(a + b).name() << std::endl;
}

This outputs "int" with vc++ and "i" with gcc.
But testing it with floats instead of shorts, the output is still "float" or "f":
#include <iostream>
#include <typeinfo>

int main()
{
    float a;
    float b;
    std::cout << typeid(a + b).name() << std::endl;
}

According to Stroustrup there are no exceptions to the floating-point promotion-rule, so I expected "double" or "d" as output.
Is the mentioned section about promotions wrong or somehow unclear? And is there any difference in C++98 and C++11 regarding type promotions?

A: In the meantime Stroustrup seems to recognised the refer sentence is not correct or at least misleading. He has removed the sentence, about the floating-point promotion, from section 10.5.1.
Please see errata of 3rd printing of 4th edition on Stroustrup's web page:

pg 267: s/Similarly, floating-point promotion is used to create doubles out of floats//

(Remark: The expression s/regexp/replacement/ is similar to sed unix tool semantics. It searches for the pattern regexp and replaces it with replacement. Nothing in our case.)

A: I don't know what exactly Stroustrup's book says, but according to the standard, floats will not be converted to doubles in this case. Before applying most arithmetic binary operators, the usual arithmetic conversions described in 5p9 are applied:

*

*If either operand is of scoped enumeration type (7.2), no conversions are performed; if the other operand does not have the same type, the expression is ill-formed.

*If either operand is of type long double, the other shall be converted to long double.

*Otherwise, if either operand is double, the other shall be converted to double.

*Otherwise, if either operand is float, the other shall be converted to float.

*Otherwise, the integral promotions (4.5) shall be performed on both operands. [...]

The integral promotions are what causes two shorts to be converted to ints. But two floats will not be converted to doubles according to these rules. If you add a float to a double, the float will be converted to a double.
The above is from C++11. C++03 contains the same rules, except for the one referring to scoped enumerations.


text:
Q: How to write CUSTOM metadata into JPEG with Python? How to write CUSTOM metadata into JPEG with Python?
I tried
import piexif
exif_dict = {
                'uwi': myvalue1,
                'activity_type': myvalue2,
                'prediction': myvalue3,
                'url_current': myvalue4,
                'url_previous': mavalue5
            }
exif_bytes = piexif.dump(exif_dict)
with open(filename, "w") as fp:
    test_image.save(fp, "JPEG", exif=exif_bytes)

but see nothing in images with XnView. What am I doing wrong?
P.S. I don't need to write camera model, exposure and other stuff. I want to write my own custom metadata.

A: Check out the docs on how to use piexif. What you are doing wrong for example is trying to write custom metadata and opening the file with open instead of opening with Image from the PIL module.
Cutting down the example from the docs, you could do something like this:
from PIL import Image
import piexif

zeroth_ifd = {
              piexif.ImageIFD.Make: u"Canon",
              piexif.ImageIFD.XResolution: (96, 1),
              piexif.ImageIFD.YResolution: (96, 1),
              piexif.ImageIFD.Software: u"piexif"
              }
exif_ifd = {
            piexif.ExifIFD.DateTimeOriginal: u"2099:09:29 10:10:10",
            piexif.ExifIFD.LensMake: u"LensMake",
            piexif.ExifIFD.Sharpness: 65535,
            piexif.ExifIFD.LensSpecification: ((1, 1), (1, 1), (1, 1), (1, 1)),
            }
gps_ifd = {
           piexif.GPSIFD.GPSVersionID: (2, 0, 0, 0),
           piexif.GPSIFD.GPSAltitudeRef: 1,
           piexif.GPSIFD.GPSDateStamp: u"1999:99:99 99:99:99",
           }
first_ifd = {
             piexif.ImageIFD.Make: u"Canon",
             piexif.ImageIFD.XResolution: (40, 1),
             piexif.ImageIFD.YResolution: (40, 1),
             piexif.ImageIFD.Software: u"piexif"
             }

exif_dict = {"0th":zeroth_ifd, "Exif":exif_ifd, "GPS":gps_ifd, "1st":first_ifd, "thumbnail":thumbnail}
exif_bytes = piexif.dump(exif_dict)
im = Image.open("foo.jpg")
im.save("out.jpg", exif=exif_bytes)

You can check all the metadata fields that you can edit with piexif here.

A: I can't find a clear answer about custom tags (these links suggest you can with a third party tool), but looking at the specifications gives only the defined tags so I'm going to say no, you can't make your own metadata tags, at least not directly.

So what you can do is write your own data to any of the defined tags. It's best to use the MakerNote tag for this - most camera makers store their own custom metadata there. Dump your custom flags into a byte string before stuffing it into the MakerNote tag:
from PIL import Image
import piexif
import pickle

tags = {'url_current'   : 'https://stackoverflow.com/q/52729428/1846249',
        'contains_fish' : False,
        3               : 0.14159265358979323, }

data = pickle.dumps(tags)
exif_ifd = {piexif.ExifIFD.MakerNote: data}

exif_dict = {"0th": {}, "Exif": exif_ifd, "1st": {},
             "thumbnail": None, "GPS": {}}

img = Image.new('RGB', (500, 500), 'green')
exif_dat = piexif.dump(exif_dict)
img.save('image.jpg',  exif=exif_dat)

Because it's your own format, you'll need to read it back out yourself:
img = Image.open('image.jpg')
raw = img.getexif()[piexif.ExifIFD.MakerNote]
tags = pickle.loads(raw)

exiftool will see the image has a MakerNote, but won't recognize it:
C:\> exiftool image.jpg -MakerNote
Warning: [minor] Unrecognized MakerNotes - image.jpg

You could also store it in the UserComment tag - storing is done in the same way.
C:\>exiftool image.jpg -UserComment
User Comment                    : Ç.ò^}ö(î.url_currentöî,https://stackoverflow.com/q/52729428/1846249öî.contains_fishöëK.G?┬.╡DB╤äu.

P.S. there's a limit of 64kB for metadata in jpeg images


text:
Q: Using new and delete on object arrays C++ Does delete call the destructor?
I have modified the code on the first answer a little bit, but i can't catch my wrong. It is being compiled with 0 errors but program crashes when i run it, also devC++ debug mode gives me SIGTRAP signal. I'd really appreciate a second hand here.
So the idea is;
reform() will delete the old array (if necessary, the second parameter is optional and i'm only using it in constructors because at that moment the pointer is actually null (?)). And then it will allocate it again with new, using the input parameter size. I really have no idea which part might be wrong. Thanks for all answers.
#include <iostream>

using namespace std;

class A
{
    private:
        int val;
    public:
        A();
        int GetVal();
        void SetVal(int Val);
};

A::A()
{
    this->val = 0;
}

int A::GetVal()
{
    return this->val;
}

void A::SetVal(int Val)
{
    this->val = Val;
}

#define DEF_A_SIZE 1

class B
{
    private:
        A *a_s;
        int aSize;
        int aCount;
        void reform(const int size, int dlt = 1);
public:
    B();
    ~B();
    void SetSize(const int newSize);
    int GetSize();
    void AddA(A a);
    A GetA(int index);
};

void B::reform(const int size, int dlt)
{
    if(dlt)
    {
        delete[] (this->a_s);
    }
    this->a_s = new A[size];
    this->aCount = 0;
    this->aSize = size;
}

B::B()
{
    reform(DEF_A_SIZE, 0);
}

B::~B()
{
    delete [] (this->a_s);
}

void B::SetSize(const int newSize)
{
    reform(newSize);
}

int B::GetSize()
{
    return this->aSize;
}

void B::AddA(A a)
{
    if (aCount < aSize)
    {
        this->a_s[aCount].SetVal(a.GetVal());
        aCount++;
    }
}

A B::GetA(int index)
{
    if (index < aCount)
    {
        return this->a_s[index];
    }
}

#define B_NUM 1

class C
{
    private:
        B *b_s;
        int bc;
        int bs;
        void reform(const int size, int dlt = 1);
    public:
        C();
        ~C();
        void addb(B b);
        B getB(int index);
};

void C::reform(const int size, int dlt)
{
    if (dlt)
    {
        delete [] (this->b_s);
    }
    bc = 0;
    bs = size;
    b_s = new B[size];
}

void C::addb(B b)
{
    if (bc < bs)
    {
        b_s[bc].SetSize(b.GetSize());
        for (int i = 0; i < b.GetSize(); i++)
        {
            b_s[bc].AddA(b.GetA(i));
        }
        bc++;
    }
}

B C::getB(int index)
{
    if (index < bc)
    {
        return b_s[index];
    }
}

C::C()
{
    reform(B_NUM, 0);
}

C::~C()
{
    delete [] (this->b_s);
}

int main()
{
    C *cptr = new C();

    B b = B();
    b.SetSize(2);

    A a = A();
    a.SetVal(10);
    b.AddA(a);

    A a2 = A();
    a2.SetVal(20);
    b.AddA(a2);

    cptr->addb(b);

    cout << cptr->getB(0).GetA(0).GetVal() << endl;
    cout << cptr->getB(0).GetA(1).GetVal() << endl;

    delete cptr;

    cin.get();

    return 0;
}

Solved
Turns out my problem was my Add or Get functions. I changed them this way;
Getters will return references to the respective objects (e.g B &getB(int index);)
And Adder's will take pointers as parameters, not objects ( or values ) (e.g void addb(B *b);)

A:
"Does delete call the destructor?"

Yes, delete or delete[] calls the destructor function of affected class instances.


text:
Q: How to customize the name displayed with Slack bot messages LiveChat is a Slack bot that provides a chat widget for webpages which you can use to send messages to a Slack workspace. I would like to reproduce the behavior of the LiveChat bot which is somehow able to customize the bot name that appears with messages in Slack with a unique identifier for each user of the webpage with the chat widget.
I see that there is an as_user field in the Slack API, but LiveChat does not seem to be using this since clicking the name on any LiveChat message in Slack shows a popup for LiveChat. So the Slack user for all messages seems to be the LiveChat bot, but the name displayed with each message in Slack is customized as a unique id for the given user.
So, I don't want to dynamically control the user for each message. I just want to control the displayed name for each message from the single bot that I'm making.
I don't see anything in the postMessage API to support this. Do you know how to do it?
https://api.slack.com/methods/chat.postMessage


text:
Q: Detecting borders of a page on a table and then "refocus" I have the following picture and I would like to detect the border of the page and then to refocus to see "only" the page. How can I start to code this with opencv3 and Python 3 ?

A: You can simply use thresholding methods to seperate the paper from background. To demonstrate:
Read image and convert to gray.
image = cv2.imread("page.jpg")
gray_image = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)

check histogram to choose threshold values. More here
color = ('b','g','r')
fig = plt.figure(figsize=(12,12))
ax = fig.add_subplot(1,2,1)
ax.imshow(image)
ax1 = fig.add_subplot(1,2,2)
for i,col in enumerate(color):
    histogram = cv2.calcHist([image],[i],None,[256],[0,256])
    ax1.plot(histogram,color = col)
    ax1.set_xlim([0,256])

Use blur to get rid of the notebook's details.
blurred_gray_image = cv2.blur(gray_image,(21,21))

Do thresholding. Using values which we got from the histogram.
_,thresholded_blurry_image = cv2.threshold(blurred_gray_image,165,255,cv2.THRESH_BINARY)

Detect contours (which are undivided, closed shapes).
contours, hierarchy = cv2.findContours(thresholded_blurry_image,
cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

Draw the biggest contour's outline to the copy of the original image if there are any contours.Source post for finding the biggest contour.
output = image.copy()
if len(contours) != 0:
    c = max(contours, key = cv2.contourArea)
    # coordinates of the contour
    x,y,w,h = cv2.boundingRect(c)
    cv2.rectangle(output,(x,y),(x+w,y+h),(0,255,0),2)

Show the result
output = cv2.cvtColor(output,cv2.COLOR_BGR2RGB)
plt.imshow(output)

You can use cv2.imwrite() function to save the image.
Hope this answer satisfies your question. But be aware that this method won't always work because we evaluate the histogram ourselves and pick the thresholding values by hand. If you want to take a more general approach try adaptive thresholding or evaluate histogram values with help of an algorithm. Best of luck.


text:
Q: Ng-checked not updating after data is being modified i have the following problem with the ng-checked component : i have a list of entries with a checked property that is passed in the html template. Initially the entries come with false on checked but after processing some data the value is set to true. Although i modify the array and i have a watch set on that directive the checked value is not updated(is set to false). I don't know what am i missing.
Template :
<span data-ng-repeat="item in data_used track by $index" ng-class="class">
        <input id="{{name_used}}_{{item.value}}"
               type="checkbox"
               name="{{name_used}}"
               value="{{item.value}}"
               data-ng-click="checkbox_click(item, $event)"
               data-ng-checked="{{item.checked}}"
               tabindex="0"/>
        <label for="{{name_used}}_{{item.value}}"
               data-ng-show="item.text">{{item.text}}
        </label>
    </span>

Controller :
$scope.$watch('data', function() {
                    var array = angular.fromJson($scope.data);
                });

Array passed to the directive :
$scope.useForAccountData = [
  {
   text: lang.get('nli_customer_data_debit_placeholder'),
   value: 'debit',
   backendValue: 'refund',
   checked: false
  },
  {
   text: lang.get('nli_customer_data_credit_placeholder'),
   value: 'credit',
   backendValue: 'withdrawal',
  checked: false
  }
];

The part where the array is update :
angular.forEach($scope.useForAccountData,function(el) {
    if(bankAccount.usedFor && bankAccount.usedFor.indexOf(el.backendValue) >= 0) {
      el.checked = true;
    }
});

Whole directive :
'use strict';

define(['angular'], function(angular) {

return angular.module('portals.vio.checkboxGroup', [])
    /* Directive */
    .directive('vioCheckboxGroup', [
    function() {
        return {
            restrict: 'AE',
            scope: {
                disabled: '@',
                click: '&',
                reset: '=?',
                data: '@',
                dataAddress: '@',
                name: '@',
                fieldsetLegend: '@',
                dynamic: '@',
                class: '@',
                validationRules: '=',
                validate: '='
            },
            controller: ['$scope','$http', 'lang', 'validationUtils', function($scope,$http,lang,validationUtils) {
                if( $scope.validationRules &&
                        $scope.validationRules.helperMessage) {
                        //show the helper message
                        $scope.textShow = 'help';
                        $scope.validationText = $scope.validationRules.helperMessage;
                    }
                $scope.itemsChecked = [];
                $scope.itemsCheckedPositions = [];
                if($scope.dataAddress) {
                    $http.get($scope.dataAddress).then(function(resp) {
                        $scope.data_used = angular.fromJson(resp.data);
                    }, function(err) {
                        $scope.data_used = angular.fromJson($scope.data);
                    });
                }
                else if($scope.data) {
                    $scope.data_used = angular.fromJson($scope.data);
                }
                $scope.name_used = ($scope.name) ? $scope.name: 'default';

                /* Trigger the given callback everytime a checkbox is toggled */
                $scope.checkbox_click = function(item, event) {
                    if(item.checked)
                        item.checked = false;
                    else
                        item.checked = true;

                    /* Create a list with all checked checkboxes */
                    angular.forEach($scope.data_used, function(val, key) {
                        if(val.checked){
                            $scope.itemsChecked.push(val);
                            $scope.itemsCheckedPositions.push(key);
                        }
                    });

                    var valid = $scope.validateCheckbox();

                    $scope.click({items: $scope.itemsChecked, valid: valid});
                };
                $scope.$watch('data', function() {
                    var array = angular.fromJson($scope.data);
                });

                /* Function triggered through the reset callback */
                $scope.reset_fields = function() {
                    angular.forEach($scope.data_used, function(val, key) {
                        val.checked = false;
                    });
                };

                $scope.reset = function() {
                    $scope.reset_fields();
                };
                if( $scope.validationRules) {
                    $scope.validate = function(obj) {
                        if(obj === undefined) {
                            if(!$scope.valid) {
                                $scope.validateCheckbox();
                            }
                        }
                        else {
                            if( obj.type && obj.message) {
                                $scope.textShow = obj.type;
                                $scope.validationText = obj.message;
                            }
                        }
                    };
                };

                $scope.validateCheckbox = function() {
                    var checkboxIsValid = true;
                    if( $scope.validationRules &&
                        $scope.validationRules.hasChecked) {

                        try {
                            if($scope.itemsChecked.length !== $scope.validationRules.hasChecked ) {
                                $scope.textShow = 'error';
                                $scope.validationText = lang.get('errorSelectionNotMatchingSetNumber') + $scope.validationRules.hasChecked + lang.get('elements');
                                checkboxIsValid = false;
                            }
                        }
                        catch(ex) {
                            checkboxIsValid = false;
                        }
                    }
                    if( $scope.validationRules &&
                        $scope.validationRules.hasCheckedAtLeast) {

                        try {
                            if($scope.itemsChecked.length < $scope.validationRules.hasCheckedAtLeast) {
                                $scope.textShow = 'error';
                                $scope.validationText = lang.get('errorSelectionLowerThanExpected') + $scope.validationRules.hasCheckedAtLeast + lang.get('elements');
                                checkboxIsValid = false;
                            }
                        }
                        catch(ex) {
                            checkboxIsValid = false;
                        }
                    }
                    if( $scope.validationRules &&
                        $scope.validationRules.hasItemsChecked) {

                        try {
                            var counter = 0;
                            angular.forEach($scope.itemsCheckedPositions, function(val,key){
                                if($scope.itemsCheckedPositions.indexOf(val)<0){
                                    counter++;
                                }
                            });
                            if(counter !== $scope.itemsCheckedPositions.length) {
                                $scope.textShow = 'error';
                                $scope.validationText = lang.get('errorSelectionDifferentThanPresetOnes');
                                checkboxIsValid = false;
                            }

                        }
                        catch(ex) {
                            checkboxIsValid = false;
                        }
                    }
                    if(checkboxIsValid) {
                        $scope.textShow = '';
                        $scope.validationText = '';
                    }

                    return checkboxIsValid;

                };

                validationUtils.registerValidationEvents($scope, $scope.validateCheckbox);

            }],
            replace: true,
            templateUrl: '../../ui.components.base/vio-checkbox-group/vio-checkbox-group.html',
            link: function($scope, elem, attrs) {

                /* Update the fieldset legend with a name, if given */
                $scope.$watch('fieldsetLegend', function(new_val, old_val) {

                    var legend_elem = elem.find('legend');
                    legend_elem.remove();

                    if(new_val !== undefined) {
                        elem.find('fieldset')
                            .prepend('<legend>' + new_val + '</legend>');
                    }
                });

            }
        };
    }]);

});
After updating the array in the watch part i see the values with checked true but in the html the ng-checked property is still false.
Thanks,
Vio


text:
Q: Boolean field vs separate table I have a keyword table where I will store all possible keywords that may be related to events (activities).
I want to allow organisers to enter custom keywords as well that will be uploaded to my database for moderation.
Is it a better idea to create a boolean field on the existing table (fieldname=active) or to create a separate table altogether for custom keywords?
An important note is that I will create a tool that will allow moderators to extract a list of inactive keywords from the table on a regular basis.
Logic tells me that they belong all together in a general "keywords" table, but performance wise it would appear better to create a separate table.
What is your thought?
Edit based on answer of Gordon Linoff:
First, the keywords are not specific to an organiser, although their id will be stored as well (just as the time as you mention it).
A customer keyword can never override a built-in keyword, because it will only be allowed when the moderators (we) consider it good.
Note: There will also be a more complex keyword management with parents - child elements that we will take into account when moderating. The purpose is to create a search engine where organisers can add keywords, and where users can access activities based on these keywords (or their parent keywords).
And the keyword is not specific for an organiser, but will be specific for an activity. But this will be managed with a many-to-many relationship (junction table), so this is not a problem.

A: This is too long for a comment.
You question doesn't provide enough information for answering this question.  For instance, are the custom keywords specific to a given organizer?  If so, merely having a boolean "isactive" flag is not sufficient.  Can a customer keyword -- in any way -- override a built-in keyword?
I suspect that the "custom" keywords have fields that are not naturally part of the built-in keywords, such as:

*

*Who created it?

*When it was created?

And perhaps some other information, such as who has access to it.
Performance can only be judged based on the queries used to access the data.  However, I doubt that putting the keywords in a single table would have a big impact on performance.


text:
Q: uuid-ossp module for PostgreSQL 8.2 to generate UUID I am trying to generate UUID in PostgreSQL 8.2. From the documentation I found uuid-ossp module can generate UUID but it supports only PostgreSQL 9+. Is there any way to use this uuid-ossp module in PostgreSQL 8.2 or generate UUID in PostgreSQL 8.2 by using query?

A: You may be confused about the packaging of that plugin for Postgres. Postgres 9.1 introduced a new packaging scheme called Extension. The idea is that the creator of a plugin does more work with regard to packaging so that the user of the plugin might do less work with regard to installation. The Create Extension command (a mis-nomer to my mind) installs a plugin into your Postgres cluster.
Previous to Postgres 9.1, you can install the UUID plugin, but doing so is not quite so simple. You must locate the "uuid-ossp" plugin appropriate to your version of Postgres. The plugin may well have been bundled with your Postgres cluster but not yet installed (activated). Within that plugin package find the SQL script used for installation. You then execute that script in your Postgres cluster.
For details, see my posting to the Postgres mailing list and my blog post on the old way to install and the new way to install the UUID plugin.
I cannot find the 8.2 doc, but did find the 8.3 doc for the uuid-ossp plugin. I do not know if 8.2 had a version of the uuid-ossp plugin, but I suppose so.

Postgres 8.2 reached end-of-life two years (2011-12). I strongly suggest planning an upgrade.
As Craig Ringer commented, you should be doing only the most basic maintenance to a Postgres 8.2 cluster. Asking about UUID support suggests some major changes. For such changes you really should first complete an upgrade to a more recent Postgres.

A: You could write a function PL/Perl or PL/Python that generates UUIDs using one of their modules.


text:
Q: how to get the console output into a label in tkinter So im trying to make a simple pyscript editor and i want to get the console output into a label inside my tkinter wiondow
here is my code so far Thanks!
from tkinter import Text, Tk
import os
root = Tk()
root.configure(background='black')
root.geometry('1920x1080')
def ok():
    input = text1.get("1.0","end-1c")
    gay = open('data.py', 'w')
    gay.write(input)
    gay.close()
    os.startfile('data.py')

text1 = Text(root, bg="#6B6B6B", height=50, width=200)
text1.place(x=320, y=40)
but1 = Button(root, text="halleo", command=ok).pack()
root.mainloop()

A: I think this is what you are after... It is hard to tell from your question. I assume by console you mean text area. I took out the file output, but you could put it back in.
from tkinter import *
import subprocess
import shlex

def run_command(the_command):
    process = subprocess.Popen(shlex.split(the_command), stdout=subprocess.PIPE)
    output = process.stdout.read()
    output = str(output).replace("b'", "").replace("\\n'", "")
    lab1.configure(text=output)

def command():
    the_input = text1.get("1.0", "end-1c")
    run_command(the_input)

root = Tk()
root.configure(background='black')
root.geometry('1920x1080')
text1 = Text(root, bg="#6B6B6B", height=50, width=200)
text1.place(x=320, y=40)
but1 = Button(root, text="halleo", command=command).pack()
lab1 = Label(root, text="asdf", background='white')
lab1.pack()

root.mainloop()


text:
Q: For loop doesn't work properly for unknown reason I have this code:
def show_hide(a, b, c, d):
    if not b[0]["text"]:  # check if text's length is 0
        b[0].configure(text="{}".format(d[0]), bd=2, bg="white", command=lambda: activate_deactivate(a[0], c[0]))  # configure button_1
        c[0]["text"] = "Status: {}".format(a[0].get())  # set text for label_1
        b[1].configure(text="{}".format(d[1]), bd=2, bg="white", command=lambda: activate_deactivate(a[1], c[1]))  # configure button_2
        c[1]["text"] = "Status: {}".format(a[1].get())  # set text for label_2
    else:
        b[0].configure(text="", bd=0, bg="#F0F0F0", command=None)  # hide the button_1
        c[0]["text"] = ""  # hide the label_1
        b[1].configure(text="", bd=0, bg="#F0F0F0", command=None)  # hide the button_2
        c[1]["text"] = ""  # hide the label_2

My button which calls this function has this command value:
command=lambda: show_hide([status, status_2], [button, button_2], [label, label_2], ["Perform action #1", "Perform action #2"]))

By using it I can show/hide buttons but rewriting the same thing changing a digit in a few places would be tedious. To fix it I tried using this code instead of the original:
def show_hide(a, b, c, d):
    for i in range(0, len(a)):  # iterates over indexes of items in a,b,c,d lists (all 4 have same length) and passes them to the if/else statement
        if not b[i]["text"]:  # check if text length is 0
            b[i].configure(text="{}".format(d[i]), bd=2, bg="white", command=lambda: activate_deactivate(a[i], c[i]))  # configure buton
            c[i]["text"] = "Status: {}".format(a[i].get())  # set label's text
        else:
            b[i].configure(text="", bd=0, bg="#F0F0F0", command=None)  # hide button
            c[i]["text"] = ""  # hide label

Theoretically, this should work fine and using just 4 lines of code (not counting for/if/else lines) do the same thing as original function which would need 4 lines for EACH status+button+label created. BUT, as a matter of fact, it makes my 2 buttons work totally wrong.
I don't really understand what is wrong with it so I can't fully describe the problem, but you can see for yourself by using the test-script I made and replacing the show_hide function definition with the one using for-loop:
import tkinter as tk
import random

class ActionButton(tk.Button):
    def __init__(self, *args, **kwargs):
        tk.Button.__init__(self, *args, **kwargs)
        self.configure(text="", font="courier 20", bd=0)

class ActionLabel(tk.Label):
    def __init__(self, *args, **kwargs):
        tk.Label.__init__(self, *args, **kwargs)
        self.configure(text="", font="courier 14")

def multi(*args):
    for func in args:
        return func

def show_hide(a, b, c, d):
    if not b[0]["text"]:
        b[0].configure(text="{}".format(d[0]), bd=2, bg="white", command=lambda: activate_deactivate(a[0], c[0]))
        c[0]["text"] = "Status: {}".format(a[0].get())
        b[1].configure(text="{}".format(d[1]), bd=2, bg="white", command=lambda: activate_deactivate(a[1], c[1]))
        c[1]["text"] = "Status: {}".format(a[1].get())
    else:
        b[0].configure(text="", bd=0, bg="#F0F0F0", command=None)
        c[0]["text"] = ""
        b[1].configure(text="", bd=0, bg="#F0F0F0", command=None)
        c[1]["text"] = ""

def activate_deactivate(a, c):
    if a.get() == "Can be done":
        a.set("To be done")
        c.configure(text="Status: {}".format(a.get()), fg="blue")
    else:
        a.set("Can be done")
        c.configure(text="Status: {}".format(a.get()), fg="black")

def step_forward(a, b, c):
    if a.get() == "To be done":
        b.configure(text="", bd=0, bg="#F0F0F0", state="disabled")
        c["text"] = ""
        result = random.choice(["success", "failure"])
        if result == "success":
            a.set("Accomplished")
            c["fg"] = "green"
        else:
            a.set("Failed")
            c["fg"] = "red"
    else:
        b.configure(text="", bd=0, bg="#F0F0F0", command=None)
        c["text"] = ""

root = tk.Tk()

status = tk.StringVar()
status.set("Can be done")

status_2 = tk.StringVar()
status_2.set("Can be done")

main = tk.Button(root, text="Show/Hide", bg="white", font="courier 30",
                 command=lambda: show_hide([status, status_2],
                                           [button, button_2],
                                           [label, label_2],
                                           ["Perform action #1", "Perform action #2"]))
main.pack()

frame = tk.Frame(root, pady=10)
frame.pack()

frame_1 = tk.Frame(frame, padx=10)
frame_1.pack(side="left")

frame_2 = tk.Frame(frame, padx=10)
frame_2.pack(side="left")

button = ActionButton(frame_1)
button.grid(row=0, column=0)

label = ActionLabel(frame_1)
label.grid(row=1, column=0)

button_2 = ActionButton(frame_2)
button_2.grid(row=0, column=1)

label_2 = ActionLabel(frame_2)
label_2.grid(row=1, column=1)

next_day = tk.Button(root, text="Next day", bg="white", font="courier 30",
                     command=lambda: multi(step_forward(status, button, label),
                                           step_forward(status_2, button_2, label_2)))
next_day.pack()

root.mainloop()

I hope there's someone who may know how to fix this and maybe even has an idea about how the function could be changed to perform everything properly.


text:
Q: Session state changes on production, but not on test web server I have a c# application that used IIS 10, that has been working for many years with using the session id to track the users selections across the site.
I did an update this week and I messed something up and I can't seem to pinpoint where the change was made.
I added a textbox on the same page on both test and production.
<asp:TextBox runat="server" ID="txtSession" ></asp:TextBox>

protected void Page_Load(object sender, EventArgs e)
{
  txtSession.Text = Session.SessionID.ToString();
}

On test when I refresh the session id stays the same, but when I'm on production the session id changes when I refresh or go to a different page.  I'm reviewed my web.config on both sides and can't see where this is an issue.  This is the only session row in web.config on both side
<sessionState mode="InProc" timeout="120"/>

Within the global.asax.ca has the following
protected void Session_Start(object sender, EventArgs e)
{
    Session.Timeout = 60;
    Session["User"] = "";
    Session["UserLevel"] = 0;
    Session["EmptyFields"] = -1;
    //Session["SelectedID"] = "";
}

So it is Any help would be greatly appreciated.  I've been going over this for almost 2 days and I can't seem to find the issue.  Part of my updated including updating to oracle managed data access dlls.  This also exists on test and it working fine.

A: I figured out the issue was the following files were deleted from the bin directory.

App_global.asax.compiled

App_global.asax.dll

As soon as I copied them back everything started working.


text:
Q: SQL Server 2019 Standard unable to create certificate from 2012 Enterprise backup cert I am trying to migrate from SQL Server 2012 Enterprise to SQL Server 2019 Standard and one of my steps involves transferring the TDE cert from 2012 to 2019. I have the cert and key backed up from 2012 and am trying to create a new cert on 2019 using the 2012 key and cert.
This is the same process I use to restore the encryption cert to a new instance of SQL Server 2012. I am getting the following message however when trying to do this same process in SQL Server 2019 Std:

The certificate, asymmetric key, or private key file is not valid or does not exist; or you do not have permissions for it.

Here is my SQL statement for restoring the cert using a backup of the cert and key:
CREATE CERTIFICATE TDECert_SQL2019
    FROM FILE = 'E:\Backup\TDECert_SQL2019.BAK'
    WITH PRIVATE KEY (FILE = 'E:\Backup\TDEkey_SQL2019.bkey',
    DECRYPTION BY PASSWORD = 'MYSECUREPASSWORD');
GO

I know the file path is correct and I know the password is correct. I can run this same SQL on a SQL Server 2012 instance with no issues.
I know that SSL certs are dealt with a little differently on SQL Server 2019, but I am not aware of changes with regards to TDE.