text:
Q: Получаю ошибку при добавлении `kotlin` плагина в проект У меня есть проект на java и вот я решил добавить kotlin
Есть вот такая статья о том как добавить kotlin в проект
https://medium.com/@elye.project/setup-kotlin-for-android-studio-1bffdf1362e8
я все сделал и теперь вот получаю такую ошибку
https://gist.github.com/alekseytimoshchenko/46432a522afdb92dd5b38e6c30d34d78

org.gradle.api.ProjectConfigurationException: A problem occurred configuring project ':app'.
      at org.gradle.configuration.project.LifecycleProjectEvaluator.wrapException(LifecycleProjectEvaluator.java:79)
      at org.gradle.configuration.project.LifecycleProjectEvaluator.addConfigurationFailure(LifecycleProjectEvaluator.java:73)
      at org.gradle.configuration.project.LifecycleProjectEvaluator.access$400(LifecycleProjectEvaluator.java:54)
      at org.gradle.configuration.project.LifecycleProjectEvaluator$NotifyAfterEvaluate.run(LifecycleProjectEvaluator.java:200)
      at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
      at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
      at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
      at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
      at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
      at org.gradle.configuration.project.LifecycleProjectEvaluator$EvaluateProject.run(LifecycleProjectEvaluator.java:110)
      at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
      at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
      at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
      at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
      at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
      at org.gradle.configuration.project.LifecycleProjectEvaluator.evaluate(LifecycleProjectEvaluator.java:68)
      at org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:687)
      at org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:140)
      at org.gradle.execution.TaskPathProjectEvaluator.configure(TaskPathProjectEvaluator.java:35)
      at org.gradle.execution.TaskPathProjectEvaluator.configureHierarchy(TaskPathProjectEvaluator.java:62)
      at org.gradle.configuration.DefaultBuildConfigurer.configure(DefaultBuildConfigurer.java:41)
      at org.gradle.initialization.DefaultGradleLauncher$ConfigureBuild.run(DefaultGradleLauncher.java:274)
      at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
      at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
      at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
      at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
      at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
      at org.gradle.initialization.DefaultGradleLauncher.configureBuild(DefaultGradleLauncher.java:182)
      at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:141)
      at org.gradle.initialization.DefaultGradleLauncher.getConfiguredBuild(DefaultGradleLauncher.java:119)
      at org.gradle.internal.invocation.GradleBuildController$2.call(GradleBuildController.java:86)
      at org.gradle.internal.invocation.GradleBuildController$2.call(GradleBuildController.java:83)
      at org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:154)
      at org.gradle.internal.work.StopShieldingWorkerLeaseService.withLocks(StopShieldingWorkerLeaseService.java:38)
      at org.gradle.internal.invocation.GradleBuildController.doBuild(GradleBuildController.java:96)
      at org.gradle.internal.invocation.GradleBuildController.configure(GradleBuildController.java:83)
      at org.gradle.tooling.internal.provider.runner.ClientProvidedBuildActionRunner.run(ClientProvidedBuildActionRunner.java:70)
      at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
      at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
      at org.gradle.tooling.internal.provider.ValidatingBuildActionRunner.run(ValidatingBuildActionRunner.java:32)
      at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner$3.run(RunAsBuildOperationBuildActionRunner.java:50)
      at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
      at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
      at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
      at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
      at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
      at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:45)
      at org.gradle.tooling.internal.provider.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:51)
      at org.gradle.launcher.exec.InProcessBuildActionExecuter$1.transform(InProcessBuildActionExecuter.java:47)
      at org.gradle.launcher.exec.InProcessBuildActionExecuter$1.transform(InProcessBuildActionExecuter.java:44)
      at org.gradle.composite.internal.DefaultRootBuildState.run(DefaultRootBuildState.java:79)
      at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:44)
      at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:30)
      at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:39)
      at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:25)
      at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:80)
      at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:53)
      at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:62)
      at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:34)
      at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:36)
      at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:25)
      at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:43)
      at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:29)
      at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:59)
      at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:31)
      at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:59)
      at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:44)
      at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:46)
      at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:30)
      at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
      at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
      at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
      at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
      at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
      at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
      at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
      at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
      at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
      at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
      at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
      at org.gradle.util.Swapper.swap(Swapper.java:38)
      at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
      at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
      at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
      at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
      at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:62)
      at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
      at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
      at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:81)
      at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
      at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
      at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
      at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:295)
      at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
      at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
      at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
      at java.lang.Thread.run(Thread.java:745)
  Caused by: org.gradle.internal.event.ListenerNotificationException: Failed to notify project evaluation listener.
      at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:86)
      at org.gradle.internal.event.BroadcastDispatch$CompositeDispatch.dispatch(BroadcastDispatch.java:324)
      at org.gradle.internal.event.BroadcastDispatch$CompositeDispatch.dispatch(BroadcastDispatch.java:234)
      at org.gradle.internal.event.ListenerBroadcast.dispatch(ListenerBroadcast.java:140)
      at org.gradle.internal.event.ListenerBroadcast.dispatch(ListenerBroadcast.java:37)
      at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
      at com.sun.proxy.$Proxy34.afterEvaluate(Unknown Source)
      at org.gradle.configuration.project.LifecycleProjectEvaluator$NotifyAfterEvaluate$1.execute(LifecycleProjectEvaluator.java:187)
      at org.gradle.configuration.project.LifecycleProjectEvaluator$NotifyAfterEvaluate$1.execute(LifecycleProjectEvaluator.java:184)
      at org.gradle.api.internal.project.DefaultProject.stepEvaluationListener(DefaultProject.java:1418)
      at org.gradle.configuration.project.LifecycleProjectEvaluator$NotifyAfterEvaluate.run(LifecycleProjectEvaluator.java:193)
      ... 95 more
  Caused by: java.lang.NoClassDefFoundError: com/android/build/gradle/internal/TaskContainerAdaptor
      at org.jetbrains.kotlin.gradle.plugin.KotlinAndroidPlugin.forceCreateJavacTask(KotlinPlugin.kt:385)
      at org.jetbrains.kotlin.gradle.plugin.KotlinAndroidPlugin.processVariantData(KotlinPlugin.kt:412)
      at org.jetbrains.kotlin.gradle.plugin.KotlinAndroidPlugin.access$processVariantData(KotlinPlugin.kt:326)
      at org.jetbrains.kotlin.gradle.plugin.KotlinAndroidPlugin$apply$2.execute(KotlinPlugin.kt:370)
      at org.jetbrains.kotlin.gradle.plugin.KotlinAndroidPlugin$apply$2.execute(KotlinPlugin.kt:326)
      at org.gradle.configuration.internal.DefaultListenerBuildOperationDecorator$BuildOperationEmittingAction$1$1.run(DefaultListenerBuildOperationDecorator.java:155)
      at org.gradle.configuration.internal.DefaultUserCodeApplicationContext.reapply(DefaultUserCodeApplicationContext.java:58)
      at org.gradle.configuration.internal.DefaultListenerBuildOperationDecorator$BuildOperationEmittingAction$1.run(DefaultListenerBuildOperationDecorator.java:152)
      at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
      at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
      at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
      at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
      at org.gradle.configuration.internal.DefaultListenerBuildOperationDecorator$BuildOperationEmittingAction.execute(DefaultListenerBuildOperationDecorator.java:149)
      at org.gradle.internal.event.BroadcastDispatch$ActionInvocationHandler.dispatch(BroadcastDispatch.java:91)
      at org.gradle.internal.event.BroadcastDispatch$ActionInvocationHandler.dispatch(BroadcastDispatch.java:80)
      at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:42)
      at org.gradle.internal.event.BroadcastDispatch$SingletonDispatch.dispatch(BroadcastDispatch.java:230)
      at org.gradle.internal.event.BroadcastDispatch$SingletonDispatch.dispatch(BroadcastDispatch.java:149)
      at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:58)
      ... 105 more


text:
Q: filter info from json file and display pdf via link i have a uni project to make a progressive web app. I am trying to make a very simple app for pdf bus timetable viewer that will filter data out of a list and present the required pdf document in application.
I have collated all the bus info into spreadsheet and converted that into a json file that can be read/ displays on the index page as a table.
I want the user to be able to filter this list by column header and either enter in text/ number to query find/ search list to find the bus they want then have app display the appropriate pdf.
How can I do I achieve this?
I have looked into parsing the data, but want more info on how I might get it to work.
essentially I have buttons I want to link to the json data,(find by: bus number, route, start, stops, finish) when one is clicked it will show all results for that column from the table only and then add additional filters for user to input search or choose from list.
below is what I currently have in my idex page:
here is a sample of the data im working with:
{
"busTimes":
[
    {
        "Bus":"Bus",
        "Route":"Route",
        "Start":"Start",
        "Stop1":"Stop1",
        "Stop2":"Stop2",
        "Stop3":"Stop3",
        "Stop4":"Stop4",
        "Stop5":"Stop5",
        "Finish":"Finish",
        "Times":"Times",
        "Maps":"Maps"
    },
    {
        "Bus":"1",
        "Route":"Casuarina (Hospital Precinct)",
        "Start":"Casuarina",
        "Stop1":"Hospital Precinct",
        "Stop2":"Tiwi",
        "Stop3":"Brinkin",
        "Stop4":"Nakara",
        "Stop5":"NO STOP",
        "Finish":"Casuarina",
        "Times":"https://nt.gov.au/__data/assets/pdf_file/0009/159309/route-1-public-bus-timetable.pdf",
        "Maps":"https://nt.gov.au/__data/assets/pdf_file/0008/159308/route-1-public-bus-map.pdf"
    },
    {
        "Bus":"2",
        "Route":"Casuarina ",
        "Start":"Casuarina ",
        "Stop1":"Wanguri",
        "Stop2":"Lyons",
        "Stop3":"Leanyer",
        "Stop4":"Wulagi",
        "Stop5":"Wagaman",
        "Finish":"Casuarina",
        "Times":"https://nt.gov.au/__data/assets/pdf_file/0003/159312/route-2-public-bus-timetable.pdf",
        "Maps":"https://nt.gov.au/__data/assets/pdf_file/0019/159310/route-2-public-bus-map.pdf"
    },
    {
        "Bus":"3",
        "Route":"Casuarina",
        "Start":"Casuarina",
        "Stop1":"Alawa",
        "Stop2":"Jingili",
        "Stop3":"Marrara",
        "Stop4":"Moil",
        "Stop5":"Anula",
        "Finish":"Casuarina",
        "Times":"https://nt.gov.au/__data/assets/pdf_file/0020/159320/route-3-public-bus-timetable.pdf",
        "Maps":"https://nt.gov.au/__data/assets/pdf_file/0008/159317/route-3-public-bus-map.pdf"
    },

}

 find bus timetable by:

 <button  id="bus_number"> bus number </button>

 <button  id="bus_route"> bus route </button>

 <button  id="bus_start"> where the bus starts from  </button>

 <button id="bus_stop"> where the bus stops </button>

 <button id="bus_finish"> where the bus finishes     </button>

SEARCH RESULTS:

                            Bus
                            Route
                            Start
                            Stop 1
                            Stop 2
                            Stop 3
                            Stop 4
                            Stop 5
                            Finish
                            Times
                            Maps

A: This is a simple implementation using hide and show function. You need to use the attribute selector to determine which tr to hide and show.

let data = {
  "busTimes": [{
      "Bus": "Bus",
      "Route": "Route",
      "Start": "Start",
      "Stop1": "Stop1",
      "Stop2": "Stop2",
      "Stop3": "Stop3",
      "Stop4": "Stop4",
      "Stop5": "Stop5",
      "Finish": "Finish",
      "Times": "Times",
      "Maps": "Maps"
    },
    {
      "Bus": "1",
      "Route": "Casuarina (Hospital Precinct)",
      "Start": "Casuarina",
      "Stop1": "Hospital Precinct",
      "Stop2": "Tiwi",
      "Stop3": "Brinkin",
      "Stop4": "Nakara",
      "Stop5": "NO STOP",
      "Finish": "Casuarina",
      "Times": "https://nt.gov.au/__data/assets/pdf_file/0009/159309/route-1-public-bus-timetable.pdf",
      "Maps": "https://nt.gov.au/__data/assets/pdf_file/0008/159308/route-1-public-bus-map.pdf"
    },
    {
      "Bus": "2",
      "Route": "Casuarina ",
      "Start": "Casuarina ",
      "Stop1": "Wanguri",
      "Stop2": "Lyons",
      "Stop3": "Leanyer",
      "Stop4": "Wulagi",
      "Stop5": "Wagaman",
      "Finish": "Casuarina",
      "Times": "https://nt.gov.au/__data/assets/pdf_file/0003/159312/route-2-public-bus-timetable.pdf",
      "Maps": "https://nt.gov.au/__data/assets/pdf_file/0019/159310/route-2-public-bus-map.pdf"
    },
    {
      "Bus": "3",
      "Route": "Casuarina",
      "Start": "Casuarina",
      "Stop1": "Alawa",
      "Stop2": "Jingili",
      "Stop3": "Marrara",
      "Stop4": "Moil",
      "Stop5": "Anula",
      "Finish": "Casuarina",
      "Times": "https://nt.gov.au/__data/assets/pdf_file/0020/159320/route-3-public-bus-timetable.pdf",
      "Maps": "https://nt.gov.au/__data/assets/pdf_file/0008/159317/route-3-public-bus-map.pdf"
    }
  ]
};

$.each(data.busTimes, function(i, f) {
  var tblRow = `

                ${f.Bus}
                ${f.Route}
                ${f.Start}
                ${f.Stop1}
                ${f.Stop2}
                ${f.Stop3}
                ${f.Stop4}
                ${f.Stop5}
                ${f.Finish}

`

  $(tblRow).appendTo("#buses tbody");
});

$('#bus_number').keyup(function() {
  // console.log($(this).val())
  if ($(this).val()) {
    $('#buses tbody tr').hide();
    $('#buses tbody td[data-bus*=' + $(this).val() + ']').parent().show();
  } else {
    $('#buses tbody tr').show();
  }

});

 find bus timetable by:

 <input type="text" placeholder="Search by bus number" id="bus_number" />

 <button id="bus_route"> bus route </button>

 <button id="bus_start"> where the bus starts from  </button>

 <button id="bus_stop"> where the bus stops </button>

 <button id="bus_finish"> where the bus finishes     </button>

SEARCH RESULTS:

          Bus
          Route
          Start
          Stop 1
          Stop 2
          Stop 3
          Stop 4
          Stop 5
          Finish
          Times
          Maps

redpajama_set_name: RedPajamaStackExchange


text:
Q: Exchanging definite integral and infinite sum in context of Fourier series I am writing a mathematics paper on the convergence of the Fourier series for periodic functions, and in the first section (where I define the Fourier series), I also derive the standard coefficients $a_n, b_n$. The standard way of doing this is to multiply both sides of the function by $\cos{kx}$ or $\sin{kx}$ depending on which coefficient you are calculating, and integrating from $-\pi$ to $\pi$, as follows:
$$\int_{-\pi}^\pi f(x)\cos(kx) \, dx = \int_{-\pi}^\pi a_0 \cos{kx} \, dx + \int_{-\pi}^\pi \left(\sum_{n=1}^\infty a_n\cos{nx}\cos{kx} + b_n\cos{nx}\sin{kx} \right)\,dx.$$
However, from this point, the standard derivation of the coefficients involves interchanging the integral and the sum, but to me this is not inherently obvious. For example, if $a_n = 1$ for all $n$, the summation does not converge and we would be integrating something infinite, which doesn't make sense. I've looked at a few posts that talk about interchanging the order of the sum and integral, and most of them don't really seem to apply.
Monotone convergence and Vitali convergence don't seem to apply since we can't make statements about pointwise convergence of $a_n\cos{kx}$ or $b_n\sin{kx}$ without being circular. Fubini's theorem tells us that if $\int\sum_n |f_n(x)| \,dx $ is finite, then we can interchange the summation and integral. However, we can't guarantee that such an integral is finite unless $\int_{-\pi}^\pi f(x) \cos(x)\, dx$ is finite--which led me to assume that the finiteness of the sum is a sufficient condition for interchanging the integral and sum, but my professor said this was insufficient.
Another thing I am thinking about is that pointwise convergence does not preserve integrability, but uniform convergence does. Does this mean that we can only derive the coefficients $a_n, b_n$ when $f$ is uniformly convergent? In that case, why would anyone care about pointwise convergence with the Dirichlet kernel proof?
I guess put simply, my question is, what can we stipulate about $f$ so that the interchange above is valid?

A: When we talk about infinite series, one always has to specify what type of convergence is intended, for example: pointwise convergence/ a.e pointwise convergence/ uniform convergence/ convergence in $L^2$ norm etc. Once you specify this then we can start discussing further. Now, the way I've usually seen things, pointwise convergence of Fourier series is a very subtle topic, and depending on how much regularity you assume on your function $f$, you get all sorts of (weird and crazy but cool) results.
I don't really feel like working with $\sin$ and $\cos$; so let $\phi_n(x)= e^{inx}$ (perhaps with appropriate normalization factors, which I can never remember, and don't feel like calculating now). Given $n\in \Bbb{N}$, let
\begin{align}
s_{n,f}= \sum_{l=-n}^n \hat{f}(l)\phi_l = \sum_{l=-n}^n \left(\int_{-\pi}^{\pi} f(t)\overline{\phi_l(t)}\, dt\right) \phi_l
\end{align}
This is the $n^{th}$ partial sum. Now, here's a couple of results:

*

*If $f$ is of class $C^p$, where $p\geq 1$ is an integer, then $\lVert s_{n,f}-f \rVert_{\infty} = O\left(n^{\frac{1}{2}-p}\right)$ as $n\to \infty$. In particular, this means $s_{n,f}\to f$ uniformly on $[-\pi,\pi]$. As a result of this, you can always interchange the series with the integral $\int_{-\pi}^{\pi}$.

*Usually, you may not want to assume such strong results. Another common thing we do is to suppose $f\in L^2([-\pi,\pi])$. In this case, $s_{n,f}$ need not converge to $f$ pointwise. However, what is true is that $s_{n,f}\to f$ in the $L^2$ norm; i.e $\lVert s_{n,f} - f \rVert_{L^2([-\pi,\pi])} \to 0$ as $n\to \infty$. So, in this case, if we write something like $f=\sum_{n=-\infty}^{\infty}\hat{f}(n)\phi_n$, then the limit which defines the series must be interpreted as an $L^2$ limit. In this case, for any $g\in L^2([-\pi,\pi])$, we can calculate the integral $\int_{-\pi}^{\pi}fg$ by bringing the series out. You can justify this as follows:
\begin{align}
\int_{-\pi}^{\pi}fg &= \left\langle f, \overline{g} \right\rangle =\left\langle \lim_{n\to \infty}s_{n,f}, \overline{g} \right\rangle = \lim_{n\to \infty}\left\langle s_{n,f}, \overline{g} \right\rangle = \sum_{n=-\infty}^{\infty}\hat{f}(n)\int_{\pi}^{\pi}\phi_n(t)g(t)\, dt,
\end{align}
where I used the fact that the inner product $\langle \cdot, \cdot\rangle$ on $L^2$ is a bilinear bounded function (because of Cauchy Schwarz inequality), or equivalently, it is continuous, so we can pull the limit outside.
Btw, note that if you take the sequence of coefficients to be all $1$, then you do not have convergence in $L^2$ even so that's just a very bad situation. Again, you may want to impose other types of regularity assumptions, in which case you get corresponding results. I obviously haven't written an exhaustive list, but hopefully this points you in the right direction.

A: How about the dominated convergence theorem? If you know the coefficients $a_n$ and $b_n$ decay rapidly enough so that the partial sums $|\sum_{n}^{N} a_n\cos(kx)+b_n\sin(kx)|$ are dominated by an integrable function, then the interchange is legal by dominated convergence. How fast the coefficients decay depends on the smoothness of $f$. For example if $f$ is twice continuously differentiable you can show using integration by parts that the coefficients grow like $\frac{1}{n^2}$. In this case the partial sums are indeed dominated by an $L^1[-\pi,\pi]$ function, namely a constant function.


text:
Q: ¿Es igual "import XXX" que "from XXX import a, b, c"? Yo entendia que
import XXX
print(XXX.a)

y
from XXX import a, b, c
print(a)

eran lo mismo, y elegir uno y otro era cuestión de preferencias personales.
El caso es que tengo este módulo servicio.py que contiene la maqueta de un servicio que lee algún dato y lo mantiene en la variable var.
Cada vez que se llama al servicio, var debería actualizarse, lo que simulo sumandole 100 en cada pasada.
servicio.py
var = 1

def cambia():
    global var
    var += 100
    print(f"cambia var = {var}")

Desde otro módulo quiero llamar al servicio y luego recuperar el valor accesando directamente la variable var.
Alternativa 1
import servicio

print(id(servicio.var), servicio.var)
servicio.cambia()
print(id(servicio.var), servicio.var)

que produce:
9788992 1
cambia var = 101
9792192 101

Alternativa 2
from servicio import var, cambia

print(id(var), var)
cambia()
print(id(var), var)

que produce:
9788992 1
cambia var = 101
9788992 1

¿Alguien me puede explicar la diferencia?

A: Como ya has descubierto "por las malas" esas sintaxis de import no son equivalentes. Pero ¿cuál es la diferencia exactamente?
import servicio

lo que hace es cargar el fichero servicio.py en memoria, ejecutarlo, y crear en el espacio de nombres local el símbolo servicio, que actúa como si fuera una objeto, en el sentido de que admite la sintaxis "punto" para acceder a sus símbolos internos, de modo que puedes poner servicio.var, servicio.cambia, etc. Todos los símbolos que servicio.py defina a nivel global() (global opera a nivel de módulo), son accesibles desde el código que lo importa a través de la notación "punto".
En cambio cuando haces
from servicio import var

lo que ocurre es que, igual que antes, se carga servicio.py en memoria, se ejecuta, y se crea en el espacio de nombres local el símbolo var.
Simplificando mucho, es como si se hubiera hecho:
import servicio
var = servicio.var
del servicio         # Esto borra el símbolo

Por tanto tenemos ahora dos símbolos var diferentes, con diferente visibilidad:

*

*El símbolo var que aparece listado si haces globals() dentro de servicio.py y que se creó como consecuencia de la línea var=1 en ese fichero.

*El símbolo var que aparece listado si haces globals() dentro de main.py, y que se creó como consecuencia del from servicio import var. Este comienza inicializado con el valor 1. Supongo que no te extrañará mucho descubrir que si hiciéramos var = 2 en main.py eso sólo cambiará el valor del símbolo local, sin afectar al símbolo descrito en el punto 1.

Cuando la función cambia() hace var+=100, está cambiando en realidad el valor del símbolo 1 de los dos antes explicados. El valor del símbolo 2 no es afectado, pues está en otro espacio de nombres.
Cuando haces el import servicio no ves estos efectos secundarios porque siempre estás refiriendo al símbolo 1, al tener que usar la sintaxis servicio.valor.
Nota: Mirar los id() de las variables no ayuda mucho aqui, y más bien resulta confuso, porque en el fondo id() lo que te devuelve es una especie de hash del valor que contiene. En realidad devuelve la dirección de memoria donde está el dato correspondiente, pero no la dirección de la variable, que es seguramente lo que tú querías averiguar. No hay forma de obtener la dirección de la variable en python, y la dirección del dato no ayuda porque obviamente cambia si cambias el valor de la variable.

A: No es exactamente igual. La diferencia entre from a import b e import a (o incluso import a.b) radica en qué es lo que hace a nivel referencias.
import a lo que hace es importar el módulo a y crear una referencia en el namespace actual
from a import b importa el módulo a y crea una referencia a b
Qué es lo que ocurre cuando hacemos from a import b, c?
El intérprete importa a y crea dos referencias diferentes a b y a c, generando situaciones como las que describes.
Aunque sean objetos del mismo módulo están referenciados por separado.

A: Simbólicamente, lo que estás haciendo en la alternativa 1 corresponde a heredar las características de un "nodo padre" llamémosle PadreA (un objeto de clase)... Cuando posteriormente usas:
print(id(servicio.var), servicio.var)
servicio.cambia()
print(id(servicio.var), servicio.var)

Desde los "nodos" estarías haciendo algo como:
método(PadreA.child1)
método(PadreA.child2)
método(PadreA.child1)

Nótese que si PadreA almacenase algún tipo de memoria tal que cambie con cada ejecución, como un contador (al final menciono que es más probable en este caso), sería distinto que la segunda alternativa:
método(PadreA.child1)
método(PadreB.child2)
método(PadreA.child1)

Porque estarías llamando solo dos veces el nodo padreA y no tres veces.

Otra diferencia como menciona @abulafia es que con la primera alternativa estás heredando todos los métodos de la clase... entonces PadreA tendría N hijos, siendo N la cantidad de métodos del modulo.
En cambio, la alternativa dos; PadreB solo tendría el hijo directo del método que invocaste. Solo tendría 1 método (no N como en la primera alternativa).
*Aclaración: Estas son conclusiones que he sacado del uso personal de clases y módulos, no tengo pruebas pero creo que tiene mucho sentido.

Entre otras cosas, siendo redundante, probando con servicio.py como:
import random

random.seed(0)
var=random.randint(1,100)

def cambia():
    global var

    var=random.randint(1,100)
    print(f"cambia var = {var}")

Se replica la salida, utilizando un debugger se comprueban los objetos en memoria (alternativa 1):

La cual contiene una sola instancia de un objeto, de la misma instancia se llaman dos métodos distintos.
y alternativa 2:

En resumen:

*

*La alternativa 1 utiliza dos características (una variable y un método) de una misma instancia.

*La alternativa 2 usas dos instancias distintas de una misma clase para lo mismo.

*Lo que en realidad sucede es que la alternativa 2 al ejecutar en instancias distintas, no tienen relación, y es incapaz de modificar la variable var, resulta teniendo el mismo id ya que no ha cambiado


text:
Q: LINQ concatenate 2 fields to search on I'm trying to concatenate two fields in LINQ so that I can then filter with a keyword. I found a question posted here that I thought was my answer, but I'm getting 0 records back for some reason. This is supposed to return a JSON result for an autocomplete textbox (it works when I don't concatenate fields).
Here's my code:
Function CostCodeList(ByVal term As String) As ActionResult

        Dim results = From c In db.ORG_CHART_V
                      Let Fullname = CStr(c.COSTCTR_CD & " - " & c.BREADCRUMB)
                      Where Fullname.ToUpper.Contains(CStr(term).ToUpper)
                      Order By Fullname
                      Select New With {.label = Fullname, .id = c.ORG_NODE_ID}

        Return Json(results.ToArray, JsonRequestBehavior.AllowGet)
  End Function

I'm also getting this error on the Return:

Public member 'ToArray' on type 'DbQuery(Of VB$AnonymousType_3(Of
  String,Integer))' not found.

Before trying to concatenate the two fields I was searching on them separately, successfully. But when I concatenate them, it seems like everything I try either gets me an error and/or zero records.
Here is a different function that does work:
Function RoleList(ByVal term As String) As ActionResult
        Dim list As New ArrayList
        Dim results As IQueryable(Of JOB_ROLE)

        If IsNumeric(term) Then
            results = From c In db.JOB_ROLE
                      Where CStr(c.JBROLE_NO).StartsWith(term)
        Else
            results = From c In db.JOB_ROLE
                      Where c.JOB_ROLE_NAME.ToUpper.Contains(CStr(term).ToUpper)
        End If

        results = results.OrderBy(Function(e) e.JOB_ROLE_NAME)

        For Each item In results
            list.Add(New With {.label = item.JOB_ROLE_NAME, .id = item.JOB_ROLE_ID})
        Next

        Return Json(list.ToArray, JsonRequestBehavior.AllowGet)
    End Function

A: Here is the new function that works as intended:
    Function CostCodeList(ByVal term As String) As ActionResult
        Dim list As New ArrayList

        Dim results = db.ORG_CHART_V.Where(Function(e) (CStr(e.COSTCTR_CD) + " - " + e.BREADCRUMB).Contains(CStr(term).ToUpper)).OrderBy(Function(o) o.COSTCTR_CD)

        For Each item In results
            list.Add(New With {.label = item.COSTCTR_CD & " - " & item.BREADCRUMB, .id = item.ORG_NODE_ID})
        Next

        Return Json(list.ToArray, JsonRequestBehavior.AllowGet)
    End Function


text:
Q: QUERY+VLOOKUP+IMPORTRANGE w/ Google Sheets I need to perform a VLOOKUP of a variable on Workbook A to find info in Workbook B, hence the IMPORTRANGE. I also need that VLOOKUP to filter based on certain criteria within Workbook B. I've been trying to make QUERY work for me, but it doesn't seem to work with VLOOKUP. I know that FILTER also exists, but I have yet to make FILTER work with VLOOKUP either.
Example:
VLOOKUP(A2,IMPORTRANGE("URL","Sheet2!C:AH"),27,0)

There are duplicate variants to be found in Workbook B/Sheet2 for the variable A2, so i need to set a condition based on Column 24 of Workbook B/Sheet2 to only return data if Column 24 contains the string "FinishProduct".
I hope this isn't super easy and I'm just being an idiot. Look forward to the help!!!
New Attempt:
QUERY(
  IMPORTRANGE(
    "1yLZ3H-tW1QaW0fDsK3kb_B96kT9-fV2We15-9KZyTGg",
    "TS Inventory!C:AC"
  ),
  "Select Col27 Where Col1='"&A2:A&"' AND Col22='FinishProduct'"
)

Still didn't work. Produced something but not what I wanted.

A: try:
=VLOOKUP(A2, QUERY({IMPORTRANGE("URL", "Sheet2!C:AH")},
 "where Col22='FinishProduct'", 0), 27, 0)


text:
Q: How do I force configuration of partially installed packages? Whenever I run aptitude safe-upgrade, I get this output:
The following partially installed packages will be configured:
  cups gconf2 ufw update-manager
No packages will be installed, upgraded, or removed.
0 packages upgraded, 0 newly installed, 0 to remove and 2 not upgraded.
Need to get 0 B of archives. After unpacking 0 B will be used.

How can I configure the four mentioned packages?
I tried dpkg-reconfigure gconf2 but that fails with
/usr/sbin/dpkg-reconfigure: gconf2 is broken or not fully installed

A: This command fixed my problem:
apt-get --purge remove program_name

But of course you need to try also @ringtail answer.

A: Run these codes
sudo apt-get update

sudo apt-get clean

sudo apt-get autoremove

sudo apt-get update && sudo apt-get upgrade

sudo dpkg --configure -a

sudo apt-get install -f

This will clean and configure your packages

A: The answer above did not work for me. I had to run dpkg with the force-depends option, to resolve a circular dependency between some kernels.
sudo dpkg --force-depends --configure -a

This turns all dependency problems into warnings. Use with caution, with minimal scope (install everything that does not have any problems first) and at own risk.


text:
Q: How to create xmlns:xsi and xsd information in an XML document I have a Delphi XE application that reads a validated XML file, modifies it and then saves it.  The saved version can be validated.  I use SML Spy to create the file and to validate it.
Now I need to create a document in memory and save it. The problem is that I cannot figure out how to generate the xmlns and xsd information attributes to the document so that it can be validated.

A: Actually, despite my comment above I found that the easiest way to do it was not with DeclareNamespace.
Here's an example that doesn't even use a TXMLDocument on the form. Just add xmldom, XMLIntf, and XMLDoc  to your implementation uses clause (Xml.xmldom , Xml.XMLIntf, and Xml.XMLDoc for XE2), and then this works:
procedure TForm1.Button1Click(Sender: TObject);
var
  TheDoc: IXmlDocument;
  iNode: IXmlNode;
  xmlText: DOMString;
begin
  TheDoc := NewXMLDocument;
  TheDoc.Version := '1.0';
  TheDoc.Encoding := 'UTF-16';
  iNode := TheDoc.AddChild('test:test_file');
  iNode.SetAttributeNS('xmlns:test', '', 'http://www.foo.com' );
  iNode.SetAttributeNS('xmlns:xsi', '', 'http://www.w3.org/2001/XMLSchema');
  TheDoc.SaveToXML(xmlText);
  Memo1.Lines.Text := xmlText;
end;

The above results in this output in the TMemo:
<?xml version="1.0" encoding="UTF-16"?>
<test:test_file xmlns:test="http://www.foo.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema"/>


text:
Q: How to get x and y offset position of legendItemClick in highcharts react js? Exactly I want is when click on each single legend items it will show dropdown on with there position.

A: Since you're using react, why not just find the offset x and y from the onClick of anywhere within the desired component.
Your question is incomplete because there's no attached code but what you need is an event listener.
To get one to show you the x and y offset of any component you click on, do this;
  componentWillUnmount() {
    window.removeEventListener('click', this.handleClick);
  }

  componentDidMount() {
    window.addEventListener('click', this.handleClick);

Now, create a function called handleClick and pass in the event as an argument like:
handleClick = (e) => {
 console.log(e.offsetX,e.offsetY)
    }
  }

Finally, give the component an onClick attribute and pass in this.handleClick as the function to be run like:
<div className="charts" onClick={this.handleClick}>
</div>

N.B: You'd ideally do all of this within a stateful component.

A: Try this solution where you can find the chartX and chartY coordinates of the clicked place.
Demo: https://codesandbox.io/s/highcharts-react-demo-xb769
Is it enough solution for your requirements?


text:
Q: How display the first element of a list ? Smarty, Prestashop module I'm trying to change a view in a Prestashop Module. I would like to display just the first one case of a list.
Here, is the original list:
 {if count($tax_details)>0 && $use_taxes}

                    {l s='TAX DETAILS' mod='opartdevis'}
                    {l s='Tax rate' mod='opartdevis'}
                    {l s='Total without tax' mod='opartdevis'}
                    {l s='Total tax' mod='opartdevis'}

            {foreach $tax_details as $tax}

                    {$tax.prefix|escape:'htmlall':'UTF-8'}
                    {$tax.name|escape:'htmlall':'UTF-8'}
                    {Tools::displayPrice($tax.total_ht)}
                    {Tools::displayPrice($tax.total_tax)}

            {/foreach}

    {/if}

It display this :

And I would like to display just this number in yellow on another place.

This is my code (it situated on the same page than the original list):
 {if count($tax_details)>0}

                            Total éco taxes :

                                {Tools::displayPrice($tax_details[0].total_tax)}

                {/if}

I have this error:

I tried many ways to write it, but I don't find how to do.
Could you help me pls ? I'm new with Smarty.
Thanks in advance
Malaury

A: You need to set up a loop again
{assign 't' '0'}
{foreach $tax_details as $tax}
    {if $t === '0'}
      {Tools::displayPrice($tax.total_tax)}
      {assign 't' '1'}
    {/if}
{/foreach}

A: Alternatively, you can use the 'first' properly like below. (docs)
In your foreach, use,
{if $smarty.foreach.tax_details.first}

            {Tools::displayPrice($tax.total_tax)}

{/if}


text:
Q: Fragment instantiation using generic type, OnCreate method Doesn't call I have an adapter which create fragments this way :
public class FooAdapter<T extends Fragment> extends FragmentPagerAdapter {
   private Class<T> c;
   public FooAdapter(FragmentManager fm,Class<T> c) {
      super(fm);
      this.c = c;
   }

   @Override
   public Fragment getItem(int position) {
      try {
         T fragment = c.newInstance();
         return fragment;
      } catch (InstantiationException e) {
         e.printStackTrace();
      } catch (IllegalAccessException e) {
         e.printStackTrace();
      }
      return null;
   }
}

instantiation of the adapter:
new FooAdapter<BarFragment>(getSupportFragmentManager(),BarFragment.class)

I put logs in onCreate(and onAttach,onCreateView) of BarFragment but nothing logged !
public class BarFragment extends Fragment{

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "on create view");
    }
}

A: For starters, your onCreate method is wrong, you should use the onCreateView method and forget onCreate.
Something like this:
public class BarFragment extends Fragment{

    public BarFragment(){

    }

    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(LAYOUT YOU WANT TO INFLATE, container, false);

        return rootView;
    }
}

I'l look more deeply into your adapter code now.


text:
Q: Show/hide another input fields using h:selectBooleanCheckbox I am using JSF2 and Java to build a web application. I want to build a form like the one at the picture below:

When somebody unchecks the checkbox the form should disappear:

Here is an example with gwt.

So far,
I tried some stuff with the <f:ajax> tag and an PropertyActionListener in the managedBean but it didn't work. Can somebody give me an example or at least some hints to accomplish my goal. I would be really thankfull

A: Use <f:ajax render="idOfPanelContainingInputFields"> in the checkbox and give the component containing the input fields a rendered attribute which depends on the checkbox's state. No need for another JS code clutter.
<h:form>
    <fieldset>
        <legend>
            <h:selectBooleanCheckbox binding="#{showUserInfo}">
                <f:ajax render="idOfPanelContainingTextBox" />
            </h:selectBooleanCheckbox>
            <h:outputText value="User information" />
        </legend>
        <h:panelGroup id="idOfPanelContainingTextBox" layout="block">
            <ui:fragment rendered="#{not empty showUserInfo.value and showUserInfo.value}">
                <p>
                    <h:outputLabel for="firstName" value="First name:" />
                    <h:inputText id="firstName" value="#{bean.user.firstName}" />
                </p>
            </ui:fragment>
        </h:panelGroup>
    </fieldset>
</h:form>

The above example binds the checkbox to the view, you can of course also bind it to a boolean bean property, you can then remove the not empty check from the rendered attribute.
            <h:selectBooleanCheckbox value="#{bean.showUserInfo}">

...

            <ui:fragment rendered="#{bean.showUserInfo}">

See also:

*

*How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar"

*Why do I need to nest a component with rendered="#{some}" in another component when I want to ajax-update it?

A: As suggested by amorfis, the idea of using Ajax here is not the best solution, as you will do a call to your server for a client-side manipulation.
The best solution is to use Javascript to hide your component(s). For example, if all your labels and input texts are nested in a <h:panelGrid> component, you can do that:
<script type="text/javascript">
    function hideOrShow(show) {
        // Get the panel using its ID
        var obj = document.getElementById("myForm:myPanel");
        if (show) {
            obj.style.display = "block";
        } else {
            obj.style.display = "none";
        }
    }
</script>

<h:form id="myForm">
    <h:selectBooleanCheckbox id="myCheckbox" onclick="hideOrShow(this.checked);"/>

    <h:panelGrid id="myPanel" columns="2">
        ...
    </h:panelGrid>
</h:form>

A: You could do it by jQuery, or another JavaScript. It is also possible by <f:ajax>, but it connects to the server, which you don't need here.
By jQuery you can just hide the form, not changing the DOM. As far as I understand, it should be enough.
Post some .xhtml if you want more :)


text:
Q: Filter a fixed amount of data using AutoFilter I would like to filter only a fixed amount of data. I am implementing a code posted on this WebPage and it works perfectly, but it filters all the data that contain "Item1" and "Approved". For example, what I would like to do is to filter only 5 rows of data with the given conditions instead of filtering all.
Private Sub CommandButton1_Click()
    Dim OriginalData As Worksheet, FilteredData As Worksheet

    Set OriginalData = ThisWorkbook.Worksheets("Sheet1")
    Set FilteredData = ThisWorkbook.Worksheets("Sheet2")

    With OriginalData
        If .AutoFilterMode Then .AutoFilterMode = False
        With .Cells(2, 1).CurrentRegion
             .AutoFilter field:=1, Criteria1:="Item1"

             .AutoFilter field:=2, Criteria1:="Approved"
             With .Resize(.Rows.Count - 1, Columns.Count).Offset(1, 0)
                If CBool(Application.Subtotal(103, .Cells)) Then
                    .Copy Destination:= _
                        FilteredData.Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
                End If
              End With
         End With
         If .AutoFilterMode Then .AutoFilterMode = False
     End With
End Sub

A: If you want to filter the first 5 rows then the Range.Resize property can be applied to the .CurrentRegion before the .AutoFilter method.
Private Sub CommandButton1_Click()
    Dim OriginalData As Worksheet, FilteredData As Worksheet

    Set OriginalData = ThisWorkbook.Worksheets("Sheet1")
    Set FilteredData = ThisWorkbook.Worksheets("Sheet2")

    With OriginalData
        If .AutoFilterMode Then .AutoFilterMode = False
        With .Cells(1, 1).CurrentRegion   'all cells radiating out from A1
            'resize to 6 rows total (5 data + 1 header)
            With .Resize(6, .Columns.Count)
                .AutoFilter field:=1, Criteria1:="Item1"
                .AutoFilter field:=2, Criteria1:="Approved"
                With .Resize(.Rows.Count - 1, .Columns.Count).Offset(1, 0)
                    If CBool(Application.Subtotal(103, .Cells)) Then
                        .Copy Destination:= _
                            FilteredData.Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
                    End If
                End With
            End With
        End With
        If .AutoFilterMode Then .AutoFilterMode = False
    End With
End Sub

Note that if you step through the code with F8 all of the data will actually be filtered but only filtered data from the first 5 (visible or not visible) rows will be copied.
If you want to copy the first 5 filtered rows then you need to deal with the non-contiguous visible Range.Areas property and some maths.
Private Sub CommandButton2_Click()
    Dim a As Long, aa As Long
    Dim OriginalData As Worksheet, FilteredData As Worksheet

    Set OriginalData = ThisWorkbook.Worksheets("Sheet1")
    Set FilteredData = ThisWorkbook.Worksheets("Sheet2")
    aa = 5

    With OriginalData
        If .AutoFilterMode Then .AutoFilterMode = False
        With .Cells(1, 1).CurrentRegion   'all cells radiating out from A1
            .AutoFilter Field:=1, Criteria1:="Item1"
            .AutoFilter Field:=2, Criteria1:="Approved"
            With .Resize(.Rows.Count - 1, .Columns.Count).Offset(1, 0)
                If CBool(Application.Subtotal(103, .Cells)) Then
                    With .SpecialCells(xlCellTypeVisible)
                        For a = 1 To .Areas.Count
                            .Areas(a).Resize(Application.Min(aa, .Areas(a).Rows.Count), .Columns.Count).Copy Destination:= _
                                FilteredData.Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
                            aa = aa - Application.Min(aa, .Areas(a).Rows.Count)
                            If aa < 1 Then Exit For
                        Next a
                    End With
                End If
            End With
        End With
        If .AutoFilterMode Then .AutoFilterMode = False
    End With
End Sub

Both of those survive my limited testing. Post back if you run into problems I have not accounted for.


text:
Q: Why Am I Getting a Status 200 But Response is Empty Hello I'm creating a user search, my request is sent from client via a service and received on the back end (Status 200). The problem I am having is that my response is empty. I spent days thinking it was something on the back end so once I added res.status(201).json(payload) I realized
results are coming back undefined and empty. I'm thinking it is my req.body, because when I console.log I get {}.
I have app.use(express.json()) before I use the route. The Content-Type is application/json,  so when the service is sent and I console.log the results(I get undefined) because there is nothing in the payload.
I have included a snippet of my code.
header.ts
export class HeaderComponent  {

  //products is my database collection
  //Products is my model

 products:Array<Products> = [];
 results = [];
 hasQuery:Boolean = false;

//function called when user types in input box
sendData(event:any){

  //console.log(event.target.value);
  let query:string = event.target.value;
  //Will match if query is nothing or only spaces
  let matchSpaces:any=query.match(/\s*/);
        console.log("What about match");
     if(matchSpaces[0] === query){
         console.log("What about query");
      this.products=[];
      this.hasQuery = false;

    return;

  }
  console.log("about to call service")
  this.searchService.searchProducts(query.trim()).subscribe((results) =>{
    this.products = results;
     this.hasQuery = true;
    console.log(results)

  })
 }
}

search.service.ts
import { Injectable } from '@angular/core';
import{HttpClient, HttpHeaders} from '@angular/common/http';
import{map, catchError, tap} from 'rxjs/operators'
import { Observable } from 'rxjs';
import {MessengerService} from 'src/app/services/messenger.service';
import {productsUrl} from '@app/ui/header/api'
import { productUrl } from '@app/config/api';

export interface Products{
  _id: string,
  name: string
}

@Injectable({
  providedIn: 'root'
})
export class SearchService {

  constructor(private http:HttpClient) { }

  searchProducts(query:string){
    console.log("Does it get  my  searchProducts");
      return this.http.post<{payload: Array<Products>}>
      (productsUrl, {payload: query}, {

         headers: new HttpHeaders({'Content-Type':
        'application.json'})
         }).pipe(
       map(data => data.payload)

    );

  }

}

getProducts.js
var express = require('express');
const cors    = require('cors');
var bodyParser = require('body-parser')
const Products      = require('../../../liveSearch');
var router = express.Router();
const app = express();

 router.get('/', function(req, res){
   res.send('GET route on api here.');
});

router.post('/getProducts', async(req, res) =>{

     let payload = req.body;
     let search = await Products.find({name: {$regex: new RegExp('^'+payload+'.*',
   'i')}}).exec();
     //Limit search to 10
       search = search.slice(0, 10);
       console.log("Inside search",search);
       //added this to see why not getting a response
       res.status(201).json(payload)
     // res.send({payload:search});

})

//export this router to use in our server.js
module.exports = router;

server.js
const express = require('express');
const cors    = require('cors');
const router = express.Router();
const Products = require('./liveSearch');
const getProducts = require('.../../controllers/api/getProducts/getProducts')

const mongoose = require('mongoose');
mongoose.Promise = Promise;

mongoose.connect('mongodb://localhost/productLiveSearch', {useNewUrlParser:
true, useUnifiedTopology: true, });
const db = mongoose.connection;
db.on('error', error => console.log(error));
db.once('open', () =>{  console.log('Connected to Mongoose')});

const app = express();

app.use(function(req,res,next){
  res.header('Access-Control-Allow-Origin', '*');
  res.header('content-type','application/json');
  res.header('Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization');
  res.header('Access-Control-Allow-Methods','POST, GET, DELETE, PUT, OPTIONS');
  res.header('Allow', 'GET, POST, OPTIONS, PUT, DELETE');
  // res.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Token, Timestamp, X-Requested-With, Language-Code");
  next();
  });

app.use(cors());
var corsOptions = {
  origin: 'http://localhost:4200',
  optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}

/*app.options('/getProducts', cors()) // enable pre-flight
app.use(cors({
  origin: [
    'http://localhost:4200'         //this is my front-end url for development
    //'http://192.168.1.67:4200'
    //'http://www.myproductionurl.com'
  ]
}))*/

  app.use(express.json());
  app.use(express.urlencoded({extended:true}));

  app.use('/', getProducts)
  app.use('/getProducts', getProducts);

  app.get('/', function(req, res){
  res.send('hello world');
});

app.listen(process.env.Port|| 3000, () => {
    console.log("Server has started on Port 3000");

});

db schema
liveSearch.js
const mongoose = require('mongoose');

const productSchema = mongoose.Schema({
    name:{
        type: String,
        required: true
    }
});

module.exports = mongoose.model('Products', productSchema);
//module.exports = someProducts

html snippet
<input class="form-control py-2 border-right-0 border" name="payload"
  id="payload" type="search" (keyup)="sendData($event)">

<p *ngIf="products.length < 1 && hasQuery">Sorry nothing found</p>

<ng-template *ngFor let-product [ngForOf]="products" let-i="index">
</ng-template>

I really appreciate any help I have been working on this diligently trying to figure this out.
Thanks In Advance


text:
Q: python imaplib mail.search; without reply emails I'm making a script for searching emails and downloading attachments.
It works well, but I encountered a problem when an email fits the criteria but is a reply to another email.
I want to select only the emails that are no replies.
Below is my code.
#connect to imap server
mail = imaplib.IMAP4_SSL(imap_url)
mail.login(username, password)

result, data = mail.search(None, '(FROM "email-address" SUBJECT "subject")')

Could I maybe add something to the mail.search line so that it ignores replies?
I'm actually pretty new to this python module so help would be much appreciated!
Thanks

A: Good news. Visiting this page IMAP Commands you will find the command you are looking for under SEARCH.
IMAP flag to search for:
ANSWERED
    Messages with the \Answered flag set.

So an example of the RAW search string you need to send is:
SC01 SEARCH ANSWERED

And with your Python example, probably:
result, data = mail.search(None, '(ANSWERED)')

Here is another great resource for Python imaplib:
imaplib - IMAP4 client library


text:
Q: What is the upper bound of Integer in Haskell? I was solving a math problem: want to get the sum of the digits of the number 2^1000.
In Java, the solution is like:
String temp = BigInteger.ONE.shiftLeft(1000).toString();

int sum = 0;
for (int i = 0; i < temp.length(); i++)
    sum += temp.charAt(i) - '0';

Then came up a solution in Haskell, like this:
digitSum ::(Integral a) => a -> a
digitSum 0 = 0
digitSum n = (mod n 10) + (digitSum (div n 10))

The whole process is pretty smooth, one point seems interesting, we know integer type can not handle 2 ^ 1000, too big, in Java, it's obvious to use BigInteger and treat the big number to string, but in Haskell, no compiling errors means the 2 ^ 1000 could be passed in directly. Here is the thing, does Haskell transform the number into string internally? I want to  make sure what the type is and let the compiler to determine, then I type the following lines in GHCi:
Prelude> let i = 2 ^ 1000

Prelude> i
107150860718626732094842504906000181056140481170553360744375038837035105112493612249319
837881569585812759467291755314682518714528569231404359845775746985748039345677748242309
854210746050623711418779541821530464749835819412673987675591655439460770629145711964776
86542167660429831652624386837205668069376

Prelude> :t i
i :: Integer

Here, I was totally confused, apparently, the number of i is oversized, but the return type of  i  is still Integer. How could we explain this and what's the upper bound  or limit of Integer of Haskell?

A: In Haskell, Integer is a - theoretically - unbounded integer type. Fixed-width types are Int, Int8, Int16, Int32, Int64 and the corresponding unsigned Word, Word8 etc.
In practice, even Integer is of course bounded, by the available memory for instance, or by the internal representation.
By default, GHC uses the GMP package to represent Integer, and that means the bound is 2^(2^37) or so, since GMP uses a 32-bit integer to store the number of limbs.


text:
Q: Reason for an #include #include <stdio.h>
#include <conio.h>

int main(void)
{
    int num1;
    int num2;
    printf("Enter 2 numbers:\n");

    scanf("%d", &num1);
    scanf("%d", &num2);

    if (num1 == num2){
      printf("Equal");
    }
    getchar();
    getchar();
}

The tutorial has this: #include <conio.h>
i tried it without #include <conio.h> and works ok...
But why did he put it? here is this tutorial.

A: Because in the tutorial it is getch() not getchar().
getch() is declared in conio.h, whereas getchar() is declared in stdio.h.

A: conio.h is a non-standard header that was shipped with many old C compilers for MS-DOS.  It is not necessary in the code you posted, as none of that code requires its definitions.  If including it produces an error, that is because conio.h is not available on your system.  You may want to consult a more up-to-date tutorial if the one you're using is referencing DOS-specific headers.
Edit: Ouch, just looked at the linked tutorial.  2009?  Someone is including conio.h as boilerplate C code in a tutorial from 2009?  What a cruel world this is.

A: All the functions you are using are defined in stdio.h, it doesn't seem to use anything that is inside conio.h, thus rendering it useless in this case.

A: It works because all the functions used in the code - scanf, printf, getchar - are declared in stdio.h.


text:
Q: How to unseal the gate in the Archylte Steppe? In the Archylte Steppe in ??? AF it says that it's sealed, but there's a way to unseal it in this time. It seems to hint beating the Gigantuars is doing something when I beat one, but I've only found two so far, and it's still sealed. If this is how you unseal it, where are all of them? Else, how do you break the seal?

A: This is indeed how you unseal the gate in the archlyte steppe.
In total there are 3 gigantuars statues.
You can encounter 2 of them only with specific weather conditions.
Here are the locations and the weather conditions:

*

*Stoneslump Wastelands - Any weather condition.

*Clearwater Marshes (northeast) - Sunny weather condition. (also
requires a moogle hunt)

*Clearwater Marshes (central) - Rainy weather condition. (also
requires a moogle hunt)

A: You can get all three in sunny conditions, I just did. Two are close by each other in the clear water marshes, and the third is in the bunched up cacti.

A: I got all three to show up in sunny weather. I believe you need the fragment skill paradox scope to beat the monsters that show up afterwards - well at least if you dont want it to take forever.


text:
Q: Find the number that the studio should purchase to maximize profits
A studio sells photographs and prints. It costs $€$ $20$  to purchase each photograph and it takes  $ 2 $ hours to frame it. It costs $€$ $25$  to purchase each print and it takes $ 5 $ hours to frame it. The store has at most $€$  $400$ to spend and at most $ 60 $ hours to frame. The studio makes $€$ $30$ on each photograph and $€$ $50$ profit on each print.
Find the number that the studio should purchase to maximize profits.

I need to know the system of inequalities to model the problem on my graphing calculator so I can find the point of intersects.
How would I go about doing that?
I thought my way of calculating it was corrected, but my teacher told me to recheck it so now I don't trust my answers anymore. If someone could verify that would be great!
Edit: This was the system of inequalities I came up with:

$20x+25y<=400, 2x+5y<=60, X>=0, Y>=0$
The points of intersects I got were:

*

*0,5

*0,16

*20,0

  And finally the profit equation is:
$P=30x+50y$

A: Sometimes making a graph helps clarify things.  Can you make out the feasible region and its corners from the picture here?


text:
Q: C++: std::vector::reserve not reserving when containing pointers When I call std::vector::reserve when the identifier is of type std::vector<Foo*> reserve(...) does nothing:
std::vector<int*> bar;
bar.reserve(20);

//I expect bar.size to return 20...
std::size_t sz = bar.size();
for(std::size_t i = 0; i < sz; ++i) {
    //Do Stuff to all items!
}

The aforementioned for loop runs exactly zero times and bar.size() returns zero. I do not remember if this is also true for all other STL containers, but if so, including the behavior for std::vector: WHY?

A: vector::reserve() changes the capacity of a vector, not its size.
capacity is how much memory has been allocated internally to hold elements of the vector. size is how many elements have actually held by the vector. vector::resize() affects the latter.

A: reserve changes the capacity of the vector, not the size. You probably want resize

A: .reserve() doesn't change the size of a vector.  The member function you are looking for is .resize().  reserve() is simply an optimization.  If you are going to add a bunch of things to a vector one-by-one using push_back() then telling it how many you will add using reserve() can make the code run a little bit faster.  But just calling reserve() doesn't change the size.


text:
Q: Javascript: Element wont appear even its visibility is changed to visible in javascript I am kind of struggling with the following problem:
(1) Description:
I have been trying to make my own GDPR pop-up window (for those of you who do not deal with EU and do not need to know this stuff, its that annoying popup blocking half of your screen and saying: "This site is using cookies....").
The pop-up is a simple div.
The ID of this div is set to "GDPRcontainer" in the following way:
<div class="card text-center static-bottom" id="GDPRcontainer">

The visibility of this  is by default set to "hidden" in my css in the following way:
#GDPRcontainer
{
  ...
  visibility: hidden!important;
}

What I am trying to achieve is that the div appears if a specific cookie is not set (the cookie is set when the user confirms or dismisses the popup).
(2) What I tried
I am trying to achieve this by calling a function with the onLoad event from the body tag as follows:
onLoad="checkGDPR('GDPR=noted')"

This calls the checkGDPR function, that checks whether the cookie is set, and if it determines that the cookie is not set, it calls the function ukazovak('GDPRcontainer') that is supposed to change the visibility of the div to "visible":
function ukazovak(elid)
{
document.getElementById(elid).style.visibility = 'visible';

}

No matter how I try the div does not appear. In order to debug, I added
window.alert(document.getElementById('GDPRcontainer').style.visibility);

into the ukazovak() function to check, whether the visibility has been changed. The alert says "visible", but the div does not appear (does not become visible).
I am using Bootstrap, so it it possible that this is come kind of css preference clash, but I do not want to be suggestive :).
Many thanks in advance for reading all this.
I really appreciate your help!


text:
Q: Trying to test onChange function of react component form So I have a Signup component that renders a form with a simple text field and submit function. On entering text in the field the 'address' attribute should be updated. In my test I'm trying to assert that the onChange function is called but stubbing the function using jest. However when I try and simulate the change I get the error:
TypeError: result.simulate(...) is not a function
If I remove the .bind(this) is gets to the point where it's setting the state in the function but this is undefined.
Here is my code:
import React, { Component } from 'react';

class Signup extends Component {

  constructor(props){
    super(props);
    this.state = {};
  }

  onSubmit(e){
    let {address} = this.state;
    this.setState({
      address: ""
    });
    this.props.addFeed(address);
    e.preventDefault();
  }
  onChange(e) {
      this.setState({
        address: e.target.value
      });
  }

  render() {
    return (

      <form onSubmit={this.onSubmit.bind(this)}>
        Please enter your address:
        <input id='address' type="text" onChange={this.onChange.bind(this)} value={this.state.address}>
        </input>
        <input type="submit" value="Submit">
        </input>
      </form>

    );
  }
}

export default Signup;

And my test:
test("onChange() is called upon changing the text field", () => {
    const value = "Makers Academy"
    const onChange = jest.fn()
    const wrapper = shallow(<Signup onChange={onChange} />)
    const result = wrapper.find('#address')
    result.simulate('change', { target: { value: {value} } })('change');
    expect(onChange.called).toBe.true
  })

A: You try spy for onChange from props, but in your component no has any props.
Component's methods and component props are different things.
You need call this.props.onChange inside this.onChange.
import React, { Component } from 'react';

class Signup extends Component {

  constructor(props){
    super(props);
    this.state = {};
  }

  onSubmit(e){
    let {address} = this.state;
    this.setState({
      address: ""
    });
    this.props.addFeed(address);
    e.preventDefault();
  }
  onChange(e) {
      this.setState({
        address: e.target.value
      });
      // Call onChange callback
      this.props.onChange();
  }

  render() {
    return (

      <form onSubmit={this.onSubmit.bind(this)}>
        Please enter your address:
        <input id='address' type="text" onChange={this.onChange.bind(this)} value={this.state.address}>
        </input>
        <input type="submit" value="Submit">
        </input>
      </form>

    );
  }
}

And some fix in your test
test("onChange() is called upon changing the text field", () => {
    const value = "Makers Academy";
    const onChange = jest.fn();
    const wrapper = shallow(<Signup onChange={onChange} />);
    const result = wrapper.find('#address');
    result.simulate('change', {target: {value}});
    expect(onChange.called).toBe(true);
});


text:
Q: Centering images in iframes I have an iframe  <iframe src="preloader.gif" id="graphFrame"...></iframe> . I would like to centre the image inside the iframe. I have tried looking up solutions online but none of them work. Can this be done with simple css? If not, is there another solution?

A: No, you're serving an image not an html page so CSS doesn't apply.

Its going to act like a preloader
  image so when the actual content loads
  it will superimpose over the preloader
  image

That being the case I'd suggest that you:

*

*Make the iframe's background transparent by setting
allowTransparency="true" That property-name is case-sensitive in Internet Explorer iirc.

*Apply the following styles to the iframe: background-image: url('preloader.gif');
background-position: center center; background-repeat: no-repeat;

*Park the src on an html page with a transparent background html, body {
  background-color: transparent;
}
Once the content loads in the iframe it'll cover the loading image. Working Example

A: I needed to center an image in an iframe, and I couldn't get CSS to do anything, so instead of loading the image itself, I put the image in a small html page with an inline style on the body tag of padding:0; margin:0; and loaded that into the iframe instead.  Centered it perfectly with no borders around the edges!
Of course, I made the iframe height and width the same as the image's height and width.


text:
Q: Error calculating and validating 100.000 with specific combination I have an interesting problem that I would like to share with you all. On a form we have repeating rows with percent allocation. In the end all the rows combined need to equal 100.000 (or 100%). If it does then it passes validation and the form can be submitted. It is a requirement that we go out 3 decimal points.
But with the following combination the form fails to meet validation. It is really odd.

*

*Row 1: 63.877

*Row 2: 34.286

*Row 3: 1.837

*Total = 100.000

HTML
<!-- Repeating Field in Rows -->
<input type="text" name="txtDistributionPerc" id="txtDistributionPerc"
onkeypress='return chkKeys(event, "C");' maxlength="7"
onblur="txt_blur_calculateFundingTotal(this);"></input>

JavaScript JQuery
// Filters out invalid keystrokes
function chkKeys(e,type){
    var keynum = e.keyCode;
    var keychar = String.fromCharCode(keynum);

    switch (type){
        case 'C':   /* currency ($, numbers, .) */
            valChk = /[0-9\$\.]/;
            return valChk.test(keychar);
            break;
        default:
            break;
    }
}

//Calculates a specific one based on the element passed
function txt_blur_calculateFundingTotal(ele)
{
    if(ele)
    {
        var total = 0.000;
        $(ele).closest('table').find('input[name=txtDistributionPerc]').each(function (i) {
            this.value = formatCurrency(this.value, 3, '.', '');
            var tmp = parseNumber(this.value);
            if(tmp < 0.000 || tmp > 100.000) {
                this.value = '0.000';
                tmp = 0.000;
            }
            total+=tmp;
        });
        $(ele).closest('table').find('input[name=txtTotalPerc]').val(formatCurrency(total, 3, '.', ''));
        if(total != 100.000 && total != 0.000)
        {
            $(ele).closest('table').find('input[name=txtTotalPerc]').addClass('error');
            $(ele).closest('table').find('input[name=txtTotalPercValidated]').val('');
        }
        else
        {
            $(ele).closest('table').find('input[name=txtTotalPerc]').removeClass('error');
            $(ele).closest('table').find('input[name=txtTotalPercValidated]').val('true');
        }
    }
}

Is there a better way to do this? Thanks for looking.

A: Multiply the values by 1000 and work with integers.
It seems it has to be with float values.


text:
Q: When my user authenticated my objects turn it right but if its unauthenticated my objects turn false. How can I fix it? I have productDetails function and it gives me a products details and also if user authenticated, it can bookmark the products. But when I open the projectDetail page if I unauthenticated, my product object turn false how can I fix that ? Unauthenticated users can see products but cannot bookmarking
public function productDetails($slug, Product $product)
{
    $user = Auth::user();
    $product->load(['user.products' => function ($q) {
        $q->take(15);
    }, 'brand', 'color', 'size', 'images', 'category.products' => function ($q) {
        $q->inRandomOrder()->take(15);
    }]);
    $similarProducts = $product->category->products()->limit(10)->get();
    $similarArr = array();
    foreach ($similarProducts as $similarProduct) {
        $similarProduct = $this->userProductLikeAndBookmark($user, $similarProduct);
        $similarArr[] = $similarProduct;
    }
    $userProducts = $product->user->products;
    $productArr = array();
    foreach ($userProducts as $userProduct) {
        $userProduct = $this->userProductLikeAndBookmark($user, $userProduct);
        $productArr[] = $userProduct;
    }
    dd($productArr);
    $product = $this->userProductLikeAndBookmark($user, $product);
    return view('home.pages.detail', compact('product', 'similarArr', 'productArr'));
}

A: Here's the problem:
$user = Auth::user();
$product = $this->userProductLikeAndBookmark($user, $product);

When unauthenticated, $user is null and therefor whataver userProductLikeAndBookmark function in your controller is doing, it's not accepting null as a first argument as $user
Possible solution:
if (auth()->check()) {
  $product = $this->userProductLikeAndBookmark($user, $product);
}
return view('home.pages.detail', compact('product', 'similarArr', 'productArr'));

the product would be returned as is (not liked or bookmarked) from the RouteModelBinding method injection if user is unauthenticated


text:
Q: How to Factorize 170 digits long BigInteger I need to factorize 170 digits long integer, I know that this number have 2 factors. I have tried Pollard Rho algorithm but unfortunately this is not big enough hammer to crush it. The algorithm does not end. Did I make any mistake?
import java.math.BigInteger;
import java.security.SecureRandom;

public class PollardRho {
    private final static BigInteger ZERO = new BigInteger("0");
    private final static BigInteger ONE = new BigInteger("1");
    private final static BigInteger TWO = new BigInteger("2");
    private final static SecureRandom random = new SecureRandom();

    public static BigInteger rho(BigInteger N) {
        BigInteger divisor;
        BigInteger c = new BigInteger(N.bitLength(), random);
        BigInteger x = new BigInteger(N.bitLength(), random);
        BigInteger xx = x;

        // check divisibility by 2
        if (N.mod(TWO).compareTo(ZERO) == 0)
            return TWO;

        do {
            x = x.multiply(x).mod(N).add(c).mod(N);
            xx = xx.multiply(xx).mod(N).add(c).mod(N);
            xx = xx.multiply(xx).mod(N).add(c).mod(N);
            divisor = x.subtract(xx).gcd(N);
        } while ((divisor.compareTo(ONE)) == 0);

        return divisor;
    }

    public static void factor(BigInteger N) {
        if (N.compareTo(ONE) == 0)
            return;
        if (N.isProbablePrime(20)) {
            System.out.println(N);
            return;
        }
        BigInteger divisor = rho(N);
        factor(divisor);
        factor(N.divide(divisor));
    }

    public static void main(String[] args) {

        BigInteger N = new BigInteger(
                "46862651776313668832684618638310007043245135907468247470585960688008180534742005269578548831878148535158738789789506710579367525183636389872513135592162572724499935530721");
        factor(N);
    }
}


text:
Q: Python Tkinter entry-point So for a project on my school I am trying to make an GUI where I can add some info for some email so it will send it automatically through an python script.
Now I do have a small problem. I made some entry-points but for some reason I can not add text to the left of the entr-ypoints. Does anyone know how to do that?
I am trying to get 'sending to:', 'name:', and 'course:' to the left of the corresponding entry-points.
It might sounds silly, but please do not change to much of the actual code. It has to be like this for the project.
Kind regards,
Allard

import os
import smtplib
import tkinter as tk

root =tk.Tk()

root.title("Title")

def main():

    USER = os.environ.get('USERNAME_GMAIL')
    PASSWORD = os.environ.get('PASSWORD_GMAIL')
    print("-"*60)
    print("\nNew Email\n\n")

    with smtplib.SMTP('smtp.gmail.com',587) as smtp:

        smtp.ehlo()
        smtp.starttls()
        smtp.ehlo()
        smtp.login(USER, PASSWORD)

        PROFESSOR = entry2.get()
        COURSE = entry3.get()

        subject = 'Course literature: ' + COURSE
        body = 'Body of the email, doesnt really matter whats in here' + PROFESSOR

        msg= f'Subject:{subject}\n\n{body} '

        smtp.sendmail(USER, RECEIVER, msg)

canvas1 = tk.Canvas(root, height=400, width= 400)
canvas1.pack()

entry1=tk.Entry(root)
canvas1.create_window(200, 60, window=entry1)

entry2=tk.Entry(root)
canvas1.create_window(200, 80, window=entry2)

entry3=tk.Entry(root)
canvas1.create_window(200, 100, window=entry3)

def PRINT():
    x1 = entry1.get()
    x2 = entry2.get()
    x3 = entry3.get()
    label1= tk.Label(root, text = 'Sending to: ' + str(x1))
    canvas1.create_window(200,200, window=label1)

    label2= tk.Label(root, text = 'Name: '+ str(x2))
    canvas1.create_window(200,220, window=label2)

    label3= tk.Label(root, text = 'Course: '  +str(x3))
    canvas1.create_window(200,240, window=label3)

button1 = tk.Button(text = 'TEST', bg="black", fg="white", font=('helvetica', 9, 'bold'), command=PRINT)
canvas1.create_window(200,130, window=button1)

button2 = tk.Button(text = 'Verzenden via email', bg = "red", fg= "white", font=('helvetica', 9, 'bold'), command=main)
canvas1.create_window(200,160, window=button2)

A: You should not be trying to place widgets at exact coordinates. Tkinter has managers for handling layout in a logical manner: pack and grid. These take care of problems with different window sizes, different resolutions, and different fonts, and are superior to placing elements at specific x/y coordinates.
Since you want to create a grid of label/entry pairs, grid is the correct choice.
entry1=tk.Entry(root)
entry2=tk.Entry(root)
entry3=tk.Entry(root)
label1 = tk.Label(root, text="Sending to:")
label2 = tk.Label(root, text="Name:")
label3 = tk.Label(root, text="Course:")

label1.grid(row=0, column=0)
entry1.grid(row=0, column=1)
label2.grid(row=1, column=0)
entry2.grid(row=1, column=1)
label3.grid(row=2 column=0)
entry3.grid(row=2, column=1)

A: You need to save the item ID of each canvas1.create_window(...) and then use the item ID to find the position of the entry and put a text before the entry using canvas1.create_text(...):
...
# function to put a prompt before the 'entry' item
def create_prompt(prompt, entry):
    # get the bounding box of the Entry item
    bbox = canvas1.bbox(entry)
    # create a canvas text item and put it before the Entry item like below:
    #  (x-5,y)   (x,y)
    # -------+   +-----------------+
    #  prompt:   | Entry           |
    #            +-----------------+
    #
    # note that bbox[0] is the x-coordinate of the top-left of entry item
    #           bbox[1] is the y-coordinate of the top-left of entry item
    # using anchor='ne' means that the (x, y) of the text is the top-right corner of the text
    # and finally return the item ID of the canvas text item
    return canvas1.create_text(bbox[0]-5, bbox[1], text=prompt, anchor='ne')

entry1=tk.Entry(root)
entry1_item = canvas1.create_window(200, 60, window=entry1)
create_prompt('sending to:', entry1_item)

entry2=tk.Entry(root)
entry2_item = canvas1.create_window(200, 80, window=entry2)
create_prompt('name:', entry2_item)

entry3=tk.Entry(root)
entry3_item = canvas1.create_window(200, 100, window=entry3)
create_prompt('course:', entry3_item)
...


text:
Q: How can I deduce this interval on this inequality? Good morning to everyone. I have an inequality and I have to find the sign of it. At first I thought that it's positive on all intervals (excepting the number $2$), but after looking on my answer sheet I saw that on an interval it isn't, and I don't know how to deduce this interval. The inequality is the following:
$$ 2\sqrt{x^2-4}-x+1 \ge 0 \rightarrow x \ge 2$$
$$ 2\sqrt{4-x^2}-x+1\ge 0 \rightarrow 0 < x < 2 $$
For the first the function is positive for all $ x \ge \frac{-1+2\sqrt{13}}{3}$ and for $ (2,\frac{-1+2\sqrt{13}}{3}) $ (Here I just assume that it's positive); we obtain that it's negative in $x=2$.
The second function is positive for all $ x \in (0,\frac{1+2\sqrt{19}}{5})$ and I also assume that it's positive for all $ x \in (\frac{1+2\sqrt{19}}{5},2)$. (These are all my calculations)
Instead I don't know how they found that it is negative for $ \frac{1+2\sqrt{19}}{5} < x < \frac{-1+2\sqrt{19}}{5}$ It doesn't even make sense because the first number is bigger then the second.


text:
Q: Need help to download a file from a Web URL after certain delay I have to write a small Java program to download a file from a given server URL. However, the URL actually returns the file after 2-3 minutes. Before that, the program has already returned a response with an empty file.
What I need is that the program should wait(pause its execution) after making the hit to the URL. After waiting for a few minutes, it can check again.
I have tried doing this via Thread.sleep and other waiting modes but it does not seem to work. It keeps giving me an empty file.
Note that I have gone through a lot of existing threads before asking this question.
What am I doing wrong?

A: from my perspective, you can use "handler" and then you can create an object of "post delayed" method to delay the process. Like, we use "post delayed" method to delay the activity or a button in Android.
You can check this video, it will help you. Thank you.
[https://www.youtube.com/watch?v=3pgGVBmSVq0][1]

A: I am thinking this could be done using Thread.sleep(time) . The time should be equal or greater than the server delay time.


text:
Q: How to make php function according to the drop down menu list selection without a button Hello I am working with php and I have this drop down menu list code:
<form method="POST" >
    <select name="users" id="users">
        <option <?php if(isset($_POST['users']) && $_POST['users'] == '2') echo "selected='selected'";  ?> value="2">User one</option>
        <option <?php if(isset($_POST['users']) && $_POST['users'] == '3') echo "selected='selected'";  ?> value="3">User Two</option>
    </select>
    <input type="submit" class="fadeIn fourth"  name="refresh" value="Refresh">
</form>

and then there is this php code that starts as follows:
<?php

if(isset($_POST['refresh'])){
        ....
?>

Now I want to remove the button from the html and want to make the php code execute automatically when selected from the drop-down list menu. I tried something with javascript but wasnt what I needed it was just printing the value as an alert.
this is the code of javascript i tried
var x = document.getElementById('users').selectedIndex;
var text = document.getElementsByTagName("option")[x].text;//its a text
document.getElementById("pr").innerHTML = text;

How do i make it to submit the form?
Tried this other javascript but this makes my page stuck on refresh I put this onchange="fuksion()" on <form>
 <script>
      function funksion() {
      document.getElementById("user").submit();
       }
      funksion();
     </script>

A: Add an eventlistener (change) to submit the form:
<form action="" method="POST">
  <select name="users" id="users">
    <option <?php if (isset($_POST['users']) && $_POST['users'] == '2') echo "selected";  ?> value="2">User one</option>
    <option <?php if (isset($_POST['users']) && $_POST['users'] == '3') echo "selected";  ?> value="3">User Two</option>
  </select>
</form>

<script>
  let usersSelect = document.getElementById('users');
  users.addEventListener('change', function() {
    this.form.submit();
  })
</script>

<?php
if (isset($_POST['users'])) {
  echo "You selected " . $_POST['users'];
}
?>

On first load of the page the first option will be selected, so the change event will only trigger if you select the second option. To circumvent this, add an "empty" option:
<select name="users" id="users">
  <option value="">-- choose one --</option>
  <option <?php if (isset($_POST['users']) && $_POST['users'] == '2') echo "selected";  ?> value="2">User one</option>
  <option <?php if (isset($_POST['users']) && $_POST['users'] == '3') echo "selected";  ?> value="3">User Two</option>
</select>

A: use this code you will get value on select
form.php  page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Get Selected Option Value</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    $("select.value").change(function(){
        var selectedValue = $(this).children("option:selected").val();
        //alert("You have selected  " + selectedValue);

        $.ajax({
        type: "POST",
        url: "query-process.php",
        data: { type: selectedValue }, // serializes the form's elements.
        success: function(data)
        {
          alert(data); // show response from the php script.
        }
    });
    });
});
</script>
</head>
<body>
    <form>
        <label>Select value:</label>
        <select class="value">
             <option <?php if(isset($_POST['users']) && $_POST['users'] == '2') echo "selected='selected'";  ?> value="2">User one</option>
        <option <?php if(isset($_POST['users']) && $_POST['users'] == '3') echo "selected='selected'";  ?> value="3">User Two</option>
        </select>
    </form>
</body>
</html>

query-process.php -->> in this page you will get value by this
print_r($_POST['type']);

after getting the value, you have to run your SQL query to submit the form to your database and also you can run the query for searching value in the database


text:
Q: Toggle VideoView's audio with a Button I am using a videoView to play a video.
 bVideoView = (VideoView) findViewById(R.id.bVideoView);
 bVideoView.setVideoPath(videoPath);

Now I have a button,
audioToggle = (Button) findViewById(R.id.audioToggle);

Then I have the Button's OnClickListener
private static int aux = 0;
private AudioManager mAudioManager;

 audioToggle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                bVideoView.start();

                mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);

                if(aux % 2 == 0){

                    mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 50, 0);
                    aux++;

                } else {

                    mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
                    aux++;

                }
            }
        });

Now with this OnClickListener I am perfectly able to toggle the audio to mute and unmute when it is clicked each time. However I want something like this,

*

*On the first click the videoView should start.

*When I keep pressing the button the audio must mute.

*When I release the button the audio must unmute.

I have been trying a lot and failing in some or the other way. Please help.

A: Do you mean:

*

*The first time I hold the button,  the video should play.

*While I'm holding the button the audio must be heard.

*When I release the button, the audio must be muted.

*When I press and hold the button again, the audio must be heard again.

Then what you therefore need is not an OnClickListener but rather an OnTouchListener
What happens under the hood is that your OnClickListener is always called after you release your finger. Using View.OnTouchListener you can dispatch events when you press (you mean touch and hold) and release.
See http://developer.android.com/reference/android/view/View.OnTouchListener.html
Here's a sample snippet:
private static int aux = 0;
private AudioManager mAudioManager;

audioToggle.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent e) {

        bVideoView.start();

        mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
        switch(e.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 50, 0);
                break;
            case MotionEvent.ACTION_UP:
                mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
                break;
        }
        return true;
    }
}

Finally, I don't recommend controlling the system's volume. Use a MediaPlayer.OnPreparedListener instead, get the VideoView's MediaPlayer and then play around with its volume.
Edit:
Here's another sample snippet:
private MediaPlayer bVideoViewMP;

bVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
    @Override
    public void onPrepared(MediaPlayer mp) {
        // Fetch a reference
        bVideoViewMP = mp;
    }
});

audioToggle.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent e) {

        bVideoView.start();

        switch(e.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                bVideoViewMP.setVolume(0.75f, 0.75f);
                break;
            case MotionEvent.ACTION_UP:
                bVideoViewMP.setVolume(0, 0);
                break;
        }
        return true;
    }
}

These should be placed either on your fragment's onViewCreated() or on your activity's onCreate() method before the VideoView has been fully prepared.


text:
Q: jQuery Validator Add method not working I'm using jquery validator addmethod for validation. While clicking the .btn-md button event fires and shows the alert that I've given. But the addmethod was not working.
HTML Code:

Reset your Password

        <form method="post" class="lg_form" name="lg_form" id="formresetpwd">

Password *

                <input type="password" name="pwd" id="pwd" class="txt"/>

                Retype Password *

                <input type="password" name="rpwd" id="rpwd" class="txt"/>

*Password should atleast contain 6 characters with Alphabet, Numeric and Underscores.

<button type="submit" class="btn btn-success btn-md">Submit</button>

            <?php if (isset($msg)) { ?>

<?php echo $msg; ?>

            <?php } ?>
        </form>

Jquery:
$('.btn-md').on('click', function () {
    alert('test');
   $('#formresetpwd').validate({
        rules: {
            pwd: {
                required: true,
                minlength: 6,
                LowserCase: true,
                Digit: true,
                Special_char: true
            }
        },
        messages: {
            pwd: {
                required: "password is required",
                minlength: "Enter atleast 6 characters"
            }
        },
    });
});
$.validator.addMethod("Uppercase", function (value, element) {
    return this.optional(element) || /[A-Z]/.test(value);
}, "Enter atleast one Capital letter");
$.validator.addMethod("LowserCase", function (value, element) {
    return this.optional(element) || /[a-z]/.test(value);
}, "Enter atleast one Small letter");
$.validator.addMethod("Digit", function (value, element) {
    return this.optional(element) || /[0-9]/.test(value);
}, "Enter atleast one Number");
$.validator.addMethod("Special_char", function (value, element) {
    return this.optional(element) || /[{}|~`"'[\]$&+,:;=?@#|'<>.^*()%!-]/.test(value);
}, "Enter atleast one Special Character");

Thanks in advance.

A: Your code...
$('.btn-md').on('click', function () {
   alert('test');
   $('#formresetpwd').validate({
       ....

While clicking the .btn-md button event fires and shows the alert that I've given. But the addmethod was not working.

Based on your code, you click the button and the alert fires, then the .validate() method is called.  Nothing else is supposed to happen.
The .validate() method is not for triggering validation; it's only used to initialize the plugin on your form.  It does not belong inside of a click handler.  The plugin already captures the click of the submit button and automatically triggers any necessary validation.
$(document).ready(function() {

    $('#formresetpwd').validate({  // <- INITIALIZE plugin
        rules: {
            ....
        },
        ....
    });

    $.validator.addMethod( ....

});

Working DEMO:  jsfiddle.net/9vgpLmt5/

A: you have to set input element class="pwd"
<input type="password" name="pwd" id="pwd" class="txt pwd"/>


text:
Q: Textarea behaves weirdly when data is displayed in division I have:
<textarea id='txtSomeId'>
. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Bullet one
 </textarea>

When I use jQuery's $("#txtSomeId").val() and display it in a division like $("divId").html($("#txtSomeId").val());
 some wierd characters appeared like [[[][]][][][][ instead of &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;. This happens when I paste text in Google Chrome and save it and view the data in IE.
If I view it in Google Chrome then I don't get this issue but when I view data saved from Google Chrome in IE I get this issue. Please help me.

A: nbsp; should be  , that is what I see at the first look

A: You're not supposed to have html inside a textarea. Use htmlentities and htmlspecialchars to solve this.