text:
Q: Map collection elements and keep reference to source collection I'm looking for a way to create a collection, list, set, or map which contains the transformed elements of an original collection and reflects every modification in that collection.
For example if I have a List<Integer> from a third party API and another API is expecting a List<String>. I know I can transform the list like this:
List<Integer> intList = thirdPartyBean.getIntListProperty();
List<String> stringList = intList.stream().map(Integer::toString)
    .collect(Collectors.toList());
secondBean.setStringListProperty(stringList);

The problem is, if anything is changed in one of the lists the other one will still reflect the previous state. Let's assume that intList contains [1, 2, 3]:
intList.add(4);
stringList.remove(0);
System.out.println(intList.toString()); // will print: [1, 2, 3, 4]
System.out.println(stringList.toString()); // will print: [2, 3]
// Expected result of both toString(): [2, 3, 4]

So I'm searching for something like List.sublist(from, to) where the result is "backed" by the original list.
I'm thinking of implementing my own list wrapper which is used like this:
List<String> stringList = new MappedList<>(intList, Integer::toString, Integer::valueOf);

The second lambda is for inverting the conversion, to support calls like stringList.add(String).
But before I implement it myself I would like to know if I try to reinvent the wheel - maybe there is already a common solution for this problem?

A: I would wrap the list in another List with transformers attached.
public class MappedList<S, T> extends AbstractList<T> {
    private final List<S> source;
    private final Function<S, T> fromTransformer;
    private final Function<T, S> toTransformer;

    public MappedList(List<S> source, Function<S, T> fromTransformer, Function<T, S> toTransformer) {
        this.source = source;
        this.fromTransformer = fromTransformer;
        this.toTransformer = toTransformer;
    }

    public T get(int index) {
        return fromTransformer.apply(source.get(index));
    }

    public T set(int index, T element) {
        return fromTransformer.apply(source.set(index, toTransformer.apply(element)));
    }

    public int size() {
        return source.size();
    }

    public void add(int index, T element) {
        source.add(index, toTransformer.apply(element));
    }

    public T remove(int index) {
        return fromTransformer.apply(source.remove(index));
    }

}

private void test() {
    List<Integer> intList = new ArrayList<>(Arrays.asList(1, 2, 3));
    List<String> stringList = new MappedList<>(intList, String::valueOf, Integer::valueOf);
    intList.add(4);
    stringList.remove(0);
    System.out.println(intList); // Prints [2, 3, 4]
    System.out.println(stringList); // Prints [2, 3, 4]
}

Note that the fromTransformer needs null checking for the input value, if source may contain null.
Now you are not transforming the original list into another one and losing contact with the original, you are adding a transformation to the original list.

A: I don't know what version of the JDK you are using, but if you are okay with using the JavaFX library you can use ObservableList. You do not need to modify an existing list as ObservableList is a wrapper for java.util.List. Look at extractor in FXCollection for complex Objects. This article has an example of it.
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.ListChangeListener.Change;

public class ObservableBiList{
    //prevent stackoverflow
    private static final AtomicBoolean wasChanged = new AtomicBoolean( false);

    public static <T, R> void change( Change< ? extends T> c, ObservableList< R> list, Function< T, R> convert) {
        if( wasChanged.get()){
            wasChanged.set( false);
            return;
        }
        wasChanged.set( true);
        while( c.next()){
            if( c.wasAdded() && !c.wasReplaced()){
                for( T str : c.getRemoved())
                    list.add( convert.apply( str));
            }else if( c.wasReplaced()){
                for( int i=c.getFrom();i<c.getTo();i++)
                    list.set( i,convert.apply( c.getList().get( i)));
            }else if( c.wasRemoved()){
                for( T str : c.getRemoved())
                    list.remove( convert.apply( str));
            }
        }
        System.out.printf( "Added: %s, Replaced: %s, Removed: %s, Updated: %s, Permutated: %s%n",
                c.wasAdded(), c.wasReplaced(), c.wasRemoved(), c.wasUpdated(), c.wasPermutated());
    }

    public static void main( String[] args){

        ObservableList< Integer> intList = FXCollections.observableArrayList();
        intList.addAll( 1, 2, 3, 4, 5, 6, 7);
        ObservableList< String> stringList = FXCollections.observableArrayList();
        stringList.addAll( "1", "2", "3", "4", "5", "6", "7");

        intList.addListener( ( Change< ? extends Integer> c) -> change( c, stringList, num->Integer.toString( num)));
        stringList.addListener( ( Change< ? extends String> c) -> change( c, intList, str->Integer.valueOf( str)));

        intList.set( 1, 22);
        stringList.set( 3, "33");

        System.out.println( intList);
        System.out.println( stringList);
    }
}

A: This is exactly the kind of problems that the Observer Pattern solves.
You can create two wrappers, around List<String> and List<Integer> and let first wrapper observe the state of the other one.

A: public static void main(String... args) {
    List<Integer> intList = ObservableList.createBase(new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)));
    List<String> stringList = ObservableList.createBase(intList, String::valueOf);

    stringList.remove(0);
    intList.add(6);

    System.out.println(String.join(" ", stringList));
    System.out.println(intList.stream().map(String::valueOf).collect(Collectors.joining(" ")));
}

@SuppressWarnings({ "unchecked", "rawtypes" })
private static final class ObservableList<T, E> extends AbstractList<E> {

    // original list; only this one could be used to add value
    private final List<T> base;
    // current snapshot; could be used to remove value;
    private final List<E> snapshot;
    private final Map<Function<T, ?>, List> cache;

    public static <T, E> List<E> createBase(List<T> base) {
        Objects.requireNonNull(base);

        if (base instanceof ObservableList)
            throw new IllegalArgumentException();

        return new ObservableList<>(base, null, new HashMap<>());
    }

    public static <T, R> List<R> createBase(List<T> obsrv, Function<T, R> func) {
        Objects.requireNonNull(obsrv);
        Objects.requireNonNull(func);

        if (!(obsrv instanceof ObservableList))
            throw new IllegalArgumentException();

        return new ObservableList<>(((ObservableList<T, R>)obsrv).base, func, ((ObservableList<T, R>)obsrv).cache);
    }

    @SuppressWarnings("AssignmentOrReturnOfFieldWithMutableType")
    private ObservableList(List<T> base, Function<T, E> func, Map<Function<T, ?>, List> cache) {
        this.base = base;
        snapshot = func != null ? base.stream().map(func).collect(Collectors.toList()) : (List<E>)base;
        this.cache = cache;
        cache.put(func, snapshot);
    }

    @Override
    public E get(int index) {
        return snapshot.get(index);
    }

    @Override
    public int size() {
        return base.size();
    }

    @Override
    public void add(int index, E element) {
        if (base != snapshot)
            super.add(index, element);

        base.add(index, (T)element);

        cache.forEach((func, list) -> {
            if (func != null)
                list.add(index, func.apply((T)element));
        });
    }

    @Override
    public E remove(int index) {
        E old = snapshot.remove(index);

        for (List<?> back : cache.values())
            if (back != snapshot)
                back.remove(index);

        return old;
    }
}
        System.out.println(String.join(" ", stringList));
        System.out.println(intList.stream().map(String::valueOf).collect(Collectors.joining(" ")));
    }

    private static final class ObservableList<E> extends AbstractList<E> {

        private final List<List<?>> cache;
        private final List<E> base;

        public static <E> List<E> create(List<E> delegate) {
            if (delegate instanceof ObservableList)
                return new ObservableList<>(((ObservableList<E>)delegate).base, ((ObservableList<E>)delegate).cache);
            return new ObservableList<>(delegate, new ArrayList<>());
        }

        public static <T, R> List<R> create(List<T> delegate, Function<T, R> func) {
            List<R> base = delegate.stream().map(func).collect(Collectors.toList());
            List<List<?>> cache = delegate instanceof ObservableList ? ((ObservableList<T>)delegate).cache : new ArrayList<>();
            return new ObservableList<>(base, cache);
        }

        @SuppressWarnings("AssignmentOrReturnOfFieldWithMutableType")
        private ObservableList(List<E> base, List<List<?>> cache) {
            this.base = base;
            this.cache = cache;
            cache.add(base);
        }

        @Override
        public E get(int index) {
            return base.get(index);
        }

        @Override
        public int size() {
            return base.size();
        }

        @Override
        public void add(int index, E element) {
            for (List<?> back : cache)
                back.add(index, element);
        }

        @Override
        public E remove(int index) {
            E old = base.remove(index);

            for (List<?> back : cache)
                if (back != base)
                    back.remove(index);

            return old;
        }
    }

A: You need to create a wrapper on top of the first list, considering your example, the List<Integer>.
Now if you want List<String> to reflect all the runtime changes done to List<Integer>, you have two solutions.

*

*Don't create initial List<String>, use a method or a wrapper which will always return the transformed values from List<Integer>, so you'll never have a static List<String>.

*Create a wrapper around List<Integer>, which should have a reference to List<String>, and override the add(), addAll(), remove() and removeAll() methods. In the overridden methods, change the state of your List<String>.

A: Another option would be to use the JavaFX ObservableList class which can wrap an existing list with an observable layer on which you can define the operations you want to propagate.
Here is an example which propagates from the string list to the integer list:
List<String> strList = new ArrayList<>();
List<Integer> intList = new ArrayList<>();
ObservableList<String> strings = FXCollections.observableList(strList);
strings.addListener((ListChangeListener<String>) change -> {
    if(change.next()) {
        if (change.wasAdded()) {
            change.getAddedSubList().stream().map(Integer::valueOf).forEach(intList::add);
        } else if (change.wasRemoved()) {
            change.getRemoved().stream().map(Integer::valueOf).forEach(intList::remove);
        }
    }
});

strList = strings;

strList.add("1");
strList.add("2");
strList.add("2");
System.out.println(intList);
strList.remove("1");
System.out.println(intList);

If you execute this code you will see this output on the console:
[1, 2, 2]
[2, 2]

A: Because of your example I am assuming that the method, you have no access to, only modifies the list and does not access the data itself.
You could use Raw Types.
List list = new ArrayList<Object>();

If you want to access the data you have to convert everything to the desired type.
list.stream().map(String::valueOf).<do_something>.collect(toList())

Not the cleanest solution but might work for you.
I think the cleanest solution would be to implement a wrapper as you already stated.
Example using the System.out:
public static void testInteger(List<Integer> list) {
    list.add(3);
    list.remove(0);
}

public static void testString(List<String> list) {
    list.add("4");
    list.remove(0);
}

public static void main(String...args) {
    List list = new ArrayList<Object>(Arrays.asList("1", "2"));
    testInteger(list);
    System.out.println(list.toString()); // will print: [2, 3]
    testString(list);
    System.out.println(list.toString()); // will print: [3, 4]
}

You always use the same reference, that way you dont need to worry about inconsistencies and its more performant then to always transform the objects.
But something like this would break the code:
public static void main(String...args) {
    List list = new ArrayList<Object>(Arrays.asList("1", "2"));
    testInteger(list);
    System.out.println(list.toString()); // will print: [2, 3]
    testString(list);
    System.out.println(list.toString()); // will print: [3, 4]
    accessData(list); //Will crash
}

public static void accessData(List<Integer> list) {
    Integer i = list.get(0); //Will work just fine
     i = list.get(1); //Will result in an Class Cast Exception even tho the Method might define it as List<Integer>
}

RawTypes allow you to pass the list to every Method that take a 'List' as argument. But you lose Typesafety, that may or may not be a problem in your case.
As long as the methods only access the elements they added you will have no problem.

A: Try to implement a Thread for this. The example below simulates the context you have presented, but will always have some 100% busy core.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

public class Main {

    static List<Integer> intListProperty;
    static List<String> stringList;

    public static void main(String... args) throws InterruptedException {
        Main m = new Main();
        m.execute();
    }

    private void updateAlways(Main main) {

        class OneShotTask implements Runnable {
            Main main;
            OneShotTask(Main main) {
                this.main = main;
            }
            public void run() {
                while (main.intListProperty == main.getIntListProperty()) {}

                main.intListProperty = getIntListProperty();
                main.stringList = main.intListProperty.stream().map(s -> String.valueOf(s)).collect(Collectors.toList());

                main.updateAlways(main);

            }
        }
        Thread t = new Thread(new OneShotTask(main));
        t.start();

    }

    public void execute() throws InterruptedException {

        System.out.println("Starting monitoring");

        stringList = new ArrayList<>();

        intListProperty = new ArrayList<>();
        intListProperty.add(1);
        intListProperty.add(2);
        intListProperty.add(3);

        updateAlways(this);

        while(true) {
            Thread.sleep(1000);
            System.out.println("\nintListProperty: " + intListProperty.toString()); // will print: [1, 2, 3, 4]
            System.out.println("stringList:      " + stringList.toString()); // will print: [2, 3]
        }

    }

    // simulated
    //thirdPartyBean.getIntListProperty();
    private List<Integer> getIntListProperty() {

        long timeInMilis = System.currentTimeMillis();

        if(timeInMilis % 5000 == 0 && new Random().nextBoolean()) {
            Object[] objects = intListProperty.toArray();

            // change memory position
            intListProperty = new ArrayList<>();
            intListProperty = new ArrayList(Arrays.asList(objects));
            intListProperty.add(new Random().nextInt());
        }

        return intListProperty;
    }

}


text:
Q: Is try catch in actors always bad practice? I know excpetion handling in actors should in general be done with a supervisor strategy. But is this valid for all cases?
Example

*

*There is one actor which is some kind of database.

*There are several source actors which can add data to the database actor.

*The parent child relationships of these actors are unknown.

*To add data to the database actor the source actors must be registrated at the database actor.

*If a not registrated source actors tries to add data to the database an exception is thrown.

If I follow the the error handling strategies of akka actors strictly, a supervising actor would have to handle this case.
I would prefer to catch the exception inside the database actor and send to the source actor a message, that something went wrong. Then the source actor could react (registrate to the database and try again).
Is this a good practice? Or is the total actor setup wrong? If a supervisor strategy is preferred, how should it be implemented?

A: It's perfectly fine to catch exceptions and make them into responses when you feel it's appropriate. I'd recommend using Scala's Try, as in:
Try(dangerousOperation()) match {
  case Success(res) => sender() ! res
  case Failure(ex)  => sender() ! UnableToStoreThingy("reasons...", ex)
}

Or something like that (you can also try.failed.map { ex => doThings(ex) }), depends on your style preference.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Divide and Conquer Recurrence Relation
I have this Divide and Conquer relation and I need to provide recurrance relation of it.
I got something like
$T(n) = 4T(n) + \lfloor\frac{n}{2}\rfloor$
but still confused whether this is right or wrong.
I got $4T(n)$ because the for-loop loops 4 times with no other extra lines.
However I am not quite sure about the
$+ \lfloor\frac{n}{2}\rfloor$ part.
Since the "printer($\lfloor\frac{n}{2}\rfloor$)" recursively calls the algorithm with $\frac{n}{2}$, I just added it at the end of the relation to show that it is being processed once every time the algorithm is called.
Is this right way to provide the recurrance relation?
Any help will be much appreciated.
Thank you.

A: Close, but $T$ should be "called" when the printer function calls itself recursively. Presumably, $T(n)$ counts the number of calls to printline. The recurrence [note": recurrEnce] relation ought to be:
$$
\begin{align}
T(1) &= 0 \\
T(n) &= 4 + T(\lfloor n/2 \rfloor) \quad \text{(n > 1).} \\
\end{align}
$$


text:
Q: Is it possible to manipulate the target window of a form using Jquery I got this question regarding the forms target and its target window.. lets say we have this Html.BeginForm
@using (Html.BeginForm("TestHtmlRedirect", "Home", FormMethod.Post, new {@target="_blank", @id = "tagging_frm", @class = "form-horizontal row-border" }))
{
    <input type="submit" value="Html PsBk Click" />
}

normally upon clicking the submit button it will trigger a new tab, my question is
How, or is it Possible to append something to the newly created tab of this form?
for example i want to append a loading gif on that newly created tab by the parent tab.

A: Assuming the actions and scripts are all from the same server/origin, you can do this:
$(function() {
  $("#tagging_frm").on("submit",function(e) {
    e.preventDefault(); // cancel submit
    var w=window.open("",this.target);
    w.document.write('

');
    w.document.close();
    $.post(this.action,function(data) {
      w.document.getElementById("container").innerHTML=data;
    });
  });
});

To load a csv or pdf try this alternative
$(function() {
  $("#tagging_frm").on("submit",function(e) {
    e.preventDefault(); // cancel submit
    var w=window.open("",this.target);
    w.document.write('<form id="myForm" action="'+this.action+'" target="myframe" method="post"></form>');
    w.document.close();
    w.document.getElementById("myForm").submit();
  });
});


text:
Q: How to change default size of 25mb of notebook in anaconda So here is the deal, I have a 268mb notebook in python, and I am not able to run it because notebooks have a default size of 25mb, so I need a basic guide on how to change it, I'm kind new in programming, so I really need help.
import smtplib, ssl
import mimetypes
from email.message import EmailMessage
from email.utils import formataddr
import smtplib
from email.message import EmailMessage
import pandas as pd
import os
from email.header import Header
from email.utils import formataddr

#colocando o nome das pessoas na watermark
dados = pd.read_excel('Lista investimentos.xlsx', sheet_name='Sheet4')
#colocando o nome dos arquivos
dados1 = pd.read_excel('Lista investimentos.xlsx', sheet_name='Sheet3')
###Creating a list in excel
emails = dados.values.tolist()
nome = dados1.values.tolist()#colocando o nome das pessoas na watermark

j=0
for i in range(len(emails)):
    message = EmailMessage()
    sender = formataddr((str(Header('Sender Name', 'utf-8')), 'email@gmail.com'))
    recipient = emails[i][0]
    message['From'] = sender
    message['To'] = recipient
    message['Subject'] = 'Subject'
    body = """Body."""
    message.set_content(body)
    APOSTILA = nome[i][0]
    mime_type, _ = mimetypes.guess_type(APOSTILA)
    mime_type, mime_subtype = mime_type.split('/')
    with open(APOSTILA, 'rb') as file:
         message.add_attachment(file.read(),
         maintype=mime_type,
         subtype=mime_subtype,
         filename=APOSTILA)
    print(message)
    mail_server = smtplib.SMTP_SSL('smtp.gmail.com')
    mail_server.set_debuglevel(1)
    mail_server.login("email@gmail.com", 'password')
    mail_server.send_message(message)
    mail_server.quit()
    j=j+1
print(i)

every "apostila" has a size of 4.6mb, and the len(email) = 120


text:
Q: what's a good way to determine a global maximum in an arraylist In my program i have a loop which computes integer values and put it one after another into an arraylist.
The higher the computetd integer value is, the better it is.
Now i want to continue to compute until it seems to be that there will not come any better integer value. That is, when the computed integer decreases over a range, or it does not change anymore. I'm thinking of, comparing the current computed value with the last x (how much value do i have to concern?) If it is always smaller or equals than any of the last x elements I stop computing. But with this strategy i have no guarantee that this is the global maximum, but just a local....
What is a good strategy to do that?
EDIT:
I know that there can't be a guarantee to find the global maximum.
But i know a little about the behaviour of the function:
The more values i have already computed the more unlikely it is that the global maximum will appear.

A: Well, it seems that you need to assume some heuristics to assess when to stop. Since you cannot say "I stop now, as I found my max", you can proceed in one of the following fashions:

*

*Keep current maximum and compare the next value with the current one, if it is smaller, increase the counter. If the counter reaches X (your parameter) you stop

*Use a probablity distributionfunction which has probability of 1 at 0, and 0 at +inf. this can be tailored to your liking. Then, you simply increment the number of seen values, or a counter of smaller values, and using that counter you estimate the probability using that function. If  prob < X (your param again) you stop.

Hope this gives you some idea

A: Reservoir Sampling. Store the values in a smaller array A which represents random x samples from the computed integer values. Now for a range of computed values, you can compare each with the values in array A and if you find a decreasing trend, you can stop. This would guarantee that you are dealing with global max rather than local.


text:
Q: How to clone a hdd or raid live? Is there a way to clone my ubuntu server without shutting it down or booting into rescue mode?

A: You can't clone unless you have snapshottable disks (ZFS, BTRFS, LVM).
You can copy relatively static files from the filesystem using a tool such as rsync (or even scp at a pinch). Note that "relatively static" excludes files used within a running database, almost certainly even if it's not being actively used at the point of the copy.


text:
Q: Submit no teclado numérico - Intel XDK Olá.
Estou com dificuldades para usar o submit em um input numérico no Intel XDK.
Quero que ao clicar no "GO/IR" , execute uma função.
No JS está assim:
$('ins_prod').on('submit', function(){
   alert("oi");
 });
Só que ao executar ele reseta a aplicação.

A: Resolvido:
O input estava dentro de um form. Removi e o erro de resetar o app, parou.
Vlw pela força.


text:
Q: Plotly installed, but VSCode doesn't seem to think so I'm trying to learn how to use Plotly using VSCode, but the minute I run my code from the terminal, it says ModuleNotFoundError: No module named 'plotly' Any idea why this is happening? Python is installed via Anaconda, and if I try to do pip install plotly it tells me it's already installed. I've tried nearly everything I can find about this issue and nothing works. Any suggestions would be appreciated.
I'll also add that when I do pip install plotly it gives the following:
Requirement already satisfied: plotly in /Users/username/opt/anaconda3/lib/python3.8/site-packages (4.14.3) Requirement already satisfied: retrying>=1.3.3 in /Users/username/opt/anaconda3/lib/python3.8/site-packages (from plotly) (1.3.3) Requirement already satisfied: six in /Users/username/opt/anaconda3/lib/python3.8/site-packages (from plotly) (1.15.0)

A: It's possible that you have multiple python versions installed and pip installed plotly for the wrong version. Try to do pip --version and in your code (before the plotly import) do
import sys
print(sys.version)

to see if the python versions match. If they don't, you may have to call pip3 install instead.
(Would have posted this as a comment, but don't have enough reputation).

A: Accidental fix found: I was working with the bash shell on the VS Code terminal. I switched to the zsh shell by doing exec zsh. When I ran the file using the zsh shell, everything worked.


text:
Q: Empty allure report - Allure Report unknown NaN% I have a problem with allure reports. When I run command ./gradlew allureReport after tests execution I've got an empty report with text like 'Allure Report unknown NaN%'. Does anyone have the same problem?
Here is my build.gradle configuration file:
buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath "io.qameta.allure:allure-gradle:2.8.1"
}
}

plugins {
    id "io.qameta.allure" version "2.8.1"
    id 'java'
}

apply plugin: 'io.qameta.allure'

allure {
    version = '2.8.1'
    autoconfigure = true;
    aspectjweaver = true;
resultsDir = file('/build/allure-results')
reportDir = file('build/allure-results')
}

group 'com.poc'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

test {
    useTestNG()
    dependsOn cleanTest
    systemProperties System.getProperties()
}

dependencies {
    compile group: 'junit', name: 'junit', version: '4.12'
    compile group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '3.141.59'
    compile group: 'org.seleniumhq.selenium', name: 'selenium-firefox-driver', version: '3.141.59'
    compile group: 'org.testng', name: 'testng', version: '6.14.3'
    compile group: 'org.seleniumhq.selenium', name: 'selenium-chrome-driver', version: '3.141.59'
    compile group: 'org.seleniumhq.selenium', name: 'selenium-safari-driver', version: '3.141.59'
    compile group: 'org.seleniumhq.selenium', name: 'selenium-edge-driver', version: '2.47.1'
    compile group: 'org.seleniumhq.selenium', name: 'selenium-api', version: '3.141.59'
    compile group: 'org.projectlombok', name: 'lombok', version: '1.18.10'
    compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.13'
    compile group: 'org.apache.pdfbox', name: 'pdfbox', version: '2.0.1'
    compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.6'
    compile group: 'commons-io', name: 'commons-io', version: '2.6'
    compile group: 'io.qameta.allure', name: 'allure-testng', version: '2.8.1'
}

A: You have not added the allure-maven dependency under your dependencies section.I think that's why you are getting this NaN% error.

A: It seems that there are spaces in one of the parent folder names. So, if there are spaces in folder name, keep the folder name in double quotes. Refer to the example below:
Run Allure command(allure serve) by keeping folder name in double quotes.
Suppose folder name is test automation
Incorrect: allure serve D:\test automation\webautomation\allure-results
Correct: allure serve D:\"test automation"\webautomation\allure-results

A: I also faced the same issue and you have to specify the path within the double quotes in the command prompt if there are any white spaces between the folder names.
For example, if your allure results are in the following folder - D:\test automation\webautomation\allure-results, you have to specify the command as below.
allure serve "D:\test automation\webautomation\allure-results"


text:
Q: change permalink structure with htaccess without SEO impact I can read a lot of questions about this topic but with different interpretations.
I'm going to change my permalink structure
from
http://www.example.com/%year%/%monthnum%/%day%/%postname%/ to http://www.example.com/%postname%/
So new posts will be natively in the new url format, about old posts I'm going to add just one row in the .htaccess file, following the suggestion coming from yoast.com
RedirectMatch 301 ^/([0-9]{4})/([0-9]{2})/([0-9]{2})/(?!page/)(.+)$ https://www.example.com/$4

After few test in another small website, it seems to work.
My questions are:

*

*Is finally the "best way" to do it in terms of avoiding SEO impact? (I see a lot of people using redirect plugin..someone says that wordpress does it automatically after structure changes..someone add in htaccess one row for each link even if the structure is standard..)

*About sitemap.xml, I'm using a plugin to generate it, so basically after changing permalink structure also the sitemap content (just for the post) will be completely updated. So in theory as soon as the sitemap will be processed by Gooogle, Google will see a new set of url. Could it affect current post google ranks? Any suggestions?
Sorry if there are similar question, but as you can imagine it would be very risk change.
Thanks!!!


text:
Q: How to subset multiple dataframes from a large list R I have a large list of dataframes that I would like to subset and reorder, so that they can be horizontally joined. Ideally, I would merge them, however this consistently exceeds my computer's capabiltiies, so I need to join them manually.
My large list is a list of 10 dataframes, all with 10 unique variables and one shared variable, with over 1000 rows for each dataframe:
df1:
ID, V2, V3, etc.
df2:
ID, V2_2, V3_2, etc.
and so forth.
All of these dataframes are contained within the same large list. How can I subset all of these dataframes within that large list simultaneously, such that they only include observations where ID > 100? Similarly, how can I order all of these dataframes simultaneously by the ID column, so that I can then bind them horizontally?
This seems to be the only way to have the dataframes merge, because merging the dataframes by ID directly does not appear to work, since the size of the dataframes (even though IDs are all the same for each dataframe, and each ID is unique) causes my R to freeze.

A: Try the following. Untested, since there are no test data.
1. Filter and sort
Filter ID > 100 and sort by ID.
df_list <- lapply(df_list, \(x) {
  x <- x[x$ID > 100, ]
  x[order(x$ID), ]
})

2. Merge the data.frames
This is the complicated part. The code below creates a result data.frame df_all and then puts each data.frame in df_list in its place by matching the id's. This is probably faster and no merge and Reduce function calls are needed.
all_cols <- unique(sapply(df_list, names))
all_rows <- unique(sapply(df_list, `[[`, 'ID'))
all_rows <- sort(all_rows)
df_all <- matrix(nrow = length(all_rows), ncol = length(all_cols))
df_all <- as.data.frame(df_all)
names(df_all) <- all_cols
df_all$ID <- all_rows

for(i in seq_along((df_list))) {
  i <- match(df_list[[i]]$ID, all_rows)
  df_all[i, names(df_list[[i]])] <- df_list[[i]]
}

A: This should return the desired list:
lapply(df_list, \(df) df[df$ID > 100, ])

EDIT
Update after comment that you have a list of lists. Try this:
lapply(df_list, \(df) {
    df  <- data.frame(unlist(df, recursive=FALSE))
    df[df$ID > 100, ]
    }
)


text:
Q: inner space and orthogonality questions i found this question that is made out of 2 claims and i've got to deicde if both wrong,correct or just one right. one of them i think i succeed solving, but i've had hard time with the other one for hours.
1)in $M _{nxn}^R, n>1, exists an non-zero symmetrical matrice that is orthogonal to every diagonal matrice.
2)let U be a subspace of $R^n$ that is defined as $U={(x_1,..,x_n) \in R^n | \sum _{i=1} ^n x_i=0}$ then the vector {(1,1,1,...,1) is a basis for $U^\bot$
i don't know how to solve the first one at all. regarding the second claim, it is true since an orthogonal basis can be made if $<v_i,v_j>$=1 if i=j and 0 if $i\neq j$, so {(1,1,1,..,1)} can be a basis for $U^\bot$.
thank you for helping me.


text:
Q: Python detect and retrieve filename of open csv file I'm using VBA to save an excel worksheet as a CSV file.  The macro saves it as a CSv and then opens it in excel.    I have a python code that reads the file, by the user selecting it (using tkinter) to open.
Is there a way to modify my python code to detect an open csv file, so that I can skip the user select stage? I want it to return the filepath or read open csv file. This is the current version of my code, which works if the csv file is open in excel:
import numpy as np
from Tkinter import Tk
from tkFileDialog import askopenfilename
tk=Tk()
tk.withdraw()
filename = askopenfilename()
data = np.genfromtxt(filename, dtype=[('x',float),('y',float)],comments='"', delimiter=',',skip_header=1,missing_values=True)
tk.destroy()
x=data['x']
x = x[np.logical_not(np.isnan(x))]
y=data['y']
y = y[np.logical_not(np.isnan(y))]
print x
print y

A: Which OS? If it is Windows, take a look at Get name of active Excel workbook from Python. The code in the question itself may do what you're looking for:
import win32com.client

xl = win32com.client.Dispatch("Excel.Application")
print(xl.ActiveWorkbook.FullName)

As mentioned in that question's answer, this only prints the path to the most recently opened file, but in your case it sounds like the macro is opening the file, so perhaps it would work? Otherwise, take a look at the actual answer - it seems very complete.


text:
Q: problem connecting to remote mysql database using php If I open up a cmd shell and run
>mysql --host=12.34.56.78 --port=1234 --user=myuser --password=mypassword mydb

I can successfully connect to the remote mysql database.
But if I create a php page on my localhost containing
<?php
$hostname = "12.34.56.78:1234";
$username = "myuser";
$password = "mypassword";
$dbname   = "mydb";
$connect = mysql_connect($hostname,$username,$password) or die ("Error: could not connect to database");
?>

I get the following error:
Error: could not connect to database

Can anyone explain what might be causing the problem here?
mysql_error() => mysqlnd cannot connect to MySQL 4.1+ using old authentication

A: Auth problems are a known issue with PHP 5.3 and older versions of MySQL. Check this:
http://www.bitshop.com/Blogs/tabid/95/EntryId/67/PHP-mysqlnd-cannot-connect-to-MySQL-4-1-using-old-authentication.aspx

A: maybe in your php.ini parameter sql.safe_mode is "1"?
sql.safe_mode boolean

If turned on, database connect functions that specify default values will use those values in place of supplied arguments. For default values see connect function documentation for the relevant database.


text:
Q: I do not have access to some Power BI sheets Clearly the system does not allow me to see some tables. Whether it is the tables linked to the module time or any other one. The same goes for the Purchase module, I have access to just some of the tables.
Can you guys help me understand why I cannot get access to these tables please?

note : i can access all of the sheet's records that i do not have access to on powerbi on another dynamics365 application, so i'm really confused why is that !


text:
Q: x-axis starting value for diverging plot How can I change the "x-axis starting value" from the diverging bar chart below (extracted from here), so that the vertical axis is set at 25 instead of 0. And therefore the bars are drawn from 25 and not 0.
For instance, I want this chart:

To look like this:

EDIT
It it not the label I want to change, it is how the data is plotted. My apologies if I wasn't clear. See example below:
Another example to make it clear:

A: You can provide computed labels to an (x-)scale via scale_x_continuous(labels = function (x) x + 25).
If you also want to change the data, you'll first need to offset the x-values by the equivalent amount (in the opposite direction):
Example:
df = tibble(Color = c('red', 'green', 'blue'), Divergence = c(5, 10, -5))
offset = 2

df %>%
    mutate(Divergence = Divergence - offset) %>%
    ggplot() +
    aes(x = Divergence, y = Color) +
    geom_col() +
    scale_x_continuous(labels = function (x) x + offset)

A: I'm still not 100% clear on your intended outcome but you can "shift" your data by adding/subtracting 25 from each value, e.g.
Original plot:
library(tidyverse)
library(gapminder)

set.seed(123)

gapminder_subset <- gapminder %>%
  pivot_longer(-c(country, continent, year)) %>%
  filter(year == "1997" | year == "2007") %>%
  select(-continent) %>%
  filter(name == "gdpPercap") %>%
  pivot_wider(names_from = year) %>%
  select(-name) %>%
  mutate(gdp_change = ((`2007` - `1997`) / `1997`) * 100) %>%
  sample_n(15)

ggplot(data = gapminder_subset,
       aes(x = country, y = gdp_change)) +
  geom_bar(stat = "identity") +
  coord_flip()

subtract 25:
library(tidyverse)
library(gapminder)

set.seed(123)

gapminder_subset <- gapminder %>%
  pivot_longer(-c(country, continent, year)) %>%
  filter(year == "1997" | year == "2007") %>%
  select(-continent) %>%
  filter(name == "gdpPercap") %>%
  pivot_wider(names_from = year) %>%
  select(-name) %>%
  mutate(gdp_change = ((`2007` - `1997`) / `1997`) * 100) %>%
  sample_n(15)

ggplot(data = gapminder_subset,
       aes(x = country, y = gdp_change)) +
  geom_bar(stat = "identity") +
  coord_flip()

If you combine that with my original relabelling I think that's the solution:
ggplot(data = gapminder_subset,
       aes(x = country, y = gdp_change - 25)) +
  geom_bar(stat = "identity") +
  coord_flip() +
  scale_y_continuous(breaks = c(-25, 0, 25, 50),
                     labels = c(0, 25, 50, 75))

A: The answers that existed at the time that I'm writing this are suggesting to change the data or to change the label. Here, I'm proposing to change neither the data nor the labels, and instead just change where the starting position of a bar is.
First, for reproducibility, I took @jared_mamrot's approach for the data subset.
library(gapminder)
library(tidyverse)

set.seed(123)

gapminder_subset <- gapminder %>%
  pivot_longer(-c(country, continent, year)) %>%
  filter(year == "1997" | year == "2007") %>%
  select(-continent) %>%
  filter(name == "gdpPercap") %>%
  pivot_wider(names_from = year) %>%
  select(-name) %>%
  mutate(gdp_change = ((`2007` - `1997`) / `1997`) * 100) %>%
  sample_n(15)

Then, you can set xmin = after_scale(25). You'll get a warning that xmin doesn't exists, but it does exist after the bars are reparameterised to rectangles in the ggplot2 internals (which is after the x-scale has seen the data to determine limits). This effectively changes the position where bars start.
ggplot(gapminder_subset,
       aes(gdp_change, country)) +
  geom_col(aes(xmin = after_scale(25)))
#> Warning: Ignoring unknown aesthetics: xmin

Created on 2021-06-28 by the reprex package (v1.0.0)


text:
Q: Legacy PHP 5.2 where does $DOCUMENT_ROOT defined? When migrating a legacy PHP 5.2 server, I stumble against this code in the index.php
<?php
require_once("$DOCUMENT_ROOT/config.php");
// Other code

The $DOCUMENT_ROOT here act and behave just like the normal$_SERVER['DOCUMENT_ROOT'], which is very strange to me as I didn't see $DOCUMENT_ROOT defined anywhere.
This page is meant to be access by user and not called from other scripts, so the variable unlikely called in from other php files as well.
I am curious, is there some configuration on PHP 5.2 which makes it that the document root is specified in $DOCUMENT_ROOT? Or maybe it is some custom library we install that create this $DOCUMENT_ROOT variable?


text:
Q: running python modules in python launcher I made a small game of pong in python and the idle I used was eclipse and all of it works (for the most part). But when I try to run the game through the python launcher rather than eclipse it crashes immediately. In fact any program that I make in eclipse won't run outside of it. I'm basically trying to figure out how I will be able to put my game on other peoples computers.
What is the problem?

A: Your description is too generic, but I'll answer as to what is the most likely issue: your environment.
Fundamentally, eclipse does NOT use the pythonpath set in your environment. It has its own internal configuration (python interpreter, pythonpath, etc...).
So make sure your environment variables match your eclipse configuration. That is likely to solve your problem.


text:
Q: Edit and run Mathematica notebook on remote from local machine I have a labtop and high performance desktop machine, and mathematica is installed in both of them.
I'm looking for the way to use mathematica with remote file and remote machine as if local machine.
I'm looking for the way to edit and run mathematica notebook in remote desktop machine from local laptop with, namely the way which realize following goal.
Goal:

*

*Use mathematica interactive interface and see the execution results on laptop

*mathematica notebook fies I wanna edit and run are on remote machine and calculation is performed with resource of remote machine


text:
Q: Get crash report from app in ios I have create ios app. Now I want to get crash report from app, which means if user click a button then need to send a crash report of the app to particular mail id.
Is it possible to do?


text:
Q: What strategy should I take now that MS will no longer support LINQ to SQL? Please if you have used NHibernate and Entity Frameworks, please contrast your experiences.

A: You might also consider looking at Castle ActiveRecord, which is a layer on top of NHibernate.  It makes the whole ORM thing sparkle, in my opinion.

A: We were early adopters of LINQ to SQL, but only on a limited basis while waiting for the Entity Framework.  We have only started working with EF, but my largest complaint is still the same one that I had with LINQ to SQL, being that my domain model is still married to either the data source or the framework, meaning my POCOs are not really as independent as they should be.
Of course, on the Entity Framework Design blog, they have recognized that persistence ignorance is a very popular requested feature (and will be in the next release), and there is at least one example of how to achieve persistence ignorance while using true POCOs here.
We also evaluated NHibernate.  It is very solid and easy to use.  Realistically, with all other things being equal, NHibernate is better established but I have a personal preference to stick with the Microsoft implementations unless I have a legitimate reason not to - if for no other reason than the quality level of support I can get.


text:
Q: Como mostrar un div al cargar la pagina actualmente tengo un div oculto

   //aca esta el contenido

pero lo que busco es que cuando termine de cargar la pagina se muestre.
estuve intentando asi:

pero no resulta... habra alguna manera de que se pueda dar?

A: Veo que estas usando jQuery.  En ese caso puedes usar $(document).ready() y .show().  Quedaria asi:

$(document).ready(function() {
  $('#llave').show();
});

   //aca esta el contenido

A: Utiliza jquery.


text:
Q: How to use an if condition to select only the values different from NA in a matrix? I am trying to apply a function on the elements of an array that are different from NA. I tried to use an if statement with the !is.na function but I get an error message saying that the "argument is of length zero". Would someone have an idea on how to fix that error or an alternative way to only select the non NA values of the matrix?
F <- function(x, a, b, c, d) {
  f <- a*(tanh(b*(x - c)) - d)
  return(f)
}

nlon <- 3241 ; nlat <- 1680
p1 <- 3221 ; p2 <- 1103
pr_new <- matrix(0, nlat, nlon) # for the example
lim <- 10

for (n in 1:nlon) {
  a <- -0.5; b <- 1; c <- 0; d <- 1 #Parameters of F
  if (n < p1) { #left side of the step
    for (m in nlat - lim:nlat) {
      if (!is.na(c(pr_new[m, n]))) { #no calculation on the NA values
        pr_new[m, n] <- F(n, a, b, c, d)
      }
    }
  } else { #right side of the step
    if (is.na(c(pr_new[p2, n]))) { #if we are on the upper step
      for (m in p2 - 1:p2 - 1 - lim) {
        if (!is.na(c(pr_new[m, n]))) { #no calculation on the NA values
          pr_new[m, n] <- F(m, a, b, c, d)
        }
      }
    } else { #if we are on the lower step
      for (m in p2:p2 - lim) {
        if (!is.na(c(pr_new[m, n]))) { #no calculation on the NA values
          pr_new[m, n] <- F(m, a, b, c, d)
        }
      }
    }
  }
}

A: You can find out which value to which a loop-index was set after an error by simply typing the loop-index name at the console:
Error in if (!is.na(c(pr_new[m, n]))) { : argument is of length zero
> m
[1] 0             # R uses 1 based indexing so 0 indexed value is not there
> n
[1] 1
> str( p2:p2-lim)  # demonstrating error
 num 1093

The comment was correct from @zephryl , but it only identified one of the three times that a similar error was made.
 for (m in nlat-lim:nlat){ ...
 for (m in p2-1:p2-1-lim){ ...
 for (m in p2:p2-lim){ ...

In each of these an expression using both colons and minnus signs has been incorrectly contsructed because the ":" has a higher operator precedence than a binary minus sign. You can find the operator precedence rules at the  ?Syntax help page.
If you correct those three errors you get code that runs without error.
for (n in 1:nlon){
    a= -0.5; b=1; c=0; d=1 #Parameters of F
    if (n<p1){ #left side of the step
        for (m in (nlat-lim):nlat ){  # fix #1
            if (!is.na(c(pr_new[m,n]))){ #no calculation on the NA values
                pr_new[m,n]=F(n,a,b,c,d)
            }
        }
    }
    else{ #right side of the step
        if (is.na(c(pr_new[p2,n]))) { #if we are on the upper step
            for (m in (p2-1):(p2-1-lim) ){  # fix #2
                if (!is.na(c(pr_new[m,n]))){ #no calculation on the NA values
                    pr_new[m,n]=F(m,a,b,c,d)
                }
            }
        }
        else { #if we are on the lower step
            for (m in p2:(p2-lim) ){   # fix # 3
                if (!is.na(c(pr_new[m,n]))){ #no calculation on the NA values
                    pr_new[m,n]=F(m,a,b,c,d)
                }
            }
        }
    }
}

Regarding the tangential "answer" from a new user of low rep, I did test the theory that it might return a similar answer. I did try chatGPT on some questions and noticed that it not only returned incorrect ansers, but it was alo unable to learn from its mistakes when there were reported to it. When the title and body of the question were given to ChatGPT it gave an almost identical answer to the now-deleted one.
The which function can be used to return a vector of indices from an array or matrix but it is most useful when it is used with the arr.ind parameter is set to its non-default value: ..., arr.in = TRUE. And na.omit can be used to remove cases from matrices. It will however, remove, entire lines of values for any row that contains a single NA.


text:
Q: Can't find file saved in Propellerhead Reason 8 I made a song in Propellerhead Reason 8 and I named the file ".cubicle..reason" but now I can't find the file. I was wondering how I could use terminal to locate the aforementioned file.

A: Files that begin in a . are invisible to Finder. If you go to the directory in terminal and enter ls -a it will show the invisible files.
You can do mv .cubicle..reason cubicle..reason which will change the name and make the file visible.
To view hidden files in Finder see: How to show hidden files and folders in finder?


text:
Q: Laravel FacebookProvider Error. Undefined variable: access_token I have strange problem with facebook provider in my project (Laravel 5.2);
Undefined variable: access_token vendor/laravel/socialite/src/Two/FacebookProvider.php 80

It's strange because it worked long time and now i have error.
Nothing was changed in my code.

A: I make a patch and it works for me. In  vendor/laravel/socialite/src/Two/FacebookProvider.php Replace
parse_str($body, $data);
return $access_token;

With
parse_str($body, $data);
$json = json_decode(key($data));
return $json->access_token;

A: It may be caused by the depreciation of v2.2 Graph API.
Checkout the changelog at facebook.
In v2.3 Graph API, Oauth Access Token calls now return a valid JSON message insted of an encoded URL.
The new format of this response is {"access_token": {TOKEN}, "token_type":{TYPE}, "expires_in":{TIME}}.


text:
Q: uninstall google chrome using powershell script I am using the following code to uninstall google chrome software from my remote machines, But this script is executed with no output. And when i check the control panel, still the google chrome program exists. Can someone check this code?
foreach($computer in (Get-Content \path\to\the\file))
{
$temp1 = Get-WmiObject -Class Win32_Product -ComputerName $computer | where { $_.name -eq "Google Chrome"}
$temp1.Uninstall()
}

A: You shouldn't use the Win32_Product WMI class, one of the side effects of enumeration operations is it checks the integrity of each installed program and performs a repair installation if the integrity check fails.

It is safer to query the registry for this information instead, which also happens to contain the uninstall string for removing the product with msiexec. The uninstall string here will be formatted like MsiExec.exe /X{PRODUCT_CODE_GUID}, with PRODUCT_CODE_GUID replaced with the actual product code for that software.

Note: This approach will only work for products installed with an MSI installer (or setup executables which extract and install MSIs). For pure executable installers which make no use of MSI installation, you'll need to consult the product documentation for how to uninstall that software, and find another method (such as a well-known installation location) of identifying whether that software is installed or not.
Note 2: I'm not sure when this changed but ChromeSetup.exe no longer wraps an MSI as it used to. I have modified the code below to handle the removal of both the MSI-installed and EXE-installed versions of Chrome.

# We need to check both 32 and 64 bit registry paths
$regPaths =
"HKLM:\SOFTWARE\Wow6432node\Microsoft\Windows\CurrentVersion\Uninstall",
"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"

# Since technically you could have 32 and 64 bit versions of the same
# software, force $uninstallStrings to be an array to cover that case
# if this is reused elsewhere. Chrome usually should only have one or the
# other, however.
$productCodes = @( $regPaths | Foreach-Object {
    Get-ItemProperty "${_}\*" | Where-Object {
      $_.DisplayName -eq 'Google Chrome'
    }
  } ).PSPath

# Run the uninstall string (formatted like
$productCodes | ForEach-Object {

  $keyName = ( Get-ItemProperty $_ ).PSChildName

  # GUID check (if the previous key was not a product code we'll need a different removal strategy)
  if ( $keyName -match '^{[a-z0-9]{8}-([a-z0-9]{4}-){3}[a-z0-9]{12}}$' ) {

    # Use Start-Process with -Wait to wait for PowerShell to finish
    # /qn suppresses the prompts for automation
    $p = Start-Process -Wait msiexec -ArgumentList "/l*v ""$($pwd.FullName)/chromeuninst.log"" /X${keyName} /qn" -PassThru

    # 0 means success, but 1638 means uninstallation is pending a reboot to complete
    # This should still be considered a successful execution
    $acceptableExitCodes = 0, 1638
  }
  else {

    Write-Host "Stopping all running instances of chrome.exe, if any are running"
    Get-Process chrome.exe -EA Ignore | Stop-Process -Force

    # The registry key still has an uninstall string
    # But cannot be silently removed
    # So we will have to get creating and control the uninstall window with PowerShell
    # We need to use the undocumented --force-uninstall parameter, added to below command
    $uninstallString = "$(( Get-ItemProperty $_).UninstallString )) --force-uninstall"

    # Break up the string into the executable and arguments so we can wait on it properly with Start-Process
    $firstQuoteIdx = $uninstallString.IndexOf('"')
    $secondQuoteIdx = $uninstallString.IndexOf('"', $firstQuoteIdx + 1)
    $setupExe = $uninstallString[$firstQuoteIdx..$secondQuoteIdx] -join ''
    $setupArgs = $uninstallString[( $secondQuoteIdx + 1 )..$uninstallString.Length] -join ''
    Write-Host "Uninstallation command: ${setupExe} ${setupArgs}"
    $p = Start-Process -Wait -FilePath $setupExe -ArgumentList $setupArgs -PassThru

    # My testing shows this exits on exit code 19 for success. However, this is undocumented
    # behavior so you may need to tweak the list of acceptable exit codes or remove this check
    # entirely.
    #
    $acceptableExitCodes = 0, 19
  }

  if ( $p.ExitCode -notin $acceptableExitCodes ) {
    Write-Error "Program exited with $($p.ExitCode)"
    $p.Dispose()
    exit $p.ExitCode
  }

  exit 0
}

Incidentally, if you already know the MSI ProductCode of a given program you don't have to find the uninstall string this way. You can simply execute msiexec /X{PRODUCT_CODE_GUID}.
If you have further problems which aren't caused by the syntax of the above this would be an operational issue and would be better troubleshot over at the https://superuser.com site.

Edit
As discovered via our chat conversation, you are installing per user and with the 79.0.3945.130 version. You can remove per user Chrome with the following command if installed per user (if the version is different you will need the correct version path):
&"C:\Users\username\AppData\Local\Google\Chrome\Application\79.0.3945.130\Installer\setup.exe" --uninstall --channel=stable --verbose-logging --force-uninstall

In the future, it is not recommended to use ChromeSetup.exe or ChromeStandaloneSetup64.exe to install and manage Chrome in an enterprise environment, you should instead use the Enterprise MSI and install system-wide so you can manage Chrome more efficiently. This is the supported way to deploy Chrome in an enterprise environment, and the script I provided will work to uninstall Chrome via msiexec and searching the registry for the {PRODUCT_CODE} as provided.

A: Assuming it's an msi install and remote powershell is enabled:
invoke-command -computername comp001 { uninstall-package 'google chrome' }

For the programs provider (all users), it's something like:
get-package *chrome* | % { $_.metadata['uninstallstring'] }

"C:\Program Files\Google\Chrome\Application\95.0.4638.54\Installer\setup.exe" --uninstall --channel=stable --system-level --verbose-logging

And then run that uninstallstring, but you'd have to figure out the silent uninstall option (--force-uninstall).  It also runs in the background.


text:
Q: Automatically do ThenInclude if there is any ICollection in Include I have the following code:
public async Task<T?> SingleOrDefaultClientWhereAndSelect<T>(
    Expression<Func<Client, bool>> where,
    Expression<Func<Client, T>> select,
    List<Expression<Func<Client, object>>> includes
)
{
    if (where is null) throw new ArgumentNullException(nameof(where), "where was null");
    if (select is null) throw new ArgumentNullException(nameof(select), "select was null");

    var query = _configurationDbContext.Clients.Where(where);

    foreach (var include in includes)
    {
        query.Include(include);
    }

    return await query.Select(select).SingleOrDefaultAsync();
}

And when I call Include in foreach loop, I also want to load all ICollections (with ThenInclude) related to included object. How can I do it, if I don't know type of included object?


text:
Q: Time complexity for a variation on the hailstone sequence? Consider the following code segment.
    Looping(n)
      {
       while (true) {
         if (n <= 1) then return;
          else if (n mod 3 = 0) then n = n * 5 + 1;
         else n = n/9; // integer division
      }

What is the worst case time complexity of this code segment? `

A: One important observation we can make about this code is that after any two steps are taken, the size of n will decrease by a factor of (roughly) 2/3.  Here's why.  Consider any initial value of n and look at the remainder modulo three.

*

*If the remainder is one or two, we divide n by nine and round down.

*Otherwise, the remainder is 0.  Setting n = 5n + 1 now leaves n with a remainder of one, so on the next iteration we will divide it by nine.  The new value of n is then the floor of (5n + 1) / 9, which is (roughly speaking) 5/9ths the original value.  It's certainly no more than 2/3s of the original value.

Therefore, we get that this will terminate after O(log n) steps, since each iteration decreases n by some constant factor.
Hope this helps!

A: It's O(log(n)). Every time you do a 5n+1 you follow with a divide by 9 (since 5n+1=1 mod 3 if n=0 mod 3), so at the worst you're doing (5n+1)/9 every two steps, which is less than 2n/3 every two steps. This is O(log(n)). If it happens that n mod 3 is never 0, then you're dividing by 9 each step, which is also O(log(n)), just with a different constant.
So whatever n is, you're going to take O(log(n)) steps to get to 1 or 0.


text:
Q: Proof involving sets and reflexive tuples under modulo Intro:
Recently, in a Deep Learning class, I was asked to prove that circulant matrices are commutative under matrix multiplication (you may see where my problem comes from with this information). There was one part of my original approach to this proof that I could not figure out. I already submitted the assignment with a different approach, but I was very curious about what this proof would look like.
Problem Statement:
Let $g(a, b) = (a-b)\mod n$ where $n \in \mathbb N$. For any two integers $i, k$ such that $0 \leq i, k \leq n-1$. We define the set $S_{ik}$ of tuples as $S_{ik} = \{(g[i, j], g[j, k]): j \in \mathbb Z \text{ and } 0 \leq j \leq n-1\}.$ Prove that if $(x, y) \in S_{ik}$, then $(y, x) \in  S_{ik}$.
Example:
Say $i = 2, k = 2$, and $n = 5$. Then, our set looks like
$$
S_{22} = \{(2, 3), (1, 4), (0, 0), (4, 1), (3, 2)\}
$$
We clear reflections of the tuples with $(2, 3),(3, 2)$ and $(1, 4), (4, 1)$. I've tried a fair number of examples and they all turn out with this property.
If anyone has any ideas on how one would prove this, or a good counter-example, it would definitely satisfy my curiosity here.


text:
Q: derived equivalences and finite representation type Given two finite dimensional connected quiver algebras $A$ and $B$. Is there an easy example such that $A$ and $B$ are derived equivalent and $A$ has finite representation type but $B$ has infinite representation type? Easy should mean, that it is not hard to see that the algebras are derived equivalent and not hard to see that one is representation finite and the other representation infinite.
addition: The easiest example I found yet can be found in http://link.springer.com/article/10.1007%2Fs10468-009-9169-y#page-1 where some Nakayama algebras are derived equivalent to tame heredtiary algebra of type $\overline{E_7}$ or $\overline{E_8}$.

A: Take the path algebra $B$ of the $\tilde{D}_4$ quiver
$$\require{AMScd}\begin{CD}
@.3@.\\
@.@AAA@.\\
1@>>>2@>>>4\\
@.@VVV@.\\
@.5@.
\end{CD}$$
This has infinite representation type. The module $T=I_1\oplus P_1\oplus P_3\oplus P_4\oplus P_5$ is a tilting module whose endomorphism algebra $A$ has the same quiver, but with zero relations for all paths of length two. So $A$ and $B$ are derived equivalent.
If $V$ is a representation of $A$ with a nonzero vector space at vertex $1$, then the subrepresentation generated by a nonzero element of this vector space is either the injective at vertex $1$ or the injective at vertex $2$, and in particular is a direct summand. So the representation theory of $A$ reduces to that of the subquiver spanned by vertices $2,3,4,5$, which has finite representation type.


text:
Q: Does a straw with two branches have 2 holes? It is easy to show that a standard straw is topologically equivalent to a torus (thus it has one hole). However, what if you had something that was straw-like that had a second "branch" off of it so to speak (like pictured here)? What would this be topologically equivalent to? Does it have 2 holes?

A: Yes, it has two holes.  Here's one way to think of it.  Let's take an ordinary "double torus", like a donut with two holes in it.

Now put some fertilizer on the top part of the torus.  The torus will grow upwards, but only near the places where we put the fertilizer.  The black ring is where we want to put the fertilizer:

That upward hollow growth is the bottom part of your straw, or the waist part of a pair of cutoff trousers.
We want the growth on the bottom, to match your straw picture, so turn the torus over.  Now add fertilizer to the other side:

This time the torus grows upwards in two hollow tubes that are like the sleeves of the trousers or the arms of your straw.

Another way to think about it: a torus has the property that you make a cut all the way through it without cutting the surface into two pieces.  On a sphere this is impossible, any cut divides the sphere in two. But on a torus you can do it by having the cut go  through the hole:

But you cannot make two such cuts without dividing the torus into at least two pieces.
With a double torus, you can make two cuts without cutting the surface into two pieces, as long as you have one cut go through each hole:

You can make any two of the indicated cuts, and the double torus will stay in one piece.  But if you make all three cuts, it falls apart.
Now what kind of thing is your straw?  You can indeed make two cuts in it without it falling apart, if you send the two cuts through the two holes:

The blue cut goes down one hole, and the red cut down the other.
You could also have made one of the cuts go down one arm and back up the other arm.  The analogous cut on the figure-8-shaped double torus is to cut through the middle section of the figure-8, the purple cut in the double-torus picture above.
As with the double torus, you can make any two of the indicated cuts, and the straw will stay in one piece.  But if you make all three, it falls apart:


text:
Q: How does $(VE_1)(VE_1)^*=F_2$ hold in the proof? I am trying to understand the proof of the following proposition from the book Kadison-Ringrose vol II

Proposition 6.2.4. If $E$ and $F$ are projections in a von Neumann algebra $\mathcal{R}$ such that $E\preceq F$ and $F \preceq E$, then $E \sim F$.

Proof. Let $V$ and $W$ be partial isometries in $\mathcal{R}$ such that $V^*V=E(=E_0), VV^*=F_1\le F (=F_0), \dots$. Since $V$ maps range of $E$ isometrically onto that of $F_1$,  $V$ maps the range of $E_1$ isometrically onto that of a subprojection $F_2$ of $F_1 -$ algebraically, $(VE_1)^*(VE_1)=E_1$ and $(VE_1)(VE_1)^*=F_2$.

*

*I didn't understand the last line in the proof above.

*I have to verify that: "$V$ maps the range of $E_1$ isometrically onto that of a subprojection $F_2$ of $F_1$" holds if and only if "$(VE_1)^*(VE_1)=E_1$ and $(VE_1)(VE_1)^*=F_2$"

if part: Suppose, $(VE_1)^*(VE_1)=E_1$ and $(VE_1)(VE_1)^*=F_2$ holds. This means $VE_1$ is a partial isometry (in $\mathcal{R}$) with initial space range($E_1$) and final space range($F_2)$ this implies, in particular, $V$ maps range of $E_1$ isometrically onto that of $F_2$.
Only if: If $V$ maps the range of $E_1$ isometrically onto that of a subprojection $F_2$ of $F_1$ then we have: $(VE_1)^*(VE_1)=E_1 V^*VE_1=E_1EE_1=E_1$ this is fine but I cannot prove the 2nd relation! $(VE_1)(VE_1)^*=VE_1V^*=???$; We know $V$ maps ran$E_1$ isometrically onto  ran$F_2$, but how do I use this??
Can anyone please explain the proof of the "only if" part . Thank you.
EDIT: I think I got it. First of all assume $V$ maps ran$E_1$ isometrically onto  ran$F_2$. From the given conditions on $V$ and $E_1$ (as above) we saw that $VE_1$ is a partial isometry with initial projection $E_1$, i.e., with initial space ran$E_1$. But then
$(VE_1)(VE_1)^*$ is the final projection of $VE_1$, i.e., $(VE_1)(VE_1)^*$ is the projection on $\mathcal{H}$ whose range is $VE_1(\mathcal{H})$ which equals $F_2(\mathcal{H})$ and so $(VE_1)(VE_1)^*= F_2$.

A: It looks to me that you are making this too complicated. You have
$$
E_1\leq E,\qquad V^*V=E,\qquad VV^*=F_1.
$$
All the authors are saying is that $VE_1$ is a partial isometry with initial projection $E_1$ and final projection a subprojection of $F_1$. That is, they define $F_2=VE_1V^*$, and they  automatically have that
$$
(VE_1)^*VE_1=E_1V^*VE_1=E_1EE_1=E_1,
$$
which already gives you that $VE_1$ is a partial isometry. You also have that
$$
F_2=VE_1(VE_1)^*=VE_1V^*\leq VV^*=F_1.
$$


text:
Q: is it possible? passing address of local static value to main pointer? #include<stdio.h>

void f(int *p) {
    static int data = 5;
    p=&data;
}

int main(void) {
    int *ip=NULL;
    f(ip);
    printf("%d\n", *ip);
    return 0;
}

if it is possible.
what is cause error?
how can I fix the code?

A: In this way you end up changing the value of a local pointer, you need to pass a pointer to pointer (&) from main and use the dereference operator (*) in the function:
#include <stdio.h>

void f(int **p) {
    static int data = 5;

    *p = &data;
}

int main(void) {
    int *ip = NULL;

    f(&ip);
    printf("%d\n", *ip);
    return 0;
}

But usually we prefer to work with the same level of indirection returning the address from the function, this is easier to read (at least for me):
#include <stdio.h>

int *f(void) {
    static int data = 5;

    return &data;
}

int main(void) {
    int *ip = f();

    printf("%d\n", *ip);
    return 0;
}

A: You have to pass a pointer to the pointer to change the value of the actual pointer:
void some_fun(int **p)
{
    static int i = 10;
    *p = &i;
}

That being said, it is not necessarily advisable to do that. The only direct use I could think of is to delay the execution of the initialization of a global until its first use.


text:
Q: Creating NFC Reader application I want to develop a NFC tag reader application.  I have some knowledge about the NFC API in the Android SDK.  I have even imported the NFCDemo sample app from the Android SDK sample apps.  The NFCDemo app just creates fake tags and capture them.  I want to recognize NFC tags when they are tapped on the back of phone. I have a Google Nexus Phone to test this.
My question is, when I tap a tag on the back of the phone, the "ACTION_TAG_DISCOVERED" intent is dispatched ... How and where this intent is to be handled?  How is "ForegroundDispatch" used for the same?
Thanking in anticipation,
Shivdattam.

A: Check TagViewer.java class in NFCDemo app (http://developer.android.com/resources/samples/NFCDemo/src/com/example/android/nfc/TagViewer.html). It will give solution for your question.

A: It seems like your problem is "the Intent ACTION_TAG_DISCOVERED" is fired automatically or is to be fired by yourself after tag is touched on the back of your phone.Is it?

A: I have created an Android boilerplate project you might be interested in, it seems to cover what you are looking for.


text:
Q: Validating AVRO schema on Confluent server If we enable the property confluent.value.schema.validation on Confluent server, how is the actual validation performed? Does the broker deserialize the message and check its format? Or does it validate only that the message has the correct id of the schema?

A: It would need to deserialize the data, even partially to actually get the ID, so yes, it does both.
Try testing by forging a Avro Kafka record with an existing ID but an invalid payload for the schema of that ID.


text:
Q: error when using of nnet it is an old question about nnet. However, i did not see the answer to this problem.
when we use nnet, sometimes, it will report error as the following:
Error in y - tmp : non-numeric argument to binary operator

example
seedsANN = nnet(train, trainlabel, size=1, entropy=F,softmax=F)
# weights:  17
initial  value 62.959997
iter  10 value 27.216423
iter  20 value 23.659429
iter  30 value 23.451713
iter  40 value 23.326524
iter  50 value 23.221853
iter  60 value 22.933211
iter  70 value 20.989597
iter  80 value 20.354299
iter  90 value 20.219403
iter 100 value 20.185571
final  value 20.185571
stopped after 100 iterations
Error in y - tmp : non-numeric argument to binary operator

      AGTR1  EPAS1  EPAS2
17  0   0.399   0.8233
239 0.5038  0.6312  0.7317
151 0.3993  0.7989  0.915
259 0.3092  1   0.9124
260 0   0.3781  0.4116
29  0.06    0.4205  0.3437333333

trainlable is

0
1
0
1
1
0
1

A: For classification problems you should use:

softmax=TRUE

A: Look at the help page for predict.nnet for an example of classification nnet.  My guess is that you don't have a matrix for the y answer.


text:
Q: reconstructing a linear order corrupted by noise Suppose we have a partial order (efficiently computable), $\leq$, on $\mathbb{R}^n$, a set $S \subset \mathbb{R}^n$, and let $\rho$ be the standard Euclidean metric.  We want to find a set $S^\prime = \{f(x): x \in S\}$ such that $S^\prime$ is a linear order under $\leq$ and the "error", $E = \sum_x {\rho(x,f(x))}$, is minimal over all such $S^\prime$ such that $S^\prime$ is linearly ordered.
Is there an efficient algorithm for this problem?
It's ok to relax "minimal" to "nearly minimal" or "good" (in some sense) and to vary $\rho$ or $E$ in reasonable ways.


text:
Q: How should I construct a prior distribution with a particular kind of count data For context I will first explain the overall problem that I am working on.  I am given a catalog of product names and I am also given a large text dataset that may contain mentions of these catalog products.  The problem is that the actual product name in the catalog can be very different from how it is mentioned in the text dataset (therefore regex would not produce very good results).  Furthermore, there are many product names (or parts of product names) that are ambiguous which means that they can be present in the text dataset but not necessarily refer to the product in the catalog.
The evidence that I am using is the measure of how strong the match is between the catalog product name and the mention in the text (this is done with minimum-edit-distance).
I want to try to inject some prior information in order to solve some of these problems.  The prior information that I have and think would be useful is a measure of popularity of each product in the catalog.  My hypothesis is that popular products are more likely to be mentioned and any candidate mention that is also a very popular product should have its posterior probability of P(catalog_entry | mention_text) boosted and vice versa.  I am using wikipedia pageviews of the the wikipedia article associated with the product in the catalog as a proxy for its popularity (note that all catalog products are within the same product type/category so the pageviews should be an accurate representation of relative popularity).
So my question is what is the best way to tranform the pageview data into probabilities (i.e. what is the best distribution to model the pageview data with).  Pageviews are discrete so I suppose I need a discrete distribution where there is a large probability mass at high values.  But pageviews are also unbounded on the right.  At first I considered a Poisson distribution but it does really fit with what I want because at large enough values the probability mass will start decreasing.  I suppose that I could artificially bound the distribution between 0 and the largest pageview that I observe over all products and then use some kind of Gamma distribution.  However, a Gamma distribution is not discrete.  Can anyone see a solution to this problem?

A: I would consider the pageviews to be categorical, multinomial to be specific.  Thus a natural estimator to use as your prior would be the sample proportions
$p(\text{product j}) = \frac{ \text{totalnumber of page views for product j}}{\text{total number of page views for all products}}$
I assume you already have a model in mind for the minimum edit distance conditional on product j?  If so, then the posterior probability of product j would be
$ p( \text{product j } \vert \text{ text} ) = \frac{p( \text{text } \vert \text{ product j}) p( \text{product j}) }{ p(\text{text}) }$
where the denominator,
$p(\text{text}) = \sum_j p(\text{text } \vert \text{ product j}) p( \text{product j})$

A: Why not perform a normalizing approximation to the data and perform subsequent computations?


text:
Q: DateTime in SQLServer and VB.net I am trying to write the current date into a database table. I have set the field of the table as 'date'. I am writing
DateTime.Now.Date.ToString as a parameter to the insert/update query. So, my code is something like:
cmd.CommandText = "update tab set dt = @d where id=1"
cmd.Parameters.add("@d",DateTime.Now.Date.ToString)

This doesnt seem to be updating values in the database. Is something amiss here?

A: Don't pass in a string to something that expects a DATE.
Pass in the DateTime instance instead:
cmd.Parameters.AddWithValue("@d",DateTime.Now.Date)

A: If this is SQL Server get remove the parameter and change the SPROC to use GETDATE() that will cause this to always insert the SQL Server's current DateTime Stamp.


text:
Q: How to insert banner along with the text in shiny app How do I insert a banner along with my text I have in my APP? I saw an app that did this, I will insert the image below. The link to access this APP is:https://shiny.rstudio.com/gallery/lego-mosaic.html
Notice it has the text and a blue banner. I would like to do something similar to this. Can you help me?
Thank you very much!
Executable code below:
library(shiny)

ui <- shiny::navbarPage(
  title="Test", collapsible = TRUE,

  tabPanel("",

           br(),
           hr(),

           h2(HTML("Project <b>Description</b>"),
              style="text-align:center; color: blue;"),
           hr(),
           div(
             style = "width: 75%; margin: auto;",
             h2(HTML("Lorem Ipsum is simply dummy text of the printing and typesetting industry.
                                      Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
                                      when an unknown printer took a galley of type and scrambled it to make a type
                                      specimen book. It has survived not only five centuries, but also the leap into electronic
                                      typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of
                                      Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software
                                      like Aldus PageMaker including versions of Lorem Ipsum"),
                style="text-align:center"),
             h2(HTML("Lorem Ipsum is simply dummy text of the printing and typesetting industry.
                                      Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
                                      when an unknown printer took a galley of type and scrambled it to make a type
                                      specimen book. It has survived not only five centuries, but also the leap into electronic
                                      typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of
                                      Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software
                                      like Aldus PageMaker including versions of Lorem Ipsum"),
                style="text-align:center"))
  )
)

server <- function(input, output,session) {

}

shinyApp(ui = ui, server = server)

A: It's not entirely clear what you want. What about that:
library(shiny)

ui <- fluidPage(
  div(
    style =
      "height: 80px; background-color: blue; width: 100%; position: absolute; right:0;",
    div(
      style = "height: 100%; background-color: cyan; position: relative; width: fit-content;",
      tags$p(
        "Here some text vertically centered",
        style =
          "position: relative; top: 50%; -ms-transform: translateY(-50%); transform: translateY(-50%); padding-right: 10px; padding-left: 10px;"
      )

    )
  )
)

server <- function(input, output, session){}

shinyApp(ui, server)


text:
Q: Wordpress 'on behalf of' email Hi all the below contains example names so not to give my website away.
I have a wordpress site called blah.com that has a woocommerce shopping cart which is blah.com/products
When someone receives an email order confirmation it comes through as products@blah.com on behalf of 'Products catalogue [firstname.lastname@xyz.com]' in the header of the email in outlook 2013.
'[firstname.lastname@xyz.com]' is my personal email address and what I used when I first created the site for testing purposes.
'Products catalogue' is the name of the website (entered in the wordpress settings section)
When I use the Post SMTP plugin to send a test email its comes through correctly as products@blah.com [blah products catalogue]
Can anyone help me find where this email address is stored so I can change it to products@blah.com.
I have updated the email address in the wordpress General Settings page to products@blah.com where is was previously [firstname.lastname@xyz.com]
My email address at my hosting and email provider is products@blah.com.
I have updated the woo commerce email settings so that any emails that were previously [firstname.lastname@xyz.com] are now products@blah.com
I'm not sure what else to check? [firstname.lastname@xyz.com] must be stored somewhere in wordpress but I'm not sure where.
Many Thanks

A: is one of the "two email settings you updated" the one at "WooCommerce > Settings > Emails > Email  Sender Options"?


text:
Q: C# NPOI Formats Numbers as Text error I am trying to store zip codes (US) into an excel file using C# and NPOI.
The zip code goes in as say "12345-6789" and i don't get the error in excel "the number in excel is formatted as text or preceded by an apostrophe" ( because it has the - char in there )
Then the next line has a zip of just "12345" and it does get the error since it is a number.  but...  I would rather it not.
here is some code:
        ICellStyle cellStyleString = eWorkBook.CreateCellStyle();
        cellStyleString.DataFormat = HSSFDataFormat.GetBuiltinFormat("General");  // also tried "@", "Text"

            IRow excelRow = eWorkSheet.CreateRow(0);
            foreach (var field in zipRecord.ItemArray)
                ICell newCell = excelRow.CreateCell(fieldNumber++);
                newCell.SetCellType(CellType.String);
                newCell.CellStyle = cellStyleString;
                newCell.SetCellValue(field.ToString());


text:
Q: What is the minimum energy a quantum can bear? ...and more Here are my assumptions:

*

*Energy can be transferred only in limited dosages.

*When two particles collide, they exchange energy, so that the more energetic particle carries less and the less energetic particle carries more energy, than before the collision.

*These interactions happen on and on.

*Less and more energetic particles tend to mix.

Let's have a dissipative system with more and less energic particles. Should the system get perfectly balanced (to the state where all the particles have exactly the same amount of energy) after some time?
If some of my assumptions don't work, would my hypothesis about the perfect balance apply if these assumptions were correct?

A: Your initial assumption is wrong.
If a system has quantised energy levels then it is true that energy can be transferred only in discrete chunks that correspond to the spacing between levels. However free particles do not have quantised energy levels - the energy of a free particle lies on a continuous spectrum.
So in your model system of colliding, but otherwise free, particles any amount of energy can be transferred in a collision. However this doesn't mean all particles will have the same energy. The random nature of the collisions mean the energy distribution will follow a Maxwell-Boltzmann distribution.

A: No, in the assumptions there are some (very common, I think) misunderstandings.
The third and fourth is right, of course, this is very general.

*

*The second assumption has nothing to do with quantization, you mean it should also work for macroscopic billard balls, right? Consider two counterexamples:
a moving ball frontally hits one that is at rest. Afterwards the first is at rest and the second moving, they have exchanged their energy. So indeed the less energetic one lost energy to the other -- but too much, the energies did not move a little to the mean value, but swapped past it.
a massive and slow ball gets hit from the back by another which has double velocity and half of the mass. Obviously the first one had more energy, and obviously it will get still faster and further increase its energy. So even this is possible (but only with differently massive particles though).
You are right in that sense, that if you have half of the particles with high energy and half of them with low, than after some time the mean energy of both kinds will become equal. Even it they were of completely different type. But every single particle will have a random energy, which can become arbitrarily high (with an arbitrarily low probability ;))

*Your first assumption is a common misunderstanding. No, there is no minimum quantum of energy; only some cases where this seems so...:
Well, if you consider e.g. red light, than this is true, all energy values transferred will be a multiple of a certain quantum $\hbar \omega$. But that's because you chose to work with red light only, i.e. with particles of a certrain energy. It's not surprising, that they all have this energy :)
Also normally, quantum (= very small) systems have some energy levels ( = amounts of energy they are allowed to have), with gaps in between ( = not allowed). In that case the change of energy is obviously also restricted to certain amounts. But usually (not always, though) above a certain energy (which it is convenient to call zero) there are no more gaps and every energy is allowed. Those are called the free states of the system, as opposed to bound states with negative energy. Consistent to these notations, a free particle is in a free state and can have an arbitrary energy.
As to your last question: yes, if the particles were systems which are restricted to energies that are integer multiples of some minimal value, and if they interact only in a manner that allows energy transfers towards the mean value, then they would after a finite number of interactions all have the same energy (or with difference 1, if it doesnt add up).


text:
Q: Dynamic content for additional column with copy activity from table Storage to CosmosDb I am trying to copy form Azure Table Storage to Azure CosmosDb sql Api using Azure Data Factory V2.
During copy I want to add a new field (column) to each document by concatenating two of the column values from table. E.g. my table has 2 columns imageId and tenantId and I want to make the id of document in cosmos db like image_tenant_ImageID_TenantID.
For this I am trying to add dynamic content for "Additional Columns" under "Source" in the ADF but couldn't figure out how to do that. Can anyone please help with this?

A: Seems like I can not do it as part of copy activity. So first I copy from table to temporary cosmos container and then use dataflow to create new column by using "Derived column" activity and copy the results to a new container.

A: Another way to achieve this is using Change Feed to get your documents and then add this property. Then replace documents.


text:
Q: A regex with more than one white space package stringsplit;

public class StringSplit {

    public static void main(String[] args) {
        String s = "hello world we are anonymous ";
        String[] s3 = s.split("\\s",2);
        for(String temp:s3){
            System.out.println(temp);
        }
    }

}

O/P:
hello
world we are anonymous

The above code splits my string into two parts after 1 space character
is encountered by compiler.I then introduced '\\s+' so as to split after
2 space characters to get
o/p:
hello world
we are anonymous

But it didn't work.Thanks for you guidance in advanced.

A: According javadoc String split(regex) and split(regex, limit) work like expected. Depending on result you're trying to achieve you can use something of these below:
String s = "hello   world we are anonymous";
String[] s1 = s.split("\\s",2); //result is ["Hello", "  world we are anonymous"]
String[] s2 = s.split("\\s+",2); //result is ["Hello", "world we are anonymous"]
String[] s3 = s.split("\\s+",3); //result is ["Hello", "world", "we are anonymous"]
String[] s4 = s.split("\\s+"); //result is ["Hello", "world", "we", "are", "anonymous"]

A: You can solve your problem using String::indexof :
String s = "hello world we are anonymous ";
s = s.replaceAll("\\s+", " ").trim();//----------------------------------------------(0)
String s1 = s.substring(0, s.indexOf(" ", s.indexOf(" ") + 1));//--------------------(1)
String s2 = s.substring(s.indexOf(" ", s.indexOf(" ") + 1) + 1, s.length() - 1);//---(2)

(0)-Just to make sure that you don't have multiples spaces between the words
(1)-Get the first part from 0 to the second space
(2)-Get the second part from the second space to the end of the string

Output
hello world
we are anonymous

A: Read the Split doc, "The limit parameter controls the number of times the pattern is applied", so you can't with achieve it with split.
So if you want to split after 2 spaces, you have to write:
String s = "hello world we are anonymous ";
int firstSpace = s.indexOf(' ')+1;
int secondSpace = s.indexOf(' ', firstSpace)+1;
String part1 = s.substring(0, secondSpace);
String part2 = s.substring(secondSpace, s.length());
System.out.println(part1); // return "hello world"
System.out.println(part2); // return "we are anonymous "


text:
Q: Rename column within function in r using dplyr In this case, I have a loop that triggers a function, which in turn triggers a function that collects the data.
One weird thing, is I cannot rename the columns in the dataset created - d. Bascially I need standardised names such that I can pass different variables, and as a result, I need to rename the columns during the dplyr transformation. The problem is here: %>% rename(Con = 1, DV = 2). In the dataset I have selected, I want to label the first column con, and the second column DV, such that I can pass this into the CollectDEffect function to run the cohensD analysis. All of this works when I run line by line, but I want to run the function by all the DVs and create a table, hence why I need to get this working within the loop.
# Function to run analyses and create the dataframe with output
CD_EE_DF <- data.frame("Test" = character())

CollectDEffect = function(cd, d){
  excess <- data.frame("Test" = cd,
                       "Sample Size"  = nrow(d),
                       "Original Cohen's d" = cohensD(d$DV ~ d$Con))

  CD_EE_DF <- rbind(CD_EE_DF, excess)
  return(CD_EE_DF)
}

# Data transformation, where the error is
CollectDEffect_Trigger = function(DVTest){
  # Problem occurs here with the rename
  d <- df %>%  filter(Gender == "Female", Target_Gender != "") %>% select(Target_Gender, DVTest) %>% rename(Con = 1, DV = 2) %>% na.omit()
  CD_EE_DF <- CollectDEffect(paste0("A_",DVTest),d)
}

# Loop that triggers all of the analyses

vec_dv <- c("Status", "warmth")

for (DVTest in vec_dv) {
  CD_EE_DF <- CollectDEffect_Trigger(DVTest)
}


text:
Q: Angular CLI prod build mangles Font Awesome icons My Angular 7 application has some font awesome icons that are partially mangled when running a production build, it seems fine in dev mode. Error is:

 attribute d: Expected number, "…
  158-141.6h-108c-***************…".

I import FontAwesome using the following code in my angular.json file:
"scripts": [
              "node_modules/bootstrap/dist/js/bootstrap.min.js",
              "src/assets/js/font-awesome.js"
            ]
]

Can anyone help as to why this error occurs?
Example

Thanks!

A: This is the official font awesome angular library, you should use this:
https://github.com/FortAwesome/angular-fontawesome#upgrading-font-awesome


text:
Q: how do i add a system call / utility in xv6 Can any one tell me/ point me any references to how to add a system call / utility in XV6
exhaustive search on google was futile and hacking the hard way also was not productive so far .
the reference book also did not have any hello world example to start with
any help greatly appreciated

A: To add a system call that can be called in xv6's shell,
you should so something with the five files

*

*sysproc.c add the real implementation of your method here

*syscall.h define the position of the system call vector that connect to your implementation

*user.h define the function that can be called through the shell

*syscall.c external define the function that connect the shell and the kernel, use the position defined in syscall.h to add the function to the system call vector

*usys.S use the macro to define connect the call of user to the system call function

*defs.h add a forward declaration for your new system call

*sysfunc.h add the new system call handler into this file too like "int sys_newsystemcall(void)"

A: Read this: http://zoo.cs.yale.edu/classes/cs422/2010/xv6-book/trap.pdf
It explains it quite well

A: I will explain a simple example on adding a system call in xv6.
Assume that you have to add a system call to get the address space size of the currently running user program. You can name your system call as getmysize() and call this system call from within a user program.
You can write your user program as follows. Let the program name be myprog.c I assume that you know how to add a user program to xv6. So I will skip mentioning those steps here because it will be off the topic.
#include "types.h"
#include "stat.h"
#include "user.h"

int main(void){
  printf(1,"The size of my address space is %d bytes\n", getmysize());
  exit();
}

This program is written for the purpose of demonstrating the working of the system call only.
Now we will add our system call to xv6.
First add the following line at the end of the file syscall.h.
#define SYS_getmysize 23

Note that the 23 here might change depending on the number given before the line you are going to add in the file. That is if the system call  number is 22 in the line before the line that you are going to add, your line should have the number 23. Simple as that.
Now add the following lines to the syscall.c file.
extern int sys_getmysize(void);

and in the array of syscalls, append the following line in.
[SYS_getmysize] sys_getmysize,

In the file sysproc.c, that is where the implementation of your system call goes if it is a system call related to process handling or memory management, put the implementation of our system call as follows.
int
sys_getmysize(void)
{
   return proc->sz;
}

Now in the usys.S file, add the line,
SYSCALL(getmysize)

Then in the user.h file, add the following. This is how your user program sees your system call.
int getmysize(void);

Ok. Now you are ready to run your user program and see how your system call runs.
When you run myprog.c which calls your system call, the size of the address space of this same program will be returned according to what we have implemented here.


text:
Q: IE8 force refreshes the webpage using compatibility view I'm using a simple JavaScript method to open colorbox on button click & it works fine in all browsers except IE8 where it will refresh the page push browser in compatibility mode. Here is sample of my code:

If, I remove overflow tag from style on div, it works fine. Is there any conflict between colorbox & overflow? Any work around to fix div height?

A: I have also experienced this type of behaviour where IE8 will automatically go to comp mode. In my case, I changed some css and it was ok.
You could try overflow auto but I am not 100% sure if IE8 will provide scrollbar or not.


text:
Q: How to get the last 10 elements in a string in Python? Making a program to check whether the inputted value has a '@gmail.com' in the end.
input="abc@gmail.com"
count=1 for i in input:
    count+=1
print(input[count-11:count-1])

Output:: @gmail.com


text:
Q: Grep with multi-threading I have the following (big) file with 30233088 strings:
head mystringfile.txt:
GAATGAACACGAAGAA
GAATGAACACGAAGAC
GAATGAACACGAAGAG
GAATGAACACGAAGCA

cat sequence.txt
AAATAGAGGGCGGTCCAGGCGTGTCGAAACACTGGGTCCAGGGCAAGAGCGGTTCGGGTGTCAGGAAAGCCCCCAAGGGGGTTCGCGCGGTTTGCAGTGAGGTAGAGGCCGGTGTATGGGTAGACAATTGGGGTCCCAAAGAAAAAGGCTCGTCCAACATCATAATAAACCCAAGCACGATAAAAAGCAAACGCAGACTTCAATAGGGTACGAGCAATTGTGGCAGGGTGCTCGCTGTCAGGGTTAGATCTTCTTGGAGTCGCGTCGCTCGGGGGGGCAAGGCCAACGTAAGATCGTGGCTGATCGCTGGCAATGCGGTCGGTTGGGTGGTCGCTAGTAGGGGCACGGCGGTCTCTTATGGCGTCGTAAAATGCGTCTCCAAAGCGAAAAGGGGCGGCAGACAAGTCACCGGGCAAGCTTAGAGGTCTGGGGCCCGTGGCTTTAGGGGAATGAACACGAAGACGCGAAACGAAGTCGTGTTTCTTGTTGGCTGTAGAGGGGAAAACCGTCTGGGGCGATCTGGCGTAGTAGTGCGTGTCTTGCAGTGAGCTCCCCGTCCGTAAGGATTCGCAGGAATCCTGCGTGAAGCTCGGTCGTCTCGGCCGTGTCTCGGGGTTTGATTGCGGGTTCAGATTGGAAAGGTCTCCTCGGGTCGTTTGCTGCATTTGCTCGCAACCCTGACGTGAAAGGGGTGAGCTGTCTCCAATCTGCCACGCTGGGTGTTGCGTCGTCAGTAAAAGACTTGGTCAAGCTGGGACCTCGCAAGATCGCGAGAGGGTTAAGCACAAAAGGTATGGCGAAGCTCCCGGGTGCTCTTGTGGCCACCCAGAATCATGGTGACGTAGGTTTTGCGAAGCCATCAAAAATTCAGGCGGCAAAACGAGCCAGTAGGGTCCTGGGCAGCTGGGCTTGTAGTGGGTAGGCGGCAAAACGCAAAGAATGAACACGAAGCAACTCCGTAGTGTGACGGGGGTTCTGACAAACGTCCTGCAAGAAGTTCGTCTTGGG

which I need to grep in another sequence file to determine the position of the match, which I do as following:
while read line; do grep -b -o $line sequence.txt >>sequence.txt.count; done<mystringfile.txt

Running the code like this of course takes a very long time and just runs part of 1 thread, so how can I modify it (with parallel or xargs?) so that it is running on as many threads as I want to specify?

A: Your idea is wrong with using shell loop to process text. You are opening one new file descriptor for re-directing to output file for each of the 30233088 iterations on your input file. It is prone to a huge performance impact or a case of running out of open file descriptors.
Use the right tool for the job. Awk is your friend here. If the sequence.txt is just a huge pattern as you say, you can just slurp it into a variable for regex match as below. The solutions involves no memory overhead of having to store entries in RAM
awk -v sequence="$(<sequence.txt)" 'n=index(sequence, $1){print n":"$1}' mystringfile.txt

This should be relatively faster than the approach you have and to speed up things further, change your locale settings to match the C local,
LC_ALL=C awk -v sequence="$(<sequence.txt)" 'n=index(sequence, $1){print n":"$1}' mystringfile.txt

To match with the grep's option of -b to print the byte offset start, use n-1 in the answer above instead of just n.
If you still want to use GNU parallel, use --pipepart to split the file physically into parts and specify the --block size to how much MB of file content to read
parallel -a mystringfile.txt --pipepart --block=20M -q awk -v sequence="$(<sequence.txt)" 'n=index(sequence, $1){print n":"$1}'

A: If all your search strings in mystringfile.txt are of the same length (like in your sample file, 16 bytes), you could store all 16 byte strings from sequence.txt to an associative array (if you have the memory) and speed up the searching. Let's try that. First we need some test material, let's create a 2400000 byte sequence.txt, takes about a second:
$ awk -v seed=$RANDOM 'BEGIN{a[0]="A";a[1]="C";a[2]="G";a[3]="T";srand(seed);for(i=1;i<=2400000;i++)printf "%s", a[int(4*rand())];print ""}' > mystringfile.txt

and mystringfile.txt with 30233088 16 byte search strings (4 mins 50 secs):
$ awk -v seed=$RANDOM 'BEGIN{a[0]="A";a[1]="C";a[2]="G";a[3]="T";srand(seed);for(i=1;i<=30233088;i++){for(j=1;j<=16;j++)printf "%s", a[int(4*rand())];print ""}}' > mystringfile.txt

Then the script:
$ awk '
NR==FNR {                              # process the sequence file
    l=length($1)-15                    # length-15 16 byte strings coming up
    for(i=1;i<=l;i++) {                # using l as variable name is stupid
        s=substr($0,i,16)
        a[s]=a[s] (a[s]==""?"":",") i  # hash string start indexes to a, string as key
    }                                  # a["ACTGTGCACGTATAGC"]=3,141,592
    next
}                                      # the search part
$1 in a {                              # if search string is found
    print a[$1], $1                    # output index and string
}' sequence.txt mystringfile.txt

Storing the 2400000 byte sequence.txt to the hash took 13 seconds and used 721 MB of memory on my mini laptop. The whole script ran 35 seconds and found around 17000 hits.