text:
Q: How to put a horizontal line above the notes using ThreePartTable? Thanks to this post Longtable with threeparttable (but the one that I can't comment because I'm really new here) I found that I can use footnotes with longtable, if I use threeparttable package.
However, I'd like to have a line above my notes.
Anyone know how to do it?
(I want something like this)

Here it's an example of my code. The table 1 (longtable) is the one that have footnotes with ThreePartTable package. It hasn't line above the notes. The table 2 (with minipage environment) has line above the notes. I want a similar line in table 1.
\documentclass[a4paper]{article}
\usepackage{longtable}
\usepackage{multirow}
\usepackage{lipsum}
\usepackage{booktabs,threeparttablex}
\usepackage{etoolbox}
\appto\TPTnoteSettings{\footnotesize}
\usepackage{caption}
\usepackage[labelfont=bf,labelsep=period]{caption}

\begin{document}

\lipsum[2-3]

\begin{ThreePartTable}
\renewcommand\TPTminimum{\textwidth}
\setlength\LTleft{0pt}
\begin{TableNotes}
  \item[*] A note adsfasdf
  \item[] Another note asdfasfasd

\end{TableNotes}

\begin{longtable}{|l|l|l|l|l|l|}
\caption{\textit{AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA}} \\
\hline
\textbf{Col1} & \textbf{Col2} & \textbf{Col3\tnote{*}} & \textbf{Col4} & \textbf{Col5} & \textbf{Col6\tnote{}} \\
\hline
\endfirsthead
\multicolumn{6}{l}{\tablename\ \thetable:
\textit{AAAAAAAAAAAAAAA}(Cont\ldots)}\\
\hline
\textbf{Col1} & \textbf{Col2} & \textbf{Col3} & \textbf{Col4} & \textbf{Col5} & \textbf{Col6} \\
\hline
\endhead
\hline \multicolumn{6}{l}{}\\
\endfoot
\insertTableNotes
\endlastfoot
\multirow{3}{*}{23412} & AAAA & A & AAAAAAA & AAAAAAA & A \\
                       & AAAA & A & AAAAAAA & AAAAAAA & A \\
                       & AAAA & A & AAAAAAA & AAAAAAA & A \\
\hline
\multirow{3}{*}{23412} & AAAA & A & AAAAAAA & AAAAAAA & A \\
                       & AAAA & A & AAAAAAA & AAAAAAA & A \\
                       & AAAA & A & AAAAAAA & AAAAAAA & A \\
\hline
\multirow{3}{*}{23412} & AAAA & A & AAAAAAA & AAAAAAA & A \\
                       & AAAA & A & AAAAAAA & AAAAAAA & A \\
                       & AAAA & A & AAAAAAA & AAAAAAA & A \\
\hline
\multirow{3}{*}{23412} & AAAA & A & AAAAAAA & AAAAAAA & A \\
                       & AAAA & A & AAAAAAA & AAAAAAA & A \\
                       & AAAA & A & AAAAAAA & AAAAAAA & A \\
\hline
\multirow{3}{*}{23412} & AAAA & A & AAAAAAA & AAAAAAA & A \\
                       & AAAA & A & AAAAAAA & AAAAAAA & A \\
                       & AAAA & A & AAAAAAA & AAAAAAA & A \\
\hline
\multirow{3}{*}{23412} & AAAA & A & AAAAAAA & AAAAAAA & A \\
                       & AAAA & A & AAAAAAA & AAAAAAA & A \\
                       & AAAA & A & AAAAAAA & AAAAAAA & A \\
\hline
\multirow{3}{*}{23412} & AAAA & A & AAAAAAA & AAAAAAA & A \\
                       & AAAA & A & AAAAAAA & AAAAAAA & A \\
                       & AAAA & A & AAAAAAA & AAAAAAA & A \\
\hline
\multirow{3}{*}{23412} & AAAA & A & AAAAAAA & AAAAAAA & A \\
                       & AAAA & A & AAAAAAA & AAAAAAA & A \\
                       & AAAA & A & AAAAAAA & AAAAAAA & A \\
\hline
\multirow{3}{*}{23412} & AAAA & A & AAAAAAA & AAAAAAA & A \\
                       & AAAA & A & AAAAAAA & AAAAAAA & A \\
                       & AAAA & A & AAAAAAA & AAAAAAA & A \\
\hline
\multirow{3}{*}{23412} & AAAA & A & AAAAAAA & AAAAAAA & A \\
                       & AAAA & A & AAAAAAA & AAAAAAA & A \\
                       & AAAA & A & AAAAAAA & AAAAAAA & A \\
\hline
\multirow{3}{*}{23412} & AAAA & A & AAAAAAA & AAAAAAA & A \\
                       & AAAA & A & AAAAAAA & AAAAAAA & A \\
                       & AAAA & A & AAAAAAA & AAAAAAA & A \\
\hline
\multirow{3}{*}{23412} & AAAA & A & AAAAAAA & AAAAAAA & A \\
                       & AAAA & A & AAAAAAA & AAAAAAA & A \\
                       & AAAA & A & AAAAAAA & AAAAAAA & A \\
\hline
\multirow{3}{*}{23412} & AAAA & A & AAAAAAA & AAAAAAA & A \\
                       & AAAA & A & AAAAAAA & AAAAAAA & A \\
                       & AAAA & A & AAAAAAA & AAAAAAA & A \\
\hline

\end{longtable}
\end{ThreePartTable}

\begin{table}[!ht]
\centering
\caption{AAAAAAAAAAAAAAAAAAAA}

\begin{minipage}{\textwidth}
\renewcommand*{\thempfootnote}{\fnsymbol{mpfootnote}}

\begin{tabular}{|l|l|l|l|l|l|}
\hline
\textbf{Col1} & \textbf{Col2} & \textbf{Col3\footnote[1]{A note adsfasdf}} & \textbf{Col4} & \textbf{Col5} & \textbf{Col6\footnote[0]{Another note asdfasfasd}} \\
\hline
AAAAAA & AAAAAA & A & AAAAAA & AAAAAA & A \\
\hline
AAAAAA & AAAAAA & A & AAAAAA & AAAAAA & A  \\
\hline
AAAAAA & AAAAAA & A & AAAAAA & AAAAAA & A  \\
\hline
AAAAAA & AAAAAA & A & AAAAAA & AAAAAA & A \\
\hline
\end{tabular}
\end{minipage}
\end{table}
\end{document}

Thanks in advance!

A: Problem solved thanks to Bernard!
The way for put a horizontal line above the footnotes using ThreePartTable (and would be similar like minipage environment' footnotes) is:
\noalign {\rule [-1.4ex]{6.7cm}{0.4pt}}


text:
Q: JAXB MOXy external bindings file not being read I want to use external bindings so that I can have multiple xml configurations for the same java classes without using annotations in the code. The problem is my program does not seem to use the external bindings file that I use and instead just does default unmarshalling/marshalling.
I have the following classes:
Customer.java
@XmlRootElement(name="customer")
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {

    private String firstName;
    private String lastName;
    private Address address;
    private List<PhoneNumber> phoneNumbers;

//getters and setters

Address.java
public class Address {

    private String street;
    //getters and setters
}

PhoneNumber.java
public class PhoneNumber {

    private String type;
    private String number;
    //getters and setters
}

Demo.java
public class Demo {

    public static void main(String[] args) throws Exception {

        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        InputStream iStream = classLoader.getResourceAsStream("src/blog/bindingfile/binding.xml");
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, iStream);
        JAXBContext jc = JAXBContext.newInstance(new Class[] {Customer.class}, properties);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        StreamSource xml = new StreamSource("src/blog/bindingfile/input.xml");
        Customer customer = unmarshaller.unmarshal(xml, Customer.class).getValue();

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(customer, System.out);
  }

I also tried an alternative version of Demo.java
public class Demo {

    public static void main(String[] args) throws Exception {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        InputStream iStream = classLoader.getResourceAsStream("src/blog/bindingfile/binding.xml");
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, iStream);
        JAXBContext jc = JAXBContext.newInstance(new Class[] {Customer.class} , properties);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        Customer customer = (Customer) unmarshaller.unmarshal(new File("src/blog/bindingfile/input.xml"));

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(customer, System.out);
}

My Binding.xml is as follows:
<?xml version="1.0"?>
<xml-bindings
    xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
    package-name="blog.bindingfile">
    <xml-schema
        namespace="http://www.example.com/customer"
        element-form-default="QUALIFIED"/>
    <java-types>
        <java-type name="Customer">
            <xml-root-element/>
            <xml-type prop-order="firstName lastName address phoneNumbers"/>
            <java-attributes>
                <xml-element java-attribute="firstName" name="first-name"/>
                <xml-element java-attribute="lastName" name="last-name"/>
                <xml-element java-attribute="phoneNumbers" name="phone-number"/>
            </java-attributes>
        </java-type>
        <java-type name="PhoneNumber">
            <java-attributes>
                <xml-attribute java-attribute="type"/>
                <xml-value java-attribute="number"/>
            </java-attributes>
        </java-type>
    </java-types>
</xml-bindings>

And the input.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<customer>
    <first-name>Jane</first-name>
    <last-name>Doe</last-name>
    <address>
        <street>123 A Street</street>
    </address>
    <phone-number type="work">555-1111</phone-number>
    <phone-number type="cell">555-2222</phone-number>
</customer>

Whatever Demo.java I use the output I get is:
<?xml version="1.0" encoding="UTF-8"?>
<customer>
   <address>
      <street>123 A Street</street>
   </address>
</customer>

Can someone please tell me what I am doing wrong. I noticed that no matter what I pass in as the binding.xml (even if the file doesn't exist) it doesn't complain.

A: The problem was in this line:
InputStream iStream = classLoader.getResourceAsStream("src/blog/bindingfile/binding.xml");

iStream was null. Because the program couldn't find the file. However it will not throw any exceptions.
Then this null InputStream was passed into
    properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, iStream);
    JAXBContext jc = JAXBContext.newInstance(new Class[] {Customer.class} , properties)

Again no exceptions are thrown, therefore the unmarshaller/marshaller does the unmarshalling/marshalling using the default rules and so we get the xml output shown in the question.
The file error was fixed by adding a new folder (resources) at the src folder level and then moving the binding.xml file there. Then the path was resources/binding.xml. Even using the full path did not work for me

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a way to find out if a number contains a specific decimal digit from its binary representation? If the number has 2 on it: starting from 2 >> 0000 0010, 12 >> 0000 1100,  20 >> 0001 0100 and so on.
I tried to figure out a relationship whether the number contains e.g. 2 and the number of one's and their position on its binary representation? Is there a relationship in the first place?

A: There is a relationship, of course. Just continue listing all numbers with $2$ in their decimal representations, and give the binary for each, and you have the members of that relationship.
To derive an algorithm that will allow you to deduce whether there is a $2$ in the decimal representation of some binary number, without converting the binary number to decimal or consulting a list such as the one described in the last paragraph, is a harder question.
For example, the binary representation of $20\,000\,000_\mathrm{ten}$
is $1001100010010110100000000_\mathrm{two}.$
There are eight $1$s in that representation, and if we change the binary
number just by changing any of these $1$s to a $0,$
the decimal representation will not have a $2$ in the $10^7$ place.
On the other hand, we can change some of the $1$s to zero and still have a
$2$ in the $10^7$ place, provided that we change certain $0$s to $1$s.
In short, if we have a large binary number,
we have to look at more than eight bits of the binary number
in order to determine whether there is a $2$ in the $10^7$ place
of the decimal representation of that number.
It is actually worse than this sounds, because powers of $2$ typically have non-zero digits in most places of their decimal representations,
so when you change the binary digit of a large number that corresponds
to such a power of $2,$ it changes most of the digits of the decimal
representation of that number in places that are less than that power of $2.$
That means that whether a $2$ occurs at the $10^n$ position in a decimal number depends not only on many of the digits that would occur in the binary representation of $10^n,$ but also on many of the digits to their left.
I also discuss the question of determining a digit of a number in
this answer.
In short, if you want to see whether a particular digit of the decimal representation of a binary number will be a $2,$ the number of digits of the binary number that you will have to examine is limited only by the size of the binary number itself.
As for whether there is some pattern in the digits that you can use
to easily evaluate whether all these binary digits somehow determine a
$2$ in the decimal representation: if anyone had found such a pattern
that is easier to apply than simply converting the number to decimal,
we would already be using it to make binary-to-decimal or decimal-to-binary
conversions easier.
This is not a rigorous proof that no such "easy" method exists, but the prospects to find one do not look good.


text:
Q: How do i avoid, that the domain layer knows the adapters? Let's say i have a usecase (business logic), an adapter (database) and a domain object. I need to call the database from my domain logic, but the question is how. The way a do it right now is by giving the domain the adapter: (1. variant)
function usecase(adapter, domain):
     domain(adapter)

function domain(adapter):
    [some logic]...
    adapter.save_to_database()
    [more logic]...

call usecase(adapter, domain)

Now in order to avoid letting the domain logic know the adapter, i would need to return all data and call the adapter from the usecase: (2. variant)
function usecase(adapter, domain):
     data = domain.some_logic()
     other_data = adapter.save_to_database(data)
     domain.more_logic(other_data)

call usecase()

So, everytime i use an adapter, i need to exit the domain, in order to call the adapter. Is that correct? If, so why is it better than the solution above?

A: In your first variant, you can call the "infrastructure" layer from the domain layer. But when you call it from the domain, you have only to use an interface (@see Dependency inversion principle, API, SPI).
If you want to call the infrastructure layer from the use case (application layer), it's possible. But prefer the first solution when you have business logic in your feature.
Some rules :

*

*when you have business logic, use the domain layer even if you call the infrastructure layer.

*when you don't have business logic, you can call the infrastructure from the application layer.


text:
Q: Passing state from one component to another with React language switch I am translating my React App with headless CMS. I have a language switcher in my navbar and on each component has to be the specified language.
The language Switcher logic:
const [selected, setSelected] = useState('en-us');

const handleEnglish = () => {
    cookies.set('chosenLang', 'en-us');
    setSelected('en-us');
};

<button onClick={handleEnglish}>EN</button>

const handleFrench = () => {
    cookies.set('chosenLang', 'fr-fr');
    setSelected('fr-fr');
};

<button onClick={handleFrench}>FR</button>

And logic in component based on which the language is recognised (pretty simple):
{lang: selected}

This works, but just because the language switcher is in the same file as translated component. Once I created separate component for navbar (where is the lang switch) it does not work and I don't know how to pass the state of it to other components)
I tried in my page component to do something like <Navbar {...selected} />, how I would normally pass the props but no luck with that.

A: Just use the context API, the selected language state is available only locally in that component.
https://reactjs.org/docs/context.html#when-to-use-context

A: You can do like this:
https://codesandbox.io/s/languagecontext-example-t33pm
You can you context or redux, react-redux to share state between components across app.


text:
Q: How to run multiple applications on the same server in rails? I want run more than one application on rails server so I user following command:
Command :
 rails s 3001

But it is not working

A: You can use :
rails s -p 3001

or
rails s -b 0.0.0.0 -p 3001


text:
Q: Loop corrections to propagator (QFT of Srednicki) Perhaps this is a very basic question.
In chapter 14 of Srednicki's QFT textbook (2007), $O(g^2)$ loop corrections to the propagator of $\phi^3$ theory is discussed. However, I don't know how to derive the Eq. 14.34 on page 103 (I can't present the full context as it would be too long).
From
\begin{equation}
\Pi(k^2)=\frac{1}{2}\alpha\Gamma(-1+\epsilon/2)\int_0^1\,dxD(4\pi\mu^2/D)^{\epsilon/2}-Ak^2-Bm^2+O(\alpha^2),   (14.32)
\end{equation}
and take the $\epsilon \rightarrow 0$ limit using
\begin{equation}
A^{\epsilon/2}=1+\frac{\epsilon}{2}ln(A)+O(\epsilon^2)
\end{equation}
and the following property of Gamma functions
\begin{equation}
\Gamma(-n+x)=\frac{(-1)^n}{n!}\left[\frac{1}{x}-\gamma+\sum_{k=1}^nk^{-1}+O(x)\right],
\end{equation}
he got
\begin{equation}
\Pi(k^2)=-\frac{1}{2}\alpha\left[\left(\frac{2}{\epsilon}+1\right)\left(\frac{1}{6}k^2+m^2\right)+\int_0^1\,dxDln\left(\frac{4\pi\mu^2}{e^\gamma D}\right)\right]-Ak^2-Bm^2+O(\alpha^2), \qquad (14.34)
\end{equation}
where $\alpha\equiv\frac{g^2}{(4\pi)^3}$.
I don't know how to do the integral correctly (although it seems elementary). Can anyone familiar with this part help me out?

A: I find it's not a problem if one simply omits the $O(\epsilon)$ terms since we are taking the $\epsilon \rightarrow 0$ limit. The author just didn't state it clearly.


text:
Q: Android Studio build.gradle compile error I'm using a the MPAndroidChart to plot graphs in my android application. I am doing a radar plot, a pie chart and a line graph. My problem is that the radar plot needs a different version of this library which does not work for the other two plots.
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.2.0'
compile 'com.android.support:support-v4:24.2.0'

compile 'com.github.PhilJay:MPAndroidChart:v3.0.1'

compile 'com.github.PhilJay:MPAndroidChart:v2.1.6'

}

As you can see in my dependancies I compile two different versions. This causes errors and only one of them will work therefore either the radar plot will not work, or else the other two won't work.
Does anyone know how I can compile two versions of the same library?

A: To download multiple version of the same library:
repositories {
  mavenCentral()
}

configurations {
  compile5
  compile6
}

dependencies {
  compile5 'org.osgi:org.osgi.core:5.0.0'
  compile6 'org.osgi:org.osgi.core:6.0.0'
}

task libs(type: Sync) {
  from configurations.compile5
  from configurations.compile6
  into "$buildDir/libs"
}

You can check
How to get Multiple Versions of the same library

A: There were major changes with MPCharts in v3.0.0 vs 2.x.x.
I think you would be better off using the latest library and adjusting the two charts that are not working properly.


text:
Q: Bash -c with Java Process API I've been messing about with the java process API and ran into the following case:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException, InterruptedException {
        var command = "echo foo";
        System.out.println(command);
        run(command);

        command = "bash -c 'echo bar'";
        System.out.println(command);
        run(command);
    }

    public static void run(String command) throws IOException, InterruptedException {
        Process p = Runtime.getRuntime().exec(command);
        p.waitFor();
        var br = new BufferedReader(new InputStreamReader(p.getInputStream()));
        br.lines().forEach(System.out::println);
    }
}

Why does bar not print? I've also tried other commands like systemctl poweroff and mkdir, but none seem to execute. I've also experimented with nohup, which works on its own but not with bash -c.

A: You call exec(String), which in turn calls exec(String,String,File), which in turn uses a StringTokenizer to chop the command line passed as a single string into an argument list, and then calls exec(String[],String,File).
However, that tokenizer just chops at spaces (it doesn't know that it's working with a command line or what shell would be involved). That means you end up with these tokens as the command: bash, -c, 'echo, foo' --- note the single quotes; Runtime.exec does not involve a shell to handle quotes (or variable substitution or such).
bash then complains about the 'echo, but you don't see that cause you only print the child process' stdout, but not stderr. Add code like this to run:
br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
System.out.println("stderr:");
br.lines().forEach(System.out::println);

This gets me:
stderr:
bar': -c: line 1: unexpected EOF while looking for matching `''
bar': -c: line 2: syntax error: unexpected end of file

Now if you remove the single quotes from the call, you just get a single empty line because bash -c expects only one argument to run, which here is the echo, which prints a new line.
To fix this, you need to call the exec version that takes a String[] directly so that you control what is one argument:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException, InterruptedException {
        run("echo", "foo");
        run("bash", "-c", "echo bar");
    }

    public static void run(String... command) throws IOException, InterruptedException {
        Process p = Runtime.getRuntime().exec(command);
        p.waitFor();
        var br = new BufferedReader(new InputStreamReader(p.getInputStream()));
        System.out.println("stdout:");
        br.lines().forEach(System.out::println);

        br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        System.out.println("stderr:");
        br.lines().forEach(System.out::println);
    }
}

A: Personally, I'd use something higher level like the standard ProcessBuilder class or the exec library from Apache Commons instead, as they have better support for building complicated commands to execute:
import java.io.IOException;
import org.apache.commons.exec.*;

public class ExecDemo {
    // Build and execute a command with Apache Commons Exec
    private static void demoApacheExec()
        throws IOException, ExecuteException {
        var cmd = new CommandLine("sh");
        cmd.addArgument("-c");
        cmd.addArgument("echo test 1", false);
        System.out.println("Command: " + cmd);

        var executor = new DefaultExecutor();
        executor.execute(cmd);
    }

    // Build and execute a command with ProcessBuilder
    private static void demoProcessBuilder()
        throws IOException, InterruptedException {
        // Can also take a List<String> of arguments
        var pb = new ProcessBuilder("sh", "-c", "echo test 2").inheritIO();
        System.out.println("Command: " + pb.command());

        pb.start().waitFor();
    }

    public static void main(String[] args) {
        try {
            demoApacheExec();
            demoProcessBuilder();
        } catch (Exception e) {
            System.err.println("Error executing program: " + e);
            System.exit(1);
        }
    }
}

The important thing is making each argument its own separate thing instead of relying on trying to parse a single string like a shell would (A.C.E has a CommandLine.parse() function, but even it has issues with quoting; addArgument likes to put actual quotes around arguments with spaces in them when it doesn't actually need to unless you tell it not to.).


text:
Q: How to select column values based on the presence of a certain value in another column I have a list of projects, and different companies bidding for those projects.
project_name   company_name
___________________________
    abc      |        1
    abc      |        2
    abc      |        3
    def      |        9
    def      |        7
    ghi      |        8
    jkl      |        1
    jkl      |        5
    jkl      |        6
    jkl      |        7

I want to keep only the projects where company "1" is present, while also keeping the other competitors for the project. The desired result is:
project_name   company_name
___________________________
    abc      |        1
    abc      |        2
    abc      |        3
    jkl      |        1
    jkl      |        5
    jkl      |        6
    jkl      |        7

I have a feeling a subquery after WHERE is required to get that result, but I can't figure it out.

A: You can use exists:
select p.*
from projects p
where exists (select 1
              from projects p2
              where p2.project_name = p.project_name and
                    p2.company_name = 1
             );

A: Another option is window functions, often more efficient as it only requires one scan of the table. We can use a conditional count here:
select p.*
from (
    select *,
        count(case when company_name = 1 then 1 end) over (partition by project_name) hasCompany1
    from projects
) p
where hasCompany1 > 0;

A: This is the simplest query should work for this case:
select p.*
from projects p
where p.project_name in (select project_name from projects where company_name = 1)


text:
Q: factorial method doesn't work well! Hi
this is a factorial method but it prints 0 in the console please help me thanks
public class Demo {

    public static void main(String[] args) {
        Demo obj = new Demo();
        System.out.println(obj.factorial(500));
    }

    public int factorial(int n) {
        int fact = 1;

        for (int i = 2; i <= n; i++) {
            fact= fact*i;
        }
        return fact;
    }

EDITED:will return Infinity!
public class Demo {

    public static void main(String[] args) {
        Demo obj = new Demo();
        System.out.println(obj.factorial(500));
    }

    public double  factorial(long n) {
       double fact = 1;

        for (int i = 2; i <= n; i++) {
            fact= fact*i;
        }
        return fact;
    }
}

A: There's no way you can fit 500! on a 32-bit int.
For calculations involving large numbers, consider using a double or a BigInteger, depending on whether you want an approximate or an exact answer.
(Actually, for 500!, even a double would not be enough: Double.MAX_VALUE is 1.7976931348623157E+308, which will "only" let you go up to 170!)

A: Since 500! equals 1220136825991110068701238785423046926253574342803192842192413588385845373153881997605496447502203281863013616477148203584163378722078177200480785205159329285477907571939330603772960859086270429174547882424912726344305670173270769461062802310452644218878789465754777149863494367781037644274033827365397471386477878495438489595537537990423241061271326984327745715546309977202781014561081188373709531016356324432987029563896628911658974769572087926928871281780070265174507768410719624390394322536422605234945850129918571501248706961568141625359056693423813008856249246891564126775654481886506593847951775360894005745238940335798476363944905313062323749066445048824665075946735862074637925184200459369692981022263971952597190945217823331756934581508552332820762820023402626907898342451712006207714640979456116127629145951237229913340169552363850942885592018727433795173014586357570828355780158735432768888680120399882384702151467605445407663535984174430480128938313896881639487469658817504506926365338175055478128640000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 you can't fit it into an int (which ranges up to 2147483647).

*

*Using an int you can only store up to 12!.

*Using a long you'll get up to 20!

*Using a double you'll get up to 170!.

*By convention 0! equals 1;

Here is a solution using BigInteger:
public static BigInteger factorial(int i) {
    if (i == 0) {
        return BigInteger.ONE;
    }
    BigInteger n = BigInteger.valueOf(i);
    while (--i > 0) {
        n = n.multiply(BigInteger.valueOf(i));
    }
    return n;
}

A: There are two things you should be looking into if you need to calculate the factorial function:
1) Memoization. This will dramatically speed up your calculations, since the factorial function has a recursive definition. What you do is cache previous calculations, so when you ask for k!, you can get it in one step by calculating k*((k-1)!) if you have (k-1)! cached.
2) Stirling's approximation. If you need to calculate large factorials, you can approximate them very rapidly this way, and with guaranteed bounds on the error, so you can tell whether the approximation will be acceptably close for your application.
If you do neither of these, you will find that there is some relatively small k for which you simply can't calculate k! in a reasonable amount of time.

A: Grodriguez is right - this is almost certainly caused by integer overflow.
If you test your method with more modest inputs it appears to return the right output:
public static void main(String[] args) {
   Demo obj = new Demo();
   for (int i = 0; i < 10; i++)
      System.out.println(i + "! = " + obj.factorial(i));
}

500! is massive; when testing your function, starting with smaller inputs would be prudent.

A: 500! is way too big to fit a long, or double.
You would have to use other techniques to get this.
But first, what kind of program needs 500!?

A: There are some very nice optimization for the implementation of factorizations: see for instance luschny.de for a nice implementation of them in Java. Some require more mathematical insight then others... Have fun with the library :-)


text: Q: Can substitution rules be compiled? I am thinking of having a custom multiplication operation CenterDot[A,B] for non-commutative operators, and some rules that should commute the operators to a desired ordering. The calculation would be very time intensive, while manipulations would just be trivial swapping of entries and addition of other entries. Therefore, I wonder if there is any (perhaps hacky?) way to Compile a code of this type in Mathematica? Thanks for any suggestion!


text:
Q: Equal Image Method Java I'm trying to write a method to test if pixel by pixel two images are equal, and a lot of the ways I'm seeing are really complicated and above my knowledge. This is the way I'm trying to do it, but I'm getting errors:
public boolean equals(Object other)
{
    if(!(other instanceof MyArt))
    {
        return false;
    }
    MyArt otherArtObject = (MyArt)other;
    for(int x = 0; x < image.getWidth(); x++)
    {
        for(int y = 0; y < image.getHeight(); y++)
        {
            Pixel pixelObj = this.image.getPixel(x,y);
            Pixel otherPixelObj = otherArtObject.image.getPixel(x,y);
            if((pixelObj == otherPixelObj)&&(pixelObj.getRed()==otherPixelObj.getRed())&&(pixelObj.getBlue()==otherPixelObj.getBlue())&&(pixelObj.getGreen()==otherPixelObj.getGreen()))
            {
                return true;
            }
        }
    }
    return false;
}

The my art class just creates another image. So it creates another object, and then if the two objects are equal, and the red, green and blue, values are equivalent it returns true. If not it returns false. Thanks for any input!

A: That code will return true if the first pixel (0,0) is the same reference (see pixelObj == otherPixelObj) and does not bother checking the rest. Is that what you want?
I recommend you push the pixels equals up into pixel as it would make the code more readable. I might even push the loop up into the image class.
What tests do you have for this class? Do you have any that use different sized images?


text:
Q: Unable to update guest OS hard drive size I am running VMWare Fusion 6.0.4 on OS X 10.10.3.  I have Windows 7 as the guest OS.  Originally I had the hard drive set to 60GB. It was running out of space so I increased it to 100GB.  However, Windows 7 still thinks there is only 60GB on the C: drive.  Fusion thinks there is 100, on the Windows side, in disk management, Disk0 is listed as 100GB, but the C: volume is 60GB and the option to extend it is greyed out.  How do I get my 40GB to be recognized?

A: There is lots of useful information in this VMWare Knowledge Base Article:
http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1004071


text:
Q: How to determine which network interface VPN is connecting through? I help manage several remote systems that automatically connect to our VPN server when they boot using openvpn. At some of the sites, they connect to both the eth0 and wlan0 network interfaces but I do not know how to tell which interface the tun0 interface is being routed through. Any advice on how to determine this? I don't want to remotely disable one or the other interface to check as I could lose my ability to log back and re-enable it.

A: Here are some possibilities:

*

*netstat -r will provide you with a breakdown of your network connections and the gateways.  In most cases the one with the gateway 0.0.0.0 is likely the device through which the VPN will be active.

*sudo netwatch -e tun0 -nt will also provide useful information for monitoring device behavior. You could attempt to use telnet to send a quick message and monitor the eth0 and wlan0 using netwatch and see which sends the text in an encrypted format.

*last resort: list devices using nmcli c. Get the long device {UUID#} from the list then turn one off using nmcli c down {UUID#} and see which one breaks your VPN tunnel. Restore with nmcli c up {UUID#} You could use chron to automatically reissue the nmcli c up {UUID#} or restart to ensure it comes back up after a given period--provided the VPN is setup to automatically reconnect to the interface.

Best Luck!


text:
Q: 360 videos on IE I have been trying to explore the possibility of playing 360 degrees videos on Internet Explorer. I am using A-Frame/angular to render all my videos on other browsers and they work well except on IE they play flat.
I recently bumped into Youtube 360 videos on IE11 and was wondering how they achieve that feat. I checked some other websites like Facebook on IE and they play flat.
Is it possible to play 360 videos on IE ? How is youtube doing it? Any ideas would really help me in my research further.

A: A-Frame supports VR for any browser that implements the WebVR specification. The list of supported browsers can be found here in the A-Frame docs, Microsoft Edge is listed, IE is not: https://aframe.io/docs/0.7.0/introduction/vr-headsets-and-webvr-browsers.html


text:
Q: Android Volley - Updating cached request after a HTTP POST I have a cached request which returns me a list of items. I create a new item via a HTTP POST which needs to be added to the list. A trivial way to get the new list of items would be to invalidate the cache and re-do the request. But a more optimal way would be to add the item I just created to the already cached request so that I do not have to a network request.
How can I add an item to an existing request cache? If not is there a better approach to do this?

A: Well, to update the cache is not the best idea. In onResponse you should take the response - whatever it is and store it in your data structure. For example some list. and just add there new data received with new http Post.
You can alway access the cache with url of the request.


text:
Q: Tableau Trend line -date calculations I have dimension as date,  --(Date has discrete dates- some dates from this months , some dates from last  and so on - with data.)
more dimensions are : Team name & Team ID
other dimension is Result.
Result column has value : pass or fail  ---only two values.
below data gets refreshed everyday.
date      Team name Team ID Result
24/07/2008  lol      458    pass
27/01/2017  pop     1478    fail
28/02/2018  laugh     99    pass
and so on

I want to show dates on x axis, Result : Pass or Fail on trend-lines .
what would be my Y axis?
Want to show pass or fail team ID wise on trend lines!
If its December month then team ID  which have passed /failed for 31st of December 2017 should show up.
similarly for Jan month (team ID )  which have passed or failed should show of 31st jan 2018.
AND for Feb month it should show pass / fail for current date --- {Team count pass or fail for particular current day}
please help with calculated filed calculations

A: Try This:
if Date= today() then 1
elseif dateadd('day',-
day(DATEADD('month',1,Date)),DATEADD('month',1,Date))=Date then 1
else 0

than set filter to 1


text:
Q: Java SWT Key, MouseWheel Listener I added a "KeyListener" to Shell for changing FullScreen or not.
Also I added a "MouseWheelListener" to GLCanvas for changing its depth.
But there is a problem that if I enable the KeyLisetner in Shell, the MouseWheelListener doesn't work.
If I disable the other one, the KeyListener doesn't work either.
What may cause it?
code:
http://codepad.org/4V5ExY27      shell
http://codepad.org/BYnTWlMf      mouse wheel
thanks.


text:
Q: Sum columns with the same prefix in SQL Server I think it's a really basic question, but I couldn't find the answer how to do it in SQL Server.
I have a table:

ID
Pref_01
Pref_02
...
Pref_40

01
5
2
...
7

02
6
7
...
5

I want my output to contain two columns: ID, Sum_pref with the sum of columns which names stars with "pref". I know how to do it in R or SQL in SAS but now I have to do it in SQL Server and I'm stuck. I will be greatful for any help.

A: Please try the following solution.
It is using SQL Server's XML and XQuery functionality to achieve what you need.
Notable points:

*

*1st CROSS APPLY is tokenizing columns for each row as XML.

*2nd CROSS APPLY is summarizing values where XML element names (and original column names) are matching a particular naming convention.

SQL
-- DDL and sample data population, start
DECLARE @tbl TABLE (id INT IDENTITY PRIMARY KEY, Pref_01 INT, Pref_02 INT, Pref_40 INT);
INSERT @tbl (Pref_01, Pref_02, Pref_40) VALUES
(5, 2, 7),
(6, 7, 5);
-- DDL and sample data population, end

SELECT t.*
   , [sum-columns-across-the-row]
FROM @tbl AS t
CROSS APPLY (SELECT t.* FOR XML PATH(''), TYPE, ROOT('root')) AS t1(x)
CROSS APPLY (SELECT x.value('sum(/root/*[contains(local-name(), "Pref_")]/text()) cast as xs:integer?', 'INT')) AS t2([sum-columns-across-the-row]);

Output

id
Pref_01
Pref_02
Pref_40
sum-columns-across-the-row

1
5
2
7
14

2
6
7
5
18


text:
Q: What submit type to use in Gerrit with a branching workflow? First some information:
1 base code in master branch
3 branches with projects that use the same base code, but have different looks / and some different code.
Workflow:

*

*Work on branch 1/2/3

*

*Not necessary to rebase, just commit and push to remote git rep

*Review on gerrit and merge

*Work on base code on master branch

*

*rebase all branches on master branch

*push to remote git rep

*review on gerrit merge/rebase

So my question is:
What Submit type is the best fit for this kind of workflow?

*

*Fast forward only

*merge if necessary

*Rebase if necessary

*Always merge

*Cherry pick


text:
Q: List Index Out Of Bounds when deleting elements from TObjectList I got a small but annoying problem with my Delphi School Project. At school we have to use Delphi 5 (I know, very modern) and to be able to work on it on my own without running into major annoyances, I use Delphi 7 here instead of Lazarus.
I am trying to code a small Space Invaders project with the limited OpenGL knowledge we got taught in our lessons and I am running into the problem when checking the collisions between the bullets the player shoots and the enemies.
The Collision Detection Code actually works and counts hits accordingly but when it has to delete the enemy & the bullet from a List (so that they won't be rendered anymore), the List Index Out Of Bounds Error occurs.
procedure TForm1.CheckCollision(enemies, bullets: TObjectList);
var ll, kk: integer;
begin
  for ll := Form1.bullets.Count-1 downto 0 do
  begin
      for kk := Form1.enemies.Count-1 downto 0 do
      begin
        if TBullet(Form1.bullets[ll]).tby1 >= TEnemy(Form1.enemies[kk]).tey1 then
        begin
          if TBullet(Form1.bullets[ll]).tbx2 > TEnemy(Form1.enemies[kk]).tex1 then
          begin
            if TBullet(Form1.bullets[ll]).tbx1 < TEnemy(Form1.enemies[kk]).tex1 + 0.05 then
              begin
                if TBullet(Form1.bullets[ll]).tby1 <= TEnemy(Form1.enemies[kk]).tey2 then
                begin
                  Form1.enemies.Delete(kk); //error happens here and line below
                  Form1.bullets.Delete(ll);
                  inc(score);
                end;
              end;
          end;
        end;
      end;
  end;
end;

This is the code where this error occurs. I do kinda know what this error means but I don't know how to fix it in this instance. The funny thing is, that while in the .exe of this project this error still happens, both the bullet and enemy get deleted and your score gets increased, you just have to quickly press OK after the error message appears and you can continue playing. In Delphi, the program stops after the error obviously.
Hope you guys might be able to help me out here.

A: Bullet[ll] is deleted in the first kk loop. Hence, in subsequent kk loops, bullet[ll] no longer exists (i.e ll - 1 is "highest" existing index)...


text:
Q: comparing 2 dates with javascript I want to compare 2 dates in the following format shown below in variables a and b . I want to check if a is greater than b but the code below isnt working since its not a regular number
var a = "4/29/2015";
var b = "4/10/2015";

if(a > b){
alert("working");
}

A: Convert the strings to Date objects.

var a = new Date("4/29/2015");
var b = new Date("4/10/2015");

if (a > b) {
  console.log(a + " is greater than " + b);
}

A: Use javascript's Date object:

//2nd Argument month goes from 0(January) to 11(December)
var a = new Date(2015, 3, 29);
var b = new Date(2015, 3, 10);

if(a > b){
  alert("working");
}


text:
Q: how to open a link in a view for phonegap? i want to open a link in a view,something like http://google.com . i tried it with iframe src="" but when i run it on iphone it opens in webview so i unable see header and footer.

xxx

yyy

when i open this page it directly opens google in a webview, my intention is to open when i click 'yyy'. i need it to run in iphone also.

A: Download the content of url and on button click load in view
    NSData *d = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];
    NSString *s = [[NSString alloc] initWithData:d encoding:NSUTF8StringEncoding];
    //load string s in view
    textView.text = s;

A: if you can use javascript, try with
window.open("www.google.com");

in your html will be:


text:
Q: Delay Returns with NSubstitute I have an interface IDiscosClient, for testing/demo purposes while I'm developing the app, I want a mock to return a new model when the .GetSingle<T>() method is called with a random delay of between 1 and 5 seconds. This is mostly so I can see that all of my various loading spinner components and whatnot work.
So, I thought I'd be able to do something like this:
Fixture fixture = new();
fixture.Customize(new DiscosModelFixtureCustomizationNoLinks());

builder.Services.AddTransient(_ =>
                              {
                                  IDiscosClient client = Substitute.For<IDiscosClient>();
                                  DiscosObject  obj    = fixture.Create<DiscosObject>();
                                  client.GetSingle<DiscosObject>(Arg.Any<string>()).Returns(Task.Delay(Random.Shared.Next(1000,5000)).ContinueWith(_ => obj));
                                  return client;
                              });

However, while there seems to be a delay when I first call the method, once this has resolved, it just seems to return the completed task with the same model in it every time I call it for that IDiscosClient instance.
Is there a simple enough way to accomplish this?

A: So the issue is that the code above only creates a fresh Task the first time and then returns the same one (which has already completed) each subsequent time.
To fix this, we can either change the code above to:
client.GetSingle<DiscosObject>(Arg.Any<string>()).Returns(_ => Task.Delay(Random.Shared.Next(1000,5000)).ContinueWith(_ => obj));

Or, for legibilities sake, we can extract it into a method and make the whole code block:
builder.Services.AddTransient(_ =>
                              {
                                  IDiscosClient client = Substitute.For<IDiscosClient>();
                                  client.GetSingle<DiscosObject>(Arg.Any<string>()).Returns(GetDiscosObject);
                                  return client;
                              });

async Task<DiscosObject> GetDiscosObject(CallInfo _)
{
    await Task.Delay(Random.Shared.Next(1000, 5000));
    return fixture.Create<DiscosObject>();
}


text:
Q: Why is my R Function throwing an error I am trying to turn this piece of code into an R function
separea=quantile(foo6$area,seq(0,1,0.001),na.rm=T)
nb=length(separea)[1]-1
resultats=matrix(NA,nb,8)
for (count in 1:nb){
  print(c("area: ",separea[count] ))
  b=foo6[foo6$area >= separea[max(1,count-20)] & foo6$area <= separea[min(count+20,nb+1)],]
  q01 = quantile( b$nq , 0.01,na.rm=T)
  q10 = quantile( b$nq , 0.10,na.rm=T)
  q25 = quantile( b$nq , 0.25,na.rm=T)
  q50 = quantile( b$nq , 0.50,na.rm=T)
  q75 = quantile( b$nq , 0.75,na.rm=T)
  q90 = quantile( b$nq , 0.90,na.rm=T)
  q99 = quantile( b$nq , 0.99,na.rm=T)
  if(dim(b)[1]>100){
    resultats[count,]=cbind(separea[count],q01,q10,q25,q50,q75,q90,q99)
  }
}
resultats=resultats[!is.na(resultats[,1]),]
dim1=dim(resultats)[1]

And I wrote this function:
quantile.prep<-function(dframe,xvar,yvar){
  separea=quantile(dframe$xvar,seq(0,1,0.001),na.rm=T)
  nb=length(separea)[1]-1
  resultats=matrix(NA,nb,8)
  for (count in 1:nb){
    print(c("area: ",separea[count] ))
    b=dframe[dframe$xvar >= separea[max(1,count-20)] & dframe$area <= separea[min(count+20,nb+1)],]
    q01 = quantile( b$yvar , 0.01,na.rm=T)
    q10 = quantile( b$yvar , 0.10,na.rm=T)
    q25 = quantile( b$yvar , 0.25,na.rm=T)
    q50 = quantile( b$yvar , 0.50,na.rm=T)
    q75 = quantile( b$yvar , 0.75,na.rm=T)
    q90 = quantile( b$yvar , 0.90,na.rm=T)
    q99 = quantile( b$yvar , 0.99,na.rm=T)
    if(dim(b)[1]>100){
      resultats[count,]=cbind(separea[count],q01,q10,q25,q50,q75,q90,q99)
    }
  }
  resultats=resultats[!is.na(resultats[,1]),]
  dim1=dim(resultats)[1]
}

But I am getting this error: Error in dframe$xvar : $ operator is invalid for atomic vectors
When I call using quantile.prep(dframe='foo6',xvar='area',yvar='nq')
dput(droplevels(head(foo6)))

structure(list(area = c(162.6513, 162.6513, 162.6513, 162.6513,
162.6513, 162.6513), nq = c(0.140843018162167, 0.152855833307204,
0.193245919337872, 0.156860105022216, 0.171658019333384, 0.18628194179819
)), .Names = c("area", "nq"), row.names = c(NA, 6L), class = "data.frame")

Could you please help?
The proposed output
WORKING SOLUTION
quantile.prep<-function(dframe,xvar,yvar){
  separea=quantile(dframe[,xvar],seq(0,1,0.001),na.rm=T)
  nb=length(separea)[1]-1
  resultats=matrix(NA,nb,8)
  for (count in 1:nb){
    print(c("area: ",separea[count] ))
    b=dframe[dframe[,xvar]>= separea[max(1,count-20)] & dframe[,'xvar']<= separea[min(count+20,nb+1)],]
    q01 = quantile( b[,yvar] , 0.01,na.rm=T)
    q10 = quantile( b[,yvar] , 0.10,na.rm=T)
    q25 = quantile( b[,yvar] , 0.25,na.rm=T)
    q50 = quantile( b[,yvar] , 0.50,na.rm=T)
    q75 = quantile( b[,yvar] , 0.75,na.rm=T)
    q90 = quantile( b[,yvar] , 0.90,na.rm=T)
    q99 = quantile( b[,yvar] , 0.99,na.rm=T)
    if(dim(b)[1]>100){
      resultats[count,]=cbind(separea[count],q01,q10,q25,q50,q75,q90,q99)
    }
  }
  resultats=resultats[!is.na(resultats[,1]),]
  dim1=dim(resultats)[1]
}

A: Does this do what you want?
# An example data set
area = seq( log10(10), log10(10000), length.out=5000 )
discharge = seq(1,0.08,length.out=5000) + rnorm(5000, 0, 0.2)
df = data.frame( area=area, nq=discharge )

# Quick peak at the data
plot( df )

# Bin the data into 1,000 bins
# If I read your code right, you are essentially looking at
# a window of your data that has
# a width of of 40/1000*range(data[,"area"])
# You are looking at that window at 1,000 evenly spaced points
# along the x-axis (here saved as xout)
xout = seq( min(df[,"area"]), max(df[,"area"]), length.out=1000)
window.size = 40/1000*diff(range(df[,"area"]))
results = matrix(NA,nrow=length(xout),ncol=8) # allocate matrix that stores quantiles
for( i in seq_along(xout) ) {

  window = df[,"area"] < (xout[i] + window.size/2) &
           df[,"area"] > (xout[i] - window.size/2)
  values = df[window,"nq"]
  quantiles = quantile(values, probs=c(0.01,0.1,0.25,0.5,0.75,0.9,0.90), na.rm=TRUE )
  results[i,] = c(xout[i],quantiles)
}

# Now plot the results
library(reshape)
library(ggplot2)
colnames(results) = c("area","q01","q10","q25","q50","q75","q90","q99")
results = as.data.frame(results)
melted.results = melt(results, id.vars="area")
ggplot() +
  geom_point(data=df, aes(x=area,y=nq), alpha=0.15) +
  geom_line(data=melted.results,aes(x=area,y=value,group=variable,color=variable),size=2)


text:
Q: how to iterate one value twice in for loop (Python) I am having a problem in really simple program. My problem is that i lose value (y = 50 or 100 or 150) because at that time first condition is not valid. so how can i repeat loop for let say y = 50. (i don't want to use '=' e.g  y< = (50+increment) because this is just a dummy program.
thanks
increment = 0
b = 1
var = 0
for y in range(1,1000):
    if y>= increment and y< (50+increment):
        print(f'{y}  in List {b}')

    else:
        var = y
        increment += 50
        b+=1


text:
Q: Определённая последовательность добавляемых элементов в массив Есть, например, такой массив:
let arr_1 = [1, 2, 10, 4, 2, 8, 9, 3, 4, 3, 6, 3, 6, 7, 4]
Есть второй массив:
let arr_2 = [2, 11, 7, 4, 8]
Суть задачи в том, что должно быть что-то вроде сравнения массивов, из arr_1 нужно найти и добавить дубликаты чисел в arr_2, при этом не нарушая последовательности элементов arr_2, и при этом не должно исчезнуть число, которого нет в arr_1, то есть число 11 должно остаться в массиве.
Результат должен быть: [2, 2, 11, 7, 4, 4, 4, 8]
Если честно, уже ума не приложу как это сделать. Хотелось бы это как-то провернуть с помощью циклов без методов, чтобы разобраться.
Несколько стыдно показывать свои тщетные попытки с помощью г-нокода, но все же я выложу:
let step = [];

for (let i = 0; i < arr_1.length; i++) {
        for (let j = 0; j < arr_2.length; j++) {
            if (arr_1[i] == arr_2[j]) {
                step[i] = arr_1[i]
            }
        }
    }

// Результат: [empty, 2, empty, 2, 8, empty × 2, 4, empty × 4, 7, 4]

Потом нужно было избавиться от пустых ячеек:
let ident = step.join(',').replace(/,/g, '').split('').map(Number)

Затем надо было как-то добавить 11, это я уже делал с помощью indexOf:
    for (let i = 0; i < arr_2.length; i++) {
        if (ident.indexOf(arr_2[i]) === -1) {
            ident.push(arr_2[i])
        }
    }

    // Получается такая фигня: [2, 4, 2, 8, 4, 7, 4, 11]

Меня не устраивает порядок. Как работает push я знаю, последний код я написал для того, чтобы вообще хоть как-то удалось добавить недостающий элемент. Под конец совсем запутался, как дальше поступить - ума не приложу, и вообще как это сделать, поскольку вышенаписанный код явно не подходит для этого.
Помогите плз. Заранее спасибо.

A: *

*Создаём пустой массив, в который будем записывать числа в нужном порядке и в нужном количестве.

*Так как порядок должен совпасть с порядком второго массива, будем следовать по второму массиву, попутно совершая поиск в первом массиве и добавляя найденные.

*Если число в первом массиве отсутствует, то добавим это ненайденный элемент второго массива.

let arr1 = [1, 2, 10, 4, 2, 8, 9, 3, 4, 3, 6, 3, 6, 7, 4];
let arr2 = [2, 11, 7, 4, 8];

let len2 = arr2.length;
let res = [];

for (let i = 0; i < len2; i++) {
    let j = 0, isFound = false;
    let elem = arr2[i];
    while ((j = arr1.indexOf(elem, j)) != -1) {
        j++;
        isFound = true;
        res.push(elem);
    }
    if (!isFound) res.push(elem);
}

console.log(res);


text:
Q: Can syntax parameters be used to replace syntax? I'm trying to use syntax parameters in order to inject new syntax where I need it to be injected. The result of this is then used in other syntax.
However, it's not working as I expect it to. Here's a minimal working example:
(require racket/stxparam)
(require (for-syntax racket/stxparam))

;; declare parameter to be replaced with code
(define-syntax-parameter placeholder
  (lambda (stx)
    (raise-syntax-error
     (syntax-e stx)
     "can only be used inside declare-many-commands")))

;; this is just to print what 'arg' looks like
(define-syntax (print-syntax stx)
  (syntax-case stx ()
    [(_ arg)
     #'(displayln 'arg)]))

;; this is the top-level entity invoked to produce many commands
(define-syntax-rule (declare-many-commands cmds)
  (begin
    (let ([X 10])
      (syntax-parameterize
       ([placeholder (make-rename-transformer #'X)])
       cmds))
    (let ([X 20])
      (syntax-parameterize
       ([placeholder (make-rename-transformer #'X)])
       cmds))))

(declare-many-commands
 (print-syntax placeholder))

What I would like to get as result when running this is:
10
20

but what I get is:
placeholder
placeholder

EDIT:
Posted a new question to refine the problem: Injecting syntax at compile time using Racket's syntax parameters?

A: The problem here is that your print-syntax macro quotes its input, and inputs to macro transformers are unexpanded syntax. This means that the expansion of (print-syntax placeholder) will always be (displayln 'placeholder), and no macroexpansion ever occurs under quote, so the placeholder binding in scope is irrelevant.
If you want to use the syntax parameter, you need to actually produce a reference to the placeholder binding. In this case, you just need to remove the use of quote. You could change print-syntax to (displayln arg), but at that point, there's really no reason for print-syntax to be a macro, since it's equivalent to the displayln function. Just use that instead:
(declare-many-commands
 (displayln placeholder))

This will print 10 and 20 as you expect.
It's possible you really do want the quote, and I don't understand your question. In that case, though, I think it's difficult for me to understand what you're getting at without some additional context.


text:
Q: Reformatted Windows 8 laptop not loading Installed Ubuntu 13.04 x64 I have a new(er) HP Pavillion G6, and I completely wiped the hard drive to install ubuntu primarily, with a small Windows 7 partition. I created a partition for "/", the "/home" directory, a little for swap, and one for the windows section. Finished installing, restarted, it says "boot device not found, please install operating system. What steps should I take to install ubuntu and windows 7? Thank you for any help offered.

A: Ouch, sounds like you need to check out the UEFI Documentation from Ubuntu. If it was a Windows 8 machine, it can be a pain. Stopped buying those Windows machines because of that annoyance. There are other options, but this is a forum to help with Ubuntu questions.


text:
Q: Managing promises in RXJS observables I've poked about SO and found many similar questions/answers but I may be missing something in my basic understanding on how to work with with this stack.
I'm working on a react native project along with RXJS/obervables. At some point I doing file downloads, this part is not a problem. A combo of pre-existing axios-rxjs and react-native-file-system get me where I want. The issue is I'm not sure how to handle it cleanly without async/await which I understand is an anti-pattern.
I want to transform this working code into a clean obervable-style flow.
I've implemented an Epic that does the operations I want as such:
const myDownloadEpic = (
  action$,
  state$
) =>
  action$.pipe(
    ofType(myDownloadActionType), // catches the relevant action
    map(action => action.payload),
    mergeMap(payload =>
      downloadManager       // a class with the relevant utils to get files
        .download(payload), // this axios call returns my Blob file as Observable<Blob>
        .pipe(
          mergeMap(async response => {

            // a promise is returned by RNFS to read the contents of a folder
            const files = await RNFS.readDir(RELEVANT_TARGET_PATH)
...
            // a promise returned from a custom function that converts my blob to bas64
            const data = await convertToBase64(response)

            // another promise returned by RNFS to write to the file system
            await RNFS.writeFile(FULL_PATH, data, 'base64');

...
          })
        )
    )
   )

I've tried splitting this into several pipes, for example, I tried splitting the READ operation into a previous pipe but it ends up looking very verbose. Is there not a clean simple way to "hold" until the promises are done so I can make decisions based on their result?
What would be considered cleaner in this situation?

A: The from() operator can convert a promise into an observable that will emit the promised value then completes.
If you need to wait until all promises are resolved, I recommend forkJoin() as it won't emit a value until all observables complete.
Lastly, to make the code a little cleaner, I would also recommend declaring separate variables/functions to define your observables for each promise.
const files$ = from(RNFS.readDir(RELEVANT_TARGET_PATH));
const getData = (response: unknown) => from(convertToBase64(response)).pipe(
  mergeMap(data=>
    from(RNFS.writeFile(FULL_PATH, data, 'base64')).pipe(
      mapTo(data)
    )
  )
);

const myDownloadEpic = (action$, state$) =>
  action$.pipe(
    ofType(myDownloadActionType),
    map(({ payload }) => payload),
    mergeMap(payload => downloadManager.download(payload)),
    mergeMap(response =>
      forkJoin({
        files: files$,
        data: getData(response)
      })
    ),
    map(({ files, data }) => {
      // check something with `files` and `data`
    })
  );

I'm assuming RNFS.writeFile() response is void, so I put it as an effect when subscribing to getData(). The mapTo() operator ignores any emitted value from the source observable, and returns whatever value you put in the parameter.

A: You can try something like this. It should be roughly equivalent to what you've written above.
const myDownloadEpic = (
  action$,
  state$
) => action$.pipe(
  ofType(myDownloadActionType),
  map(action => action.payload),

  mergeMap(payload => downloadManager.download(payload)),

  mergeMap(response => from(RNFS.readDir(RELEVANT_TARGET_PATH)).pipe(
    map(files => ({response, files}))
  )),

  mergeMap(values => from(convertToBase64(values.response)).pipe(
    map(data => ({...values, data}))
  )),

  mergeMap(({response, files, data}) => RNFS.writeFile(FULL_PATH, data, 'base64'))
);


text:
Q: postgresql: error duplicate key value violates unique constraint This question have been asked by several people but my problem seems to be different.
Actually I have to merge same structured tables from different databases in postgresql into a new DB. What I am doing is that I connect to remote db using dblink, reads that table in that db and insert it into the table in the current DB like below
INSERT INTO t_types_of_dementia SELECT * FROM dblink('host=localhost port=5432 dbname=snap-cadence password=xxxxxx', 'SELECT dementia_type, snapid FROM t_types_of_dementia') as x(dementia_type VARCHAR(256),snapid integer);

First time this query runs fine, but when I run it again or try to run it with some other remote database's table: it gives me this error

ERROR:  duplicate key value violates unique constraint
  "t_types_of_dementia_pkey"

I want that this new tables gets populated by entries of others tables from other dbs.
Some of the solutions proposed talks about sequence, but i am not using any
The structure of the table in current db is
CREATE TABLE t_types_of_dementia(
    dementia_type VARCHAR(256),
    snapid integer NOT NULL,
    PRIMARY KEY (dementia_type,snapid)
);

P.S. There is a specific reason why both the columns are used as a primary key which may not be relevant in this discussion, because same issue happens in other tables where this is not the case.

A: As the error message tells you - you can not have two rows with the same value in the columns dementia_type, snapid since they need to be unique.
You have to make sure that the two databases has the same values for dementia_type, snapid.
A workaround would be to add a column to your table alter table t_types_of_dementia add column id serial generated always and use that as primary key instead of your current.


text:
Q: SSLenabled kafka configuration: Error : no suitable method found in creating map/configuration I am new to kafka-stream and we are trying to send message to kafka topic protected with SSL.
Hence, we have added extra SSl-config-properties to the stream configuration as:
@Configuration
@EnableKafkaStreams
public class KafkaStreamConfig {

  @Autowired
  private PreferredMediaMsgStreamProperties appProperties;

  @Value("${spring.kafka.streams.properties.receive.buffer.bytes}")
  private String receiveBufferBytes;

  @Bean(name = KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME)
  public KafkaStreamsConfiguration kStreamsConfigs() {
    Map<String, Object> props = Map.of(
            StreamsConfig.APPLICATION_ID_CONFIG, appProperties.getApplicationId(),
            StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, appProperties.getBootstrapServers(),

            //configure the following three settings for SSL Encryption
            CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL",
            SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, "/etc/ssl/container/truststore.jks",
            SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG,  "changeit",

            // configure the following three settings for SSL Authentication
            SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG, "/etc/ssl/container/server.jks",
            SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, "changeit",
            SslConfigs.SSL_KEY_PASSWORD_CONFIG, "changeit",

            StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, PreferredMediaMsgStreamProperties.Constants.KEY_SERDE.getClass().getName(),
            StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, PreferredMediaMsgStreamProperties.Constants.VALUE_SERDE.getClass().getName(),
            StreamsConfig.DEFAULT_TIMESTAMP_EXTRACTOR_CLASS_CONFIG, WallclockTimestampExtractor.class.getName(),
            StreamsConfig.RECEIVE_BUFFER_CONFIG, receiveBufferBytes

    );

    return new KafkaStreamsConfiguration(props);
  }

  @Bean
  public KafkaAdmin admin() {
    Map<String, Object> configs = Map.of(
            AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, appProperties.getBootstrapServers());
    return new KafkaAdmin(configs);
  }

}

And the error message , I am seeing during compilation is:
error: no suitable method found for of(String,String,String,String,String,String,String,String,String,String,String,String,String,String,String,String,String,String,String,String,String,String,String,String)
    Map<String, Object> props = Map.of(
                                   ^
    method Map.<K#1,V#1>of() is not applicable
      (cannot infer type-variable(s) K#1,V#1
        (actual and formal argument lists differ in length))
    method Map.<K#2,V#2>of(K#2,V#2) is not applicable
      (cannot infer type-variable(s) K#2,V#2
        (actual and formal argument lists differ in length))
    method Map.<K#3,V#3>of(K#3,V#3,K#3,V#3) is not applicable
      (cannot infer type-variable(s) K#3,V#3
        (actual and formal argument lists differ in length))
    method Map.<K#4,V#4>of(K#4,V#4,K#4,V#4,K#4,V#4) is not applicable
      (cannot infer type-variable(s) K#4,V#4
        (actual and formal argument lists differ in length))
    method Map.<K#5,V#5>of(K#5,V#5,K#5,V#5,K#5,V#5,K#5,V#5) is not applicable
      (cannot infer type-variable(s) K#5,V#5
        (actual and formal argument lists differ in length))
    method Map.<K#6,V#6>of(K#6,V#6,K#6,V#6,K#6,V#6,K#6,V#6,K#6,V#6) is not applicable
      (cannot infer type-variable(s) K#6,V#6
        (actual and formal argument lists differ in length))
    method Map.<K#7,V#7>of(K#7,V#7,K#7,V#7,K#7,V#7,K#7,V#7,K#7,V#7,K#7,V#7) is not applicable
      (cannot infer type-variable(s) K#7,V#7
        (actual and formal argument lists differ in length))
    method Map.<K#8,V#8>of(K#8,V#8,K#8,V#8,K#8,V#8,K#8,V#8,K#8,V#8,K#8,V#8,K#8,V#8) is not applicable
      (cannot infer type-variable(s) K#8,V#8
        (actual and formal argument lists differ in length))
    method Map.<K#9,V#9>of(K#9,V#9,K#9,V#9,K#9,V#9,K#9,V#9,K#9,V#9,K#9,V#9,K#9,V#9,K#9,V#9) is not applicable
      (cannot infer type-variable(s) K#9,V#9
        (actual and formal argument lists differ in length))
    method Map.<K#10,V#10>of(K#10,V#10,K#10,V#10,K#10,V#10,K#10,V#10,K#10,V#10,K#10,V#10,K#10,V#10,K#10,V#10,K#10,V#10) is not applicable
      (cannot infer type-variable(s) K#10,V#10
        (actual and formal argument lists differ in length))
    method Map.<K#11,V#11>of(K#11,V#11,K#11,V#11,K#11,V#11,K#11,V#11,K#11,V#11,K#11,V#11,K#11,V#11,K#11,V#11,K#11,V#11,K#11,V#11) is not applicable
      (cannot infer type-variable(s) K#11,V#11
        (actual and formal argument lists differ in length))
  where K#1,V#1,K#2,V#2,K#3,V#3,K#4,V#4,K#5,V#5,K#6,V#6,K#7,V#7,K#8,V#8,K#9,V#9,K#10,V#10,K#11,V#11 are type-variables:
    K#1 extends Object declared in method <K#1,V#1>of()
    V#1 extends Object declared in method <K#1,V#1>of()
    K#2 extends Object declared in method <K#2,V#2>of(K#2,V#2)
    V#2 extends Object declared in method <K#2,V#2>of(K#2,V#2)
    K#3 extends Object declared in method <K#3,V#3>of(K#3,V#3,K#3,V#3)
    V#3 extends Object declared in method <K#3,V#3>of(K#3,V#3,K#3,V#3)
    K#4 extends Object declared in method <K#4,V#4>of(K#4,V#4,K#4,V#4,K#4,V#4)
    V#4 extends Object declared in method <K#4,V#4>of(K#4,V#4,K#4,V#4,K#4,V#4)
    K#5 extends Object declared in method <K#5,V#5>of(K#5,V#5,K#5,V#5,K#5,V#5,K#5,V#5)
    V#5 extends Object declared in method <K#5,V#5>of(K#5,V#5,K#5,V#5,K#5,V#5,K#5,V#5)
    K#6 extends Object declared in method <K#6,V#6>of(K#6,V#6,K#6,V#6,K#6,V#6,K#6,V#6,K#6,V#6)
    V#6 extends Object declared in method <K#6,V#6>of(K#6,V#6,K#6,V#6,K#6,V#6,K#6,V#6,K#6,V#6)
    K#7 extends Object declared in method <K#7,V#7>of(K#7,V#7,K#7,V#7,K#7,V#7,K#7,V#7,K#7,V#7,K#7,V#7)
    V#7 extends Object declared in method <K#7,V#7>of(K#7,V#7,K#7,V#7,K#7,V#7,K#7,V#7,K#7,V#7,K#7,V#7)
    K#8 extends Object declared in method <K#8,V#8>of(K#8,V#8,K#8,V#8,K#8,V#8,K#8,V#8,K#8,V#8,K#8,V#8,K#8,V#8)
    V#8 extends Object declared in method <K#8,V#8>of(K#8,V#8,K#8,V#8,K#8,V#8,K#8,V#8,K#8,V#8,K#8,V#8,K#8,V#8)
    K#9 extends Object declared in method <K#9,V#9>of(K#9,V#9,K#9,V#9,K#9,V#9,K#9,V#9,K#9,V#9,K#9,V#9,K#9,V#9,K#9,V#9)
    V#9 extends Object declared in method <K#9,V#9>of(K#9,V#9,K#9,V#9,K#9,V#9,K#9,V#9,K#9,V#9,K#9,V#9,K#9,V#9,K#9,V#9)
    K#10 extends Object declared in method <K#10,V#10>of(K#10,V#10,K#10,V#10,K#10,V#10,K#10,V#10,K#10,V#10,K#10,V#10,K#10,V#10,K#10,V#10,K#10,V#10)
    V#10 extends Object declared in method <K#10,V#10>of(K#10,V#10,K#10,V#10,K#10,V#10,K#10,V#10,K#10,V#10,K#10,V#10,K#10,V#10,K#10,V#10,K#10,V#10)
    K#11 extends Object declared in method <K#11,V#11>of(K#11,V#11,K#11,V#11,K#11,V#11,K#11,V#11,K#11,V#11,K#11,V#11,K#11,V#11,K#11,V#11,K#11,V#11,K#11,V#11)
    V#11 extends Object declared in method <K#11,V#11>of(K#11,V#11,K#11,V#11,K#11,V#11,K#11,V#11,K#11,V#11,K#11,V#11,K#11,V#11,K#11,V#11,K#11,V#11,K#11,V#11)
Note: /Users/pbose/patrali_sand/notification-preference-stream/src/main/java/com/talentreef/notification/preference/utils/RecipientPoolValueJoiner.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error

If I take out the propertiesbelow, then it compiles fine:
//configure the following three settings for SSL Encryption
CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL",
SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, "/etc/ssl/container/truststore.jks",
SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG,  "changeit",

// configure the following three settings for SSL Authentication
SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG, "/etc/ssl/container/server.jks",
SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, "changeit",
SslConfigs.SSL_KEY_PASSWORD_CONFIG, "changeit",

May I get any insight on what's going on here?

A: Map.of() has overloads for a maximum of 10 entries ( check this ) . You have 11 in total. That is why, when you remove 6 of them compiles.
If you want this to work use Map.ofEntries(). This method takes a variable argument and it doesn't have limitations regarding the number of entries.


text:
Q: read real-time data from terminal via python I have a Sensor that is connected to my ubuntu laptop. There is a small programm that plots the sensor values in a terminal in real-time.
I wanna read out these values and plot them in a smooth graph with python.
Is this possible? Even with python3?
I tried the subprocess command like here. But it does not work.


text:
Q: Finding Time for Important but not Urgent tasks OK, this is a non-tech question, but I think it pertains to a lot of sysadmins, especially at small shops.
There are a lot of tasks that are not related to a project, or day-to-day operations that do not add visible value to the organization, but nevertheless are important.  I'm thinking of things like Documenting the Network or Processes,  Researching that new tool/technology/process, development of subordinates, filing of paperwork.
All of these are important, but because they do not end up on a Gantt Chart, or directly result in your boss yelling at you if you skip it, can other be neglected.
How do you make sure that you cover these?
I have tried adding them to my task management system, scheduling recurring appointments in my calendar for things like "Research New Technologies".  But these tend to be really easy to ignore/cross off this week, etc.
PS, I like the tag calendar-management,  as the guys on Manager-Tools say, You can manage your calendar, but time is a constant, you cannot manage it to create more/less or to change how fast/slow it passes.

A: Getting Things Done is a great book, very helpful, even if you don't implement a full system. GTD is a very long commitment, don't get overwhelmed.
Here's a brief intro to GTD.
But no system is perfect. It's very easy to lose sight of WHY you are trying to get organized, if your organization system takes over all your free time.
The map is not the territory.
For a more domain specific book check out:
Time Management for System Administrators by Limoncelli. Which will provide a few more insightful tips.
I personally also use todo.sh. Which is a great todo bash script. It's also the only bash script I know that's unit tested and under revision control.

A: I found that the best way to take care of these tasks is to come up with a scheduling system, so that A) you are not spending all of your time on the day-to-day problems that come up and B) you reserve time for the documentation and other back-office issues that need to be taken care of.
In that light, I would highly recommend David Allen's Getting Things Done (GTD).  His system of managing ever changing TODO lists fits in well with how administrators and managers work.  I've been using it for 3 years now and my time is much more productive, and I never feel like I don't have a handle on all of those little issues that should be handled.
I'm sorry if this feels like an infomercial, but his book really is that helpful.

A: Since this is subjective, I thought that I'd just toss out the ones that help me the most. All of `em can be found elsewhere, cribbed from "How to do better at time management!" articles, etc. They're just what help me. They may not necessarily help YOU.
i.e. Your Mileage May Vary.
Also, while they're not necessarily a direct and succinct answer to the question at hand, I believe that when used, they contribute overall to improving time-management, which has the direct overall effect of helping me free up some time, to complete those important-yet-not-urgent-tasks.

1.) Train everybody to do your job. Meaning; if you're on a team of 5, and
  there's one guy who knows MS Exchange,
  one guy who knows LAN, routing, etc.
  One girl who knows AD and core MS
  Administration and one guy who knows
  Linux/Unix, and you're the LAN/router
  dude.. Spread your knowledge around.
  Maybe the AD girl wants to know how
  spanning-tree protocol works. Perhaps
  the Exchange guy wants to know how his
  packets get from "a" to "b" to "c" and
  back. Work with them to get them
  trained up on some good basic
  knowledge. By doing this, you'll be
  more apt to go to them for help when
  you're inundated and can't seem to
  find the time to get the
  small-but-important stuff done such as
  documentation and that equipment
  refresh projection list to your boss
  that he needed, oh, say.. Yesterday.
  If you've done a good job training
  your peers, then you can ask for, and
  expect great help with relabeling
  those switchports or verifying SNMP on
  your devices and that they're all
  plugged into your monitoring system.
That being said, be equally prepared
  to learn some of their jobs as well,
  and for good reason. It'll help you
  understand where they're coming from
  and give them the latitude that you
  enjoy as well.
2.) Set an `email schedule' for yourself and limit your email checking
  to particular times of the day. Say
  four or so, if you work in a very,
  high-traffic, busy email environment.
  Focus on what directly applies to you
  and what requires immediate attention.
  STICK to the "check email at this
  time" schedule.
3.) Break tasks up into chunks of short-term time to be spent on them.
  I.e. multitask, but don't work too
  hard on a single task and get sucked
  into it, or burn out. Work on it for
  20-30 minutes or so, then move onto
  something else. Keeping your interest
  piqued is critical to successful
  multitasking. it's altogether too easy
  for us to get sucked into
  troubleshooting WSUS and spending
  hours on chasing down one elusive
  hex-error code after another.
4.) Take a break every once in a while. Actually get up and walk
  around. Get the blood flowing. Go get
  some water. Clear your head, (what you
  were just directly focusing on) and
  think about something else. You'll be
  surprised how refreshing this is and
  how well and quickly it helps you
  focus on the next task at hand.
5.) Check out resources on the internet for Project Management.
  There's usually great tips and tricks
  in there that directly deal with
  questions like yours, along with
  general time-management skills. You'd
  be surprised.
6.) This is gonna sound weird, but work at being lazy. Learn how to
  automate, automate, automate. Don't
  waste your time repeating tasks over
  and over. Learn how to do it with a
  script if you can. I suppose that the
  proper way to say this would be, "work
  smarter, not harder".
7.) Use a SIMPLE to-do list broken up into daily, weekly and monthly.
  Prioritize the tasks in a similar way
  by, "critical", "not-critical" and
  "long-term". STICK to the list. Update
  it, don't let it get stale. Make it
  the first thing you do every morning
  and the last thing you update before
  you leave. This does wonders for
  continuity of thought, etc.
8.) If you work in a meeting-heavy organization and you find your time
  being taken up by tons upon tons of
  pointless meetings each week, use this
  philosophy; If invited to a meeting,
  does it directly apply to you, or are
  you a key stakeholder? If not,
  consider how your time could be better
  spent. Especially if you get an
  emailed summary of the meeting
  minutes. Meeting invites usually (in
  email) come with, `Accept, Tentative,
  Decline' options. Don't be afraid, you
  can use them.
When attending a meeting, if there's
  no clear agenda or one displayed in
  the first five minutes, leave the
  meeting immediately. Get out. 9 times
  out of ten, it'll ramble on for an
  hour or so, with no point. It's the
  equivalent of sending a team of people
  to the grocery store with no list.
  What they come out with will be a
  hodgepodge mix of foodstuffs. Much
  like what you'll walk out of that
  meeting with.

Anyway, again, check out the PM references out there on the internets. They're worth it.
HTH..

A: I like the "handle it only once" technique: whenever possible, get rid of things on your to-do list as soon as possible.

*

*When you some form from HR in your inbox, do it immediately and send it back.

*If you fill out timesheets in your company, once you start on it don't stop until it's done.

*For documenting processes, the next time it's a bit slower and you're doing the process, type up the process as you go (or update the document if that's what needs doing).

For other documentation tasks, even though they add a bit of time to the job, you have to get into a habit of doing them.  e.g. if you have a spreadsheet of switch/patch-panel connections, you have to take the time to update it whenever you make a change, otherwise you'll spend more time later sorting things out.  Similarly, we keep our patch panels very tidy with lots of velcro tape and it takes a little bit longer to re-do all the velcro when we change patch connection, but it's worth it because you can see where everything is.

A: How about replacing "Research New Technologies" with more specific items, e.g.

Spend 15 (or 30) minutes researching SELinux and work towards answering one of:

*

*How do I install it?

*What mode of operation best suits my environment and how do I configure it?

*How do I interpret its log entries?

*How do I create rules?

Similarly for "Documenting the Network" etc.

A: I like "personal organization" as the moniker for this kind of stuff.
There are two separate things here.  The first is getting a system in place and being disciplined enough to follow it.  There are a ton of systems out there .. GTD gets lots of press.  Personally, I use a hybrid of Franklin and GTD.  Have a framework to capture the things you need to do and to let you easily prioritize and schedule them.  I suspect that this is where you are breaking down .. as you noted, you scheduling then crossing out.
The second is to have a way within that framework that Quadrant 2 stuff {important but not urgent} actually gets some attention. Quadrant 2 is the place of real, lasting value to the organization (and to you personally), and usually does not get nearly enough attention.
You can start by not thinking of (or referring to) them as "me" tasks .. if they aren't important to the organization you shouldn't do them on company time.  If they are, they need to be folded into the mix somehow.  If they truly are about you .. apply the same principles on your own time.
The best way I have found is to treat these things as any other project.  Any good personal organization system has a process to capture and include the tasks from projects.  Take the amorphous ideal (say, Document Server Configuration) and break it down into the smallest tasks (Build empty doc, doc network config, doc shares, etc.) you can get down to.  Then include some of those tasks in your daily/weekly plan, and find a way each week, to get those little pieces done.  Note that I said each week, not every week.  It is kind of like recovery .. today is all that matters, you work your system today, and tomorrow you worry about tomorrow.
This won't get you all the way there, but it is a start.  In the end, this is a relatively small extension of the discipline to keep on a system.  But it is the part that turns you from "getting the job done" to "making things better".

EDIT - respond to comment from original author.
Be clear - this discussion is NOT about those items that are "low organizational value". You should not waste time on unimportant tasks unless you have nothing else to do.  This dilemma (and my answer) is about tasks that are HIGH organizational value, but not time-sensitive.
One additional strategy, that I recalled thinking about the comment.  I have found that virtually all Quadrant 3 (high urgency, low importance) tasks can simply be ignored or deferred until convenient. The trick is knowing which urgent items are important and which aren't.

A: I think that is one very important thing to fight with taht,
Is that you do a good segmentation of tasks,
Draw a circle divided in four fields, for each field in circle give atribute

*

*VI- LU Very important less urgent

*VI - VU Very important very urgent

*LI - VU Less important very urgent

*LI - LU Less important less urgent

Then You can in nice way segment jobs and , do cross working for better picture where is time gone.
Some time I said to myself for two of VI LU task You can pick up one LI - LU.
In general they said that position one in my list should be addressed to investors, owners, and people who making big decisions but in no hurry,
2nd step is for Top managers whose job is fireplug
3th and 4th are for lower ratings of employers

A: I find I end up learning new technologies on "my time" and I view it as "continuing education" and something good for my career.

A: Make doing these things part of the task that generated them.
Installed new software? Include documenting it in part of the plan to install it.
Staff Development - this can be an ongoing thing throughout all new tasks aside from the one or two specific training things, and these are important and hence deserve to be given the time they need.
Paperwork to do? Include that in part of the plan for the task that generated the paperwork.
Block out a certain amount of time for administrivia each day - if you don't let a backlog develop then keeping up with it will be easy.
No time for research? This is also an important part of the job, not a trivial addition. If you don't have time for it then you're either under-resourced or you have another problem if you're constantly being dragged away from stuff like this to fight fires.

A: Probably not the answer you want to hear but I've found that I get more time for that kind of work the older I got - people just give you more time and don't 'rag' on you so much.
If you show you're always happy to take crap from people then they'll carry on doing it, once you're older you get less people trying this so you can pick and choose how best to benefit your organisation.
And yes I know we're the same age :(


text:
Q: How to get data from linked table? I'm new in VBA so i don't know how to get data from linked table in ms access, But i tried some code but it show this error
"Run time error '3219'
Invalid Operation

I already search this error everywhere but not find right answer.
Code
 Dim db As DAO.Database
 Dim db As DAO.Recordset
 Set db = CurrentDb

 Set rsHoliday = db.OpenRecordset("Holidays", dbOpenTable)
//Error Occur in this line

A: You are trying to assign a Table to a Recordset. Loose the dbOpenTable parameter from the code. It would compile just fine and do what you want. Unless you wish to open the table you need to use DoCmd.OpenTable


text:
Q: post_before, post_after identical on update gutenberg bug I am trying to get the $post_before and $post_after objects for comparison when updating a post in WordPress.
However, when I submit the update, the $post_before and $post_after objects are identical and show the updated post object.
add_action('post_updated', [$this, 'comparePosts'], 10, 3);
function comparePosts($post_ID, $post_after, $post_before)
    {
        echo 'Post ID:
';
        var_dump($post_ID);

        echo 'Post Object AFTER update:
';
        var_dump($post_after->post_name);

        echo 'Post Object BEFORE update:
';
        var_dump($post_before->post_name);
    }

After researching, I have found two related bug tickets https://core.trac.wordpress.org/ticket/47908 and https://core.trac.wordpress.org/ticket/45114.
The Bug is related to the Gutenberg editor's order of processing the update hooks. The ticket has been closed, but even in the latest version of WordPress [5.9.2], the issue still exists.
I have also tried to use different hooks including pre_post_update, post_updated, save_post but all of them carry the updated post object in $post_before and $post_after.  How can I get the real $post_before and $post_after objects.

A: Just tested this in WordPress 6.0.2(latest) and latest gutenberg plugin and it's working as expected. Make note post name is the slug, so you must modify slug to see difference.
Also if that doesn't work, do a comparison check first before dumping:
if ($post_after->post_name !== $post_before->post_name) {
    var_dump($post_after->post_name);
    var_dump($post_before->post_name);
}
else {
    var_dump('no change')
}

I see you tried a bunch of hooks but you can also try wp_after_insert_post hook which works well with gutenberg.

A: I can confirm this known issue is happening on WP 6.0.2 for me.
You can overcome this by using both pre_post_update and wp_after_insert_post  hooks within a class.
<?php
class BeforeAfter {

    public string $old_post_name = '';

    public string $post_name = '';

    public function __construct() {
        add_action( 'pre_post_update', array( $this, 'before_update'), 10, 2 );
        add_action( 'wp_after_insert_post', array( $this, 'after_update'), 10, 4 );
    }

    public function before_update( $post_ID, $data ): void {

        $this->old_post_name = get_the_title( $post_ID );
    }

    public function after_update( $post_ID, $post, $update, $post_before ): void {

        $this->post_name = get_the_title( $post_ID );

        /* Both available */
        var_dump($this->old_post_name);
        var_dump($this->post_name);
    }
}


text:
Q: Что не так с кодом на Python 3? Есть задача на Python 3 с условием:

Дана цепочка, состоящая из синих (B) и красных (R) точек. Нужно
удалить наименьшее одинаковое количество синих и красных точек так,
чтобы сначала шли только синие, а потом – только красные.
Входные данные
Входная строка содержит только символы 'B' и 'R' без пробелов.
Выходные данные
Нужно вывести полученную цепочку, в которой сначала идут только синие
точки, а потом – только красные. Во второй строке нужно вывести
количество удалённых (синих и красных) точек.

и примерами:

Примеры
Ввод
BBBRBBRBRBRRRRRR
Вывод
BBBBBRRRRRRR
4

Пытаюсь пол часа решить, использую разные варианты, но всё равно не получается.
Вот последний вариант кода:
n = input()
s = ''
count = 0
for g in range(0, len(n)):
    if g == len(n) - 1:
       break
    if n[g] == 'B' and n[g + 1] == 'B':
       s += 'B'
       continue
    elif n[g] == 'B' and n[g + 1] == 'R':
        if count == 0:
            s += 'B'
        else:
            s += 'R'
        continue
    elif n[g] == 'R' and n[g + 1] == 'B':
        s += 'R'
        count += 1
        continue
    elif n[g] == 'R' and n[g + 1] == 'R':
        continue
print(s)
print(count)

Что я делаю не так? В чём и где ошибки? Подскажите, пожалуйста, как правильно решить задачу и что использовать?!

A: Это конечно не лучший вариант, но все же рабочий
def ed(a):
    if a:
        b = a.split('R')
        r = a.split('B')
        sorted_b = [y for y in b if y]
        sorted_a = [y for y in r if y]
        sorted_b.sort()
        sorted_a.sort()
        count_b = sorted_b.count(sorted_b[0])
        count_a = sorted_a.count(sorted_a[0])
        cb = min(map(len, sorted_b))
        bb = ''.join(list(filter(lambda x: len(x) > cb, sorted_b)))
        cr = min(map(len, sorted_a))
        rr = ''.join(list(filter(lambda x: len(x) > cr, sorted_a)))
        res = bb.count('B') * "B" + rr.count("R") * "R"
        return f'{res} {count_a + count_b}'

print(ed("BBBRBBRBRBRRRRRR"))

Вывод будет:
BBBBBRRRRRR 5

A: данное решение подойдет сугубо для данного ввода строки, выглядит так:
s = "BBBRBBRBRBRRRRRR"
bb = s[:s.find('RR')]
rr = s[s.find('RR'):]
bb = bb.replace('R', '')
print(bb + rr, s.count('BR'))

1-делим на две части строку, до момента, где начинаются RR,
2-потом в первой заменяем R на пуcтое значение, т.е. удаляем.
3-в выводе "склеиваем" назад в строку, подсчитываем буквосочетание BR


text:
Q: Connecting multiple wireless devices to one main device using bluetooth What I want to do is connect to bluetooth enabled devices to one main device. For example two bluetooth speakers to connect to my iPhone and play music.
Do speaker A needs to connect to Speaker B through bluetooth and then connect to the iPhone? IS this even possible?

A: iPhones music app can only output to one bluetooth speaker at a time.
Either the software would need to support multiple outputs or the speakers would need to have a feature to pair with each other.
So it is technically possible, but not supported by iOS' music app, nor do I personally know of a speaker that does that.


text:
Q: Upload image to Google Drive for OCR I'm trying to upload an image to Google Drive for Optical Character Recognition (OCR). Here are my codes:
require_once('vendor/autoload.php');

// Initialize Google Client
$client_email = 'xxxxxx@yyyyy.iam.gserviceaccount.com';
$private_key = file_get_contents('key.p12');
$scopes = array(
    'https://www.googleapis.com/auth/drive.file'
);
$credentials = new Google_Auth_AssertionCredentials(
    $client_email,
    $scopes,
    $private_key
);
$client = new Google_Client();
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
  $client->getAuth()->refreshTokenWithAssertion();
}

// Initialize Google Drive service
$service = new Google_Service_Drive($client);

// Upload File
$file = new Google_Service_Drive_DriveFile();
$file->setName('Test Image for OCR');
$file->setDescription('Test Image for OCR');
$file->setMimeType('image/jpeg');
try {
  $data = file_get_contents($filename);
  $createdFile = $service->files->create($file, array(
      'data' => $data,
      'mimeType' => 'image/jpeg',
  ));
  var_dump($createdFile);
  // ===========
  // So, what's next?
  // ===========
} catch(Exception $e) {
  echo 'Error occurred: ' . $e->getMessage();
}

The above codes run without error, and the $createdFile is a valid resource in Google_Service_Drive_DriveFile object form.
Questions:

*

*I guess the upload is successful, as the create() function does not return an error. However, I can't see the files got uploaded in my Google Drive. Shouldn't it be uploaded to Google Drive's root folder?

*How can I perform OCR? I can read from here that there is a parameter named ocrLanguage. Where should I put it and how do I obtain the result?
Thanks in advance.
UPDATE The var_dump() results are as follow:
object(Google_Service_Drive_DriveFile)#18 (55) {
  ["collection_key":protected]=>
  string(6) "spaces"
  ["internal_gapi_mappings":protected]=>
  array(0) {
  }
  ["appProperties"]=>
  NULL
  ["capabilitiesType":protected]=>
  string(42) "Google_Service_Drive_DriveFileCapabilities"
  ["capabilitiesDataType":protected]=>
  string(0) ""
  ["contentHintsType":protected]=>
  string(42) "Google_Service_Drive_DriveFileContentHints"
  ["contentHintsDataType":protected]=>
  string(0) ""
  ["createdTime"]=>
  NULL
  ["description"]=>
  NULL
  ["explicitlyTrashed"]=>
  NULL
  ["fileExtension"]=>
  NULL
  ["folderColorRgb"]=>
  NULL
  ["fullFileExtension"]=>
  NULL
  ["headRevisionId"]=>
  NULL
  ["iconLink"]=>
  NULL
  ["id"]=>
  string(28) "0B_XXXXX1yjq7dENaQWp4ckZoRk0"
  ["imageMediaMetadataType":protected]=>
  string(48) "Google_Service_Drive_DriveFileImageMediaMetadata"
  ["imageMediaMetadataDataType":protected]=>
  string(0) ""
  ["kind"]=>
  string(10) "drive#file"
  ["lastModifyingUserType":protected]=>
  string(25) "Google_Service_Drive_User"
  ["lastModifyingUserDataType":protected]=>
  string(0) ""
  ["md5Checksum"]=>
  NULL
  ["mimeType"]=>
  string(10) "image/jpeg"
  ["modifiedByMeTime"]=>
  NULL
  ["modifiedTime"]=>
  NULL
  ["name"]=>
  string(18) "Test Image for OCR"
  ["originalFilename"]=>
  NULL
  ["ownedByMe"]=>
  NULL
  ["ownersType":protected]=>
  string(25) "Google_Service_Drive_User"
  ["ownersDataType":protected]=>
  string(5) "array"
  ["parents"]=>
  NULL
  ["permissionsType":protected]=>
  string(31) "Google_Service_Drive_Permission"
  ["permissionsDataType":protected]=>
  string(5) "array"
  ["properties"]=>
  NULL
  ["quotaBytesUsed"]=>
  NULL
  ["shared"]=>
  NULL
  ["sharedWithMeTime"]=>
  NULL
  ["sharingUserType":protected]=>
  string(25) "Google_Service_Drive_User"
  ["sharingUserDataType":protected]=>
  string(0) ""
  ["size"]=>
  NULL
  ["spaces"]=>
  NULL
  ["starred"]=>
  NULL
  ["thumbnailLink"]=>
  NULL
  ["trashed"]=>
  NULL
  ["version"]=>
  NULL
  ["videoMediaMetadataType":protected]=>
  string(48) "Google_Service_Drive_DriveFileVideoMediaMetadata"
  ["videoMediaMetadataDataType":protected]=>
  string(0) ""
  ["viewedByMe"]=>
  NULL
  ["viewedByMeTime"]=>
  NULL
  ["viewersCanCopyContent"]=>
  NULL
  ["webContentLink"]=>
  NULL
  ["webViewLink"]=>
  NULL
  ["writersCanShare"]=>
  NULL
  ["modelData":protected]=>
  array(0) {
  }
  ["processed":protected]=>
  array(0) {
  }
}

The file can be obtained via $service->files->get($file_id);, but it's invisible in my Google Drive. The File Resource object returned does not contain anything useful either.

A: I just found the way to OCR in V3.

*

*Upload the image

*Copy the image to a Google Document using mimeType "application/vnd.google-apps.document"

*Export the Document as plain text using mimeType "text/plain"
P.S. Seems like step 2 won't work with "appDataFolder".
UserCredential credential = null;
try
{
    credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
        new Uri("ms-appx:///Assets/client_secret.json"),
        new[] { DriveService.Scope.DriveFile }, "user", CancellationToken.None);
}
catch (AggregateException ex)
{
    Debug.Write("Credential failed, " + ex.Message);
}

// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
    ApplicationName = "TestApp",
});

// Create folder
var folderMetadata = new Google.Apis.Drive.v3.Data.File();
folderMetadata.Name = "NewFolder";
folderMetadata.MimeType = "application/vnd.google-apps.folder";
var request = service.Files.Create(folderMetadata);
request.Fields = "id";
var folder = request.Execute();
Debug.WriteLine("Folder ID: " + folder.Id);

// Upload the image file
var fileMetadata = new Google.Apis.Drive.v3.Data.File();
fileMetadata.Name = inputFile.Name;
fileMetadata.Parents = new List<string> { folder.Id };
FilesResource.CreateMediaUpload requestUpload;
using (var stream = new System.IO.FileStream(inputFile.Path, System.IO.FileMode.Open))
{
    requestUpload = service.Files.Create(fileMetadata, stream, "image/jpeg");
    requestUpload.Fields = "id";
    requestUpload.Upload();
}
var imgFile = requestUpload.ResponseBody;
Debug.WriteLine("File ID: " + imgFile.Id);

// Copy image and paste as document
var textMetadata = new Google.Apis.Drive.v3.Data.File();
textMetadata.Name = inputFile.Name;
textMetadata.Parents = new List<string> { folderId };
textMetadata.MimeType = "application/vnd.google-apps.document";
FilesResource.CopyRequest requestCopy = service.Files.Copy(textMetadata, imgFile.Id);
requestCopy.Fields = "id";
requestCopy.OcrLanguage = "zh";
var textFile = requestCopy.Execute();

// Now we export document as plain text
FilesResource.ExportRequest requestExport = service.Files.Export(textFile.Id, "text/plain");
string output = requestExport.Execute();

A: A service account isn't you its more like a dummy user.  It has its own drive account.
If you want to upload to your personal account.  Take the service account email address and share it a directory in your personal drive account.   Just like you would any other user you wanted to share a directory or file with.
Then you need to figure out the directory id only way I have found to do that was to have the service account do a files.list to get a list of everything it now has access to.   Once you find the directory id or parent id
you can change your code above to something like
'data' => $data,
'mimeType' => 'image/jpeg',
'parents'   => 'the directory id'

I think by the looks of your code you are using the V3 api I haven't had time to play with it.  'parents'   => 'the directory id'  <-- that is an educated guess.   If it doesn't work let me know and I will google around a bit to figure out how to pass parent to v3.
Option nr 2:
Another option would be for the service account to share its folder with you then you will have access to its drive account, and you will be able to see that folder in your web version of Drive.   Search around for permissions again I think you are using V3 I haven't looked at it yet.  Difference is where the data is stored and who the storage gets counted against.

A: Don't use a service account. If you want to upload to your own account, then you simply need to obtain an appropriate Access Token for your account. Using an intermediate account using shared folders is really ugly (imho).