text:
Q: Passing an object to an abstract class? I am taking a programming course at the local college. My instructor doesn't speak the best English, so sometimes it's hard to understand what he's asking for.
The first part of the assignment, which I have already completed, is as follows:
A mechanic shop has 100 customers, each of which is an object in an array, which holds various data. The Base class is Service, and there are four derived classes for specific services (tires, oil, radiator, and brakes). Each customer is assigned one service. A list of all customers with the details is printed.
The second part, I do not understand what he is asking for at all:
We are printing coupons if the last service was done over a certain number of months ago. I have already made calculations for the dates, and if the service was done a certain amount of time ago, I need to pass one object in the service array to the abstract coupon class. His exact instructions are these:

Coupon is an Abstract parent class. The abstract class should have
  variable year, month and day. Make a Service Coupon extend the
  Abstract coupon class. Several child classes - BrakeService Coupon,
  Tire Coupon, Engine Oil Coupon, Radiator Coupon extend the Service
  Coupons. Add an Expiry date to a random date in 2013 and Make it final
  in the constructor of the objects. The service object calls the coupon
  passing the service object. The coupon determines the type of service
  object it receives and accordingly prints the message. This should be
  simple.

Here is what I think it is asking for (purely as an exercise for demonstrating we know how to use abstract and inheritance):
http://www.java-forums.org/attachments/new-java/4632-passing-object-abstract-class-rtc3ild.png
Am I supposed to be passing the object to the abstract class? If so, am I supposed to take my main class and make it an extension of the abstract coupon class?
What I have now is the abstract Coupon class extending the concrete Service class, with the ServiceCoupon class extending Coupon, and four concrete classes extending that. I am not sure how to call the Coupon class or pass it the object from its base class though.
Sorry that I can't be more clear. I don't know what he wants either.
edit: **The main problem I am having is that I want to pass an object to a different class that is abstract. I cannot instantiate this class because it is abstract, so I do not know how to pass an object to the method.

A: I think what he wants is a factory pattern, i.e. you pass in your Service and the factory determines the type of Service and then returns the appropriate Coupon implementation. Something based on a Map would probably do the trick
final Map<Class<? extends Service>, Class<? extends Coupon>> myMap;

public Coupon getCoupon(final Service service) {
  final Coupon coupon = myMap.get(service.getClass()).newInstance();
  //init stuff
  return coupon;
}

Obviously this would only work if you had a noargs constructor for your Coupon.

A: Coupon should not extend the Service class.  You should have two inheritance trees, one for coupon and one for services.

A: I Guess the second part of question is asking for something like this:
import java.util.*;
abstract class Coupon
{
    int year;
    int month;
    int day;
}
class Service extends Coupon
{
    public String getCouponMessage(Coupon coupon)
    {
        if (coupon instanceof BrakeService)
        {
            return "BreakService message";
        }
        else if (coupon instanceof Tire)
        {
            return "TireService message";
        }
        else if (coupon instanceof Engine_Oil)
        {
            return "Engin_Oil Message";
        }
        else if (coupon instanceof Radiator)
        {
            return "Radiator Message";
        }
        else
        {
            return "Invalid Service";
        }
    }
}
class BrakeService extends Service
{
    final Date exp_date;
    public BrakeService(int day,int month , int year)
    {
        Calendar cal = Calendar.getInstance();
        this.day = day;
        this.month=month;
        this.year=year;
        cal.set(year, month, day);
        exp_date = cal.getTime();
    }
}
class Tire extends Service
{
    final Date exp_date;
    public Tire(int day,int month , int year)
    {
        Calendar cal = Calendar.getInstance();
        this.day = day;
        this.month=month;
        this.year=year;
        cal.set(year, month, day);
        exp_date = cal.getTime();
    }
}
class Engine_Oil extends Service
{
    final Date exp_date;
    public Engine_Oil(int day,int month , int year)
    {
        Calendar cal = Calendar.getInstance();
        this.day = day;
        this.month=month;
        this.year=year;
        cal.set(year, month, day);
        exp_date = cal.getTime();
        System.out.println(exp_date);
    }
}
class Radiator extends Service
{
    final Date exp_date;
    public Radiator(int day,int month , int year)
    {
        Calendar cal = Calendar.getInstance();
        this.day = day;
        this.month=month;
        this.year=year;
        cal.set(year, month, day);
        exp_date = cal.getTime();
    }
}


text:
Q: Kotlin: function parameters sent in but not executed? I have the following code that pass in an Integer and two functions.
choseNavigation(childPos, {Toast.makeText(ctx, "hello1", Toast.LENGTH_SHORT).show()},
                                {Toast.makeText(ctx, "hello2", Toast.LENGTH_SHORT).show()})

The function definition as below:
private fun choseNavigation(pos: Int, action1: () -> Unit, action2: () -> Unit) {
    when(pos) {
        0-> {
            action1
            Toast.makeText(ctx, "hello-again1", Toast.LENGTH_SHORT).show()
        }
        1->{
            action2
            Toast.makeText(ctx, "hello-again2", Toast.LENGTH_SHORT).show()
        }
    }
}

When my childPost is 0, I expect it to Toast hello1 and hello-again1. And when it is 1, I expect it to Toast hello2 and hello-again2.
However, when I run the function, it only toast hello-again1 or hello-again2. The sent in function is not being activated at all. Did I miss anything?

A: You forgot to actually invoke your lambdas with ():
...
action1()
Toast.makeText(ctx, "hello-again1", Toast.LENGTH_SHORT).show()
...

For the additional information on why lambdas need to be invoked: cannot explain it better than @hotkey did.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using transform scale on table without borders creates space between  elements So I'm using transform scale on hover on my table. This is before I hover (and scale the table)

This is after the hover (and after it scales)

You see it somehow creates space between  elements, and whatever else.
I've tried a lot of things, like border-collapse but I just can't remove it.
This is the HTML:

                    something

                    something

                    something

This is the CSS:
.custom-table {
    margin-bottom: 0px;
    border: none;
}

.custom-table td{
    border: none;
}

.custom-table tbody tr:hover {
    background-color: #edf0f3;
}

.kartica:hover {
    -webkit-transform: scale(1.05);
    -moz-transform: scale(1.05);
    -o-transform: scale(1.05);
    transform: scale(1.05);

    -webkit-transition: all 70ms ease-in-out;
    -moz-transition: all 70ms ease-in-out;
    -o-transition: all 70ms ease-in-out;
    transition: all 70ms ease-in-out;
}

Is there a way to remove it?
Edit: Here is the codepen.
You should see the thin white lines when you hover over the table.

A: I see there is still no answer for this but I managed to figure it out. Those lines are appearing because you are seeing the color of the table through the "cracks". By matching the table's background-color attribute these lines go away.


text:
Q: What is faster in C#, an if statement, or a virtual function call to a function that does nothing? And why? Say you have a class called MyClass which has a certain behavior encapsulated using a reference (myBehavior) to another class called Behavior.  By default MyClass should have no behavior.
For instances which hadn't set myBehavior to anything after it was initialized   -  Would it be more speed efficient if myBehavior was initialized to null, and each time it was needed checked with if(myBehavior) or would it be faster if it were initialized to an instance of a NullBehavior, derived from Behavior, which does nothing?  and why?
class MyClass
{
   Behavior myBehavior = null;

   void doSomething()
   {
      if(myBehavior)
      {
         myBehavior.performAction();
      }
   }
}

or:
class NullBehavior : Behavior
{
   override void performAction()
   {
      // don't do anything
   }
}

class MyClass
{
   Behavior myBehavior = new NullBehavior(); // or equals some static universal instance of NullBehavior

   void doSomething()
   {
      myBehavior.performAction();
   }
}

A: Let's imagine what will happen with ASM code (after IL):

*

*wrapping it with if will generate extra mov + cmp + jnz instructions.

*calling function will execute call and ret calls which affect callstack maintenance (saving and restoring). It will probably generate something like: call ... then push ebp mov  ebp, esp ... pop ebp retto save it and then extra code to restore it.
Obviously calling function consume more CPU operations comparing to if. But on other hand if your call function will be called each time (i.e. myBehavior is typically set) then we are wasting extra operation on jnz/if.
So if you can predict that myBehaviour will be most likely set (not null / NullBehavior) then you should go with second option without extra if but if it's more likely to be null then it worth wrapping it with if.


text:
Q: Obtain endpoint URL programatically inside wso2 custom handler I have a custom mediator which obtains the endpoint url from message context property ENDPOINT_PREFIX.
I am trying to do the same in my authentication handler, but the get property returns null.
Is there a different way to obtain this information inside a custom handler?
Note that I am not after the endpoint itself (e.g. /api/1.0.0) but after the url to which it points to (in the publisher ui it appears as production/sandbox url).


text:
Q: Investigate for convergence in $z\in\mathbb{C}, \ |z|<1$: $\Sigma_{k=1}^{+\infty}\left(\cos (z^k)-1\right).$
Investigate for convergence in $z\in\mathbb{C}, \ |z|<1$:
$$\Sigma_{k=1}^{+\infty}\left(\cos (z^k)-1\right).$$

We were recommended to use $\cos(z^k)$ expansion first:
$$
\Sigma_{k=1}^{+\infty}\left(\cos (z^k)-1\right)=\Sigma_{k=1}^{+\infty}\Sigma_{n=1}^{+\infty}\left(\frac{(-1)^n z^{2kn}}{(2n)!}\right) =
$$
here we need to reference some theorem that says that $n$ and $k$ changing places $\Sigma_{k=1}^{+\infty}\Sigma_{n=1}^{+\infty}\left(\frac{(-1)^n z^{2kn}}{(2n)!}\right)=\Sigma_{n=1}^{+\infty}\Sigma_{k=1}^{+\infty}\left(\frac{(-1)^n z^{2kn}}{(2n)!}\right)$ is allowed. I don't remember such theorem, and failed to google it. I don't see why $n$ and $k$ changing places would not always be okay. I would be very grateful if someone could give a statement of the theorem.
$$=\Sigma_{n=1}^{+\infty}\frac{(-1)^n}{(2n)!}\Sigma_{k=1}^{+\infty}
 \ z^{2kn}=\Sigma_{n=1}^{+\infty}\left(\frac{(-1)^n}{(2n)!}\cdot\frac{z^{2n}}{1-z^{2n}}\right)$$
Ratio test:
$$\frac{(-1)^{n+1} z^{2n+2}}{(2n+2)! \ (1-z^{2n+2})} \cdot \frac{(2n)! \ (1-z^{2n})}{(-1)^n \ z^{2n}}
=
\frac{(-1) z^{2}(1-z^{2n})}{(2n+1)(2n+2) \ (1-z^{2n+2})} \longrightarrow_{n \longrightarrow \infty} 0 < 1, $$ so the original series is convergent in the given region.
I feel like my solution is wrong. If it is, could someone please point out mistakes, and give hints or explain how to solve correctly?
Thank you.

A: What's wrong with using the ratio test as-is? As long as $z\neq0$, in which case convergence is trivial, we get:
$$\lim_{k\to\infty}\left|\frac{\cos(z^{k+1})-1}{\cos(z^k)-1}\right|=\lim_{k\to\infty}\left|\frac{-\frac{1}{2}z^{2k+2}+o(z^{4k+3})}{-\frac{1}{2}z^{2k}+o(z^{4k-1})}\right|=\left|\lim_{k\to\infty}\frac{z^2+o(z^{2k+3})}{1+o(z^{2k-1})}\right|=0<1$$
As $z^m\to0,\,m\to\infty$.
As for the interchange, I suspect it is only valid when you already know the series to be absolutely convergent, else you could run afoul of the Riemann series pathologies. Interchanges are generally not valid when using them to ascertain convergence - only after convergence has already been ascertained!

A: Note that we have for $|z|<1$
$$\begin{align}
\left|\sum_{k=1}^K (\cos(z^k)-1)\right|&\le \sum_{k=1}^K |1-\cos(z^k)|\\\\
&=\sum_{k=1}^K \left|\sum_{n=1}^\infty \frac{(-1)^{n}z^{2kn}}{(2n)!}\right|\\\\
&\le \sum_{k=1}^K \sum_{n=1}^\infty \frac{|z|^{2kn}}{(2n)!}\\\\
&=\sum_{n=1}^\infty \frac{1}{(2n)!}\frac{|z|^{2n}(1-|z|^{2Kn})}{1-|z|^{2n}}\\\\
&\le \frac{1}{1-|z|^2}\sum_{n=1}^\infty \frac1{(2n)!}\\\\
&<\infty
\end{align}$$
and the series converges as was to be determined.

A: Since $\cos z$ is analytic at $z=0$, there is $M>0$ such that
$$\Big|\frac{\cos(z)-1}{z}\Big|\leq M$$
for all $|z|\leq 1$.
Notice that
$$F(z):=\sum_n(\cos(z^n)-1)=\sum_n\frac{\cos z^n-1}{z^n} z^n$$
Then, by comparison, converges absolutely and uniformly  for all $z$ in a compact subset of the unit disc $|z|<1$: $|\cos z^n -1|\leq M|z|^n$.


text:
Q: Repeating certain columns when merging two data frames of different length (pasting?) I have two data frames for an event study and struggle a bit with preparing the data for the analysis. df1 has two rows with company ID and event date. Some companies have more than one event date, so the company ID is listed for every event date (which means there's more columns than unique company ID's). The other (df2) has share price of every company: row 1 is the company ID and every row below is share price for that specific firm at different dates which are specified in column 1.
I want to merge (or paste?) the two data frames so that for every company ID in df1, it will copy the information below the matching company ID (share price) of df2 to itself.
I've searched around for a solution, however it looks like I'm bad at searching at the moment because my searches yield no significant results. I've tried different merge commands and expand.grid, but I'm rusty in r.
df1 <- data.frame(X1 = c("Event date","Company ID"),
               X2 = c("2018-01-01","AA"),
               X3 = c("2017-05-03","BB"),
               X4 = c("2016-04-08","CC"),
               X5 = c("2015-02-02","BB"))
df2 <- data.frame(X1 = c("Date","2018-12-31","2018-01-01","2017-05-03","2016-12-31","2016-04-08","2015-02-02"),
               X2 = c("AA",100,102,101,98,99,99),
               X3 = c("BB",85,78,80,77,75,74),
               X4 = c("CC",55,53,54,55,54,54))

df-desired <- data.frame(X1 = c("Event date","Company ID","2018-12-31","2018-01-01","2017-05-03","2016-12-31","2016-04-08","2015-02-02"),
             X2 = c("2018-01-01","AA",100,102,101,98,99,99),
             X3 = c("2017-05-03","BB",85,78,80,77,75,74),
             X4 = c("2016-04-08","CC",55,53,54,55,54,54),
             X5 = c("2015-02-02","BB",85,78,80,77,75,74))

My current data is like df1 and df2 and my desired result is df-desired. I would appreciate if anyone could help me out with what command I should look into. I can't think of what command I should spend my efforts on, so I'm hoping someone can point me in the right direction!

A: One approximation is to use dplyr::union() function after column renaming:
colnames(df1) = df1[2,]
colnames(df1)[1] = "Date"

colnames(df2) = df2[1,]

dplyr::union(df1,df2)

#        Date         AA         BB         CC         BB
#1 2015-02-02         99         74         54         74
#2 2016-04-08         99         75         54         75
#3 2016-12-31         98         77         55         77
#4 2017-05-03        101         80         54         80
#5 2018-01-01        102         78         53         78
#6 2018-12-31        100         85         55         85
#7       Date         AA         BB         CC         BB
#8 Company ID         AA         BB         CC         BB
#9 Event date 2018-01-01 2017-05-03 2016-04-08 2017-05-03

You can finally remove that repeated row


text:
Q: Discord music bot in Javascript After running this script there is no errors, but somehow when I try to use any of arguments like play nothing happens. I don't get any errors. Script just logs into Discord bot and nothing happens except that last line in which script gives feedback about proper login.
const { Client, Intents, Attachment} = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
const PREFIX = '!';
const ytdl = require("ytdl-core");

var servers = {};

client.on('message', message => {
    let args = message.content.substring(PREFIX.length).split(" ");

    switch (args[0]) {
        case 'play':

            function play(connection, message){
                var server = servers[message.guild.id];

                server.dispatcher = connection.playStream(ytdl(server.queue[0], {filter: "audioonly"}));

                server.queue.shift();

                server.dispatcher.on("end", function(){
                    if(server.queue[0]){
                        play(connection, message);
                    }else {
                        connection.disconnect();
                    }
                });
            }

            if(!args[1]){
                message.channel.send("give a link");
                return;
            }

            if(!message.member.voiceChannel){
                message.channel.send("you must be on voice chat to play music");
                return;
            }

            if(!servers[message.guild.id]) servers[message.guild.id] = {
                queue: []
            }

            var server = servers = [message.guild.id];

            server.queue.push(args[1]);

            if(!message.guild.voiceConnection) message.member.voiceChannel.join().then(function(connection){
                play(connection, message);
            })

        break;

        case "ping":
            message.channel.send("pong");
            console.log("pong");
            break;
    }
});

client.login(token);

client.on('ready', () => {
    console.log(`Logged in as ${client.user.tag}!`);
  });

A: Try using the "play-dl" module instead of ytdl-core.
So to play a music it is now
const ytdl = require('play-dl');

// Play a music
await ytdl.stream(song_url, { filter: "audioonly" })

// Search something on YouTube
await ytdl.search(arguments, { source: { youtube: "video" } })

// Test if is a YouTube url
if (ytdl.yt_validate(url) === "video" && string.startsWith('https'))

This module can also play from Deezer, Spotify and SoundCloud
Hope this helps :)


text:
Q: "I could have loved you" What does "I could have loved you" mean? And what is the tense of that sentence? Is it a clause or a sentence? I found one if-clause sentence on google "If you had let me, I could have loved you.", could I use "I could have loved you" alone without using "If you had let me,..."? Can it still be meaningful?

A:
What does "I could have loved you" mean?

It means
"There was a time/occasion (in the past) when the possibility of my being able to love you existed." However, it carries the implication that the possibility was not realised and something prevented this and the speaker did not commence to love the listener.
It therefore encompasses the idea of a theoretical situation - something that did not happen in the past, but which, if it had happened, would have changed the present. This is sometimes known as "irrealis". It does not have a true tense as it did not happen - however, it references the past.
The "tense" of the whole sentence is governed by the main clause of the paraphrase "There was a time/occasion".
"when the possibility of my being able to love you existed." is adjectival and modifies "time".
The net result is that when spoken "I could have loved you" has a hidden/unspoken "if clause".


text:
Q: Apache camel route from cxfrs to activemq queue issue I have implemented restful webservice with the help of spring+cxf:rsServer.
 <cxf:rsServer id="cxfContainer" address="/">
    <cxf:serviceBeans>
        <ref bean="restService"/>
    </cxf:serviceBeans>
    <cxf:extensionMappings>
            <entry key="json" value="application/json" />   <!--  use .json to get data in JSON format -->
            <entry key="xml" value="application/xml" />     <!-- use .xml to get data in XML format -->
        </cxf:extensionMappings>
        <cxf:providers>
            <ref bean="jsonProvider" />
            <ref bean="jaxbXmlProvider" />
        </cxf:providers>
    </cxf:rsServer>

now i want to route xml/json input  on webservice to activemq.
so i added camelContext like
  <camelContext id="camel" xmlns="http://camel.apache.org/schema/spring" trace="true">
             <route>
            <from uri="cxfrs:bean:cxfContainer"/>
           <choice>
                <when>

                    <camel:xpath>/PlayerType/playerId= '007'</camel:xpath>
                    <inOnly uri="activemq:queue:RESTFULL.queue"/>
                </when>
                 <otherwise>
                    <inOnly uri="activemq:queue:DefaultQueue"/>
                 </otherwise>
            </choice>
             </route>

    </camelContext>

XML input File
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<PlayerType xmlns="http://benchresources.in/cdm/Player">
    <playerId>007</playerId>
    <name>abcd</name>
    <age>30</age>
    <matches>70</matches>
</PlayerType>

Its throws following error.
unwinding now
org.apache.cxf.interceptor.Fault: org.apache.camel.NoTypeConversionAvailableException: No type converter available to convert from type: org.apache.cxf.message.MessageContentsList
to the required type: org.w3c.dom.Document with value [in.benchresources.cdm.player.PlayerType@d792a03] while invoking public java.lang.String com.apache.cxf.xml.json.service.Playe
rServiceImpl.createOrSaveNewPLayerInfo(in.benchresources.cdm.player.PlayerType) with params [in.benchresources.cdm.player.PlayerType@d792a03].
    at org.apache.cxf.service.invoker.AbstractInvoker.createFault(AbstractInvoker.java:167)
    at org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:141)
    at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:211)
    at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:99)
    at org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:59)
    at org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:96)
    at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:307)
    at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
    at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:243)
    at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:223)
    at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:197)
    at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:149)
    at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:171)
    at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:286)
    at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doPost(AbstractHTTPServlet.java:206)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
    at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:262)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:957)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2476)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2465)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.camel.RuntimeCamelException: org.apache.camel.NoTypeConversionAvailableException: No type converter available to convert from type: org.apache.cxf.message.Mes
sageContentsList to the required type: org.w3c.dom.Document with value [in.benchresources.cdm.player.PlayerType@d792a03]

A: I've run into this problem many times when dealing with Camel's CXF endpoint. Essentially when you get a response from your cxfrs bean the cxf response is encapsulated in a MessageContentsList(essentially an arraylist). There error you're getting is because you're trying to a MessageContentsList object into org.w3c.dom.Document which throws this error.
You can get around this by adding a processor right after your cxfrs bean that pulls the response out of the MessageContentsList and sets it as the body of the message. Something like this:
process(Exchange e){
    MessageContentsList list = (MyObject) e.getIn().getBody();
    MyObject obj = list.get(0);
    e.getIn().setBody(obj);
}


text:
Q: Modify multiple files with spaces in the filenames in batch I have a directory c:\test that is populated automatically with files named PM1 2016-10-06 1.AL1, PM1 2016-10-06 2.AL1, PM1 2016-10-07 1.AL1 etc.  I have written (thanks to Aacini for the core code!) a batch script that works exactly the way I need it to, but my problem is that it only works on one file, and the file cannot have spaces in the filename. The code:
@echo off

cd c:\test

setlocal EnableDelayedExpansion

set LF=^

%do not remove%
%these lines%

set "EOL=!LF!" & set "EOL2=!LF!"

for /f "tokens=*" %%a in (c:\test\PM1.AL1) do (
     if %%a equ PROP-SUMMARY set "EOL=!LF!"
     set /P "=%%a!EOL!" < NUL
     set "EOL0=!EOL!" & set "EOL=!EOL2!" & set "EOL2=!EOL0!"
     if %%a equ PROP-VALUES set "EOL=,"
  ) >>c:\test\test.tmp
TYPE c:\test\test.tmp | FIND "" /V > c:\test\PM1_new.AL1"

DEL c:\test\test.tmp

If you're curious about the TYPE line, it changes all the CRs in the file to CRLFs.

A: @echo off
setlocal EnableDelayedExpansion

cd c:\test

set LF=^
%do not remove%
%these lines%

for %%f in (*.*) do (

   set "EOL=!LF!" & set "EOL2=!LF!"

   (for /f "usebackq tokens=*" %%a in ("%%f") do (
      if %%a equ PROP-SUMMARY set "EOL=!LF!"
      set /P "=%%a!EOL!"
      set "EOL0=!EOL!" & set "EOL=!EOL2!" & set "EOL2=!EOL0!"
      if %%a equ PROP-VALUES set "EOL=,"
   )) < NUL > test.tmp

   TYPE test.tmp | FIND "" /V > "%%f"

)

DEL test.tmp


text: Q: Google cloud server is slow when there is high network traffic I have a google compute engine server that runs slowly when there is high network traffic, what do I need to upgrade to improve the speed?


text:
Q: unable to create next dependency in intune i have problem with create more dependencies for win32 app in intune.
If i want create or update one dependency i use "updaterelationships" but i need create second dependency i have problem with "relationships". How to add second dependency to intune ?
 $Dependency = [ordered]@{
        "@odata.type" = "#microsoft.graph.mobileAppDependency"
        "dependencyType" = "Detect"
        "targetId" = $ID2
        #"targetDisplayName"= "Target Display Name value"
        #"targetDisplayVersion"= "Target Display Version value"
        #"targetPublisher"= "Target Publisher value"
        #"targetType"= "parent"
        #"dependencyType"= "autoInstall"
        #"dependentAppCount"= 1
        #"dependsOnAppCount"= 1
     }

     $Win32AppRelationships = [ordered]@{
        "relationships" = @($Dependency)
     }
        $uri = "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps/$ID/updaterelationships"
        Invoke-RestMethod -Uri $uri -Headers $authToken -Method Post -Body ($Win32AppRelationships | ConvertTo-Json)  -ContentType "application/json"
    }

Response if i use only "relationships" according to  https://learn.microsoft.com/en-us/graph/api/intune-apps-mobileappdependency-create?view=graph-rest-beta
Response content:
{"error":{"code":"No method match route template","message":"No OData route exists that match template
~/singleton/navigation/key/navigation with http verb POST for request /AppLifecycle_2208/StatelessAppMetadataFEService/deviceAppManagement/mobileApps

A: relationships is an array, have you tried appending a second dependency into the array?
"relationships" = @($Dependency1,$Dependency2)


text:
Q: Why is dictionary page offset 0 for `plain_dictionary` encoding? The parquet was generated by Spark v2.4 Parquet-mr v1.10
n = 10000
x = [1.0, 2.0, 3.0, 4.0, 5.0, 5.0, None] * n
y = [u'é', u'é', u'é', u'é', u'a', None, u'a'] * n

z = np.random.rand(len(x)).tolist()
dfs = spark.createDataFrame(zip(x, y, z), schema=StructType([StructField('x', DoubleType(),True),StructField('y', StringType(), True),StructField('z', DoubleType(), False)]))
dfs.repartition(1).write.mode('overwrite').parquet('test_spark.parquet')

Using parquet-tools v1.12 to inspect
row group 0
--------------------------------------------------------------------------------
x:  DOUBLE SNAPPY DO:0 FPO:4 SZ:1632/31635/19.38 VC:70000 ENC:RLE,BIT_PACKED,PLAIN_DICTIONARY ST:[min: 1.0, max: 5.0, num_nulls: 10000]
y:  BINARY SNAPPY DO:0 FPO:1636 SZ:864/16573/19.18 VC:70000 ENC:RLE,BIT_PACKED,PLAIN_DICTIONARY ST:[min: a, max: é, num_nulls: 10000]
z:  DOUBLE SNAPPY DO:0 FPO:2500 SZ:560097/560067/1.00 VC:70000 ENC:PLAIN,BIT_PACKED ST:[min: 2.0828331581679294E-7, max: 0.9999892375625329, num_nulls: 0]

    x TV=70000 RL=0 DL=1 DS: 5 DE:PLAIN_DICTIONARY
    ----------------------------------------------------------------------------
    page 0:                   DLE:RLE RLE:BIT_PACKED VLE:PLAIN_DICTIONARY ST:[min: 1.0, max: 5.0, num_nulls: 10000] SZ:31514 VC:70000

    y TV=70000 RL=0 DL=1 DS: 2 DE:PLAIN_DICTIONARY
    ----------------------------------------------------------------------------
    page 0:                   DLE:RLE RLE:BIT_PACKED VLE:PLAIN_DICTIONARY ST:[min: a, max: é, num_nulls: 10000] SZ:16514 VC:70000

    z TV=70000 RL=0 DL=0
    ----------------------------------------------------------------------------
    page 0:                   DLE:BIT_PACKED RLE:BIT_PACKED VLE:PLAIN ST:[min: 2.0828331581679294E-7, max: 0.9999892375625329, num_nulls: 0] SZ:560000 VC:70000

Question:
Should FPO (First data page offset) always bigger or smaller than DO (Dictionary page offset)? I read from somewhere that dictionary page is stored after the data page.
For column x & y, plain_dictionary is used for encoding. However, why is dictionary offset 0 for both of the columns?
If I inspect using pyarrow v0.11.1 which uses parquet-cpp v1.5.1, it tells me has_dictionary_page: False & dictionary_page_offset: None
Does it have a dictionary page or not?

A: The offset of the first data page is always larger than the offset of the dictionary. In other words, the dictionary comes first and only then the data pages. There are two metadata fields meant to store these offsets: dictionary_page_offset (aka DO) and data_page_offset (aka FPO).
Unfortunately, these metadata fields are not filled in correctly by parquet-mr.
For example, if the dictionary starts at offset 1000 and the the first data page starts at offset 2000, then the correct values would be:

*

*dictionary_page_offset = 1000

*data_page_offset = 2000

Instead, parquet-mr stores

*

*dictionary_page_offset = 0

*data_page_offset = 1000

Applied to your example, this means that in spite of parquet-tools showing DO: 0, columns x and y are dictionary encoded nonetheless (column z is not).
It is worth mentioning that Impala follows the specification correctly, so you can not rely on every file having this deficiency.
This is how parquet-mr handles this situation during reading:
// TODO: this should use getDictionaryPageOffset() but it isn't reliable.
if (f.getPos() != meta.getStartingPos()) {
  f.seek(meta.getStartingPos());
}

where getStartingPos is defined as:
/**
 * @return the offset of the first byte in the chunk
 */
public long getStartingPos() {
  long dictionaryPageOffset = getDictionaryPageOffset();
  long firstDataPageOffset = getFirstDataPageOffset();
  if (dictionaryPageOffset > 0 && dictionaryPageOffset < firstDataPageOffset) {
    // if there's a dictionary and it's before the first data page, start from there
    return dictionaryPageOffset;
  }
  return firstDataPageOffset;
}

You can see these lines of code in context here: ParquetFileReader.readDictionary, ColumnChunkMetaData.getStartingPos.


text:
Q: make curve/ concave like below image with container in flutter? I'm familier with ClipPath widget , but help of this I can only make corner round or border round and circle. I know this will fixed by ClipPath or CustomPainter widget. but don't know to how to do.
Expected image:

Actual result :

CODE:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const SampleExample(),
    );
  }
}

  class SampleExample extends StatelessWidget {
    const SampleExample({ Key? key }) : super(key: key);

    @override
    Widget build(BuildContext context) {
      return Scaffold(
        backgroundColor: Colors.red,
        body:  Container(
          alignment: Alignment.bottomCenter,
          height: MediaQuery.of(context).size.height,
          width: MediaQuery.of(context).size.width,
          child: Container(

              height: 250.0,
              decoration:  BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.vertical(
                  top: Radius.elliptical(
                        MediaQuery.of(context).size.width, 120.0)),

              ),
            ),
        ),

      );
    }
  }

A: One way you can do this is like so using CustomPainter.
class SampleExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      backgroundColor: Colors.red,
      body: Align(
        alignment: Alignment.bottomCenter,
        child: CustomPaint(
          painter: MyCustomPainter(),
          child: SizedBox(
            width: double.infinity,
            height: 250,
            child: Center(child: Text('Cool!')),
          ),
        ),
      ),
    );
  }
}

class MyCustomPainter extends CustomPainter {
  const MyCustomPainter();

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.white
      ..style = PaintingStyle.fill;

    final path = Path()
      ..moveTo(0, 0)
      ..quadraticBezierTo(size.width / 2, size.height / 4, size.width, 0)
      ..lineTo(size.width, size.height)
      ..lineTo(0, size.height)
      ..close();

    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}

A: By using Stack widget, I implemented what you want layout.

*

*Draw white background

*Stacked bottom elliptical red Rect widget

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const SampleExample(),
    );
  }
}

class SampleExample extends StatelessWidget {
  const SampleExample({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Stack(
        children: [
          Container(
            height: 250.0,
            decoration: BoxDecoration(
              color: Colors.red,
              borderRadius: BorderRadius.vertical(
                  bottom: Radius.elliptical(
                      MediaQuery.of(context).size.width, 120.0)),
            ),
          ),
        ],
      ),
    );
  }
}

A: On decoration>borderRadius replace top with bottom and use alignment: Alignment.topCenter instead of bottomCenter on body Container.
body: Container(
  alignment: Alignment.topCenter,
  height: MediaQuery.of(context).size.height,
  width: MediaQuery.of(context).size.width,
  child: Container(
    height: 250.0,
    decoration: BoxDecoration(
      color: Colors.white,
      borderRadius: BorderRadius.vertical(
          bottom: Radius.elliptical(
              MediaQuery.of(context).size.width, 120.0)),
    ),
  ),
),

A:       @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: SafeArea(
            child: ClipPath(
              clipper: CurveClipper(),
              child: Container(
                color: Colors.lightGreen,
                height: 250.0,
                child: Center(
                    child: Padding(
                      padding: EdgeInsets.only(bottom: 50),
                      child: Text(
                        "Curved View",
                        style: TextStyle(
                          fontSize: 25,
                          color: Colors.white,
                        ),
                      ),
                    )),
              ),
            ),
          ),
        );
      }
    }

 class CurveClipper extends CustomClipper<Path> {
      @override
      Path getClip(Size size) {
        int curveHeight = 40;
        Offset controlPoint = Offset(size.width / 2, size.height + curveHeight);
        Offset endPoint = Offset(size.width, size.height - curveHeight);

        Path path = Path()
          ..lineTo(0, size.height - curveHeight)
          ..quadraticBezierTo(controlPoint.dx, controlPoint.dy, endPoint.dx, endPoint.dy)
          ..lineTo(size.width, 0)
          ..close();

        return path;
      }

      @override
      bool shouldReclip(CustomClipper<Path> oldClipper) => false;
    }


text:
Q: android disable lint "unused declaration" for entire project In an android library project I have many unused declarations, cause they mostly get called from outside of the project. I use lint via

Analyze -> Inspect Code

I dont want to use
@SurpressWarning("unused")

on each file.
If I try to disable it with the same ID in gradle file
android {
    lintOptions {
        disable 'unused'
    }
}

The linter still comes up with the "Unused declaration" errors
I also tried it by creating lint.xml file in project root
<?xml version="1.0" encoding="UTF-8"?>
<lint>
    <!-- list of issues to configure -->
    <issue id="unused" severity="ignore" />
</lint>

But it still doesn´t work. Anyone know the correct lint ID?

A: You can use Analyze -> Inspect Code, then you right-click in one of the warnings. You will see there is an option called "Disable inspection":

Just click on it and you won't need to worry about unused declarations in your project anymore.


text:
Q: Scroll to element if it not in viewport jScrollPane library have a scrollToElement method which can scroll to element if it not in viewport.
Also this method have a stickToTop parameter which scroll as little as possible to show the element (not top of the viewport, like it do scrollTop).
Anyone knows standalone plugin for that functionality? Or how it can be realised in JS (I'm not an expert in JS and I can't extract this function from jScrollPane).

A: Yuu should user scrollIntoView(true) function.
https://developer.mozilla.org/en/docs/Web/API/Element/scrollIntoView


text:
Q: Cannot use a decorator on a child class inheriting from a parent class but can use it on the object itself I am creating a class inheriting from a parent class. The parent class is Telebot and the child class is my own Telegram BOT class. I am doing this to create a standard BOT that multiple scripts will call and implement with default actions etc.
Then I am trying to implement a decorator to treat default incoming messages on this child class. Here is how I am doing it (file is telegram.py):
# Importo a biblioteca que vou usar pra criar meu BOT
import telebot

class TelegramBot(telebot.TeleBot):
    """
    Essa classe é chamada para criar uma instância de um BOT do Telegram.
    Ela herda a classe Telebot do módulo telebot.
    Doc: https://pytba.readthedocs.io/en/latest/sync_version
    """

    def __init__(self, token):
        """Esta função é chamada no momento que a classe é instanciada.
        Herda os atributos do telebot"""

        super().__init__(token)

    def polling(self):
        """Este método está sendo incrementado com algumas funcionalidades
        próprias do bot, ao invés de ser feito o override/polimorfismo."""
        super().polling()

    @telebot.TeleBot.message_handler(commands=["testar_bot"])
    def resposta_teste(self, mensagem):
        """Esse método utiliza do Decorator para ter uma nova caracteristica e funcionalidade,
         que define o padrão para cada mensagem recebida.
         O método testa a resposta padrão para fazer o teste no BOT.
         """

        self.reply_to(mensagem, "Olá! Teste passou. Tudo funcionando :)")

When doing it like this, I receive the error:
TypeError: TeleBot.message_handler() missing 1 required positional argument: 'self'
The weirdest thing is that if I remove the decorator alongside the method and implement in my bot object on my main.py file, it works like a charm.
Here is the code that works - I remove the decorator from the class and put it on main.py:

import telegram

bot = telegram.TelegramBot("blablabla_mytokenhidden")

@bot.message_handler(commands=["testar_bot"])
def resposta_teste(mensagem):
    """Esse método utiliza do Decorator para ter uma nova caracteristica e funcionalidade,
     que define o padrão para cada mensagem recebida.
     O método testa a resposta padrão para fazer o teste no BOT.
     """

    bot.reply_to(mensagem, "Olá! Teste passou. Tudo funcionando :)")

bot.polling()

This does not gives me any error, and the decorator works like a charm. I really don't understand the logic behind this.
Why the decorator I used on my object works but on my child class (telegram.py with TelegramBot class) doesn't?
Edit #1
Following the object logic, I tried replacing telebot.TeleBot with self, also tested with object and it still did not work...
So I am clearly NOT getting the logic here.

A: A method defined in a class requires an instance of the class to be passed as the first argument (self) when it is called. (This is done for you when you invoke it using dot notation, i.e. instance.method().) The decorator @telebot.TeleBot.message_handler() is called during class definition, before there are any instances. Therefore the handler doesn't know what instance it is attached to, which is why it wants you to pass self in yourself. Which of course the bot framework is not set up to do.
Naturally, this isn't a problem when the handler is defined outside the class because it doesn't require an instance of the class it's attached to, not being attached to a class and all.
One solution is to instead apply the decorator when an instance is created:
def __init__(self, token):
        """Esta função é chamada no momento que a classe é instanciada.
        Herda os atributos do telebot"""

        super().__init__(token)
        self.resposta_teste = telebot.TeleBot.message_handler(
            commands=["testar_bot"])(self. resposta_teste)

This makes the handler a bound method of its instance, with self already baked in. Note that this might cause problems if you create multiple instances of the class, because you'll have multiple handlers attached to the same event. The framework you're using might be OK with that, or it might not.
Another thing you can do, if you won't have multiple instances of the bot (or if the handler doesn't need to know what instance it's attached to) is to make the method a static method. Then it behaves as a regular function (albeit in the class namespace) and doesn't need to be passed an instance.
class TelegramBot(telebot.TeleBot):

    # ...

    @telebot.TeleBot.message_handler(commands=["testar_bot"])
    @staticmethod
    def resposta_teste(mensagem):
        """Esse método utiliza do Decorator para ter uma nova caracteristica e funcionalidade,
         que define o padrão para cada mensagem recebida.
         O método testa a resposta padrão para fazer o teste no BOT.
         """

        self.reply_to(mensagem, "Olá! Teste passou. Tudo funcionando :)")


text:
Q: How can I generate column in R which has Pairwise of one column V1  ------> FA MA GA RA TA
I want to have output like below
column1 -> FA FA FA FA  MA MA MA GA GA
column2 -> MA GA  RA TA GA RA TA RA TA

A: you can do that with combn function, which generates all combinations. For example, we want combinations of a, b, c by two elements:
 v <- c("a", "b", "c")
 combn(v, 2)

Would result as combinations matrix:
     [,1] [,2] [,3]
[1,] "a"  "a"  "b"
[2,] "b"  "c"  "c"

If you want this matrix as vector of pairs, you can apply paste over the columns and collapse it by "." - a dot:
apply(combn(v, 2), 2, function(x) paste(x, collapse = "."))

This would give you vector of characters combinations - "a.b" "a.c" "b.c"

A: The length generated by the unique combination of rows/elements of column V1 would be greater than the nrow of dat.  So, I am not sure how you want to generate a new column V2 on the same dataset.  Perhaps you can create another dataframe with a single column
 dat2 <- data.frame(V2=combn(unique(dat$V1),2, FUN=paste, collapse="."), stringsAsFactors=FALSE)

 dat2$V2
 #[1] "FA.MA" "FA.GA" "FA.RA" "FA.TA" "MA.GA" "MA.RA" "MA.TA" "GA.RA" "GA.TA"
 #[10] "RA.TA"

If you need to paste the first value with all the others
 paste(dat$V1[1], dat$V1[-1], sep=".")
 #[1] "FA.MA" "FA.GA" "FA.RA" "FA.TA"

Update
If you need don't need to paste, then (as mentioned by @aosmith) you can just do:
  dat2 <- as.data.frame(t(combn(unique(dat$V1),2)))
  dat2
  #   V1 V2
  #1  FA MA
  #2  FA GA
  #3  FA RA
  #4  FA TA
  #5  MA GA
  #6  MA RA
  #7  MA TA
  #8  GA RA
  #9  GA TA
  #10 RA TA

data
 dat <- data.frame(V1=c("FA", "MA", "GA", "RA", "TA"), stringsAsFactors=F)

A: Try:
> for(i in 1:(length(V1)-1))
         V2[i] = paste(V1[1], V1[i+1],sep='.')
> V2
[1] "FA.MA" "FA.GA" "FA.RA" "FA.TA"


text:
Q: How to compute volume of parametric regions? I guess this is something pretty standard in calculus, but I was unable to google the answer.
Assume I have unit hypercube $C_n = [0,1]^n$. I also have a function $f : \mathbb{R}^n \to \mathbb{R}^{n+1}$. The components $f_i : \mathbb{R}^n \to \mathbb{R}$ are polynomials $\forall i = 1,...,n+1$, so it's all quite well behaved. I want to find the n-volume (measure) of $f(C_n)$. How do I do that in general?

A: For $t=(t_1,\dots,t_n)$ in the cube $C_n$, let $A(t)=(a_{ij}(t))_{i,j=1}^{n+1}$ be the matrix whose entries $a_{ij}(t)$ are defined as follows:
$a_{ij}(t):=\partial_i f_j(t)$ for $i=1,\dots,n$ and $j=1,\dots,n+1$, where $\partial_k f_j(t)$ denotes the partial derivative of the function $f_j$ with respect to its $k$th argument $t_k$;
$a_{n+1,j}(t):=e_j$ for $j=1,\dots,n+1$, where $(e_1,\dots,e_{n+1})$ is the standard basis of $\mathbb R^{n+1}$.
In other words, for $i=1,\dots,n$, the $i$th row of the matrix $A(t)$ is the vector $\partial_i f(t):=(\partial_i f_1(t),\dots,\partial_i f_{n+1}(t))$, and the last row of $A(t)$ is $(e_1,\dots,e_{n+1})$.
So,
\begin{equation*}
 \det A(t)=\bigwedge(\partial_1 f(t),\dots,\partial_n f(t)),
\end{equation*}
the generalized $n$-ary cross product of the vectors $\partial_1 f(t),\dots,\partial_n f(t)$ in $\mathbb R^{n+1}$; see e.g. Section Multilinear algebra.
It follows that the volume in question is
$$\int_{C_n}\|\det A(t)\|\,dt=\int_{C_n}\Big\|\bigwedge(\partial_1 f(t),\dots,\partial_n f(t))\Big\|\,dt,$$
where $\|\cdot\|$ is the Euclidean norm in $\mathbb R^{n+1}$.

The latter formula is an extension of the formula for the area of a 2D surface in $\mathbb R^3$ in terms of the cross product (in which case $n=2$), and its derivation in general is quite similar to that for $n=2$; cf. e.g. formulas (16.6.8)--(16.6.12). The key fact here is as follows. For any vectors $v_1,\dots,v_n$ in $\mathbb R^{n+1}$, let $B$ the matrix in $\mathbb R^{(n+1)\times(n+1)}$ with rows $v_1,\dots,v_{n+1}$, where $v_{n+1}:=\bigwedge(v_1,\dots,v_n)$. Note that the vector $v_{n+1}$ is orthogonal to the vectors $v_1,\dots,v_n$.
So, the $(n+1)$-volume $V_{n+1}(v_1,\dots,v_{n+1})$ of the parallelotope defined by the vectors $v_1,\dots,v_{n+1}$ is
\begin{equation*}
 |\det B|=V_n(v_1,\dots,v_n)\|v_{n+1}\|; \tag{1}
\end{equation*}
here, $V_n(v_1,\dots,v_n)$ is of course the $n$-volume of the parallelotope defined by the vectors $v_1,\dots,v_n$.
On the other hand, expanding $\det B$ along its last row, we see that
\begin{equation*}
 \det B=v_{n+1}\cdot\bigwedge(v_1,\dots,v_n)=\|v_{n+1}\|^2, \tag{2}
\end{equation*}
where $\cdot$ denotes the dot product.
Comparing (1) and (2), we conclude that
\begin{equation*}
 V_n(v_1,\dots,v_n)=\|v_{n+1}\|=\Big\|\bigwedge(v_1,\dots,v_n)\Big\|.
\end{equation*}


text:
Q: React Hooks Exhaustive Deps suggest infinit loop I get the following esLint error
React Hook useEffect has a missing dependency: 'time'. Either include it or remove the dependency array. (react-hooks/exhaustive-deps) (ESLint)
If i follow the suggestion, and provide time as part of the dependency array I will get an infinite loop because the setTime prop will keep updating the time prop.
const TimeValidator = ({
    time,
    setTime
}: {
    time: Time;
    setTime: (time: Time) => void;
}) => {
    const [newTime, setNewTime] = useState(time);

    useEffect(() => {
        // Save the duration from the time property
        const duration = time.end - time.start;
        if (newTime.start > time.end) {
            // Use the duration to create a valid time object, where "start" < "end"
            setTime({ start: newTime.start, end: newTime.start + duration });
        } else if (newTime.end < time.start) {
            // Use the duration to create a valid time object, where "start" < "end"
            setTime({ start: newTime.end, end: newTime.end + duration });
        } else {
            setTime({ ...time, ...newTime });
        }
        // react-hooks/exhaustive-deps suggests "time". But this will lead to
        // infinite update loop
    }, [newTime, setTime]);

    return <TimeChooser time={time} setTime={setNewTime} />;
};

Link to expo snack - Try to update the time in dependency array
The idea is that the parent pass down a time object and a callback to update the time object. The TimeValidator pass the time object down to the child - TimeChoser, but overwrites the callback. If the updated time from the child of TimeValidator is not valid, the TimeValidator  will try to update the time object, so that start is always less than end.
Is there a good pattern on how to fix this? Thanks!

A: Sometimes es-lint will have some exceptions in genuine usecases. In these cases you have to use // eslint-disable-next-line comment.
useEffect(() => {
 ----
 // eslint-disable-next-line
},[newTime, setTime])

A: I think i can convert my useEffect into a useCallback instead:
const TimeValidator = ({
    time,
    setTime
}: {
    time: Time;
    setTime: (time: Time) => void;
}) => {
    const updatedTracking = useCallback(
        (newTime, updateTime) => {
            // Save the duration from the time property
            const duration = time.end - time.start;
            if (newTime.start > time.end) {
                // Use the duration to create a valid time object, where "start" < "end"
                updateTime({
                    start: newTime.start,
                    end: newTime.start + duration
                });
            } else if (newTime.end < time.start) {
                // Use the duration to create a valid time object, where "start" < "end"
                updateTime({ start: newTime.end, end: newTime.end + duration });
            } else {
                updateTime({ ...time, ...newTime });
            }
        },
        [time]
    );

    return (
        <TimeChooser
            time={time}
            setTime={time => updatedTracking(time, setTime)}
        />
    );
};


text:
Q: "All the good people" vs. "all of the good people" I've heard both of these before.

*

*All the good people

*All of the good people

Are they both correct?

A: Both correct! They both have the same meaning. The "of" variant is a partitive genitive, like French bouteille de vin (bottle of wine). I'd say "all of" has a connotation of "all members of group x", whereas "all" without "of" is completely neutral, just the entirety of x. In most cases either connotation will result in the exact same meaning.


text:
Q: Convert audio from mono to stereo for use in AVPlayer (iOS) I have an AVPlayer that plays audio from a mono AVAsset, doing some processing via an audio processing tap along the way. How can I convert this asset to stereo before reaching the tap? The second channel can be empty or a copy of the first channel (it'll get filled up manually in the tap).
I've tried converting the mono to stereo within the tap, but apparently we have no control over the ASBD or AudioBufferList structure once we're inside the tap. I've also done offline conversion, but this presents big obstacles (can be quite slow, not suitable for web streaming).
Here is the barebones (but complete) code which you can use with any mono audio file. You'll see that by the time it hits the processing tap, there's just the one channel available instead of the desired two channels. To use the code, you just need to add the MediaPlayer and TapProcessor classes below to a blank Single View Application, use the following ViewController code in place of the default code, and add in your own mono audio file to your project. Thanks for reading.
MediaPlayer.h
#import <Foundation/Foundation.h>

@interface MediaPlayer : NSObject

@end

MediaPlayer.m
#import "MediaPlayer.h"
#import "TapProcessor.h"
#import <AVFoundation/AVFoundation.h>

@interface MediaPlayer()

@property (nonatomic, strong) AVAsset *asset;
@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) TapProcessor *audioTapProcessor;

@end

@implementation MediaPlayer

- (id)init {
    if (self = [super init]){
        NSString *path = [[NSBundle mainBundle] pathForResource:@"MonoSource"
                                                         ofType:@"mp3"];
        [self loadFileWithPath:path];
    }
    return self;
}

-(void)loadFileWithPath:(NSString*)path{
    NSURL *fileURL = [NSURL fileURLWithPath:path];
    NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES]
                                                        forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    self.asset = [AVURLAsset URLAssetWithURL:fileURL options:options];
    [self.asset loadValuesAsynchronouslyForKeys:@[@"tracks"] completionHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            AVKeyValueStatus status = [self.asset statusOfValueForKey:@"tracks" error:nil];
            switch (status) {
                case AVKeyValueStatusLoaded:
                    [self setupPlayer];
                    break;
                default:
                    break;
            }
        });
    }];
}

- (void) setupPlayer{

    AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:self.asset];

    AVAssetTrack *audioTrack = [[self.asset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0];
    [self printInfoForTrack:audioTrack];
    TapProcessor *newProcessor = [[TapProcessor alloc] initWithTrack:audioTrack];

    AVAudioMix *audioMix = [newProcessor audioMix];
    item.audioMix = audioMix;

    self.player = [AVPlayer playerWithPlayerItem:item];

    [self.player play];
}

-(void) printInfoForTrack:(AVAssetTrack*)track{
    CMAudioFormatDescriptionRef item = (__bridge CMAudioFormatDescriptionRef)[track.formatDescriptions objectAtIndex:0];
    const AudioStreamBasicDescription* desc = CMAudioFormatDescriptionGetStreamBasicDescription(item);
    NSLog(@"Number of track channels: %d", desc->mChannelsPerFrame);
}

@end

TapProcessor.h
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>

@interface TapProcessor : NSObject

- (id)initWithTrack:(AVAssetTrack *)track;

@property (readonly, nonatomic) AVAssetTrack *track;
@property (readonly, nonatomic) AVAudioMix *audioMix;

@end

TapProcessor.m
#import "TapProcessor.h"

// TAP CALLBACKS
static void tap_InitCallback(MTAudioProcessingTapRef tap,
                             void *clientInfo,
                             void **tapStorageOut){
}

static void tap_FinalizeCallback(MTAudioProcessingTapRef tap){
}

static void tap_PrepareCallback(MTAudioProcessingTapRef tap,
                                CMItemCount maxFrames,
                                const AudioStreamBasicDescription *processingFormat){
    NSLog(@"Number of tap channels: %d", processingFormat->mChannelsPerFrame);
}

static void tap_UnprepareCallback(MTAudioProcessingTapRef tap){
}

static void tap_ProcessCallback(MTAudioProcessingTapRef tap,
                                CMItemCount numberFrames,
                                MTAudioProcessingTapFlags flags,
                                AudioBufferList *bufferListInOut,
                                CMItemCount *numberFramesOut,
                                MTAudioProcessingTapFlags *flagsOut){
    MTAudioProcessingTapGetSourceAudio(tap, numberFrames, bufferListInOut, NULL, NULL, NULL);
    *numberFramesOut = numberFrames;
}

@implementation TapProcessor

- (id)initWithTrack:(AVAssetTrack *)track{
    self = [super init];
    if (self){
        _track = track;
    }
    return self;
}

@synthesize audioMix = _audioMix;
- (AVAudioMix *)audioMix {
    if (!_audioMix){
        AVMutableAudioMix *audioMix = [AVMutableAudioMix audioMix];
        if (audioMix){
            AVMutableAudioMixInputParameters *audioMixInputParameters = [AVMutableAudioMixInputParameters audioMixInputParametersWithTrack:self.track];
            if (audioMixInputParameters) {
                MTAudioProcessingTapCallbacks callbacks;
                callbacks.version = kMTAudioProcessingTapCallbacksVersion_0;
                callbacks.clientInfo = (__bridge void *)self,
                callbacks.init = tap_InitCallback;
                callbacks.finalize = tap_FinalizeCallback;
                callbacks.prepare = tap_PrepareCallback;
                callbacks.unprepare = tap_UnprepareCallback;
                callbacks.process = tap_ProcessCallback;

                MTAudioProcessingTapRef audioProcessingTap;
                if (noErr == MTAudioProcessingTapCreate(kCFAllocatorDefault,
                                                        &callbacks,
                                                        kMTAudioProcessingTapCreationFlag_PreEffects,
                                                        &audioProcessingTap)){
                    audioMixInputParameters.audioTapProcessor = audioProcessingTap;
                    CFRelease(audioProcessingTap);
                    audioMix.inputParameters = @[audioMixInputParameters];
                    _audioMix = audioMix;
                }
            }
        }
    }
    return _audioMix;
}

@end

ViewController.h
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@end

ViewController.m
#import "ViewController.h"
#import "MediaPlayer.h"

@interface ViewController ()

@property (nonatomic,strong) MediaPlayer *mediaPlayer;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.mediaPlayer = [[MediaPlayer alloc] init];
}

@end


text:
Q: Full page vertical slideshow like apple.com/iphone-5c/ How can we make a http://www.apple.com/iphone-5c/ like webpage using jquery.
Would we have to use plugins or just the jquery api would be enough. I was thinking of using '.scroll()'.
But then we cannot really specify which direction the user scrolls in. Any jquery plugin or any js library recommendation most welcome.

A: Maybe this is what you're looking for
Jquery
            $('.bxslider').bxSlider({
                   mode: 'vertical',
                    slideMargin: 5
             });

HTML

A: You have a lot of jquery plugin. here there's a list with some of them. Scrollrama should help you


text:
Q: Django Admin - populate other fields after changing foreignkey I have this model:
class Order(models.Model):
    client = models.ForeignKey(
        Client,
        on_delete=models.CASCADE,
        related_name='orders',
        related_query_name='order',
    )

    delivery_country = CountryField('Kraj wysyłki', null=True, blank=True)
    delivery_city = models.CharField('Miasto wysyłki', max_length=255, null=True, blank=True)
    delivery_street = models.CharField('Ulica wysyłki', max_length=255, null=True, blank=True)

    billing_country = CountryField('Kraj dla faktury', null=True, blank=True)
    billing_city = models.CharField('Miasto dla faktury', max_length=255, null=True, blank=True)
    billing_street = models.CharField('Ulica dla faktury', max_length=255, null=True, blank=True)

    products = models.ManyToManyField(Product, through='OrderProduct')

class Client(models.Model):
    name = models.CharField('Imię', max_length=255)
    surname = models.CharField('Nazwisko', max_length=255)
    country = CountryField('Kraj', null=True, blank=True)
    city = models.CharField('Miasto', max_length=255, null=True, blank=True)
    street = models.CharField('Ulica', max_length=255, null=True, blank=True)

And I would like to achieve this behaviour in Django Admin:
After every change of Order.client I want to prepopulate other fields like this:

*

*Order.delivery_country = client.country

*Order.delivery_city = client.city

*Order.delivery_street = client.street

*Order.billing_country = client.country

*Order.billing_city = client.city

*Order.billing_street = client.street
Is there any package/plugin to achieve this?
Or maybe you have some ideas how I could do it myself?

A: Ok I achieved this:
JS:
(function ($) {
    $(document).ready(function(){
        $("select[name='client']").on("change", function(){
            $.ajax({
                url: "/admin/clients/"+$(this).val(),
                type: "GET",
            }).done(function(data){
                client_data = $.parseJSON(data);
                client_data = client_data[0];

                $("select[name='delivery_country']").val(client_data.fields.country);
                $("input[name='delivery_city']").val(client_data.fields.city);
                $("input[name='delivery_street']").val(client_data.fields.street);

                $("select[name='billing_country']").val(client_data.fields.country);
                $("input[name='billing_city']").val(client_data.fields.city);
                $("input[name='billing_street']").val(client_data.fields.street);
            });
        });
    });
})(django.jQuery);

And View:
def get_client_ajax(request, id):
    return JsonResponse(serializers.serialize('json', Client.objects.filter(id=id)), safe=False)


text:
Q: pass onChange function already argument checkbox I have a checkbox where I pass the props to the parent, and I have stopped for the handleChange function and cannot understand what I am doing wrong

My child component
import Checkbox from "@material-ui/core/Checkbox";

const Form = (props) => {
const {values: {debtorIsIndividual},handleChangeCheck } = props
  return (
    <Checkbox
        checked={debtorIsIndividual}
        onChange={() => handleChangeCheck("debtorIsIndividual")}
        value="debtorIsIndividual"
      />
  )
}

My Parent Component class Component
handleChangeCheck = name => ({ target: { checked } }) => {
   this.setState({ [name]: checked });
};

const {  debtorIsIndividual } = this.state;
const values = {
  debtorIsIndividual: debtorIsIndividual
};

return
  <Form  handleChangeCheck={this.handleChangeCheck} />

what am I doing wrong?
Demo https://codesandbox.io/embed/checkbox-material-35kqr

P.S. Of course, i can pass a static argument, but I need it to be dynamic, because I will have more than one checkbox in this form

A: It looks like the issue ultimately stems from using an anonymous function in the onChange event-handler in place of directly referencing the desired prop.
onChange={() => handleChangeCheck("debtorIsIndividual")}

This is likely specific to the material-ui API: https://material-ui.com/api/checkbox/
I've created a sandbox for you to give you an idea on how to make this work: https://codesandbox.io/s/optimistic-archimedes-1cewz
Essentially, it looks like you just want to be able to pass up the values from the Checkbox up to the Parent-component. Here's the code as well:
Parent
class App extends React.Component {
  state = {
    name: false,
    age: false,
    docs: false
  };

  handleOnChange = e => {
    const { name, checked } = e.target;
    this.setState(
      {
        [name]: checked
      },
      () => console.log(this.state)
    );
  };

  render() {
    return (

        <Form {...this.state} handleOnChange={this.handleOnChange} />

    );
  }
}

Child
import React from "react";
import { Checkbox } from "@material-ui/core";

const Form = props => {
  return (

        User Verifed:{" "}
        <Checkbox
          onChange={props.handleOnChange}
          name="name"
          checked={props["name"]}
        />

        Age Verifed:{" "}
        <Checkbox
          onChange={props.handleOnChange}
          name="age"
          checked={props["age"]}
        />

        Docs Verifed:{" "}
        <Checkbox
          onChange={props.handleOnChange}
          name="docs"
          checked={props["docs"]}
        />

  );
};


text:
Q: How is state managed in Scala Play! 2.0 Websockets? I'm looking at the example at https://github.com/playframework/Play20/tree/master/samples/scala/websocket-chat
To make a websocket controller, you write something like:
def chat(username: String) = WebSocket.async[JsValue] { request  =>
    ChatRoom.join(username)
}

Chatroom.join returns a scala.concurrent.Future[(Iteratee[JsValue,_],Enumerator[JsValue])] . But where are the iteratee and the enumerator used within the Play! framework? The WebSocket class (WebSocket.scala) seems to ignore the inputs:
case class WebSocket[A](f: RequestHeader => (Enumerator[A], Iteratee[A, Unit]) => Unit)        (implicit val frameFormatter: WebSocket.FrameFormatter[A]) extends Handler {

  type FRAMES_TYPE = A

  /**
   * Returns itself, for better support in the routes file.
   *
   * @return itself
   */
   def apply() = this
}

How does Play! manage the changing state of the iteratee as it consumes input?

A: It's worth noting that the WebSocket itself is just a dumb container. The magic happens in various classes within play.core.server.netty.
To understand what that magic is, it's instructive to look at the signature of f (the function that a WebSocket contains:
RequestHeader => (Enumerator[A], Iteratee[A, Unit]) => Unit

This is a function that takes a RequestHeader, an Enumerator, and an Iteratee, and does something with them.
So, at some point in the future, the framework will provide our WebSocket with a RequestHeader (which should be self explanatory), an Enumerator[A] (Enumerators are sources, in this case, these are the messages being received from the client), and an Iteratee[A, Unit] (Iteratees are sinks, in this case, this is where we send messages to go back to the client).
In the case of WebSocket.adapter, the WebSocket will connect the Enumerator to the Iteratee via an Enumeratee. In the case of WebSocket.using, the WebSocket will connect the remote Enumerator to a local Iteratee, and connect the remove Iteratee to a local Enumerator.
Rather than defining WebSocket directly, it's likely to be easier to use one of the convenience methods in the WebSocket object. The following code will echo the previous message received:
  def mySocket = WebSocket.adapter {implicit req =>
    var lastMessage = "No previous message"
    Enumeratee.map[String] {msg =>
      val response = lastMessage
      lastMessage = msg
      response
    }
  }

Note that this code almost certainly has thread safety issues - in Scala, you should try to avoid mutable state whenever possible, or use actors or similar if not.
Or, try WebSocket.using, and look at a pushee Enumerator, in conjunction with a foreach Iteratee, although it's a little fiddler. Perhaps understandably, the pushee enumerator is deprecated in Play 2.1, as it's being superseded by the new channels system.


text:
Q: Calling a Method at NSDate I'm trying to call a method at a certain time and date (using an NSDate) but I can't work out how to do it.
I don't want to use NSTimer because that becomes paused when the app goes into the background or is closed. I don't want to run one in the background either because this only solves half of the problem and is a wasteful way of doing it in my opinion. I thought that if I could fire a method at an NSDate in the future, when the app is opened again I can see if the current date has passed the fire date and so whether to call it instantly or carry on waiting.
I suppose I'm looking for something like UILocalNotification, without the notification.
I am hoping that there is a simple way of doing this that I just can't seem to find, so any help would be greatly appreciated.

A: Why don't you just use the NSTimer, and in the...
- (void)applicationDidBecomeActive:(UIApplication *)application

callback, check the time and date, and update the timer, or call the function if the date has passed.

A: At first, it sounded to me like you want the performSelector:withObject:afterDelay: method. So you have an NSDate *date when you want to call the selector.
NSTimeInterval delay = [date timeIntervalSinceNow];
[self performSelector:@selector(methodToFire) withObject:nil afterDelay:delay];

Of course, this won't live past your runtime, so you've pretty much outlined what you need to do already. You just save your date somewhere (there are MANY ways to do that), and then check against it in applicationDidBecomeActive. You can use the same timeIntervalSinceNow method I used above. (If the date has past, the the interval would be negative.)
if ( [date timeIntervalSinceNow] <= 0 ) {
    // do something...
}


text:
Q: how to submit html form with current hash location I have a HTML form which i want to be able to submit with the current hash location
<form action="editcustomer.php?seq=<?php echo $_GET["seq"]; ?>#" method="post" name="form1">

Is this possible?

A: To get the current hash value, you'll need something like this:
<form onSubmit="this.action='editcustomer.php'+location.hash" action="editcustomer.php" method="post" name="form">

off topic: It's common practice to do this, as it makes it possible to jump to the added anchor point, for example directly to the submitted form (#form-xy), thus enhancing user experience.


text:
Q: Bootstrap working on Local Host but not on online server The code was working perfectly on local host with xampp. All I've done is upload it to a server and now it's not working.
I uploaded all the BS files as well. I also fixed the href links to be '..../js/bootstrap.min.js' etc. No images load and nor does bootstrap I do not think. The reason I think the problem comes from Bootstrap is because all the text/buttons still appear, they just aren't customised with the css/JS as BS does.
They are php files.
This is a link to the site: http://www.johnnythyroid.com.
I'm only new and this is just for learning so all advice is much appreciated.
This is the relevant code I think, I deleted a lot of the stupid text to make it shorter:

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Jod</title>

 <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
 <link rel='stylesheet' type='text/css' href="johnnythyroidcom.ipage.com/css/custom icons.css">
 <link href='https://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
 <link href='https://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'>

    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
      Navbar toggle

    </button>
    Some Name

Home

About

Contact

      Account

Login

Create Account

 Welcome, Guest!

 The

 A simgn

    Bg
    ng

 Rjj

sum dolor sit amet.

     View more

 Ss

Lorenim.

     View more

 y

Lorenim.

     View more

 aaaaaa

A: Try this
change

into

add http:// to your all images src

A:
Check the console for errors.

It says, Bootstrap's JavaScript requires jQuery, As I could see, You have included it and it is loaded correctly. Include that file before including bootstrap.min.js
Also correct that path of images. Your request url becomes: http://www.johnnythyroid.com/johnnythyroidcom.ipage.com/Img/first%20rocket.jpg which is incorrect.
Note: Just a blind guess, Incorrect path could be because of .htaccess

A: when reffering 3rd party include css or jss
you have to use https if your server is using https
else use http
for example you are accessing your site http://yoursite.com or http://localhost
then http://getbootstrap.com/css/bootstrap.min.js or css will work
that is why it works on localhost
but if you use https for yoru site  https://yoursidte.com
then http://getbootstrap.com/css/bootstrap.min.js or css will not work
you will have to user https
e.g  https://getbootstrap.com/css/bootstrap.min.js or css
THIS WAS THE CASE WHY MY menu were wroking on localcomputer but not over https , after changing from http to https://getbootstrap.com/css/bootstrap.min.js or css now it is working ..
all these files can be in different locations
for example you may save bootstrap.min.css in your site folder in case you edited that file ..


text:
Q: Embedding Python in C++: error when importing module in Debug mode (except for standard modules such as os or sys) I am embedding python in C++ using pydind11. It seems like I cannot import any module (e.g. numpy) outside the standard ones (e.g. os, sys, ...) when I run the application in debug mode. Instead, in release mode, everything seems fine.
I have no idea to what could be the problem. Please, let me know what other information you may need.
Edit:
To give an example, I have a project organised as follow:
  |__ CMakeLists.txt
  |__ my_lib/
  |      |____ CMakeLists.txt
  |      |____ my source/header files
  |
  |__ lib_pybind/  # The folder contains the pybind files form the repo (latest ver)
           |______ CMakeLists.txt
           |______ include/
           |           |_____ pybind/
           |                     |_____ pybind .h files
           |______ [...]

Then, I have an external python library that is provided with a wheel installation (I cannot share). However, this library also uses common libs as numpy.
The main CMakeLists.txt (I am only including the part relative to this issue) is as follow:
project (
  my_proj
  VERSION 0.1
  DESCRIPTION "my_proj"
  LANGUAGES CXX)

set(PYBIND11_INCLUDE_LIB "${PROJECT_SOURCE_DIR}/lib_pybind11/include/pybind11")
set(PYBIND11_INCLUDE_DIR "${PROJECT_SOURCE_DIR}/lib_pybind11/include/")
include_directories(${PYBIND11_INCLUDE_DIR})

add_subdirectory ("src/my_lib")
add_subdirectory ("lib_pybind11")

Instead, the .\my_lib\CMakeLists.txt (I am only including the part relative to this issue) is
set(MYLIB_SRC
     [...cpp]
)
set(MYLIB_H
     [...h]
)
set(Python_FIND_ABI "OFF" "ANY" "ANY")
find_package(Python3 REQUIRED COMPONENTS Development)

add_library(my_lib ${MYLIB_SRC} ${MYLIB_H})
target_compile_features(my_lib PUBLIC cxx_std_17)
set_target_properties(my_lib PROPERTIES LINKER_LANGUAGE CXX)

target_link_libraries(my_lib PUBLIC Python3::Python pybind11::embed)
target_include_directories(my_lib INTERFACE ${PYBIND11_INCLUDE_LIB})

When I try to use the external Python library and loading the module, e.g. from external_lib import Channel with
pybind11::initialize_interpreter();
py::object Channel = py::module_::import("external_lib").attr("Channel");

everything runs fine if VisualStudio2022 is in Release mode. I get an exception error error_already_set if I run it in Debug mode and I don't understand why. I was using numpy as an example because also importing numpy gives me the same problem.


text:
Q: How do I get the path selected by the user in Explorer? I have a program that makes voice text using .txt ,but os.startfile doesn't let me select the file, hence get the path to it) I will be very grateful for your help!!
Как должно быть.
enter image description here
Как у меня)
enter image description here
import os
import pyttsx3 as pyt
from gtts import gTTS

class DICTOR:

    def __init__(self, path):
        self.engine = pyt.init()

        #voices = self.engine.getProperty('voices')
        self.engine.setProperty('voice', 0)

        #rate = self.engine.getProperty('rate')
        self.engine.setProperty('rate', 150)

        with open(path, 'r') as file:
            self.file = file.read()

    # def speak(self):
    #     self.engine.say(self.file)
    #     self.engine.runAndWait()

    def save(self, filename):
        tss = gTTS(text = self.file, lang='en')
        tss.save(filename)
        #rate = self.engine.getProperty('rate')

path = os.startfile(filepath = 'D:\Python\Road_map\DICTOR')

DICTOR(path).save('.mp3')

A: I'm guessing your problem is with the formatting. You should add r to the start. It should be:
path = os.startfile(filepath = r"G:\EEGdatabase\6541455.docx")

the r is needed because \ is considered to be a special character by python. Another option is to escape \ with \\:
path = os.startfile(filepath = 'D:\\Python\\Road_map\\DICTOR')

More info in the docs.
Finally, since you haven't provided your error message, maybe this isn't your problem at all. If this doesn't fix it, add your error log so we know exactly what is going on.

Edit: It seems you have misunderstood the use of os.startfile. This function takes in something you need to "start", and starts it. So if you had said
os.startfile("something.pdf")

Then something.pdf will be opened in your default PDF software. If you instead passed in something like file.html, then this html file will be opened in your default web browser.
So you are now passing in D:\Python\Road_map\DICTOR, which is a folder, and the startfile function simply opens up that folder in Windows Explorer. A full reference for startfile can be found in the docs.
In any case, I don't think you need startfile at all. You need a file selector, which you can get using the Tkinter package. You can then say:
from Tkinter import Tk     # from tkinter import Tk for Python 3.x
from tkinter.filedialog import askopenfilename

Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file
print(filename)
path = filename

(Taken from  https://stackoverflow.com/a/3579625/3730626)


text:
Q: Eigenvalues of the $m^{th}$ power of a matrix Let $K$ be a commutative ring or field and $A\in\mathcal{M}_n(K)$ a general matrix. I am trying to establish a connection between the eigenvalues of $A$ and the eigenvalues of $A^m$, where $m\in \mathbb{N}$.
So far, I've been dabbling with two big cases - when $A$ is diagonalizable and when $A$ is not. Of course, when $A$ is diagonalizable, we have that $A\sim D$, where $D=\begin{pmatrix} \lambda_1 & 0 & 0 & \dots & 0 \\ 0 & \lambda_2 & 0 & \dots & 0 \\ \vdots & \vdots & \vdots & \dots & \vdots \\ 0 & 0 & 0 & \dots & \lambda_n \end{pmatrix}$, where $\lambda_i,~i=\overline{1,n}$ are the eigenvalues of A. It follows that $A^m\sim D^m$, i.e. $A^m$ has the same eigenvalues as $D^m$, namely the roots $l$ (in $K$) of $(\lambda_1^m-l)(\lambda_2^m-l)\dots(\lambda_n^m-l)=0$. This is where I continued with two subcases, namely if $K$ has and doesn't have zero-divisors.
If $K$ does not have zero-divisors, then $\exists~i\in \{1,2,\dots,n \}~\text{such that}~ l_i=\lambda_i^m$ (in $K$). This is mostly where I am stuck, I'm not sure how to determine the rest of the eigenvalues $l$. Any bibliography and ideas are highly appreciated.


text:
Q: Lots of files being used by blank web page. What are they? I am trying to optimise a website and I was using the network waterfall facility in Google Chrome. When I looked at the results there were lots of files which I didnt recognise. I first thought they might be something to do with Google Chrome itself, so I put a blank HTML file on my desktop and checked but there was nothing in the waterfall except the file itself. So I put a blank file on my server and I got the output below. What are all these files, are they all necessary, is this normal and do I need to be in any way concerned. My hosting provider has always been excellent in every regard that I'm aware of.
My host is shared hosting, using cpanel and is based on a LAMP server.
I also note that a couple of those file have problems but I have no idea how to fault find that or whether it's a concern.
EDIT: I have cleared the cache so I don't think it's a browser cache issue.

A: I'd look at the website access file itself.   That is a better indicator of what is being sent to a specific ID.  I'd suggest what you are seeing is browser related and not website related but going to the horses mouth is the best approach.

A: It turned out to be a combination of two chrome browser extensions. One of them was an extension called Fast Save which looks like it I might have been tricked into installing http://www.fergeeks.com/chrome-tips/fast-save-1-1-chrome-extension-adding-ads-causing-havoc/ but the other was the popular lastpass extension.

A: This question is completely off topic but something resulting in a blank page can involve many requests for the web server. If you have a look at the files involved you'll notice that nearly all produce no output on their own. As for the rest, they may not be displayed if there is an error in your code. Just because an image is requested does not mean it will be displayed. If it's not displayed it won't show in the resultant "source" code. e.g. Images may be requested because they are used in your JavaScript, ready to be displayed on some event or other.


text:
Q: How to prove $(a_1+a_2+\dots a_n)\left(\frac{1}{a_1}+\frac{1}{a_2}+\dots+\frac{1}{a_n}\right)\ge n^2$? let $a_1,a_2,\dots ,a_n$ be a positive real numbers . prove that
$$(a_1+a_2+\dots a_n)\left(\frac{1}{a_1}+\frac{1}{a_2}+\dots+\frac{1}{a_n}\right)\ge n^2$$
how to prove this inequality ..is this result prove by Induction

A: It's just C-S!
$$(a_1+a_2+\dots a_n)\left(\frac{1}{a_1}+\frac{1}{a_2}+\dots+\frac{1}{a_n}\right)\ge $$
$$\geq\left(\sum_{k=1}^n\left(\sqrt{a_k}\cdot\frac{1}{\sqrt{a_k}}\right)\right)^2=\left(\sum_{k=1}^n1\right)^2=n^2.$$
Also, we can use AM-GM here:
$$(a_1+a_2+\dots a_n)\left(\frac{1}{a_1}+\frac{1}{a_2}+\dots+\frac{1}{a_n}\right)\geq n\sqrt[n]{\prod_{k=1}^na_k}\cdot\frac{n}{\sqrt[n]{\prod\limits_{k=1}^na_k}}=n^2 .$$
Also, we can use the Tangent Line method.
Indeed, since our inequality is homogeneous, we can assume that $$a_1+a_2+...+a_n=n$$ and we need to prove that
$$\sum_{k=1}^n\frac{1}{a_k}\geq n$$ or
$$\sum_{k=1}^n\left(\frac{1}{a_k}-1\right)\geq0$$ or
$$\sum_{k=1}^n\frac{1-a_k}{a_k}\geq0$$ or
$$\sum_{k=1}^n\left(\frac{1-a_k}{a_k}+a_k-1\right)\geq0$$ or
$$\sum_{k=1}^n\frac{(a_k-1)^2}{a_k}\geq0.$$
Done!

A: this is true since
$$\frac{a_1+a_2+a_3+...+a_n}{n}\geq \frac{n}{\frac{1}{a_1}+\frac{1}{a_2}+\frac{1}{a_3}+...+\frac{1}{a_n}}$$

A: Hint: By Cauchy Schwartz inequality we have
$$n=\sum_{i=1}^{n}1= \sum_{i=1}^{n}\frac{1}{\sqrt{a_i}}\sqrt{a_i}\le \left(\sum_{i=1}^{n}\frac{1}{a_i}\right)^{1/2}\left(\sum_{i=1}^{n}a_i\right)^{1/2}$$

A: This is just the AM-HM inequality. it is easily proved by observing that the following quantity is positive
\begin{eqnarray*}
\sum_{1 \leq < i < j \leq n} \left( \sqrt{ \frac{a_i}{a_j}}- \sqrt{\frac{a_j}{a_i}} \right) ^2 \geq 0
\end{eqnarray*}
Expand this out & add $ \sum_{i=1}^{n} \frac{a_i}{a_i} =n $ to both sides and factorise.

A: Here is a simple proof: Let $b_i:=1/a_i$ so that $a_ib_i=1$ for all $i$.
Note that $x+1/x\ge1+1$ for $x\gt0$ so apply it to $x=a_ib_j$ for all $i\lt j$ in the following:
$(a_1+a_2+\dots+a_n)(b_1+b_2+\dots+b_n)=$ $(1+a_1b_2+\dots+a_1b_n)+(a_2b_1+1+\dots+a_2b_n)+\dots+(a_nb_1+a_nb_2+\dots+1)=$  $(1+1+\dots+1)+(a_1b_2+a_2b_1)+(a_1b_3+a_3b_1)+\dots+(a_1b_n+a_nb_1)+(a_2b_3+a_3b_2)+$
$\dots+(a_2b_n+a_nb_2)+\dots+(a_{n-1}b_n+a_nb_{n-1})\ge n\cdot(1)+n(n-1)/2\cdot(1+1)=n^2.$
You can easily rephrase the above argument as an induction proof if you want to do so.

A: Another proof: See Art of Problem Solving about Chebyshev's inequality.
There are two different versions of it. Use the second version.
If $a_1\ge a_2\ge \ldots \ge a_n$ and $b_n\ge b_{n-1}\ge \ldots \ge b_1$, then $$n\left(\sum_{i=1}^{n} a_ib_i\right)\le \left(\sum_{i=1}^{n}a_i\right)\left(\sum_{i=1}^{n}b_i\right)$$
In this case, you're given $a_1,a_2,\ldots,a_n>0$. Use the inequality.
Notice that if WLOG (without loss of generality) $a_1\ge a_2\ge \ldots\ge a_n$, then $\frac{1}{a_n}\ge \frac{1}{a_{n-1}}\ge \ldots \ge \frac{1}{a_1}$.


text:
Q: Mysql trigger is throwing syntax errors on my trigger When executed the trigger throws the error below . Please help
DELIMITER |
CREATE  TRIGGER `Problem_created` AFTER UPDATE  ON `WorkOrder_Fields` FOR EACH ROW
BEGIN
DECLARE problem_time_stamp   int;

IF   NEW.UDF_CHAR37 ='Problem'  AND  OLD.UDF_CHAR37='Incident'

    THEN

        SET problem_time_stamp    = (SELECT UNIX_TIMESTAMP(now())*1000);

        update workorder_fields set UDF_DATE6=problem_time_stamp    where WORKORDERID=OLD.WORKORDERID ;

    END IF;
END |
DELIMITER ;

========================================================================
[root@vmesx42s32 bin]#  mysql -u root -S../tmp/mysql.sock supportcenter
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 263 to server version: 4.1.18-pro

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql> DELIMITER |
mysql> CREATE  TRIGGER `Problem_created` AFTER UPDATE  ON `WorkOrder_Fields` FOR EACH ROW
    -> BEGIN
    -> DECLARE problem_time_stamp   int;
    ->
->
    -> IF   NEW.UDF_CHAR37 ='Problem'  AND  OLD.UDF_CHAR37='Incident'

IF   NEW.UDF_CHAR37 ='Problem'  AND  OLD.UDF_CHAR37='Incident'
    ->
 -> THEN
    ->
     ->  SET problem_time_stamp    = (SELECT UNIX_TIMESTAMP(now())*1000);
 ->

        -> update workorder_fields set UDF_DATE6=problem_time_stamp    where WORKORDERID=OLD.WORKORDERID ;
 ->
    -> END IF;
 -> END |
**ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near     'TRIGGER `Problem_created` AFTER UPDATE  ON `WorkOrder_Fields` FOR EACH ROW
BEGIN' at line 1**
mysql> DELIMITER ;

A: You generally don't want to do an update on the table being modified by the trigger.  Instead do a before insert trigger and:
IF   NEW.UDF_CHAR37 ='Problem'  AND  OLD.UDF_CHAR37='Incident'
THEN
    SET new.UDF_DATE6 := UNIX_TIMESTAMP(now())*1000);
END IF;

This assumes that WORKORDERID is not being updated, but based on its name, that seems unlikely.


text:
Q: WooCommerce Change Total Price on Checkout by custom field I'm struggling finding a solution to this problem:
I need to create a custom number field on checkout page and change total price according to this field.
The user can put a number starting from 4 to maximum the total Cart quantity and gets a discount based on this number.
How can I update total price after user set number field?
Below there is my code to add a custom field to checkout page
/**

* Add custom field to the checkout page

*/

add_action('woocommerce_before_checkout_form', 'custom_number_field');

function custom_number_field($checkout)

{

echo '

' . __('Vuoto a rendere') . '
';

woocommerce_form_field('custom_field_name', array(

'type' => 'number',

'class' => array(

'my-field-class form-row-wide'

) ,

'label' => __('Quanto vuoi rendere?') ,

'placeholder' => __('New Custom Field') ,

) ,

$checkout->get_value('custom_field_name'));

echo '
';

}

Then I read that it's not possible updating total price directly into checkout page and I need to refresh page using a button and passing to the new page the value of my custom field.
So I need to use this WooCommerce field:
add_filter( 'woocommerce_calculated_total', 'change_calculated_total', 10, 2 );
function change_calculated_total( $total, $cart ) {
    return $total - "value of my custom field";
}

How can I create a button link with the value of my custom field and pass it to the WooCommerce function to update cart?
I was thinking to use php GET and putting the value of custom field inside the link button and then retrieve the value from the link inside the cart function.
Some help will be highly appreciated.


text:
Q: How to show that for a continuous function on $\mathbb{R}$ that satisfies $-f(-x)=f(x)$ for all $x \neq0$ then $f(0)=0$ How to show that for a continuous function on $\mathbb{R}$ that satisfies $-f(-x)=f(x)$ for all $x \neq0$ then $f(0)=0$
For $-f(-x)=f(x)$ to be true, it appears we must have an odd function without a constant at the end. You can tell this from examination (it's obvious for a linear function, but should also hold true for cubic functions and upward). So it seems obvious to me that the proposal is true, but I don't know of a theorem to prove my observation, or to move from my observation to an actual proof. Any help?

A: $$f(-x)=-f(x), \forall x \ne 0$$
$$\lim_{x \to 0}f(-x)=\lim_{x \to 0}-f(x)$$
By continuity,
$$f(\lim_{x \to 0}-x)=-f(\lim_{x \to 0}x)$$
$$f(0)=-f(0)$$
$$2f(0)=0$$
$$f(0)=0$$

A: With an elementary "$\varepsilon$-$\delta$" proof.
By continuity, we have $f(0) = \lim_{x\to 0} f(x)$. We will use the definition of limit.
Fix any $\varepsilon > 0$; and let $\delta_\varepsilon > 0$ be such that
$$
\forall x \neq 0 \text{ s.t. } |x|\leq \delta_\varepsilon, \, |f(x)-f(0)| \leq \varepsilon. \tag{1}
$$
In particular, fix any $x\in (0,\delta_\varepsilon]$. We have, applying the above to both $x$ and $-x$,
$$
|f(x)-f(0)| \leq \varepsilon \;\text{ and }\; |f(x)+f(0)| = |-f(x)-f(0)| = |f(-x)-f(0)| \leq \varepsilon \tag{2}
$$
so that (using the triangle inequality)
$$
2|f(0)| = |f(0)-f(x)+f(x)+f(0)| \leq |f(0)-f(x)|+|f(x)+f(0)| \leq 2\varepsilon \tag{3}
$$
i.e., $|f(0)| \leq \varepsilon$. Since the above works for every $\varepsilon > 0$, this implies $|f(0)|=0$, i.e., $f(0)=0$.

A: Consider the sequence $$\{1/n\}$$
Due to continuity of $f(x)$ we have $$ \lim _{n\to \infty} f(1/n)
 =f(0)$$
Similarly we have $$ \lim _{n\to \infty} f(-1/n)
 =f(0)$$
Since we have $$f(1/n)=-f(-1/n)$$ We have
$$ f(0)= -f(0)$$
Thus $$f(0)=0$$

A: Suppose $f(0)>0$. The case $f(0)<0$ is analogous.
Let $\varepsilon=\dfrac{f(0)}{2}>0$.
How $f$ is continuous at $0$ (in particular), there exists $\delta>0$ such that $|x-0|<\delta \Rightarrow |f(x)-f(0)|<\varepsilon$.
So, $f(x)\in \left( f(0)-\varepsilon, f(0)+\varepsilon \right) = \left( \dfrac{f(0)}{2}, \dfrac{3\cdot f(0)}{2} \right)$
$\Rightarrow f(x)>\dfrac{f(0)}{2}>0$, $\forall x \in (-\delta, \delta)$.
But, if $f(x)>0$ for some $x\in(-\delta,\delta)$, then $f(-x)<0$ with $-x\in(-\delta,\delta)$. Contradiction!
Therefore $f(0)=0$

A: Define $\, g(x) := f(x) + f(-x). \,$ As a sum of continuous functions, $\, g(x) \,$ is continuous  and $\, g(x) = 0 \,$ for all $\, x \neq 0. \,$ By continuity, $\, g(0) = f(0) + f(-0) = 2f(0) = 0. \,$ Now $\, f(0) = 0.$


text:
Q: Convert a list of strings to a pandas dataframe I have a list of strings reflecting a conversation. I am trying to find a way to convert the conversation into a dataframe with columns for an index, the utterance (text) itself, and a speaker label column.
myconvo = ['Speaker1: this is one utterance',
            'Speaker2: this is another utterance',
            'Speaker1: this is a third utterance']

I assume that I will need to transform the list of strings into a list of lists, where each sub-list will comprise the speaker ID and the utterance.
So far I have used the below regular expression, but it is returning an extra blank object.
for i myconvo:
    a = re.split(r'(Speaker\d)', i, flags=re.MULTILINE)

['', 'Speaker1', ': this is one utterance']
['', 'Speaker2', ': this is another utterance']
['', 'Speaker1', ': this is a third utterance']

Worst case scenario I could just delete that first column, but I'm thinking there are clearly things I am doing that could be improved.


text:
Q: Why does LightInject use an ImmutableHashTree to store registrations, instead of a simple Dictionary? I'm looking at several IoC contains in order to choose one to use in my work, and taking a look at LightInject's codebase I came across something I don't understand...
In ServiceContainer's GetInstance(Type serviceType, string serviceName) method, it forms a key from the parameters and calls 'Search' on 'namedDelegates':
var key = Tuple.Create(serviceType, serviceName);
var instanceDelegate = namedDelegates.Search(key);

namedDelegates is an ImmutableHashTree<TKey, TValue>, an internal class that implements (from its own comments):
/// A balanced binary search tree implemented as an AVL tree.

The reason I'm looking at LightInject is because of its excellent scores in Daniel Palme's IoC Performance Comparison and I'm puzzled as to why a O(log n) binary search algorithm is preferable to using a O(1) Dictionary in this case?
Can anyone educate me here?

A: Have not used, just peeked at the source code
My theory is so that duplicate keys can used as needed either from their API point of view or the consuming dev's. Search(TKey) handles checking duplicates it found in the tree so that's what lead me to that.
Another is also probably for performance -- as you mentioned in your question it looks quite speedy. Their search on the ImmutableHashTree graciously handles the issue of a value not being found as it just returns default(TValue).
This seems like it would be faster than the following with a Dictionary<TKey, TValue> which already is doing a lot of the same work to find your value based on the Key given.
if (myDictionary.ContainsKey(myKey))
    return myDictionary[myKey]; // Practically double the work has been done
else
    return default(TValue);

try
{
    return myDictionary[myKey];
}
catch(Exception ex)
{
    // Exceptions can be expensive.
    return default(TValue);
}

Their way only does search once and doesn't worry about catching exceptions to handle the fact the key wasn't present.
Again, this is what I gathered giving just a quick look at the source code and should not be considered as concrete.