How to store a value and re-use it in the same xml file?

Question: I have a autoinst.xml which will be used during the installation of the system to setup arp bonding, it is configured to take input from user with respect to ip, gateway and netmask as below
<code>        <path>networking,dns,hostname</path>
        <title>INS Server Network Settings</title>
        <question>Enter Hostname</question>
        <stage>cont</stage>
        <default></default>
    </ask>

    <ask>
        <dialog config:type="integer">2</dialog>
        <element config:type="integer">2</element>
        <path>networking,interfaces,0,ipaddr</path>
        <title>INS Server Network Settings</title>
        <question>Enter the server IP address:</question>
        <stage>cont</stage>
        <default>22.214.171.124</default>
    </ask>

    <ask>
    <dialog config:type="integer">2</dialog>
        <element config:type="integer">3</element>
        <path>networking,interfaces,0,netmask</path>
        <question>Enter the server netmask:</question>
        <stage>cont</stage>
        <default>255.255.255.0</default>
    </ask>

    <ask>
        <dialog config:type="integer">2</dialog>
        <element config:type="integer">4</element>
        <path>networking,routing,routes,0,gateway</path>
        <question>Enter the server default gateway:</question>
        <stage>cont</stage>
        <default>188.8.131.52</default>
</code>
Here I want to use the value provided in "Gateway" section above to be used below. Suppose user provides 192.168.10.100 as gateway above it should be stored in a variable and I can place the variable name inside arp_ip_target below so that the default gateway is used as the target. But I am not sure how can I do this?
<code><interfaces config:type="list">
       <interface>
          <device>bond0</device>
          <startmode>onboot</startmode>
          <bonding_master>yes</bonding_master>
          <bonding_module_opts>arp_interval=1000 arp_ip_target="**gateway**" mode=1 arp_validate=all</bonding_module_opts>
          <bonding_slave0>eth0</bonding_slave0>
          <bonding_slave1>eth1</bonding_slave1>
          <ipaddr></ipaddr>
          <netmask></netmask>
        </interface>
    </interfaces>
</code>
Answer: XML doesn't support referencing other elements or values.
Therefore it is not possible what you want to achieve. If you want to create a solution like this, you have to incorporate that in the software you use to read this file and interpret it. You could come with an own syntax for it.
Comment: Thanks for your reply, yeah even I thought the same so I hacked it and created a small shell script inside the xml file to store and call the variable later.
Comment: You are welcome. Since you are new, please don't forget to accept the answer if it was helpful to you.


Why codepush can't update native code in react-native apps?

Question: Why codepush can't update native code in react-native apps?
Answer: There are multiple reasons, but one of the biggest reasons why is Apple's publishing guidelines for App Store apps. They explicitly do not allow updating native code on client devices once they have been installed from their store. Enabling native code updates would lead to submissions being rejected en masse.


How do Iceblight and Waterblight affect Prowlers?

Question: Both blights normally affect hunters in some way related to their stamina, but since Prowlers have no stamina, how are they affected?
Answer: Waterblight makes your run speed slower.
Prowlers normally have three dodges they can do in a row, a bit like Lances, where the first two are normal dodges and the third has a longer animation. Iceblight removes the first two, making it more difficult to dodge as you can't do it as quickly.


Groovy include new Groovy script

Question: I'm pretty new to Groovy an I want to import a class from another groovy script in the main groovy script. I saw already this post. However due to environment restrictions I can't us functions like GroovyClassLoader or or import any libs/frameworks. The only possibility I have is to use the evaluate method.
I tried this:
main script (The evaluate does not throw any error)
File csvFile = new File("./Csvreader.groovy");
evaluate(csvFile);

Csvreader script
class CSVReader{
    def csvFile = new File('./test.csv');
    def separatorChar = ";"
    def values = [];
    def headers = [];

    void setSeperator(String s){
        if(s != ""){
            separatorChar = s;
        }
    }

    void readCsv(){
        csvFile.eachLine{ line, number ->
            if(number == 1){
                def head = line.split(separatorChar);
                for (entry in head) {
                    headers.add(entry);
                }
            } else{
                def value = line.split(separatorChar);
                def map =[:];
                def i = 0;
                for (entry in value) {
                    map.put(headers[i], entry);
                    i++;
                }
                values.add(map);
            }
        }

    }

    def getValues(){
        return values;
    }

    def getHeaders(){
        return headers;
    }

    def getSize(){
        return values.size();
    }

    def getLine(def keyParam, def value){
        for(int i = 0; i < values.size(); i++){
            def line = values[i];
            if(values[i][keyParam] == value){
                return values[i];
            }
        }

    }

}

However I would need to pass parameters with the evaluate call (and I would move the methods outside the class) or I need to create an instance of the class.
Unfortunately I don't really know how I can do that, does anyone have a solution for that?
Comment: Why you can't use class loader? Are you in jenkins pipeline?
Comment: Not exactly but the product I am using is so restricted that not all Groovy methods are allowed
Comment: ok. there is no such method as `evaluate` in groovy. seems it's provided by your product and you have to read a manual of this product...
Comment: Are you sure about that? Cause in the linked [post](https://stackoverflow.com/questions/9136328/including-a-groovy-script-in-another-groovy?noredirect=1&lq=1) the top answer was evaluate
Comment: ok. i got it - you mean Script.evaluate method https://docs.groovy-lang.org/latest/html/api/groovy/lang/Script.html#evaluate(java.io.File)
Comment: Ahh ok thanks for the link. As I can see the method does not allow to add parameters. Therefore I have to think of something else. Thanks for your help.
Answer: you could try to put at the end of your Csvreader.groovy file the expression return CSVReader.class that will return you a compiled class.
Then in your caller script you could create an instance of this class and use it as any other class instance.
Csvreader.groovy
class CSVReader{
    def separatorChar = ";"

    void setSeparator(String s){
        if(s != ""){
            separatorChar = s;
        }
    }
}

return CSVReader.class

caller script
File csvFile = new File("./Csvreader.groovy")
def CSVReaderClass = evaluate(csvFile)
def cvsReader = CSVReaderClass.newInstance()

cvsReader.setSeparator("Z")
println cvsReader.separatorChar

Comment: Thx that's exactly what I needed

Groovy include new Groovy script


Product of two beta distributions

Question: Say I have two random variables:
X ~ Beta(α1,β1)
Y ~ Beta(α2,β2)
I would like to compute distribution of Z = XY (the product of the random variables)
With scipy, I can get the pdf of a single Beta with:
from scipy.stats import beta
rv = beta(a, b)
x = np.linspace(start=0, stop=1, num=200)
my_pdf = rv.pdf(x)

But what about the product of two Betas? Can I do this analytically? (Python/Julia/R solutions are fine).
Answer: FWIW, same in Python
from scipy import stats
import statsmodels.api as sm
import matplotlib.pyplot as plt

N = 100000

y = stats.beta(.5, .9).rvs(N)
x = stats.beta(.9, .5).rvs(N)
z = x*y
dens_z = sm.nonparametric.KDEUnivariate(z)
dens_z.fit()

dens_x = sm.nonparametric.KDEUnivariate(x)
dens_x.fit()

dens_y = sm.nonparametric.KDEUnivariate(y)
dens_y.fit()

fig, ax = plt.subplots()
ax.plot(dens_z.support, dens_z.density, label='z')
ax.plot(dens_x.support, dens_x.density, label='x')
ax.plot(dens_y.support, dens_y.density, label='y')
ax.legend()
plt.draw_if_interactive()

Answer: For an analytical solution, have a look at this paper and this answer.
A numerical approach in R
set.seed(1) # for reproducability

n <- 100000 # number of random variables

# first beta distribution
a1 <- 0.5
b1 <- 0.9
X <- rbeta(n, a1, b1)

# second beta distribution
a2 <- 0.9
b2 <- 0.5
Y <- rbeta(n, a2, b2)

# calculate product
Z <- X * Y

# Have a look at the distributions
plot(density(Z), col = "red", main = "Distributions")
lines(density(X), lty = 2)
lines(density(Y), lty = 2)

Comment: @user815423426 All values are between zero and one. Hence, multiplying values will always result in lower values.
Comment: @user815423426 Yes, this assumes independency.
Comment: @user815423426 I don't know of any implementation of the multivariate beta distribution (in R).
Comment: Thanks - May I ask - Why is the distribution of Z skewed towards lower values of Z? (X and Y seem to be the symmetric with respect to each other)
Comment: Great. Thanks Sven - I presume that this assumes independency between `X` and `Y`? or does it not?
Comment: Great. Thanks - Any ideas on to approach the problem if they weren't independent?
Comment: sorry if im being obtuse, but dont we need to integrate to get the Z distribution? See https://en.wikipedia.org/wiki/Product_distribution

Product of two beta distributions


Return all values from row without column names in R

Question: I'm looking to return all values of a row in a data frame. However, this can't be done simply but subsetting as follows, because it also takes in the names of the columns.
df <- data.frame(person, salary, haircolor, outcome)
head(df)
          person salary haircolor  outcome
1       John Doe  21000     black  married
2     Peter Gynn  23400    blonde divorced
3     Jolie Hope  26800    blonde divorced

df_row1 <- df[1, ]
print(df_row)
>df_row1
  person   salary haircolor outcome
1 John Doe 21000  black     married

I need to create a vector for the first row values (without the column names). Actually, I'm looking to loop this through every row to create a vector for every row.
For example, I'm looking for the following for the first row:
print(df_row1_good)
>df_row1_good
John Doe 21000  black     married

Answer: If we want to remove the names attributes, unlist and specify use.names = FALSE
unlist(df[1,], use.names = FALSE)
#[1] "John Doe" "21000"    "black"    "married"

to print
cat(unlist(df[1,], use.names = FALSE), '\n')
#John Doe 21000 black married

Or unname
unname(df[1,])

Comment: The `unlist` function returns numeric values in my console. Do you know why this would produce different results for you and me?
Comment: @juansalsa The difference would be that if you have `factor` columns.  From `R 4.0`, by default ,`stringsAsFactors = FALSE` in `data.frame` call or when reading with `read.csv/read.table`.  If you have a previous version, it would be TRUE i.e. strings will be `factor` and this gets coerced to numeric one.  You can do `unlist(type.convert(df, as.is = TRUE)[1,], use.names = FALSE)`


Send MultiValueMap as MultiPartFormData in Feign Client

Question: I am trying to convert the below kotlin code from RestTemplate to Feign client. The rest template code sends multiValueMap as request with content-type header multipart/form-data and consumes JSON object as response.
RestTemplate Code:
    var headers = HttpHeaders()
    headers.contentType = MediaType.MULTIPART_FORM_DATA
    headers.add("custom-header", "value")
    val body: MultiValueMap<String, Any> = LinkedMultiValueMap()
    body.add("field1", "value1")
    body.add("field2", "value2")
    val requestEntity = HttpEntity(body, headers)
    return restTemplate.postForEntity("https://enmf7tx8y37x.x.pipedream.net/", requestEntity, Object::class.java)

In this case the request is sent as below:
Headers:
Host: enmf7tx8y37x.x.pipedream.net
X-Amzn-Trace-Id: Root=1-6303ecb2-19a833a044ab3bf83f74f256
Content-Length: 342
Accept: application/xml, text/xml, application/json, application/*+xml, application/*+json
Content-Type: multipart/form-data;boundary=_MtEGFIF4XK_aOU8QsXstQuCliV1-llj
custom-header: value
X-B3-TraceId: a67561ec329f9a16
X-B3-SpanId: a6cc94e403bfe318
X-B3-ParentSpanId: a67561ec329f9a16
X-B3-Sampled: 1
User-Agent: Apache-HttpClient/4.5.13 (Java/17.0.3)
Accept-Encoding: gzip,deflate

Body:
 --_MtEGFIF4XK_aOU8QsXstQuCliV1-llj
    Content-Disposition: form-data; name="field1"
    Content-Type: text/plain;charset=UTF-8
    Content-Length: 6

    value1
    --_MtEGFIF4XK_aOU8QsXstQuCliV1-llj
    Content-Disposition: form-data; name="field2"
    Content-Type: text/plain;charset=UTF-8
    Content-Length: 6

    value2
    --_MtEGFIF4XK_aOU8QsXstQuCliV1-llj--

I tried to do the same in Feign client:
code:
/*val headers = HttpHeaders()
    headers.contentType = MediaType.MULTIPART_FORM_DATA
    headers.add("custom-header", "value")*/
    val body: MultiValueMap<String, Any> = LinkedMultiValueMap()
    body.add("field1", "value1")
    body.add("field2", "value2")
    val result = testClient.test("value", body)

Feign Client:
@FeignClient(
  value = "testClient",
  url = "https://enmf7tx8y37x.x.pipedream.net/"
)
interface TestClient {
  @PostMapping(
    consumes = [MediaType.MULTIPART_FORM_DATA_VALUE],
    produces = [MediaType.APPLICATION_JSON_VALUE]
  )
  fun test(
    @RequestHeader(value = "custom-header") customHeader: String,
    @RequestPart("request") request: MultiValueMap<String, Any>
  ): ResponseEntity<Object>

}

The header are fine but no value present in the body.
Header:
Host: enmf7tx8y37x.x.pipedream.net
X-Amzn-Trace-Id: Root=1-6303ef0f-78c869881a5b27d0707eab9e
Content-Length: 17
Accept: application/json
Authorization: Basic aHlwb2xhYjp0ZXN0c211cmY=
Content-Type: multipart/form-data; charset=UTF-8; boundary=182c75dd399
custom-header: value
X-B3-TraceId: 2989eb4f12e3d417
X-B3-SpanId: 23414bcdf365784c
X-B3-ParentSpanId: 2989eb4f12e3d417
X-B3-Sampled: 1
User-Agent: Java/17.0.3

Body:
--182c75dd399--

I had to add consumes value as multipart/form-data instead of json to get the right header values for Accept and Content-Type.
How can I populate the request using Feign client? If the @RequestPart is String then the value is sent in the body but any other data type like multiValueMap, byteArray, etc were not working
Comment: https://github.com/OpenFeign/feign-form
Comment: https://www.baeldung.com/java-feign-file-upload
Answer: In feign client you cannot use MultiValueMap directly. You have to use MultipartFile datatype for bytearray and for the remaining metadata fields you need to mention each one as a separate argument in the method. Then FeignClient will generate the same request like the one you showed when using RestTemplate.
import org.springframework.cloud.openfeign.FeignClient
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.RequestHeader
import org.springframework.web.bind.annotation.RequestPart
import org.springframework.web.multipart.MultipartFile

    @FeignClient(
      value = "testClient",
      url = "https://enmf7tx8y37x.x.pipedream.net/"
    )
    interface TestClient {
      @PostMapping(
        consumes = [MediaType.MULTIPART_FORM_DATA_VALUE],
        produces = [MediaType.APPLICATION_JSON_VALUE]
      )
      fun test(
        @RequestHeader(value = "custom-header") customHeader: String,
        @RequestPart(name = "file") file: MultipartFile,
        @RequestPart(name = "field1") field1: String
      ): ResponseEntity<Object>

    }

code sample for How to create MultiPartFile:
import org.springframework.mock.web.MockMultipartFile

//val multipartFile: MultipartFile = MockMultipartFile("filename", byteArray)
val multipartFile: MultipartFile = MockMultipartFile("filename", "filename", "content type like application/pdf", byteArray)


Changing django-allauth render_authentication_error behavior

Question: I'm a newcomer to the python/Django universe and just started a huge project I'm pretty excited about. I need to have my users login through Facebook and my app has a really specific user flow. I've set up django-allauth and everything works as I needed. I've overriden LOGIN_REDIRECT_URL so that my users land on the page I want when they log in.
BUT. When the user opens Facebook login dialog box and then closes it without logging in, the authentication_error.html template gets rendered by allauth.socialaccount.helpers.render_authentication_error, and this is not the behaviour I want. I want the user to simply be redirected to the login page.
Yes, I know I could simply override the template by putting it in my TEMPLATE_DIRS, but then the url wouldn't be the same.
I've come to the conclusion I needed a middleware to intercept the response to the http request.
from django.shortcuts import redirect

class Middleware():
    """
    A middleware to override allauth user flow
    """
    def __init__(self):
        self.url_to_check = "/accounts/facebook/login/token/"

    def process_response(self, request, response):
        """
        In case of failed faceboook login
        """
        if request.path == self.url_to_check and\
                not request.user.is_authenticated():
            return redirect('/')

        return response

But I'm not sure about the efficiency of my solution nor the pythonesquitude (I juste came up with that word) of it. Is there anything else I could do to change that default django-allauth behavior without using a middleware or a signal?
Thanks!
Answer: I decided to use a middleware and redirect to home url in case a GET request is made on a URL of the form ^/accounts/.*$
from django.shortcuts import redirect
import re

class AllauthOverrideMiddleware():
    """
    A middleware to implement a custom user flow
    """
    def __init__(self):
        # allauth urls
        self.url_social = re.compile("^/accounts/.*$")

    def process_request(self, request):

        # WE CAN ONLY POST TO ALLAUTH URLS
        if request.method == "GET" and\
           self.url_social.match(request.path):
            return redirect("/")

Answer:
Yes, I know I could simply override the template by putting it in my TEMPLATE_DIRS, but then the url wouldn't be the same.

Overriding a template won't change the URL. In your overridden template, you could do a client-side redirect to whatever URL you prefer.
Comment: What I meant is the URL wouldn't be the same as the root url where I want to redirect on login error. Anyway, I've chose to simply use a middleware and redirect GET requests to /accounts/* to root url
Comment: Cool, glad you found a solution.


Visual C++ 2010 Express for mac

Question: Is it possible to get Visual C++ 2010 Express for Mac OS X?
If not is there another application, other than Xcode, that will do the same thing?
Comment: If you run Windows in Virtualbox/Parallels/VMWare Fusion, you can run VC2010 Express. Otherwise, try [Eclipse with CDT](http://www.eclipse.org/cdt/), which will use GCC as the compiler. If you're trying to build Windows software however, you will need to use a compiler targeting Windows.
Answer: Visual Studio C++ is not supported on OS X.
You can use either Eclipse or KDevelop. A complete listing IDEs for C++ is available at
http://en.wikipedia.org/wiki/Comparison_of_integrated_development_environments#C.2FC.2B.2B
Answer: There is no Visual Studio for Mac that I'm aware of. I think QtCreator, Eclipse and NetBeans all work on Mac.
Answer: Microsoft has a version of Visual Studio which is cross platform. It will run on Windows, Mac OSX and Linux. It is called Visual Studio Code. You can download it at: https://code.visualstudio.com/download
You will have to download the C++ extensions. It will take you to the market place where you can get the extension for free.
Personally I prefer Xcode when coding on a Mac.
It's not hard to learn, but because it is fairly new there aren't many useful videos or articles on how to navigate Visual Studio Code. If you are familiar with Visual Studio IDE for Microsoft Windows, Visual Studio Code is a totally different program.
Answer: You can try Eclipse:
http://www.eclipse.org/downloads/packages/eclipse-ide-cc-developers-includes-incubating-components/indigor
Answer: If you really want visual c++ bootcamp you MacOS. Install windows along side with Mountain Lion and you are good to go.

Visual C++ 2010 Express for mac


How to fix error Could not find class 'io.realm.rx.RealmObservableFactory$2'?

Question: I'm developing an android application with realm using Eclipse. But I am facing an issue. When I Create Object of realm, the following exception occurred at realm.createObject(Product.class).
Can you help me understand why this exception occurred? Is there any thing missing on my side?

Error: Could not find class 'io.realm.rx.RealmObservableFactory$2',
  referenced from method io.realm.rx.RealmObservableFactory.from

Product product=new Product();
Realm realm = Realm.getInstance(this);
realm.beginTransaction();
realm.createObject(Product.class);
product.setId("1001");
product.setName("John");
realm.commitTransaction();
realm.close();

Product Class object file.
 import io.realm.RealmObject;
 import io.realm.annotations.PrimaryKey;
 import io.realm.annotations.RealmClass;
 import io.realm.*;

 @RealmClass
 public class Product extends RealmObject {
 @PrimaryKey
 String id;
 String name;
 public Product(){
    super();
 }
 public Product(String id, String name){
    super();
    this.id = id;
    this.name = name;
 }
public String getId() {
    return id;
}
public void setId(String id) {
    this.id = id;
}
 public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
}

Thanks,
Answer: I'm guessing that Eclipse somehow doesn't gracefully handle the missing Rx.Observable class that is optional to include. Have you tried either of the solutions described here? https://realm.io/docs/java/latest/#jackson-databind


Why does my KitchenAid refrigerator temperature fluctuate?

Question: We have a 7-year-old KitchenAid (Model# KRSC503ES00) side by side refrigerator. The refrigerator section temperature fluctuates. It will be 50 degrees for a few days and then it returns to normal temperature in the mid 30s for a couple of days. The freezer section works fine.
We had a tech look at it and he gave up.
I have replaced the control board and both thermistors in the refrigerator section. This model has one compressor and condenser which provides cooling to the evaporator in the freezer section and the evaporator in the refrigerator section.
Any suggestions on what else to look at?
Comment: the causes of modern refrigerator failures are legion.  I would look for ice buildup on the 50 degree days.  Maybe the defrost timer is off?
Answer: Just a follow-up to my refrigerator not cooling consistently. I paid a visit to the Just Answer website. A tech there suggested that since the thermistors were replaced, the control board was replaced and the fan works, the only thing remaining was the solenoid valve. This valve provides coolant to either the refrigerator section or the freezer section (1 line in, 2 lines out).
I checked the part number with our local appliance parts store and they informed me that they had never sold one. I also talked to a local tech that has been repairing appliances for over 35 years. He never replaced one. So out of curiosity I decided to locate it and remove it. It was not that hard. I also disconnected the wiring connector. I re-installed it and the refrigerator has now been working for 4 days. Either the connector pins were corroded or there was dirt between the solenoid housing and mechanical valve housing.  Success! (so far)
Comment: Thanks for the update, and congratulations on fixing it! Be sure to Accept the answer that helped you the most (probably your own?) which officially closes the loop on the Question/Answer flow here.
Answer: The fan/fan motor (W11396715) would be the most suspect (remaining) part on this model, to me, since the freezer and fridge evaporator sections are separate. If the fan fails to start sometimes, distribution of air in the refrigerator will suffer as it's designed for fan-forced flow.
Comment: The fan works fine. The freezer and the refrigerator sections are isolated from each other. The only thing they have in common is the compressor and condenser. Each section has its own fan.
Comment: And if the refrigerator fan works fine, but only sometimes, it would expain your symptoms of the temperature being fine, but only sometimes.
Comment: The fan is not the issue. The fan works fine.  The tech verified that.


Clash Royale loading problem

Question: Whenever I open Clash Royale, the progress bar will stop at 50 %, and doesn't go further. I even tried reinstalling the game, but that didn't work. Can somebody tell me how to fix this tricky problem?
I'm playing on an iPhone 8.
Comment: I'd try talking to your carrier. Maybe it's something on their end.
Comment: How's your internet? Mine would stop at 50% if I was ever offline or had bad connection.
Comment: I'm using the mobile data, so I don't really think it's a connection problem.
Comment: This is indicative of a network issue.
Comment: Yes, that would be helpful, thank you.
Answer: Try to clear the cache for the game and then open it
if not then clear the cache and reinstall
---hopes to work fine
Comment: Yep, this worked with me. I own an Android though. But I don't think it should be any different on iOS.(if you are allowed to clear cache that is)
Answer: For iOS (expected answer) this may be found from a bug or your phone does not meet ping or quality.
 Improvements/Solutions
You can clear your data from the phone, although I do not recommend deleting your game data. Restarting your phone or force stop for a few hours may help with the problem, and if these do not help, do the following:

Contact Supercell Support

Contact Apple about the game bug/leave a review on the game (There is a small chance of Supercell responding)

 Common Solutions
Some common solutions to this **without deleting game data** is that you may update your phone on the App Store, or you can just uninstall the game and reinstall it back.

 Conclusion
Try all these methods and hopefully one will help the loading screen load to 100% and you can start playing.

Clash Royale loading problem


Resolution set too low on startup, solutions do not work

Question: After installing natty, my resolution is being set to 1024x768 instead of the proper 1368x768. The Monitors program doesn't allow me to set my resolution higher. I looked around for a solution, and I found instructions on using xrandr to set a new resolution:
xrandr --newmode "1368x768_60.00"   85.25  1368 1440 1576 1784  768 771 781 798 -hsync +vsync
xrandr --addmode VGA1 1368x768_60.00
xrandr --output VGA1 --mode 1368x768

This worked (but it broke the top Unity panel). Now I need to find a way to automatically start the xrandr commands on boot. I edited /etc/gdm/Init/Default and ~/.xprofile, but neither worked.
What do I do? Can I stop the problem from happening in the first place?
Answer: This generally happens when the monitor doesn't report it's resolution correctly.
As you've found out, at runtime you can use the xrandr tool to add a correct mode and then switch to it.  To make this permanent, you can edit /etc/X11/xorg.conf and add that mode as the preferred mode.  I find the Debian XSF XRandR howto a good guide for editing XRandR settings in xorg.conf.
Comment: I don't have an xorg.conf, and I'm still not sure what exactly should I do. I followed some instructions elsewhere and tried generating one with `sudo X -configure`, but that didn't work. What should I do now? Sorry if I'm being dumb.
Answer: Have you tried editing the file /etc/X11/xorg.conf ?
You can find many tutorials out there that explain how to add your own screen resolution in that file :

here is a link to the man page.
and this is a forum post telling you what to do more thoroughly.
Answer: I also had the same problem and solved it after reading this document. Also you might want to check the question I posted at askubuntu.com and it's answers here.


maven dependency:tree log: version1 compile (version managed from version2)

Question:
I faced a problem with dependency:tree. It troubled me a few days.
I defined solr-solrj with version 6.6.0 in my pom.xml in one of my modules named A as below:
<dependency>
    <groupId>org.apache.solr</groupId>
    <artifactId>solr-solrj</artifactId>
    <version>6.6.0</version>
</dependency>
Another module named B dependencies on module A. when I run mvn dependency:tree -Dverbose -Dincludes=org.apache.solr:solr-solrj, the console appears org.apache.solr:solr-solrj:jar:5.5.3:compile (version managed from 6.6.0). I find all the pom.xml, I haven't defined the 5.5.3 version. And I haven't found any jar dependencies on 5.5.3 version transitively in my project.
What's the meaning of 5.5.3:compile (version managed from 6.6.0 ? And why 5.5.3 version appeared in my project?

pic1 is that I use idea to show dependencies. pic2 is I clicked solrj jump to pom.xml.
Answer: Either the pom for module B or the parent pom for module B includes a <dependencyManagement> section. Dependency management is used in maven to centralize the versions used for jars. It is likely overriding the version of solr-solrj you defined to be version 5.5.3. Dependency management functions in two main ways. You are probably experiencing what is described in section 2. Please see the conclusion for a summary specific to your question.
1. It is a central place for defining versions of dependencies.
So when an artifact version is defined in the <dependencyManagement> section you can declare the dependency in your pom without defining the version, and the version defined in <dependencyManagement> will be used automatically.
Example 1
Let's say your parent pom defined the following
<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.mememe</groupId>
      <artifactId>mylib</artifactId>
      <version>1.1.12</version>
    </dependency>
  </dependencies>
</dependencyManagement>

Then if you define the following in your pom
<dependencies>
  <dependency>
    <groupId>com.mememe</groupId>
    <artifactId>mylib</artifactId>
  </dependency>
</dependencies>

Your project will automatically use version 1.1.12 as defined in the <dependencyManagement> section of your parent pom.
2. Overriding the versions of transitive dependencies.
If you have an artifact version defined in your <dependencyManagement> and one of your dependencies has a transitive dependency on the same artifact, the version of the artifact defined in your <dependencyManagement> section is used automatically.
Example 2
Let's say this artifact
<dependency>
  <groupId>com.youyou</groupId>
  <artifactId>yourlib</artifactId>
  <version>3.0.0</version>
</dependency>

Has this transitive dependency
<dependency>
  <groupId>com.morestuff</groupId>
  <artifactId>morelib</artifactId>
  <version>2.0.0</version>
</dependency>

Now let's say our parent pom defines this <dependencyManagement> section
<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.morestuff</groupId>
      <artifactId>morelib</artifactId>
      <version>2.5.2</version>
    </dependency>
  </dependencies>
</dependencyManagement>

Then if you define this dependency in your pom
<dependency>
  <groupId>com.youyou</groupId>
  <artifactId>yourlib</artifactId>
  <version>3.0.0</version>
</dependency>

Maven will override yourlib's dependency on morelib version 2.0.0 with morelib version 2.5.2.
Conclusion
Specific to your question, someone has defined a <dependencyManagement> section like the following in the pom or parent pom of module B:
<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.apache.solr</groupId>
      <artifactId>solr-solrj</artifactId>
      <version>5.5.3</version>
    </dependency>
  </dependencies>
</dependencyManagement>

Since solr-solrj is a dependency of module A and mondule A is a dependency of module B. Dependency management is overriding the version of solr-solrj to be 5.5.3 . You should speak with the person who added this dependencyManagement configuration in your project, there is likely a good reason why they only wanted version 5.5.3 to be used.
Docs
See more details in the official maven docs here.
Comment: yeah, you're right. I found version 5.5.3 defined in spring-boot-dependencies pom.xml. And spring-boot-dependencies defined in module B parents' dependencyManagement.
Comment: Thanks for such a good explanation, saved my time, I also found dependency management which is causing this.
Comment: I've a similar problem where i see ` org.freemarker:freemarker:jar:2.3.31:compile (version managed from 2.3.32)` but there is no dependencyManagement section in any of my poms


Copy the Windows 7 files to Ubuntu 14.04

Question: I was working in the Windows 7 OS previously, now i shifted to the ubuntu 14.04 version. I had important file on D && E drive of Windows 7 which i couldn't take backup. How to recover those data in Ubutnu?
(I had choose the only ubuntu option while installing the ubuntu)
Comment: You may also find http://askubuntu.com/questions/463076/partitions-disappeared-after-power-loss-while-installing/463094#463094 helpful.
Answer: If you chose the Delete Windows option, then there is no way to recover your files (if the files were in the same partition as the Windows install).
If you backed up the files to another partition/drive, then you can open them with Ubuntu's file manager by selecting where it is.
Comment: This isn't really helpful as the OP has indicated that no backup was done. Also saying something is impossible doesn't make it so.


Determine screen-size media query using Javascript

Question: Is there an easy way to determine which breakpoint "mode" is currently in place using Javascript?
For example I am using SASS to set the view according to the $small-only, $medium-only etc. variables. However if the user has resized the browser and the $small-only breakpoint is being used I'd like to be able to query this in Javascript. So something like the following:
if ($small) {
    // do something
} else {
    // do something different
}

Comment: Are you looking for this solution? https://stackoverflow.com/questions/1248081/get-the-browser-viewport-dimensions-with-javascript
Answer:

var debouncer = (function () {
  var timers = {};
  return function (callback, ms, uniqueId) {
    if (!uniqueId) { uniqueId = "Don't call this twice without a uniqueId"; }
    if (timers[uniqueId]) { clearTimeout (timers[uniqueId]); }
    timers[uniqueId] = setTimeout(callback, ms);
  };
})();

function breakpointCheck() {
  var $r = $(".responsiveChecker");

  if ($r.css("font-weight") === "500" ) {
    return 5;
  } else if ($r.css("font-weight") === "400" ) {
    return 4;
  } else if ($r.css("font-weight") === "300" ) {
    return 3;
  } else if ($r.css("font-weight") === "200" ) {
    return 2;
  } else if ($r.css("font-weight") === "100" ) {
    return 1;
  }
}

try { console.log("Breakpoint: " + breakpointCheck()); } catch(err) {}

$(window).on("resize", function() {
  debouncer(function() {
    console.log("Breakpoint: " + breakpointCheck());
  }, 500);
});
.responsiveChecker {
    font-weight: 500;
}
@media (max-width: 1600px) {
    .responsiveChecker {
        font-weight: 400;
    }
}
@media (max-width: 1120px) {
    .responsiveChecker {
        font-weight: 300
    }
}
@media (max-width: 767px) {
    .responsiveChecker {
        font-weight: 200
    }
}
@media (max-width: 374px) {
    .responsiveChecker {
        font-weight: 100
    }
}

I have put together a codepen for what I think you are trying to achieve: https://codepen.io/MayhemBliz/pen/MOGMpW


Does this septic tank have built in baffles?

Question: I had a septic tank delivered and want to understand what needs to be done for the hookup (I'm not doing it myself, just want to be sure I understand the requirements).
I'd seen / read that you usually build a sort of sideways T structure at either end of the tank with the lower end of the outlet T higher than the lower end of the inlet T-- but this tank seems to have built in baffles already at both ends-- does this not need that structure, and you just plumb a straight pipe in?

Second question is how does the pipe get sealed when it penetrates the box? Is it some sort of mastic / sealant? Or is a friction seal good enough since the fluid level probably wouldn't get this high

Thanks
EDIT: I'm just asking about the inlet / outlet baffles as shown in this drawing (not drainfield size or interior baffles in the tank itself). The tank seems to have something already installed, and I'm not sure if this is the case or if they tank still needs these baffles installed.
Comment: The piece of steel looking and the other plastic looking objects  would be called baffles.  If your local health department agrees is another matter, they have the final say
Comment: The requirements will vary depending on location. Check with the installers and the local inspectors.
Comment: The size of tank and location have requirements but I don't see a baffles. , the area , size of building or number of bathrooms / bedrooms define the size of the tank and drain field , the tank baffles are different than the surface baffles as your pics show, so more information is needed.
Comment: @EdBeal I edited the question to show the baffles I'm asking about. The tank seems to have them pre-installed, but I've never seen this before so I'm hoping someone knows. Thanks
Comment: The tanks that have been required in my jurisdiction required 2 chambers. A wall was between the chambers and most of the solids drop out in the first chamber that is what we called baffles the inspection covers allowed the tank to be pumped and for the last ~20 years a sealed shaft and manhole cover has been required to the top of the tank on the sediment side.
Answer: The plastic (which is tapered) around the pipe holes should seal when a pipe is pushed through it. Cut out the center neatly (your contractor should be experienced with this detail.)
Assuming your LAHJ agrees, the tank does appear to have baffles, though I'm sure the tank supplier could confirm that (and that the outlet baffle is also a filter) if you ask them. One aspect that the inlet baffle solves is that Tee baffles made as illustrated are prone to clogs - I went with 6x4x6 tee for that part on the advice of my LAHJ, as they claimed that had much fewer problems with clogging than 4x4x4 Tee for the same use. Your steel inlet has considerably more area than a 4" pipe, which achieves the same end, and if it's all stainless and properly fastened so it does not fall off in several years, it's less subject to breakage than a hunk of pipe is.
The presumably/hopefully stainless steel appears to be the inlet baffle.
The more complex structure at the other end appears like it might be a filter (which is a good thing to have on the outlet) and baffle in one - there should be access from above there as well to inspect/clean it. Of the two, that's the more important one to have a permanent riser to ground level and manhole cover for - knowing where the tank is from that reference, you can get to the other end if needed with a shovel, but you would very rarely need to. If your LAHJ requires a riser at both ends, you do that to keep them happy. Regular maintenance (clean filter and pump out sludge) can all be done from the outlet end.
If the presumed filter has provisions to add a handle (typically made of small diameter PVC pipe) you'll want to do that before the tank is placed in service, extending up into the riser above the tank.
Comment: Thanks-- that's very useful. There is an inspection port above the outflow baffle, though there isn't a filter in there. I'm in N Idaho, and I don't think that's code here (as far as I know anyway). The inlet baffle is actually heavy plastic, not steel, but it's screwed to the wall of the tank with stainless screws, it appears.
Comment: Whether or not code requires it, an outflow filter is good practice. Keeps things that should not be in the drain field out of it, and far better to plug a filter that can be removed and cleaned (and get you to pump the tank)  than to plug your drain field that requires a backhoe to fix/replace. They've been an established technology for a couple of decades now.


Forcing WebGL texture reload from buffer

Question: I am using (a slightly modified version of) mmap in electron to share memory between two different processes. Then I use this memory, in the form of a buffer to upload a WebGL texture and I use it to draw stuff:
buffer = mmap(196608,mmap.PROT_READ,mmap.MAP_SHARED,"shared_mmap",0)

f = function(){
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, 256, 256, 0, gl.RGB, gl.UNSIGNED_BYTE, buffer);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.bindTexture(gl.TEXTURE_2D, null)
}

This works perfectly, the first time. Although I can see the data being changed by the other process (if I evaluate buffer[100]in the console) the texture remains the same in the WebGL scene.
However, if I copy the buffer to a TypedArray, it works perfectly:
arr = new Uint8Array(buffer)
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, 256, 256, 0, gl.RGB, gl.UNSIGNED_BYTE, arr);

The problem is that doing it this way I am repeatedly copying all the data every frame, which kind of defeats the purpose of using a mmap.
Is there a way of updating the WebGL texture with buffer data without copying its contents to a new array every time?
Comment: I didn't know you could pass a node::Buffer to gl.texImage2D. But if it's work the first time, why do you need to copy it to Uint8Array for the update?
Comment: I works the first time, but it does not update with new information in the buffer. The information stored in the buffer changes because it is basically shared memory, but somehow texImage2D doesn't realize that.
Comment: Have you find a solution? I'm in a similar situation with a node native module that renders to a node::Buffer a YUV surface than then is displayed through a webgl canvas... The only way I can make it work is to create a different node::Buffer for every frame (pointing to the same data).
Answer: You are not copying the data, with new Uint8Array(buffer), you are creating a new reference to the same data.
Here you can read more about DataViews.
Comment: But [in node documentation it says otherwise](https://nodejs.org/api/buffer.html#buffer_buffers_and_typedarray):`The Buffer object's memory is copied to the TypedArray, not shared`


how can i improve a graph with plot in matlab?

Question: I need to plot two arrays with data very close together.
How can I improve the performance of the graphic
I would like to reduce the line plot.

https://dl.dropboxusercontent.com/u/41574157/my_plot.png
Comment: Upload somewhere the pictures and link them here?
Comment: Place your image on a public sharing website and I will edit your post.  Also, what do you mean by "reducing the line plot"?
Comment: I added the link. I mean a less detailed chart...
Comment: What do you mean by "less detailed"?  Do you want to decrease the resolution of your data?
Comment: Yes,decrease the resolution or do an interpolation
Comment: What are you trying to achieve? Smoothing the data? Take a look at moving averages.
Comment: I could try both, but I do not know how to do specially
 the moving averages that peraphs could be the solution)
Answer: From the comments, you either want to do some sort of interpolation, smoothing, or a subsampling of points.  Let's take a look at all approaches:
Method 1 - Subsampling
This is pretty easy to do.  Supposing that both of your data points are stored in x and y, you can specify how often you want to sample from your data.  If you wanted to sample every 10 points as an example, you can do something like:
xsample = x(1:10:end);
ysample = y(1:10:end);
plot(xsample, ysample);

plot will linearly interpolate in between each of the points for you already.  This is the default behaviour of plot.
Method 2 - Interpolating (not linear)
You can subsample your points like we did above, then use interp1 to interpolate in between the "keypoints".  Let's assume you want to do a spline interpolation.  As such:
yinterp = interp1(xsample, ysample, x, 'spline');
plot(x, ysample);

Method 3 - Smoothing
If you have the Curve Fitting Toolbox, you can use the smooth function.  The default behaviour of the smooth function is a moving average.  It basically takes your points within a finite sized window, averages them and that is the output for one sample.  The averaging gives you an output that is a smoothed version of your data.  The default window is of width 5, but you can specify whichever span you want.
ysmooth = smooth(y); %// or you can do ysmooth = smooth(y, N);
                     %// where N is the size of your smoothing window
plot(x, ysmooth);

NB: N must be an odd number (1, 3, 5, etc.)
Hopefully one of these methods will work for you!
Comment: i'm sorry, but I do not have enough reputation to vote. I'm a new user


Create EDL file with ability to step back and forward frames

Question: Right now I use MCEBuddy to automatically cut commercials and convert my recorded TV, but sometimes the commercial detection isn't the best, and I like to do it manually.
For this, I'm using mplayer with the -edlout option, which works fine.  However, I sometimes have to go back multiple times to get the cut where I want, and I can't step back frame by frame.  Mplayer doesn't seem to support this, but makes creating the edl files very easy.
I've recently found MPV, which apparently is derived from mplayer. It does have the option to step back frame by frame, as well as skip through the video with more granularity.  However, it doesn't seem to natively support creating edl files in the mplayer format like I need.
Is there an easy way to make either of these programs work how I want?  I saw that mpv allows you to use Lua scripts, but I've never worked with those and am not sure they'll allow me to do what i want.  I'm also not set on using either mplayer or mpv.  If you can suggest something better/easier that will get the job done, that's fine too.
Any help would be appreciated. Thanks
Comment: [MPV Lua scripting](https://github.com/mpv-player/mpv/blob/master/DOCS/man/lua.rst) would allow you to bind keys to Lua functions which can fetch (current) video properties and save them to a file. This way you could easily create your own custom [EDL](http://www.mplayerhq.hu/DOCS/HTML/de/edl.html) file tool. [Lua](http://www.lua.org/pil/1.html) isn't one of the hardest languages to learn.
Comment: I figured it out, thanks
Answer: If you have MCEBuddy, try using the MCEBuddy Custom Cuts tool included to mark the video cuts and create a EDL file.
It's granularity is limited to the resolution provided by the Windows DirectShow codecs it uses to display the video on the screen and mark locations.
Ref: https://www.facebook.com/479215282109210/posts/804598616237540/


directed graph edges

Question:
From what I understand, the shortest path would be from 7 to 15 is:
7-->10-->14-->13-->15
From this assumption, there are five nodes. How many edges would there be in the shortest path?
Does the formula $n * (n-1)$ still holds? If, so there would be 20, but I am having a hard time seeing that many edges.
Comment: How many edges or paths ?
Comment: I am looking for edges
Comment: 5 nodes, then 4 edges ?
Comment: SO is the formula above for paths?
Answer: There are four edges in your path. The edge from 7 to 10, the edge from 10 to 14, the edge from 14 to 13, and the edge from 13 to 15.
$n * (n-1)/2$ is the number of edges in a complete graph on $n$ vertices. A path with $n$ vertices always has $n-1$ edges.

directed graph edges


Android UI shows RadioButton as selected, although it is not

Question: When my UI is recreated on orientation change, I use super.onCreate(savedInstanceState) and getLastNonConfigurationInstance() to access custom data I stored to fill the dynamic parts of my layout.
I have a RadioGroup which has two RadioButtons and is already defined in the XML file. The XML automatically makes the first one selected.
When an orientation change happens and the SECOND RadioButton is selected, everything seems to work fine; the second RadioButton is still selected in the UI.
But RadioGroup.getCheckedRadioButtonId() says the first RadioButton is selected. And I actually WANT the first one to be selected. But nothing changes when I call rb1.setChecked(true) - second one still shown as selected, and still the RadioGroup tells me the first one is selected (now it would make sense, but it's not shown).
This is REALLY strange behavior, does anyone have tips?
(edit)
Parts of my code:
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.itemselected);
    (...)
    radioGroupServingType = (RadioGroup) findViewById(R.id.radioGroupServingType);
    (...)

    RadioButton radioOwnServing = (RadioButton) findViewById(R.id.radioOwnServing);
    RadioButton radioUseServing = (RadioButton) findViewById(R.id.radioUseServing);

    radioOwnServing.setOnClickListener(this);
    radioUseServing.setOnClickListener(this);

    //FIXME WTF
    Log.d("", radioOwnServing.isChecked()+"/"+radioUseServing.isChecked()+" own/use checked");
    radioOwnServing.setChecked(true);
    Log.d("", radioOwnServing.isChecked()+"/"+radioUseServing.isChecked()+" own/use checked");

If I select radioUseServing in the UI and change the orientation, the log says true/false own/use checked both times - although radioUseServing is shown as selected in the UI.
By the way, logcat also outputs
W/asset(4040): deep redirect failure from 0x0103003e => 0x02060007, defStyleAttr=0x0101007e, defStyleRes=0x0103001a, style=0x00000000

when changing the orientation, sometimes multiple times. I haven't found anything with google on what that means.
Comment: I just did a workaround for the problem by removing the two RadioButtons from the RadioGroup, creating two new RBs and adding them instead, so that the RBs in the xml are only placeholders. This works, but is kind of dirty and doesn't solve the underlying problem...
Answer: I already spoke with you on IRC, but I believe that if you get the view, and post a runnable to it that will call .setChecked(), this will in effect cause the setChecked call to occur at the proper time, and thus avoiding having called setChecked before the view hierarchy was ready for it.
Something like this:
final View myRadioButton  = findViewById(R.id.myradiobutton);
myRadioButton.post(
    new Runnable() {
        @Override
        public void run() { myRadioButton.setChecked(true); }
    }
);


Does the improved usability of making account creation in checkout optional apply to subscription service e-commerce?

Question: Making account creation a requirement for e-commerce checkout experiences has been shown to creation friction that unnecessarily slows users to completing a purchase.
Does this apply to purchasing software products, specifically subscription-based ones, that require setting up an account to use them?
My argument has been that any extra fields slow down checkout and the one for password is a high conversion risk. Engineers have pointed to some competitors and other subscription services which require account set up to make a purchase.
I assume this is irrelevant to the issue at hand and just because a competitor made a trade-off for reasons we don't know, that doesn't invalidate usability research proving otherwise.
Answer:
...any extra fields slow down checkout...password

Bring the customer through payment process with only what is necessary for that, along with either a phone or email verification.
Once payment is complete give them the option to configure their account. Let them know they can always do so later using their phone or email. At the same time send them a SMS or email with instructions how to configure their account.
Until then their phone or email acts as their "password".


changing color glutWireSphere in animation in OpenGL

Question: i want to change a wireSphere during an animation with openGL.
But it won´t work.
What must i do that it changes a color during an animation?
So far i only have this :
<code>   glColor3f(1.0,1.0,0.0); //yellow color
   glutWireSphere(0.5,60,50);
</code>
Answer: Works for me. Here's a minimal GLUT program that uses your code, and successfully displays a yellow sphere on my Mac:
<code>#include <GLUT/glut.h>

static void display()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glColor3f(1.0f, 1.0f, 0.0f);
    glutWireSphere(0.5f, 50, 60);
    glutSwapBuffers();
}

int main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
    glutCreateWindow("WireSphere");
    glutDisplayFunc(display);
    glutMainLoop();
    return 0;
}
</code>
I suspect that there's some state you're setting outside the code you copied that prevents this from working for you. But it's hard to speculate what that could be. I think you'll need to post more code, or at least be more specific about the unexpected behavior than "it won't work".
Comment: I understand that, my question was that i want different colors for one WireSpere. For example: glColor3f(1.0,1.0,0.0); //yellow color
   glColor3f(0.0,1.0,1.0); glColor3f(1.5,1.5,1.5);
Comment: different colors in a gluWireSphere ?


How to merge a number of loops into one in a VBA program?

Question: I am fairly inexperienced with VBA, and I can't figure out how to make this loop. I set up 4 separate statements and it works this way, but I want to make this one statement.
i = 1
Do Until i > combos
        Range(Cells(i, 10), Cells(i + Defrepeat - 1, 10)) = Range(Cells(3, 4), Cells(3, 4))
i = i + TErepeat
Loop

w = 4
Do Until w > combos
        Range(Cells(w, 10), Cells(w + Defrepeat - 1, 10)) = Range(Cells(4, 4), Cells(4, 4))
w = w + TErepeat
Loop

p = 7
Do Until p > combos
        Range(Cells(p, 10), Cells(p + Defrepeat - 1, 10)) = Range(Cells(5, 4), Cells(5, 4))
p = p + TErepeat
Loop

k = 10
Do Until k > combos
        Range(Cells(k, 10), Cells(k + Defrepeat - 1, 10)) = Range(Cells(6, 4), Cells(6, 4))
k = k + TErepeat
Loop

Answer: Dim c As Range, i As Long, n As Long

Set c = Cells(3, 4)

For n = 1 To 10 Step 3
    i = n
    Do Until i > combos
        Range(Cells(i, 10), Cells(i + Defrepeat - 1, 10)) = c.Value
        i = i + TErepeat
    Loop
    Set c = c.Offset(1, 0)
Next n

Comment: Thanks for the response Tim. There seems to be a problem starting with the second loop though. I'm getting an error message: "Run-time error 1004. Application-defined or object-defined error." It ran through the first time and worked, but the second loop didn't work.


Upstart service never starts or stops completely

Question: I'm trying to make a simple upstart script for teamspeak server, but can't make it work.
When I say initctl start  it just executes but never finishes or even  emits any message. Same is happening for stop.
To be sure I am not doing anything wrong, I have copied the cron script and tried to run it, but it happens the same.
what am I doing wrong here?
UPDATE:
here is my script for TS3:
# myservice - myservice job file
description "my service description"
author "Me <firstname.lastname@example.com>"

# Stanzas
#
# Stanzas control when and how a process is started and stopped
# See a list of stanzas here: http://upstart.ubuntu.com/wiki/Stanzas#respawn

# When to start the service
start on runlevel [2345]

# When to stop the service
stop on runlevel [016]

# Automatically restart process if crashed
respawn

# Essentially lets upstart know the process will detach itself to the background
expect fork

# Start the process
script
       emit going into TS3 dir
       chdir /home/danizmax/teamspeak3-server_linux-x86/
       emit starting TS3
       exec su -c "/home/danizmax/teamspeak3-server_linux-x86/ts3server_startscript.sh start" danizmax &
       emit done
end script

I tried even with simplest script, and that also doesn't work:
description     "regular background program processing daemon"

start on runlevel [2345]
stop on runlevel [!2345]

expect fork
respawn

exec echo example
console output

Thank you for your help.
Comment: You might want to show the upstart job you're trying to run so that we can debug it?  Hard to know why it's hanging without seeing it.
Comment: I have copied the cron script and tried to run it and it happens the same, just stops and never returns to the shell
Comment: We still need to see your upstart script. Without it, there is nothing we can do. Please post it, or provide us with a link to it.
Comment: Without seeing the script, all I can do is guess: Does your script care that it's run as root by upstart? Root's PATH is different. If your script wants to use an application that's not in in root's PATH you must specify the full path. Is there a prog in your script that doesn't return?
Comment: See http://askubuntu.com/questions/14810/from-init-d-to-upstart-is-there-a-bridge
Comment: I updated my post with my script.
Comment: We may also need the ts3server_startscript
Answer: there are a number of oddities in your upstart job that have me scratching my head.
1) emit isn't a program that I know of, so unless you've added it to the system path, that is probaly causing errors. Did you mean 'echo' ? That may not be helpfull either, since it will go to the system console which may not be visible.
2) Assuming the 'emit' stanza works, you say 'expect fork' but then actually fork twice. Once for the 'script', and then again when the teamspeak script forks to background itself.
3) you "su" to run the script, but start-stop-daemon is actually simpler for most cases:
With 11.10, you don't need to do the chdir in script, not sure if that was added after whatever version of upstart you have. Check man 5 init for the word chdir
start on runlevel [2345]
stop on runlevel [^2345]

respawn

chdir /home/danizmax/teamspeak-server
expect fork

exec start-stop-daemon --start --user danizmax --group danizmax --exec /home/danizmax/teamspeak3-server_linux-x86/ts3server_startscript.sh -- start

Also, errors will likely be reported in /var/log/syslog . You can increase the error level quite a bit by running
initctl log-priority info

man initctl for more log levels.
Comment: Not the OP, but he is using (danimaz) su to execute the server as his user, not to become root.
Comment: Hah doh, missed the scroll bar on the bottom.. perfectly aligned to hide the username. :-P


Tryin to do ping to several pc with python. .

Question: I'm trying to read a file which contains the ips of 300 computers an then writing in a new file if exists or not each one.
import os
import datetime
import platform
import subprocess

date = datetime.datetime.now()
day = date.day
hour = date.hour

os.chdir ('Path')
openips = open ("ips.txt","r")
ipfile = openips.readlines()
print (ipfile)

for ips in ipfile():
    ips = ips.strip()
    print (ips)
    args = ["ping", "-n", "4", "-l", "1", "-w", "1000", ips]
    pping = subprocess.Popen(args, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
    for line in pping.stdout:
        print (line)
    os.chdir ('Path')
    presult = open ("pingresults_{}_{}.txt".format(day,hour), 'a')
    presult.write ('{}_{}\n'.format(ips, line))
    presult.close ()

Dunno why, everytime I'm testing my code. . . the result is:

TypeError: 'list' object is not callable

I've tried everything, even when I change the variable to string . . . say the same, just changing the list for string
Comment: You need to provide the full traceback in your question (not just the final error).
Comment: Also use standard tcp or udp connection built in to python instead of "ping" which is a very very slow program testing on port 0 (which can be closed). Also spawn a thread for each connection test as there will be a lot of "wait" time that your program can do without.
Comment: @thebjorn So sorry, the next time I'll write all the traceback
Comment: @ege Thanks for your suggest, I'll think about. . . the true it's I just wanna know if the equip is alive (like true or false), doesn't care about anything else. But again, thanks, I'll consider use tcp or udp.
Answer: change:
for ips in ipfile:
   ...

no brackets
Comment: ¡Thanks! :)

Just one more question . . . what's the difference between this for and the normal one? Why in this case I shouldn't use it?

Again, thanks a lot . . . I'm new in this.
Comment: `xxx()` is calling the method. `xxx` is using the value of the variable.


Form with multiple rows of selectable options displayed on material UI cards, need help with adjusting the design

Question: I have a form that has around 3 rows with selectable cards (only about 3 to 4 options each row). We do not have a UI/UX designer and I want to adjust the UI design but do not have a good idea about what direction I would need to go in to improve this design.
Each card has an onclick method and a value that is updating a local react state form. I have tested with radio buttons, but my manager prefers the very apparent selected choice with the green background and checkbox.
I appreciate any input and guidance, I am not a UI/UX designer.
Answer: If the manager made the decision, there is little you can do. Although according to the image there are things that could be improved:

When designing use layout guides.
Unify measures:

Unify sizes in buttons with similar content. The buttons in the image have up to six different sizes and can be reduced to just 2.
Unify the distance between buttons. The image has three different distances and should be always the same.

Nor do I think it's so necessary to follow the typical table scheme  with its title and cell with content. Knowing they are items to be selected under the same concept, everything can be in the same line:


Throttling akka-actor that keeps only the newest messages

Question: Situation
I am using akka actors to update data on my web-client. One of those actors is solely repsonsible for sending updates concerning single Agents. These agents are updated very rapidly (every 10ms). My goal now is to throttle this updating mechanism so that the newest version of every Agent is sent every 300ms.
My code
This is what I came up with so far:
/**
  * Single agents are updated very rapidly. To limit the burden on the web-frontend, we throttle the messages here.
  */
class BroadcastSingleAgentActor extends Actor {

    private implicit val ec: ExecutionContextExecutor = context.dispatcher
    private var queue = Set[Agent]()

    context.system.scheduler.schedule(0 seconds, 300 milliseconds) {
        queue.foreach { a =>
            broadcastAgent(self)(a) // sends the message to all connected clients
        }
        queue = Set()
    }

    override def receive: Receive = {
        // this message is received every 10 ms for every agent present
        case BroadcastAgent(agent) =>
           // only keep the newest version of the agent
           queue = queue.filter(_.id != agent.id) + agent
    }

}

Question
This actor (BroadcastSingleAgentActor) works as expected, but I am not 100% sure if this is thread safe (updating the queue while potentionally clearing it). Also, this does not feel like I am making the best out of the tools akka provides me with. I found this article (Throttling Messages in Akka 2), but my problem is that I need to keep the newest Agent message while dropping any old version of it. Is there an example somewhere similar to what I need?
Answer: No, this isn't thread safe because the scheduling via the ActorSystem will happen on another thread than the receive. One potential idea is to do the scheduling within the receive method because incoming messages to the BroadcastSingleAgentActor will be handled sequentially.
  override def receive: Receive = {

    case Refresh =>
      context.system.scheduler.schedule(0 seconds, 300 milliseconds) {
        queue.foreach { a =>
          broadcastAgent(self)(a) // sends the message to all connected clients
        }
      }
      queue = Set()
    // this message is received every 10 ms for every agent present
    case BroadcastAgent(agent) =>
      // only keep the newest version of the agent
      queue = queue.filter(_.id != agent.id) + agent
  }


Are remote preference tests (A vs. B) always flawed because of learning effect?

Question: Currently doing UX testing on low budget. We have prototypes in Figma and user tests in Maze.
Now one of the main goals is to compare two versions of a feature.
The problem?

All the remote testing tools I've tried don't offer the possibility of randomization of tasks. So there will always be a strong learning effect for each user, because they start with A and go to B.
Solution Ideas
So what can I do?

Add a general "intro task" that lets the subject get to know the
user interface & context
(resulting in unnecessary length of the test)

Create two user tests and handle the randomization myself and send each person the correct link individually
(resulting in annoying manual work & having to aggregate the results from 2 tests)

Find a magic tool that somehow handles this randomization for me and gives me one single share link
(still manual work of aggregating results)

Does someone have experience with this or has solved this problem before?
Answer: Well, as you say, the obvious answer is to randomize (there are other, more sophisticated ways to do this, but probably too much for what you're looking for).
If you use the same pool of participants and show 2 versions in a row, there is no way to avoid stimulus exposure biased results. for this, you need to use a technique called Counterbalancing
The following is a translation of a Psychology Research Methodology Manual in Spanish (couldn't find a similar one in English, it's possible counterweights is not the proper translation)

Counterweights or counterbalances
It is used mainly to control the effect of progressive order or error,
and is based on the existence of a linear relationship between
progressive error and the order each treatment occupies within the
experimental sequence. As the ordinal number increases, the level of
progressive error increases. Each subject is presented with the
experimental conditions in a different order, so that in the total set
of conditions in the experiment, each of them has been applied the
same number of times in the same order.
Intrasubjective counterbalancing
It controls for progressive error at the individual level by ensuring
that each subject receives the conditions or treatments in a
particular order first and in the reverse order second. If we have
three ABC conditions, they are ordered as follows: ABCCBA. The order
ABC is applied to the subjects first and then the order CBA.
The role control technique distributes the progressive error evenly
throughout the series of trials.
The intra-subject balancing technique has the disadvantage that each
subject receives each treatment more than once, which increases the
experiment time. To overcome this inconvenience, the following control
techniques can be used.
Intragroup counterbalancing
It consists of administering different treatment sequences to
different subgroups of subjects. With this technique, the effect of
progressive error is controlled in the group and not formed
individually as in intra-subject counterbalancing. Full Intragroup
Counterbalancing
In this case, all possible permutations of the treatment sequences
must be used. To calculate these, the factorial of the number of
conditions is found.
Subgroup 1 AB sequence
Subgroup 2 sequence BA
If we have three experimental conditions ABC, the number of sequences
is
n! = 3! = 3 · 2 · 1 = 6
ABC, BCA, CAB, ACB, BAC, CBA

But just in case you want to do it anyway: If you have some JS /PHP knowledge, you could just create a page and serve a random version and save the results to a DB. You could even record the response time. If you know Python you could also use PsychoPy, there are some templates to do this.
Otherwise, it's best if you separate the groups. One will see version A, the other version B, which is classic A/B testing. Because if you use the same pool, you have to use at least ANOVA, and that's a lot more work than doing a little manual work.
All in all, I would opt for splitting the groups, it's much less effort and the results will be more accurate
Comment: @musefan Yeah I understand what you mean, a pure 50/50 randomizer would be too stupid to work for this. I'll have to try different methods to see what works best.
Comment: _"you could just create a page and serve a random version and save the results to a DB"_ damn that's exactly what I've been trying to find on Google, it sounds so simple that I thought there must already be a tool for it. Put 2 links in, get one share link out. Then participants get one of the links randomly (50% chance).
Comment: Otherwise interesting points, thank you for sharing
Comment: Nice resource! Do you want to include the source as well, or name of the publication?
Comment: @Big_Chair: Be careful with randomly showing links. 50% chance is exactly that, chance! If you are really unlucky you could end up with all users testing the same feature and nobody testing the alternative. Obviously that becomes less likely the more users you have, but do you really want to risk a 75/25 split for example?
Comment: @maxathousand as a matter of fact it's in an internal manual from my wife's university chair, but this specific part comes from a book in English, just couldn't find it online so I translated it. The book is really worth it, it's called "Quantitative Psychological Research", but I'm not sure if it's the same version I have in Spanish , because the English version has a subtitle "the complete student's companion" and the one I have translates to "from experimental design to research reporting" .
Comment: Link: https://www.routledge.com/Quantitative-Psychological-Research-The-Complete-Students-Companion/Clark-Carter/p/book/9781138226180
Answer: My first thought would have been to set up two test groups: One starting with A the other starting with B just as you stated in your possible solutions. With the results of both groups combined, we can probably assume, negates the learning effect.
I'm also not certain that randomizing the tasks would yield an accurate result (80% starting on A could still happen randomly i suppose?), think sequential alternation of start task would give you a more balanced 50/50 view, of course this becomes more complicated when you have more than 2 tasks (A/B/C...).


Can I build an adjustable slanted table by placing bearings between the legs and the desk?

Question: The legs' length is adjustable, each leg is connected to the desk by means of a plate with 4 screws on the perimeter. I want to lower the table's front legs so the table becomes slanted. I would like to be able to adjust the slant degree so placing wedges between the legs and the desk does not help me. I've been thinking on adding some kind of bearing between the desk and the legs but haven't found any bearing that would enable me to do that. Any suggestions?
Answer: I would use a hinge on each leg as the attachment, with the hinge facing forward. You want something reasonably tight so it doesn't shake the desk around.
You'll probably have to put a wood block on top of the legs, so that the legs and hinge both have something to attach to.
Comment: Constrain that sucker into a [four bar linkage](http://en.wikipedia.org/wiki/Four-bar_linkage) so it's only got one degree of freedom. A hinged cross-piece that's parallel to the tabletop should be placed between the legs. Otherwise it will be unstable. Good concept idea to get things rolling though.
Comment: Greg, thanks. I'll do that and use a crosspiece for the legs as @Doresoom said.


HTML5 tags like(autofocus,required,type="email" do not work in IE9

Question: I'm using the html 5 tags like header,section,nav,article,autofocus,required, input type="email" and pattern.
i noticed that autofocus,type="email" and pattern do not work and i already use eric css reset and
<code><!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</code>
Comment: btw, the only thing the html5shiv does is allow HTML5 tags to work in IE. If you try to use an 'unrecognized' tag like `header`, `footer`, or `aside` in IE without the shiv, IE doesn't render the tag at all (and missing elements often make a page look real messy real fast).
Answer: IE9 is an incompetent browser and this, among a multitude of other things, does not work in IE9. http://www.quirksmode.org/html5/inputs.html
Comment: wew, so there is no other way to fix this? thanks for the link
Answer: You can test the browser compatibility here : http://www.html5test.com
Chrome supports the most features of HTML5.
Answer: I recently found a great library called Webshims Lib. The library works in concert with Modernizr to determine what capabilities a browser has, and then polyfills the missing features.
The forms portion of the library is just freaking beautiful, and should meet your needs nicely. It handles a majority of the new HTML5 form features in browsers that don't already have support (like IE9).
I'd highly recommend giving it a try.


How would i write a function in python using variables for a sum of exponential series?

Question: I am trying to create a code in which you input a starting integer, number of terms, and the exponent. This is my current code, i have run it with just numbers, but cannot figure out how to run it with variables, that are prompted by the user.
def squares(s,n,e):
    for x in range(s,s+n):
        Sum=0
        Sum=sum(Sum+x**e)

s=int(input("input starting integer:"))
n=int(input("input number of terms:"))
e=int(input("input exponent:"))

print(squares(s,n,e))

Comment: Looks like you're solution should almost work. what problems are having?
Comment: Using `numpy`: `np.sum(np.arange(start, start+n)**e)`
Answer: Fixing some of the syntax (e.g. sum() takes an iterable, not a constant), I believe your code works:
def squares(s,n,e ):
    for x in range(s,s+n):
        Sum=0
        Sum+=sum([Sum, x**e])
    return Sum

s=int(input("input starting integer:")) #e.g. '9'
n=int(input("input number of terms:"))  #e.g. '4'
e=int(input("input exponent:"))         #e.g. '3'
print(squares(s,n,e))     # result: 1728


Hog mode / Exclusive access to audio output device with SoX

Question: I would like to know whether SoX/LibSoX offers the possibility to access a sound device in exclusive/hog mode. The idea is to prevent other applications from accessing the sound card / DAC that is being used by the focal app.
My main target is OSX CoreAudio output, but I am also eager to know about Linux (OSS/Alsa).
I know this is possible in CoreAudio, because I have seen it implemented in several apps, including this open source one.
Answer: On Mac OS X at least, the answer appears to be no.  In http://sourceforge.net/p/sox/code/ci/master/tree/src/coreaudio.c SoX uses the default input or output device but there is no provision for hog mode.
Comment: SoX can open manually specified devices as well -- see line 137 and on. But you are right, it doesn't seem to contain any provision for an eventual hog mode. Someone should probably do it one day...


how to load data from database to my own custom field type (form)

Question: I would like to create a custom form field. For example, select field of cities in the world.
I read this article. In this article, the data are loaded using parameter file config.ynl. I, however, I'd like to upload this data from my database.
http://symfony.com/doc/current/cookbook/form/create_custom_field_type.html
Can somebody tell me how to do this or send the link to the example
Comment: For choice field see my answer [here](http://stackoverflow.com/a/13320439/1218997).
Answer: In this case, better is to use an Entity Field instead of a Choice Field. It allows you to request your database to load your entities as follow,
$builder->add('MyField', 'entity', array(
    'class' => 'MyBundle:MyEntity',
    'query_builder' => function(EntityRepository $er) {
        return $er->createQueryBuilder('e');
    },
    'property' => 'something',
));

The property option define the entity property you want to use.
You can then customize your field using the "multiple" and "exanded" options to behave the way you want. Read the documentation
Comment: ther is:

**For example, suppose that you're storing the gender parameters in configuration:**

okej, so How get gender from datebase not from parameters in configuration
Comment: Why do you need to use a custom field? update your action with your code so that we can figure out what you're trying to do.
Comment: because I want to create a separate field consisting of two select fields
Comment: Ok, So just use Entity Fields to define your select fields. It should work fine.
Comment: [Create a Custom Form Field Type](http://symfony.com/doc/master/cookbook/form/create_form_type_extension.html)  and [upload from config files or database](http://symfony.com/doc/2.0/cookbook/form/create_custom_field_type.html#creating-your-field-type-as-a-service)
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/20516/discussion-between-ahmed-siouani-and-pawel-brzoski)


What game is Yu Ishigami playing in Kaguya-sama: Love Is War Final (the 2021 sequel)?

Question: Update: In a better quality version, we can see something called 'AK-12 Rebellion'.

What game is Yu Ishigami playing in Kaguya-sama: Love Is War Final (2021 sequel to the 2019 adaptation of Kaguya-sama)?
Note: This is really in the 2021 live movie rather than in the 2021 mini live movies.

Looks like some FPS. If I didn't know better, then I'd say it's CS:GO, specifically Mirage when you come out of underpass and then Yu is using an SG (Krieg) or something.
Here's the GIF:
Comment: I think the "better quality screenshot" section would work better in your answer, rather than the question
Comment: It could be the Chinese [*Counter-Strike: Global Offensive Perfect World Edition*](https://counterstrike.fandom.com/wiki/Counter-Strike:_Global_Offensive_Perfect_World_Edition)
Comment: @TimmyJim So where does the footage come from? It's made specifically for the movie instead of taken from an actual game? Wow really? I cannot imagine they would spend so much time to make this instead of just filming Yu to play csgo or valorant or whatever.
Comment: @Joachim wait 'The image on the monitor seems to loop' does it? Looks like strafing or something...
Comment: @BCLC maybe not for this particular scenario, but [it's been done before](https://gaming.stackexchange.com/questions/289777/what-game-is-this-as-seen-in-charlie-and-the-chocolate-factory-2005)
Comment: @BCLC That game is basically the same game as the CSGO we have, save for censorship to some textures and effects (no more skulls, no more hammer-and-cickles, no more red blood, no more Italian flags(?), etc) and (non-censorship related) alterations to comply with China's laws. I actually went looking for videos to see if there were other changes not mentioned in the CS wiki (like, major UI changes (changing the mini-map from rounded to squared), new weapons, etc), but could find nothing. So, I find it unlikely to be CSGO:PWE.
Comment: The image on the monitor seems to loop, so I think the actor/character is not actually playing anything. (Shall I post that as an answer? :)
Comment: @Joachim Lol good observation, but what is the game?
Comment: @BCLC what Joachim means is that they aren't playing a real game, and therfore it can't be identified. This is actually quite common in films/shows. We've had a few game identification questions that result in this answer.
Comment: @TimmyJim ok fine thanks, but I think that has a higher budget than Kaguya-sama 2.
Comment: Very much doubt it's CSGO. Weapon viewmodel and animations don't really look like something out of CSGO, and I don't agree about the weapon looking like the SG (looks more like a modern AK rifle, like a AK-12). Map doesn't really look like Mirage either (and it's definitely not mid, since 1. left wall is too high 2. wall in front (which would be upper mid) has a hole 3. no visible incline/ramp and 4. right wall doesn't seem to have a hole (connector)). UI also doesn't match. I can still see this being a CS game, though. Wasn't there, like, 3 or 4 Asia-exclusive CS games?
Comment: @LeoS. thanks. Stevoisiak said earlier 'Chinese Counter-Strike: Global Offensive Perfect World Edition' what do you think?
Comment: @LeoS. Thanks! post as partial answer? Perhaps you could include some youtube video links to explain why it's unlikely to be the perfect world CSGO?
Answer: After looking up AK-12 Rebellion, this looks like something called Alliance of Valiant Arms aka 'AVA'. There's a video AVA - Cursed AK-12 Rebellion, where we seem to see the same kind of gun that Yu uses.
Comment: UI elements appear to also match that game.


How to replace eregi()

Question: I tried looking around and thought i figured it out by using preg_match, but preg match gives me the error:
Warning: preg_match(): No ending delimiter '^'
here is my original code which php says is depreciated:
if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $_POST['email'])) {
    $erroR= "Invalid Email address";
}

can someone explain what the ending delimiter '^' is, and how to add it. thanks@
Comment: Replace at least by `{2,6}`. But validate email with regex is a very hard stuff. Have a look at http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html
Comment: Your regex doesn't match many valid email, ie. `email@example.com`, also domain names could hold accentuated characters like `àéü`...
Comment: im not very good with regex, but i have noticed the `{2,3}` at the end. i wasnt sure what to do. do you have any suggestions?
Answer: Swap eregi() with preg_match(), and add delimiters to the regular expression. I chose the standard / here, but you can use other characters.
if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $_POST['email'])) {
    $erroR= "Invalid Email address";
}

The reason you get this warning...

Warning: preg_match(): No ending delimiter '^'

...is because preg_match() expects delimiters, and it assumed the ^ was being used, and it couldn't match a trailing one.
Comment: Note that `preg_match()` is case sensitive like `ereg()` and there's no case-insensitive variant like `eregi()`.  Instead, you have to specify the appropriate mode modifier.  The most common way to do that is to add `i` after the trailing delimiter: `'/xyz/i'`
Comment: that did it, thanks. i didnt even realize the regex wasnt inside slashes.
Answer: Add a / before and after your expression - you need a delimiter for preg_replace to tell it where the regex starts and finishes. It can be:
A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character.
Often used delimiters are forward slashes (/), hash signs (#) and tildes (~).

So this will work:
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/"

How to replace eregi()


How to present a list of sentences in a beautiful and useful way

Question: This might not only be a user experience question but also a design one.
I am designing a corporate website and my manager didn't really like the first idea I presented.
I have to show a list of sentences and the title of the section with its subtitle.
I wanted to show the list of sentences in a more web friendly style rather than the old sequential and "text documents" style. Therefor I used a slider:
Large Image

From his point of view, the list of sentences loses it since it is shown sentence by sentence and he prefers to show it all together.
His suggestion was to move the title of the section to the bottom and use the space above to show the sentences in a kind of box.
This is what I came up with (which I personally find horrible):
Large Image

Not only do I think it's a worse design, but also I believe the title of the section should be at the very top as is the main text the users should be reading.
What would you recommend? Is there any other possible way to show a list of sentences that is more user-friendly and useful?
Comment: I prefer yours, but don't like the slider too much either. It requires interaction when there probably shouldn't be any. Don't put the "sentences" over the photo, especially not with a large colored background. If these sentences need to be on the page, find a way on your original to include more of them. Possibly "just" a centered list in the location and in place of the slider.
Comment: Help others to help you. I don't think you'll get anything of a value directly related to your problem without sharing some examples of these sentences (the real ones to end on the site). There are a multitude of UX concepts and solutions that may apply here, but you can't advise someone on how big a button should be without knowing what the button actually does!
Comment: Do you have real content you are working with? If so, focus on that. As it is, this all feels very arbitrary and generic and stock-photo-ish. Make sure these sentences have purpose and emphasize that purpose.
Answer: The question is: in what way is this copy (the sentences) relevant for the users of this website?
If it is information that is very interesting for them, then by all means show all of the copy at the same time; don't hide it from the users.
However, from the look of your images, it appears that this page is introducing a section of your website. In that case I would say: keep the copy short and to the point; one sentence should be enough to introduce a section.
Don't expect users to go and explore your 'sentences' using the arrows — they will simply skip this area and scroll down to the rest of the page to see if there is any interesting/relevant content for them.
Comment: I am sorry I misunderstood you twice. Now I guess I am missing the context of what these sentences mean for the user, and what, if anything, could compel them to click to see the next sentence. (As usual in UX, it boils down to: who is the user and what are they here for? Before you know that you cannot really say what the best solution is.)
Comment: It's not introducing it. It's just the section itself. There's no much text for it, only those sentences. But this is an slider with multiple sections inside the same area, all pretty similar and with the same background image size.
Comment: I was referring to a section of your website. When you click on the chair icon in the top nav, I assume you would arrive on this page. I would then expect the top area of this page to explain what the 'chair section' is all about.
Comment: Still being the content and not an introduction :) The icons on the menu just scroll down the page to each sections. There won't be more info to explain about the chair :)
Answer: First off, I would recommend not using a carousel: http://shouldiuseacarousel.com/
Especially so in the context you're using it in. It seems that you have a navigation bar on top that acts as anchor links to jump the user to different sections of what I'm assuming is a long page full of content. Hiding content inside a carousel that is halfway down a page simply doesn't make sense.
If the content is worth showing, then find a way to include it in your layout. And make sure it isn't the way your boss is asking for, because that is horrible. ;)
Comment: +1 Thanks for that information! It's good to see those kind of studies. I've also been reading [this one](http://econsultancy.com/uk/blog/61995-carousels-on-ecommerce-sites-are-they-worth-bothering-with) Although in my site I only have one "section" with carousel and it doesn't move automatically, it works with arrows. (or keyboard keys)
Comment: Just to add to the idea that carousels suck: internal testing on our multinational site shows that less than 5% of users ever interact with carousel controls. Most people recognize carousels and sliders as marketing crap and, as such, they generally ignore content placed there.
Answer: The text could be placed like in this picture.

But most people will not read it, so it's better not to have text at all.
Nice big detailed pictures catch the attention, short big titles are read fast, so every slide communicates to the users.
Having a lot of text:

Increases cognitive load, as users try to read the text but a picture is a more powerful attractor. So it could be hard to focus on text.
Increases significantly displaying time for each slide, so the carousel looses its advertising effect. To calculate the time for each slide look at the answer.

Probably the disadvantages could convince the manager.
Comment: As this is not an introduction but just the content itself, some text is needed to explain the topic although I always try to reduce the text as max as possible.
I like the position for it!


How to tab through components?

Question: My Swing program has a lot of fields that the user has to fill in in order to make a query to a DB.
The problem is that when I press tab in one field, the focus is not moving anywhere at all.
All the info I read about the focus subsystem makes me think any program should do that by default, hence I'm asking, because my program doesn't do it.
I'm using netbeans and also tried setting nextFocusableComponent on the components but with no luck.
Any tips?
Comment: tabbing out off textfields should work without any tweaks (btw: better not use deprecated methods, strictly speaking there is no guarantee they will remain, though they will ... ) Let's see an sscce which demonstrates the problem
Comment: something is wrong with your code and we can only help if we see it - **not** your complete code but an SSCCE which demonstrates the misbehaviour. It's your job to provide that SSCCE (often, you'll find the error yourself while preparing it :-)
Comment: OK sounds dumb (as much as I am) but the problem was happening because I set the frame focusable property to false which makes me think that any component contained in it would lose the ability to be focusable.

Thanks all anyway!
Comment: @kleopatra the problem is that my code is too big, i don't really know what to post so you can try to find where the problem is. And tabbing right now is just not working in any component at all.
Comment: do you use some 3rd prty control (apart from Swing's own)?
Answer: Not sure if there are other part of your code that could be causing you issues. But here is a reference from oracle that shows you how to set tab focuses and next focus. In this it also document other things you need to setup before it will work.
http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html
I suggest you post portion of your code so other can see if there are other underlining issues.
Also there is another thread on stackoverflow about this issue: Java tab order: How to set Tab order in java swing table
Comment: Copy/paste kleopatra's comment to Daniel.
Answer: Have a look on the FocusTraversalPolicy class.
Hopefully this will help you: http://www.java2s.com/Code/Java/Swing-JFC/FocusTraversalExample.htm
Comment: if the tab isn't recognized at all, a custom FTP doesn't help at all :-)
Comment: @kleopatra that's exactly the problem, all the FTP explain the order and whatnot but I don't have a problem with the order, my problem is that it just doesn't happens

How to tab through components?


$atts are user input, how to sanitize and escape in WordPress

Question: I create a shortcode in WordPress. Shortcode code below:
function wp_test_shortcode($atts){
    $atts = shortcode_atts(array(
        'id'    =>  'TESTTEST',
        'thumb' =>  ''
    ),$atts);

    $thumb = $atts['thumb'] ? $atts['thumb'] : 'https://i3.ytimg.com/vi/'.$atts['id'].'/0.jpg';

    return '

';
}
add_shortcode('test','wp_test_shortcode');

Now my question is, Since $atts are user input, how to sanitize and escape.
Comment: How are `$atts` user input?
Comment: This is what you need https://developer.wordpress.org/themes/theme-security/data-sanitization-escaping/
Comment: Thanks for your response. Finally, I get a solution.
Comment: $atts are considered an input to anyone who has Contributor role or above.
Answer: Assuming someone with a Wordpress Contributor role is the bad actor here, Monzur Alam is right - you have to sanitize the attributes.
function wp_test_shortcode($atts){
    $atts = shortcode_atts(array(
        'id'    =>  'TESTTEST',
        'thumb' =>  ''
    ),$atts);

    // Sanitize Inputs

    $id = sanitize_text_field($atts['id']);
    $thumb = sanitize_text_field($atts['thumb']);

    $thumb = $thumb ? $thumb : 'https://i3.ytimg.com/vi/'.$atts['id'].'/0.jpg';

    // Escape Outputs

    return '

';
}

add_shortcode('test','wp_test_shortcode');


Two Keyboards with different layouts on Ubuntu 18

Question: I know similar questions have been asked already, but I did not find an answer to my problem. My Laptop has a German QWERTZ Keyboard Layout, as well as my pairing keyboard. My primary Keyboard is an US QWERTY keyboard. On Ubuntu Gnome 16.04 LTS, I used the following script to change the Layout just for the US keyboard :
<code>#!/usr/bin/env bash
for id in $(xinput -list | grep 'Logitech USB Keyboard' | cut -f 2 | cut -d= -f 2); do
    setxkbmap -device $id -layout us -variant altgr-intl
done
</code>
I also set "org.gnome.settings-daemon.plugins.keyboard active" to 'false' to prevent Gnome from overwriting these settings. I'm not completely sure if I did anything else in ubuntu Gnome 16.04, but as far as I know this used to work fine.
After upgrading to Ubuntu 18 I find that the keyboard layout is changed back to the system-wide default (german qwertz) after some time. Does anyone know how I can prevent Gnome from doing that?
Answer: Maybe this can help you?

First, use xinput to identify your keyboards.
   Then, use setxkbmap to set the layout.
My keyboards are id 10 (laptop integrated) and id 17 (external keyboard).
Now, set my external keyboard to be Swedish layout, and my internal to Dvorak:
<code>$ setxkbmap -device 17 se
$ setxkbmap -device 10 dvorak
</code>