Extracting the bytes from a UTF-8 QString

Question: I need to extract all the bits from a QString that holds a UTF-8 encoded unicode string.
To be clear, I need the bits to be stored in ideally a byte * (byte array) or alternatively a char *.
The reason I need to do this is because I want to hash the UTF-8 string and the hash function REQUIRES a byte array for the string that is to be hashed.
Any help, would be greatly appreciated.
I just want to extract the bit stream from the QString as it is stored in the QString and dump it into a byte *.  Therefore, ideally, once I have this byte * equivalent, I should be able to make a new QString and initialize it in the QString's constructor with this char * and it should be a proper UTF-8 QString.
Answer: You're most likely looking for the QByteArray you get from QString.toUtf8().
http://doc.qt.io/qt-5/qstring.html#toUtf8
A QString can be re-created from a QByteArray (but be sure to use QString.fromUtf8 since the constructor for QString that takes a QByteArray assumes it's in ASCII).
You can get const (or non-const) access to a char* from a QByteArray...
http://doc.qt.io/qt-5/qbytearray.html#data
...but note that Qt has built-in support for cryptographic hashes of QByteArray, as long as you're happy with MD4, MD5, or SHA-1:
http://doc.qt.io/qt-5/qcryptographichash.html
Comment: THANKS! Sorry, Jon Skeet posted first with the same info so I had to give him the answer.
Comment: Actually no...you don't have to give the first answerer any priority.  There is a natural bias to the first answerer getting more upvotes, but the accepted answer should be whichever is best for your purposes.  You can even change which answer you accept if you've already accepted one, and a better answer comes later.  Do avoid the problem on meta known as "fastest gun in the west": http://meta.stackexchange.com/q/19533/141442


The definition of subbasis in Topology

Question: I have a question regarding the subbasis; in Munkre's topology, the subbasis is defined in the following picture. But if I take a collection that only contains the set X, can it be a subbasis for a topology on X?

Thanks for your help.
Comment: What is your thought about your question?
Answer: If you take a collection that contains only the set $X$, then clearly union of all the members of that collection will be $X$. So, definitely that collection will be a subbasis and the topology generated by this subbasis is the indiscrete topology which contains only two sets $X$ and the null set $\phi$.
Answer: Actually you can normally take any set of subsets (subset of $\mathscr P(X),$ the power set) and consider the topology it generates. That's the smallest (coarsest) topology that contains it.
But Munkres has chosen to say that to be a subbasis it must have union equal to $X.$

The definition of subbasis in Topology


Fast calculation for $\int_{0}^{\infty}\frac{\log x}{x^2+1}dx=0$

Question: I want to show that $\int_{0}^{\infty}\frac{\log x}{x^2+1}dx=0$, but is there a faster method than finding the contour and doing all computations?
Otherwise my idea is to do the substitution $x=e^t$, integral than changes to $\int _{-\infty}^{\infty}\frac{t e^t}{1+e^{2t}}dt$. Next step is to take the contour $-r,r,r+i\pi,-r+i\pi$ and integrate over it...
Comment: did you try expanding the Geometric series $\frac{1}{1+x^2}=\sum_{k=0}^{\infty} (-1)^k x^{2k}$?
Comment: Duplicate of http://math.stackexchange.com/questions/625360/slightly-tricky-integral (but Martin Agerami's answer here is very nice).
Answer: If you use the substitution $x=1/t$, you can check directly that
$$
\int_0^1\frac{\log x}{1+x^2}\,dx=-\int_1^\infty\frac{\log t}{1+t^2}\,dt.
$$
Comment: or just $\int_0^\infty$ on both sides directly
Answer: Use the substitution $x=\tan\theta$.
$$I=\int_0^{\pi/2} \ln(\tan\theta)\,d\theta=-\int_0^{\pi/2}\ln(\tan\theta)\,d\theta=0$$
Answer: Here is a general approach. Consider the integral
$$ F(s) = \int_{0}^{\infty}\frac{x^{s-1}}{1+x^2}=\frac{\pi}{2\sin(s\pi/2)},\quad 0<Re(s)<2. $$
which is the Mellin transform of the function $\frac{1}{1+x^2}$. Now, our integral can be evaluated as

$$ I = \lim_{s\to 1} F'(s) = 0.$$

Note:

To evaluate the above integral, you can use the technique.

$$ F(s)= \int_{0}^{\infty} x^{s-1}f(x)dx \implies  F'(s)= \int_{0}^{\infty} x^{s-1}\ln(x)f(x)dx .$$
Comment: Thanks, this helped me since I evaluated the above integral already.
Comment: This is a good answer. If you included this level of detail to all your answers, we would avoid many disappointments. +1
Comment: @UlrichOtto: Good job. Note that, this is a general integral which can be used to handle harder problems.


Regular Expression for Finding N or More Continuous Zeros in the String

Question: I trying to figure out how to contruct a regex which will check whether my string matches the following pattern:

if N or more continuous zeros are present in the string, then it
  should say mathches, otherwise, say not mathces.

I trying to implement this in Java. I know that I need to use the mathches(regex: String) method of String class in order to check the existance of the pattern, however, I do not know how to construct the regex itself.
Comment: I'm quite sure this is more of a `google how to do regex in java` question
Comment: `0{N}` will be sufficient
Comment: `0{100}`, replace 100 with the actual N
Comment: Before posting on Stackoverflow, [search and research](/help/how-to-ask). There are tons of answers to this kind of question all over the internet already.
Answer: For N zeros you can do
<code>// anything with n continuous zeros in it.
boolean matches = str.matches(".*0{"+n+"}.*");
</code>
Or you can use
<code>boolean matches = Pattern.compile("0{"+n+"}").matcher(str).find();
</code>
Comment: Doesn't Java have a Find function or such so that the entire string doesn't have to be matched?
Comment: The first one is simpler, I guess, thanks. @PeterLawrey


How to extract all the sentences with review/text in the below text?

Question: Here I want to extract the review/text.But its extracting only few parts from it.
Following are the outputs:-
<re.Match object; span=(226, 258), match='review/text: I like Creme Brulee'>
<re.Match object; span=(750, 860), match='review/text: not what I was expecting in terms of>
import re
text='''
'product/productId: B004K2IHUO\n',
 'review/userId: A2O9G2521O626G\n',
 'review/profileName: Rachel Westendorf\n',
 'review/helpfulness: 0/0\n',
 'review/score: 5.0\n',
 'review/time: 1308700800\n',
 'review/summary: The best\n',
 'review/text: I like Creme Brulee. I loved that these were so easy. Just sprinkle on the sugar that came with and broil. They look amazing and taste great. My guess thought I really went out of the way for them when really it took all of 5 minutes. I will be ordering more!\n',
 '\n',
 'product/productId: B004K2IHUO\n',
 'review/userId: A1ZKFQLHFZAEH9\n',
 'review/profileName: S. J. Monson "world citizen"\n',
 'review/helpfulness: 2/8\n',
 'review/score: 3.0\n',
 'review/time: 1236384000\n',
 'review/summary: disappointing\n',
 "review/text: not what I was expecting in terms of the company's reputation for excellent home delivery products\n",
 '\n',
'''

pattern=re.compile(r'review/text:\s[^.]+')
matches=pattern.finditer(text)

for match in matches:
  print(match)

Comment: Did you want to extract everything up to the newline? Then change the dot to a newline in the negated character set.
Comment: `review/text:\s.+` should work
Comment: Why do you have strings inside strings? It looks like those triple quotes should just be parentheses.
Comment: @AlexHall In that case, `finditer` won't work. But I agree there's something off with the text.
Comment: You can do it without `re`. You need to parse the string as a list, use `import ast` and then `matches = [s for s in ast.literal_eval(f'[{text.replace(chr(10),"")}]') if s.startswith("review/text:")]`. See [this Python demo](https://ideone.com/UpdUoM).
Answer: If you don't mind not using re and if the identifier is 'review/text' and your data is always comma seperated, you can get the lines simply with:
matches = [s.strip() for s in text.split(',') if s.strip(' "\n\'').startswith('review/text')]
for match in matches:
  print(match)

where s.strip(' "\'\n') removes spaces, ", ', and newline characters from the beginning and ends of the line for a string comparison.These two lines are returned:
'review/text: I like Creme Brulee. I loved that these were so easy. Just sprinkle on the sugar that came with and broil. They look amazing and taste great. My guess thought I really went out of the way for them when really it took all of 5 minutes. I will be ordering more!
'
"review/text: not what I was expecting in terms of the company's reputation for excellent home delivery products
"

Comment: @Tim Jim Thanks for the answer.I appreciate your effort but is there any way to extract it using regular expressions?
Comment: Just made the following changes and it worked:-pattern=re.compile(r'review/text:\s[^\n]+')
matches=pattern.findall(text)
Comment: I doubt OP's actual data looks like that, I think they pprinted the result of `file.readlines()` or something and then stuck that inside triple quotes without understanding what they were doing.
Comment: It does look like a rather strange text input, that's for sure (with the mixed quotes)! But in case they have no control of the input, I thought I'd add a non-`re` solution.
Comment: @VikasKumarOjha This is exactly what [anubhava suggested](https://stackoverflow.com/questions/67555515/how-to-extract-all-the-sentences-with-review-text-in-the-below-text#comment119406396_67555515), `matches = re.findall(r'review/text:\s.+', text)`
Answer: Use
matches = re.findall(r'review/text:.+', text)

See proof.
EXPLANATION
--------------------------------------------------------------------------------
  review/text:             'review/text:'
--------------------------------------------------------------------------------
  .+                       any character except \n (1 or more times
                           (matching the most amount possible))


Why does Django not generate CSRF or Session Cookies behind a Varnish Proxy?

Question: Running Django 1.2.5 on a Linux server with Apache2 and for some reason Django seems like it cannot store CSRF or Session cookies. Therefore when I try to login to the Django admin it gives me a CSRF verification error upon submitting the login form. Has anyone come up against this and found a solution?
I AM able to make a valid post when i try this at the url of my VPS that was provided by my host. Example: vps123.hostdomain.com/admin/ and for that domain the cookies DO get set. However, when I go to www.sitedomain.com/admin/ and try to login I get a CSRF 403 error saying the cookie is not there and when I check in my browsers cookies they are not set.
I have tried setting the following in my settings file:
SESSION_COOKIE_DOMAIN = 'www.sitedomain.com'
CSRF_COOKIE_DOMAIN = 'www.sitedomain.com'

Also tried:
SESSION_COOKIE_DOMAIN = 'vps123.hostdomain.com'
CSRF_COOKIE_DOMAIN = 'vps123.hostdomain.com'

I have 'django.middleware.csrf.CsrfViewMiddleware' added to my MIDDLEWARE_CLASSES in settings.py and there is a CSRF token in the form and it shows up in the POST.
I have cookies enabled. I have tried this on multiple browsers and machines.
There is a varnish proxy server sitting in front of www.sitedomain.com that I think may be part of the problem. Anyone with experience using proxy servers and Django may be able to shed some light on that.
My apache2 config:
NameVirtualHost *:80

<VirtualHost *:80>
    ServerName www.sitedomain.com
    ServerAlias www.sitedomain.com
    <Location "/">
        Options FollowSymLinks
        SetHandler python-program
        PythonInterpreter nzsite
        PythonHandler django.core.handlers.modpython
        PythonDebug On
        PythonPath "['/var/www/django_projects', '/var/www', '/usr/lib/python2.6/dist-packages'] + sys.path"
        SetEnv DJANGO_SETTINGS_MODULE project_one.settings
    </Location>
    <location "/phpmyadmin">
        SetHandler None
    </location>
</VirtualHost>

<VirtualHost *:80>
    ServerName othersite.sitedomain.com
    ServerAlias othersite.sitedomain.com
    <Location "/">
        Options FollowSymLinks
        SetHandler python-program
        PythonInterpreter ausite
        PythonHandler django.core.handlers.modpython
        PythonDebug On
        PythonPath "['/var/www/django_projects', '/var/www', '/usr/lib/python2.6/dist-packages'] + sys.path"
        SetEnv DJANGO_SETTINGS_MODULE project_two.settings
    </Location>
    <location "/phpmyadmin">
        SetHandler None
    </location>
</VirtualHost>

Comment: i think the question is too complex without having: apache settings, django settings, etc... Does the _exact_ same code work using the builtin dev server?
Comment: I edited my question to show more detail. Thank you!
Comment: little off topic, but is there any reason why you have to use modpython?
Comment: and do cookies get set when using the dev server?
Comment: @Josh, not helpful at all. What would you suggest in its place?
Comment: @thomallen, sorry I should have fleshed that out a bit. mod_wsgi is the way to go with django on apache. mod_python has been deprecated.
Answer: The problem was that I have a Varnish Proxy server in front of my site. Varnish was taking requests and stripping cookies from them. To fix this I had to have the company that is managing the Varnish Server add '/admin' to a list of exceptions so that cookies could be passed. Sorry I can't shed more light on how the Varnish process works.
Comment: oh that's interesting! Was it only the admin site that wasn't successfully working with CSRF? I'd also imagine that any future URLs that have forms will need to be added to the exception list. Can I suggest editing the title of your question to include the word varnish proxy so future users suffering this problem are able to find this answer easily?
Answer: Are you including the {{csrf_token}} in your form template?
<form autocomplete="off" method="post" action="{% url auth_login %}">{% csrf_token %}
    {{form|as_p}}
    <input type='submit' />
</form>

And including the middleware?
    'django.middleware.csrf.CsrfViewMiddleware',

From your edit, at a guess, it might have something to do with the VirtualHost configuration in Apache (if your provider is using apache). Here is an edited version of one of my apache configurations.
<VirtualHost *:80>
ServerName www.domain.com

WSGIProcessGroup my-django-site
WSGIScriptAlias / /path-to-my-django-site/wsgi/production.wsgi
Alias /media /path-to-my-django-site/media
</VirtualHost>

It may be the case that the server name within apache has to match the domain name you are hitting the box at, along with the *_COOKIE_DOMAIN settings in your Django configuration. I'm not sure if you'll be able to change this though. Might be worth speaking to your provider if no other answers yield a win.
Answer: Are you updating your template data with the csrf info?
from django.core.context_processors import csrf

def index(request)
    data = {"listitems": items}
    data.updates(csrf(request))

    return render_to_response('template.html', data)

Comment: If you return a context_instance=RequestContext(request), then your suggestion is not needed.


Show Cron expression as text in Hangfire Dashboard in mvc core

Question: Q1- I used Hangfire Dashboard in ASP.NET MVC Core 2.2, but I need to show a cron expression in "Recurring Job" as Text.
Example:  when cron value is * * * * *  show text in table is  "Every minute"
<code>       when cron value is 0 8 * * *   show text in table is "At 08:00"
</code>
And so on ...... as show in attachment image
Q2- Can I edit on Hangfire Dashboard code or do I have access to Hangfire Dashboard code and edit it as HTML?
Answer: You can use the attribute [DisplayName("...")] on the method you hand over to HangFire as your job. The text given to DisplayName is then shown on the HangFire dashboard
Comment: I've tested and tried to do this on a a project that the Dashbaord does not have assemblies. Instead of DisplayName working, i only get 'Could not find target method'. Does the Dashboard HAVE to have the assembly reference in order to override in order for the DisplayName attribute to work ?


load website in to a page via ajax or iframe and avoid navigation

Question: This is what i need to do.
there is a web page and another website, both are hosted in same domain. i want to load that whole web site in to a div or iframe of that web page. similar example for this is a free proxy browser like hidemyass.com.
i know this can be easily done but the point is that i also need to avoid navigation. say that the web site has 2 pages called a.htm and b.htm . there is a link to b.htm from a.htm. so when some one click the link on a.htm, the browser will redirect to b.htm
when i embed that a.htm in a part of my page, if some one click the link; it will redirect to the b.htm in browser. what i want to do is that avoid that redirect and when some one click on the link, b.htm should load in my page itself.
i have no way to change that website(in this case a.htm and b.htm), everything should be done in that page.
how can i achieve this?
Comment: `` should do just that but apparently no browser supports this feature correctly yet.
Comment: ya i read about this. this is in HTML5 isn't it?
Comment: Yes, that's HTML5. MDN says that currently only Chrome supports it but in other places you can read that Chrome support is also incomplete/broken.
Answer: If you are only looking at link clicks and not navigation via JavaScript then the following code should do:

This will check the links the user clicks on and add target="_parent" attribute to them if no explicit target is defined. This means that links targeted at a new window/tab will still work as usual, links meant to replace the current page will replace the parent document instead. But this only works of course as long as the JavaScript code in a.html doesn't interfere.
Answer: If you only want to skip the link from your page only, you can add onclick handle to you link and return false when the frame has not completely loaded

this is the script
function checkLink(){
  if (canNavigate){
    return true;
  }
  return false;
}

but if you want to disable navigation on browser address you have to do like linkbuck website
http://c6f11ddd.linkbucks.com/url/http://www.google.com
linkbuck will not allow you to navigate away while ads has not been loaded yet.
They archive this by using these code, you should investigate it
Buster: function () {
  var interval = setInterval(function () {
    if (Lbjs.IsClick) {
     clearInterval(interval);
    }
    else if (Lbjs.Unload > 0) {
     Lbjs.Unload -= 2;
     window.top.location.replace("/cancelnavigation/");
     Lbjs.NavigationNotice();
    }
  }, 1);
  var clearDelay = (this.Countdown > 0) ? this.Countdown : 8;
  setTimeout(function () { clearInterval(interval); }, clearDelay * 1000);
},
NavigationNotice: function () {
  var navNotice = document.getElementById("navNotice");
  navNotice.innerHTML = "Request Cancelled - Navigation is disabled for 8 Seconds...";
  if (navNotice.style.display == "none") {
    this.Fader.FadeIn(navNotice, 200, function () {
      setTimeout(function () {
      Lbjs.Fader.FadeOut(navNotice, 200, null);
    }, 1500);
  });
}


Cannot find the element

Question: https://www.xendpay.com
Here is the page. It is necessary to pull out an input from it
<input id = "paymentAmount" class = "input-text pull-left" tabindex = "1" name = "paymentAmount" type = "text">

And enter another text into it.
I tried to do this through ID, through xpath, through @name. What could be the problem?
elem = WebDriverWait(driver, 20).until(EC.visibility_of_element_located(
        (By.XPATH, "//input[contains(@id, 'paymentAmount')]")))

Comment: I enter the page and didn't even find element with this ID and name. using:

***len(driver.find_elements_by_name('paymentAmount'))***
I've got 0 elements with this ID and name, tell some more
Comment: I don't see either, but there is one on the page. This block is loaded using js
Answer: Your element is located in iframe html tag.
You need to switch to the iframe (iFrameResizer0 in the link you provided):
driver.SwitchTo().Frame(driver.FindElement(By.Id("iFrameResizer0")));

... do your find here.

// switch back to default
driver.DefaultContent();

Answer: There's iFrame, you should switch to it, wait for loader to disappear, delete old value in the input and than set yours.
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
wait = WebDriverWait(driver, 20)
driver.get("https://www.xendpay.com/")
wait.until(EC.frame_to_be_available_and_switch_to_it((By.ID, "iFrameResizer0")))
wait.until(EC.invisibility_of_element_located((By.CLASS_NAME, "loader")))
payment_amount = wait.until(EC.element_to_be_clickable((By.ID, "paymentAmount")))
ActionChains(driver).double_click(payment_amount).send_keys(Keys.DELETE).send_keys("999").perform()

Comment: It's a very beautiful
Answer: got it:
driver.switch_to_frame("iFrameResizer0")
driver.find_elements_by_name('paymentAmount')

Cannot find the element


What Flex Developers Ought To Know

Question: What should know the Entry Level, Mid-level, Senior Developer? Theoretical knowledge, development tools, libraries etc. What issues are usually at the interview? Do I need to know Java?
Answer: Object-oriented knowledge is a must. So good questions would be about:

polymorphism
inheritance
encapsulation

Some main concepts that come to my mind:

event handling, custom events
invocation of server-side code
collections
exception handling, logging, debugging
browser navigation support

About Java - Java knowledge is a plus on the object-oriented side, but Java experience made me expect Flex to be Java, which it isn't, and that might introduce some difficulties.
Comment: I would add to that: writing custom components in flex. If you really want to make it your every day job, working as good as possible is important. Also knowledge of the development environment would be a good question. (Eclipse or Flash/Flex builder) Setting up an eclipse environment for flex-development is a bit more work then just installing the Adobe flash/flex builder and how you code in it is diffirent. While flash/flex builder has an autocomplete function, this is (mostly) not in Eclipse.
Comment: i'd add: swf format restrictions, security sandboxes, and information from here: http://www.scribd.com/doc/913908/Flash-AS3-and-AVM2-Performance-Tuning
Answer: in additional to Bozho's answer...
At lower level
using source control
Basic skinning
Mid level
Understanding of a framework (like Mate / Robotlegs) and a collection of design patterns
Writing code that conforms to various coding standards
more advanced skinning
Using modules / libraries
Garbage collection
At higher level
Using the profiler to identify issues
Knowing when to ignore the design patterns
Being able to review others code at a high level.
Architectural design (What to actually put in those modules and libraries as well as maintaining them)
Flash Player internals
In general
In general the further up the chain you get, the more theoretical knowledge and general knowledge you have. A senior developer might have more advanced coding skills (but not necessarily), but can bring to the table a wider breadth of abilities and experience. Especially knowing when to throw the rule book away.
It definitely varies from company to company, one might value hard core coding skills in their senior developers, while another may treasure softer skills, leadership, and reviewing talents.

What Flex Developers Ought To Know


Visual Studio 2013 strcpy_s and size of a word

Question: I am new to C++ and I have started to work with strings recently, but I have problems with strcpy_s(). In Visual Studio if I use the old strcpy() it said that it is unsafe and after reading  more on the internet and I found out why so I started to use no more the strcpy().
In strcpy(), I have to tell it the size of buffer, but with this I have problems,because if I use strlen() it said that the buffer it is too small, even if I put a=strlen(string)+1,so I found out about another one called size_t(),and now I have no more problems with the error related to  the buffer, but I got another error.
Error Link
Code:
#include <iostream>
#include <cstring>
#include <conio.h>
using namespace std;
int main()
{
    int  i, size_of_word;
    char word[202];
    cin.get(word, 201, '\n');
    cin.get();
    i = 0;
    while (i < strlen(word) - 1)
    {
        if (word[i] == word[i + 1])
        {
            size_of_word = size_t(word + i ) + 1;
            strcpy_s(word + i + 2, size_of_word, word + i);
        }
        else
        {
            i++;
        }
    }

    cout << word;
}

Comment: Why not use `std::string`?
Comment: Get rid of c-style strings and use a [`std::string`](http://en.cppreference.com/w/cpp/string/basic_string)
Comment: strings and streams are your friend in c++. Use them when possible.
Answer: As commented, prefer std::string to char arrays, they are easier to use.
If you can't use them:
strcpy_s second parameter is the size of the destination buffer, whiwh is different than the size of the string.
word buffer size is 202, so, word + i + 2 buffer size is 202-i-2, not size_of_word
size_of_word = size_t(word + i ) + 1; sets size_of_word to [address of word buffer] + i + 1 which does not make any sense...
This should work (I moved buffer size to a variable to make it easier to be changed):
#include <iostream>
#include <cstring>
#include<conio.h>
using namespace std;
int main()
{
    int  i;
    static const size_t bufferSize = 202;
    char word[bufferSize];
    cin.get(word, bufferSize - 1, '\n');
    cin.get();
    i = 0;
    while (i < strlen(word) - 1)
    {
        if (word[i] == word[i + 1])
        {
            strcpy_s(word + i + 2, bufferSize - i - 2, word + i);
        }
        else i++;
    }

    cout << word;
}


What are the existing rules on linking to self hosted content

Question: On my post here:What are the meanings of the word 'gender'?
I downloaded the PDF which was published without any restrictions and hosted it on my own website.  I then added reference links to various related resources including the source site, related material on the topic, and the questions on Stack where I used the pdf to ask relevant and real questions or answer questions.
The webpage I created was literally a hub which joined multiple related sources of information on the topic and is meant to grow as I learn more.
So, my question is, is there a rule against this?
Answer: What was done, wasn't wrong necessarily if certain requirements were carried out.
Two of the main things we need to be mindful of within the whole StackExchange community, not just Psychology.SE is the issues of plagiarism, and copyright theft.
Citations and referencing for images and documents helps enormously with this as it credits the original author and shows transparency regarding where the information came from.  It seems that when going to the original link provided, although the document is stated to be from somewhere else, the original source was not provided at the target url.  Was permission sought to reproduce the document in the manner provided?  Was it needed or was the source document produced under a Creative Commons License? This was also not made explicit.
Another point to be made, which is where this question arose is that I highlighted in the comments that linking in the manner provided could be seen as spam.  This link was provided in the manner of saying:

Source: PDF, slide 7, from the AAP

and the link went to your own website with no indication of the fact.  When linking to the source, it should be to the source and not to an intermediary point or otherwise unless indicated.
Where this would have been fine is if:

The link to your site is relevant in order to provide more on your answer,
you declared the link to your own website by saying for example:

I downloaded the source document (<Author>, <Year>) in PDF which was published without any restrictions and hosted it on my own website. I then added reference links to various related resources including the source site, and related material on the topic.  This can be found at this address

the source document is fully referenced at the bottom of the answer.

This way, everything is clear and open, and the reader has a choice to either go to your own website to view the document or go straight to the source.
Comment: What you say sounds reasonable.  I appreciate you taking the time to communicate it to me.


Can these be support columns with these brackets

Question: Is there any way these columns with the top and bottom brackets can be supporting columns. If I can't tell by the brackets, I will need to break into their drywall at places to see if it or another beam is supporting.  I want to remove them.[Images

Image2
Answer: Yes, those posts are probably supporting the beam (above). You'll need to determine the load on the beam, size of existing beam, span from post(s) to wall, and location of footings.
The post without the metal base connector may just be decorative...to match the other post. However, either hire an architect or structural engineer OR submit more info regarding beam sizes, spans, footing locations, etc. for additional help.
Comment: Thanks, what is throwing me off is that the metal brace is installed under drywall on the top and on top of the old linoleum floor.
Comment: @KevinS Ahhh...very interesting. That's true...if the bearing plater is below the gypsum board, then it can't be a structural connector. However, you'll need to determine if there's a bearing plate up above. Also, you'll want to check if there's a footing under the post. (Maybe both posts are decorative.)


Finding middle of user input (int) and increasing/decreasing half of the values in JAVA

Question: Im trying to implement a program in Java that a user inputs a number greater than 10 & another number (whatever number) then it will list whatever first number the user inputs for example if it was 11 then it'd print 1-11 with corresponding numbers in which it increases by 50 in the first half (1-6) and decreases 25 for the rest (7-11). I have the following code but im having trouble trying to figure out the logic/how to go about the values being increased/decreased.
again the output would be something like this:
1 550
2 600
3 650
4 700
5 750
6 800
7 775
8 750
9 725
10 700
11 675
import java.util.Scanner;

public class Periods2
{

public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);
    System.out.print("enter the number of days in a given period:");
    int numbers = 1;

   int number = Integer.parseInt(reader.nextLine());

   if(number < 10){
  System.out.print("the number of days doesnt meet the required criteria enter it again:");
  number = reader.nextInt();

   }

    System.out.print("enter the number of sharepoints:");
   int sharepoints = Integer.parseInt(reader.nextLine());

    while (numbers <= number && sharepoints > number){
        System.out.println(numbers + "  " + sharepoints);
        numbers++;
    }
}
}

Comment: What's your question? Keep in mind that SO is not for "Why is this code not working" questions.
Comment: "*Increases by 50 everyday in the first half (1-6) and decreases for the rest (7-11)*" decreases for how much? `25`?
Comment: @Taelsin my question is how would I get half of the users input and increase the first half & decrease the second half
Comment: @Fureeish whoops didn't see that I left that out yes 25 ! Thanks for pointing that out I have edited.
Comment: what is the sharepoints input? 500?
Comment: @roshan in this example 11 is the number > 10 & 550 is the sharepoint
Answer: Find the half of your input, and in your loop you can add 50 to sharepoints until the value of numbers reaches half, and then decrease by 25 after that:
int half = (int) Math.ceil(number/2.0);

while (numbers <= number && sharepoints > number){

    System.out.println(numbers + "  " + sharepoints);

    if(numbers < half) {
    sharepoints += 50;
    }
    else {
    sharepoints -= 25;
    }
    numbers++;
}


Are mesh plots with Octave/XQuartz/GNUPlot supposed to be slow?

Question: Rotating a 3D mesh plot is very slow in Octave when used with XQuartz and GNUPlot in OSX Mavericks. I understand slow is hard to quantify, but what I mean here is, that upon dragging the mouse, the plot lags behind and skips a lot of frames, to the point where it's even a little hard to see where you'll end up once you are done dragging.
Thanks!
Answer: Hold the Ctrl-key while rotating. This displays only the axis during rotation and redraws the mesh only when you have finished rotating.
Comment: That helps a lot. Also, it sounds like XQuartz is not at fault, but rather gnuplot. Thanks!
Answer: I am on Debian, ver tell me that:
GNU Octave Version: 4.0.0
GNU Octave License: GNU General Public License
Operating System: Linux 3.16.0-4-amd64 #1 SMP Debian 3.16.7-ckt11-1 (2015-05-24) x86_64

I have a 1000x1000 mesh and it is extremely slow, in my setup the answer https://stackoverflow.com/a/19954741/15485 does not work.
I had a look at https://www.gnu.org/software/octave/doc/interpreter/Introduction-to-Plotting.html and call graphics_toolkit ("fltk") before my call to mesh: it improved a lot, it is not super fast but at least I can rotate the mesh.
Comment: Have you seen the answer from Christoph on holding `Ctrl-` to rotate?
Comment: @Miquel Yes I did, I wrote it in my answer :-)


References to calculate lumber size and span for flat roof?

Question: I want to design a flat roof extension to create a screen patio. I would like to find a reference for maximum span and sizing with standard (such as SY pine) lumber for beams and joists. I'm not going to decide on final dimensions until I know whether I have to change from 2x6 to 2x8, for example, if I want joists to run x number of feet between beams -- and to know how big the beams have to be. Can anyone point to an online site or a reference book for these types of calculations? I'm in Florida USA, so no snow load -- but I will use some kind of steel hurricane straps/joist tie downs.
Answer: To calculate the maximum span of roof joists you first add up the Dead Load (weight of joists, roofing material, etc.) to Live Load (weight of snow) to determine the Total Load.
Your Dead Load is

roofing, which is going to be from 1 lbs. per square foot (psf) up to 3 psf, depending on the type of roofing.
roof sheathing is going to be from 1 1/2 psf up to 2 psf depending on the thickness, which depends on the spacing between the joists.
joists are from 2 psf for 2x6's 12" on center, or 1 psf for 2x6's 24" on center up to 3 psf for 2x8's at 12" on center.
ceiling material, if any.

I'd guess your Total Load is about 7 psf, because you have no Live Load. Then you can use a joist calculator like this one:
https://www.awc.org/codes-standards/calculators-software/spancalc
You'll notice that the span calculator only goes down to 10 psf Live Load. This is okay for your situation because you may hang lights, hanging flower pots, etc.
So, your total load will be about 17 psf. Then try various sizes and spans until you get one you like.
If you use 16" on center, don't forget to convert your load from psf to 16" on center by multiplying 1.33 to your psf load. (So, 17 plf becomes about 23 lbs. per linear foot on your 2x6 joist. )
Comment: Great info, Lee, thanks! It looked like you were going to start with a list, but then forgot. I do that all the time, so I added that in for ya'. Is there a reference somewhere to get the standard dead loads you referenced, in case someone in the future wants to use a different type of material?
Comment: Excellent information Lee Sam, things I hadn't considered. You laid it all out for me, thank you!


Can't connect to docker via SSH when VPN is connected

Question: I using Ubuntu 22.04 LTS and FortiClient VPN application.
Everything works fine apart from when I'm trying to connect my docker container via SSH (localhost) I get the following error: "kex_exchange_identification: read: Connection reset by peer Connection reset by 127.0.0.1 port 2222". More that that, when I'm NOT on VPN - I dont have this issue.
Answer: try to define your docker interface when trying to connect
<code>ssh -b interface-ip remote-ip
</code>
interface-ip = docker ip usually 172.x.x.x
remote ip is container ip
Answer: Check your sockets, is yours currently occupied?
Run:
<code>> netstat -vatn | xargs grep 2222
</code>


Arduino: Want to make something only print once

Question: I was writing a script for the ardunio so that it would print how far away something was, and I was trying to make it so that if it was equal to the default length (when the script first started) it would not work, and if the distance between the two numbers is greater than 3 inches to print again.  Not sure why it isn't working.  At first I tried to make it so that it would not print, also, if it was the same as the last printed length, so if anyone could figure that out instead, that would be amazing.  Also, sorry if I sound stressed, I've been working on this probably super-simple script for at least 3 hours now.
#include <Ping.h>
Ping ping = Ping(13,0,0);
int defaultlength = 0;
int length = 0;
int afterlength = 0;
void setup(){
  Serial.begin(9600);
  ping.fire();
  defaultlength = ping.inches();
}

void loop(){
  ping.fire();
  length = ping.inches();
  delay(100);
  afterlength = length - defaultlength;
  sqrt(afterlength^2);
  if (afterlength >= 3) {
    Serial.print(afterlength);
    ping.fire();
    Serial.print("Inches: ");
    Serial.print(ping.inches());
    Serial.print(" | Centimeters: ");
    Serial.print(ping.centimeters());
    Serial.print(" | Light: ");
    if (analogRead(A0) >= 1000) {
      Serial.print("ON");
      Serial.println();
    }
    else {
      Serial.print("OFF");
      Serial.println();
    }

  }

  delay(1000);

}

Also, It is not printing anything at all ever.  I'm not sure if its not going through the loop or what.
Comment: You say "Not sure why it isn't working." What are you expecting? What is it doing that is different?
Comment: When things like this don't work, you should consider dumping information near statements "where nothing is supposed to happen" - just litter your code with Serial.print() statements, and dump everything that is going on.
Comment: Also - when you are debugging code, take out "everything you can do without". For example, you could take out the lines that poll A0, take out the bits that print the ping in cm, and just print out the value of the ping every time you go through the loop. Usually that clears things up a lot.
Comment: Print something before the if statement... that will tell you if you are even executing the loop...
Answer: Your line sqrt(afterlength^2); doesn't do anything useful. Did you mean to take the absolute value by writing
afterlength = sqrt(afterlength*afterlength);

The ^ operator is the bitwise XOR -- not at all what you were trying to do.
Does that make it better?
As for your other question:
"At first I tried to make it so that it would not print, also, if it was the same as the last printed length, so if anyone could figure that out instead, that would be amazing." - here is what you can do:
1) define another variable in the head of the script - call it lastlength and initialize it to defaultlength (right after you did your first ping in setup())
2) in the loop, change the if statement to
if ((afterlength >= 3) && (abs(length - lastlength) > 0.1)) {

3) finally, at the end of your if{} statement, add:
lastlength = length;

The reason to put that in the if{} block is to make sure that you only update it if things have changed sufficiently - otherwise, you keep the same "don't tell me again until it's different than the number you told me before" value. Of course, the > 0.1 value can be replaced with whatever tolerance you want. Note also use of abs() - a bit more compact than the square root of the square.
Comment: Yes, that is what I meant to do.
Comment: Did it help when you fixed that?
Comment: Apprently, however, the square root of -143^2 = 0.
Comment: You should using floating point, not int, as your variable type... and use afterlength * afterlength rather than ^2. ^ is the bitwise XOR operator, which is not what you want!
Comment: Then you can "accept" the answer and go back to your toy. You might even "up vote" it. I'm going to answer the other question you had - not to print if it's "like the last answer". Watch this space... Good luck!
Comment: I get this "sketch_jan26a:19: error: expected primary-expression before ')' token" when I do the last length thing
Comment: It may be there were some parentheses missing - please check the code now, I added some. If it doesn't work, you'll just have to go back to the previous version, which was working. Or start a new question with the current source code.


Ways to attach a coat-hanger between two closets (heavy load)

Question: I am in the process of creating a wardrobe closet in my house. The basis is standard elements, like the one shown in the image (image source), which can be customized with drawers, shelves, coat hangers etc. In principle, four such elements could be fit side-by-side in the niche designated for the closet, but to save money and for practical reasons, I am thinking about buying only two elements, putting them at the extreme ends, and attaching a bar for hanging coats in between (or possibly two bars, one above the other, for smaller items like shirts.)

The question is about the best methods to attach the bar. We have lots of clothes, which are likely to be very heavy - in the past we had (portable or suspended) clothes racks regularly collapsing under the weight. Note that it is never the bar itself that breaks, but rather its support, which is what my question is about. Note also that the cases are not of solid wood, but of agglomerated wood panels.
I see several options:

bar supports attached to the cases by screws - this seems like an unreliable option, since the screws could be ripped out from the wood, possibly with the pieces of the wood itself.
drilling holes through the wood panels and attaching the screws with nuts on the other side.
cutting round holes in the panels, to pass the bar through them
attaching the bar with any of the methods above, but then adding pieces of wood just below it (attached to the panels) as supports, to distribute weight.

Some of these options intuitively seem more robust then others, but I would appreciate a judgement based on experience or/and knowledge. Other suggestions are also welcome.
Remark: My technical terminology might be unprecise, since I am translating from another language. Any suggestions for improvement are welcome.
Answer: You basically want to run a bar between two outside cabinet walls.  That should be easy, even with particle board.  Use a couple of these per bar: https://www.amazon.com/Creatyi-Stainless-Brackets-Bracket-Supports/dp/B08NP7CNKF
The problem with particle board is that screws don't hold well in tension.  In your situation, they'll mostly be in shear, which is generally OK.  But it really depends how thick the walls of the cabinets are.  I'd start with just screws, and if they fail, they are easily swapped out for machine screws and washers.
It would behoove you to secure the cabinets to the walls, though, so they don't move.
Comment: I would also be beneficial to add extra supports in the middle of the bar, to avoid sag and create a separator to prevent all the clothes being shoved to one side
Comment: It really depends on the size of the rod, and the weight of the clothes.
Comment: Thanks. Essentially, you support my solution 1 (and 2, if 1 doesn't work.) And, yes, attaching the cabinets to the walls is a part of my program.
Answer: Put fairly large screw hooks into the ceiling framing, and support the rod(s) with cables or small chains from the hooks, ignoring the shelving units as support.
This method also allows for having a single bar on one side, and two at different heights on the other side.
Comment: Sounds...wobbly.
Answer: Drilling large holes through the walls of the shelves and passing the bar through them is a good approach, but then you have the ends of the bars inside your shelves, which may not be desirable.
A good approach is to take a piece of solid 2x6, about 8 inches long, cut a round notch in one end to support the bar, and screw the 2x6 to the sides of the cabinet using many screws ... maybe 6 screws on each side, spaced all around the 2x6.   Screw from the shelf side into the solid wood of the 2x4 and use a large washer.  All this is to minimize tearing forces on the particle board.
Screw the shelves to the side walls so they don't rock left to right because that won't help the bar stay up.
If your clothes are abnormally heavy you could also use angled support brackets mounted to studs on the rear wall to support the middle.
Answer: I'd recommend wardrobe pole sockets. This would require that the cabinets be anchored so they don't move away from each other, but it's a standard trivial solution.

(Image swiped from Amazon, but they're universally available in a wide range or materials.)
Or, if you don't want to buy, you can make your own: Cut a notch out of two boards, mount to side of cabinet with notch facing up, drop pole into notch.


SQLALCHEMY Cannot insert explicit value for identity column in table 'tblsummary' when IDENTITY_INSERT is set to OFF

Question: I'm totally new to Pandas and SQL Alchemy.
I'm trying to write code to import Microsoft Access database to SQL Server.
Using the pyodbc and Pandas dataframe approach it's working fine but it's terribly slow. (sample with only two fields...there's much more fields)
for index, row in df.iterrows():
   cursor.execute("INSERT INTO  tblsummary (myDate, REG_NO) values(?, ?)", mydate, row.REG_NO)
   print(index)
cnxn.commit()

I've read that in can speed up thing with SQL Alchemy and the "fast_executemany=True" on the create_engine.
Here's what i'm doing:
from time import perf_counter
import numpy as np
import pyodbc
import pandas
import sqlalchemy as sa
from sqlalchemy.engine import URL

connection_string = (
    r"DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};"
    r"DBQ=C:\Users\myuser\Sept23.mdb;"
    r"ExtendedAnsiSQL=1;"
)
connection_url = sa.engine.URL.create(
    "access+pyodbc",
    query={"odbc_connect": connection_string}
)
engine = sa.create_engine(connection_url)

df = pandas.read_sql("SELECT * FROM tblSummary", engine, parse_dates=["VOLCOUNTSTARTDATE"])

df = df.replace({np.NaN: None})

connection_string = (
    r"Driver={ODBC Driver 17 for SQL Server};"
    r"Server=XXX\YYY;"
    r"Database=ZZZ;"
    r"Trusted_Connection=yes;"
)
connection_url = URL.create(
    "mssql+pyodbc",
    query={"odbc_connect": connection_string}
)

engine2 = sa.create_engine(connection_url, fast_executemany=True)

sqlcon = engine2.connect()

sqlcon.execute(sa.sql.text("SET IDENTITY_INSERT tblsummary ON;"))

#need to rename those two field as Django not accepting it in Models.py
df.rename(columns={'CLASS': 'myclass', 'TYPE': 'mytype'}, inplace=True)

#a constant date i need to insert
df.insert(0, 'myDate', pandas.Timestamp('2016-11-06'))

t0 = perf_counter()
df.to_sql("tblsummary", engine2, index = True, index_label="id", if_exists="append")
print(f"{perf_counter() - t0} seconds")

sqlcon.execute(sa.sql.text(f"SET IDENTITY_INSERT  tblsummary OFF;"))
sqlcon.close()

I always got that IntegrityError message telling me to "SET IDENTITY to ON"
I'm trying to do it with that line but without success:
sqlcon.execute(sa.sql.text("SET IDENTITY_INSERT tblsummary ON;"))

IntegrityError                            Traceback (most recent call last) File C:\ProgramData\anaconda3\Lib\site-packages\sqlalchemy\engine\base.py:1934, in Connection._exec_single_context(self, dialect, context, statement, parameters)    1933     if not evt_handled:
-> 1934         self.dialect.do_executemany(    1935             cursor,    1936             str_statement,    1937             effective_parameters,    1938             context,    1939         )   1940 elif not effective_parameters and context.no_parameters:

File C:\ProgramData\anaconda3\Lib\site-packages\sqlalchemy\dialects\mssql\pyodbc.py:716, in MSDialect_pyodbc.do_executemany(self, cursor, statement, parameters, context)
    715     cursor.fast_executemany = True
--> 716 super().do_executemany(cursor, statement, parameters, context=context)

File C:\ProgramData\anaconda3\Lib\site-packages\sqlalchemy\engine\default.py:918, in DefaultDialect.do_executemany(self, cursor, statement, parameters, context)
    917 def do_executemany(self, cursor, statement, parameters, context=None):
--> 918     cursor.executemany(statement, parameters)

IntegrityError: ('23000', "[23000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Cannot insert explicit value for identity column in table 'tblsummary' when IDENTITY_INSERT is set to OFF. (544) (SQLParamData);

And the echo on the SQL Server engine.
2023-11-27 19:03:22,777 INFO sqlalchemy.engine.Engine SELECT CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR)

2023-11-27 19:03:22,779 INFO sqlalchemy.engine.Engine [raw sql] ()

2023-11-27 19:03:22,807 INFO sqlalchemy.engine.Engine SELECT schema_name()

2023-11-27 19:03:22,809 INFO sqlalchemy.engine.Engine [generated in
0.00132s] ()

2023-11-27 19:03:22,872 INFO sqlalchemy.engine.Engine SELECT CAST('test max support' AS NVARCHAR(max))

2023-11-27 19:03:22,874 INFO sqlalchemy.engine.Engine [generated in
0.00134s] ()

2023-11-27 19:03:22,895 INFO sqlalchemy.engine.Engine SELECT 1 FROM fn_listextendedproperty(default, default, default, default, default, default, default)

2023-11-27 19:03:22,897 INFO sqlalchemy.engine.Engine [generated in
0.00181s] ()

2023-11-27 19:03:22,937 INFO sqlalchemy.engine.Engine BEGIN (implicit)

2023-11-27 19:03:22,937 INFO sqlalchemy.engine.Engine SET IDENTITY_INSERT tblsummary ON;

2023-11-27 19:03:22,938 INFO sqlalchemy.engine.Engine [generated in
0.00197s] ()

2023-11-27 19:03:23,126 INFO sqlalchemy.engine.Engine BEGIN (implicit)

2023-11-27 19:03:23,175 INFO sqlalchemy.engine.Engine SELECT [INFORMATION_SCHEMA].[TABLES].[TABLE_NAME]  FROM [INFORMATION_SCHEMA].[TABLES]  WHERE ([INFORMATION_SCHEMA].[TABLES].[TABLE_TYPE] = CAST(? AS NVARCHAR(max)) OR [INFORMATION_SCHEMA].[TABLES].[TABLE_TYPE] = CAST(? AS NVARCHAR(max))) AND [INFORMATION_SCHEMA].[TABLES].[TABLE_NAME] = CAST(? AS NVARCHAR(max)) AND [INFORMATION_SCHEMA].[TABLES].[TABLE_SCHEMA] = CAST(? AS NVARCHAR(max))

2023-11-27 19:03:23,177 INFO sqlalchemy.engine.Engine [generated in
0.00162s] ('BASE TABLE', 'VIEW', 'tblsummary', 'dbo')

2023-11-27 19:03:23,905 INFO sqlalchemy.engine.Engine INSERT INTO tblsummary (id, [myDate], [REG_NO], [OFF_NO], [OFFICE], [ZONE], [INSTALN], [RES_ROUTE], [GENUS], [TRIP], mytype, myclass, [ROUTEMODE], [MMC], [VEHICLE], [RWOOT], [XT_VHCLE], [XT_OTHER], [XT_WAIT], [XT_RIDE], [CUC], [CUCT], [HCALLS], [HALLOW], [SPECT], [ASSIST], [GROWTH], [VVAL_100P], [VVAL_RCOV], [TOTNVAR], [NVVAL], [PTACT], [OBTP_BVAL], [SUBD_BVAL], [PREP_BVAL], [SORT_BVAL], [TOT_BVAL], [TOT_ASSMT], [TOT_WKLOAD], [G_GROWTH], [G_INSIDE], [G_DELIVERY], [G_HALLOW], [CONTROL], [LC_SUPPORT], [RES_DATE], [VOLCOUNTSTARTDATE], [EVALVERSION], [RESTRUCTUREENDDATE]) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

2023-11-27 19:03:23,905 INFO sqlalchemy.engine.Engine [generated in
0.50666s] [(0, datetime.datetime(2016, 11, 6, 0, 0), 1, 'A001', 'AMHERST LCD MAIN', '', 'AMHERST LCD MAIN', '   LC0011', 'C', '1',
6.0, 1.0, 2.0, None, 'TWT', 58.35, 17.0, 0.0, 0.0, 11.72, 0.0, 0.0, 608.0, 1.71, 14.53, 0.0, 0.0, 292.65, 131.2, 128.24, 169.69, 608.0, 5.98, 4.9, 23.99, 27.02, 362.79, 466.14, 466.14, 0.0, 0.0, 0.0, 0.0, '', 0.0, datetime.datetime(2022, 8, 15, 0, 0), Timestamp('2022-03-07 00:00:00'), '1008.1003', datetime.datetime(2022, 4, 22, 0, 0)), (1, datetime.datetime(2016, 11, 6, 0, 0), 1, 'A001', 'AMHERST LCD MAIN', '', 'AMHERST LCD MAIN', '   LC0012', 'C', '1', 12.0, 1.0, 1.0, None, None, 58.35, 0.0, 0.0, 0.0, 12.17, 0.0, 0.0, 639.0, 2.41, 0.0, 0.0,
0.0, 306.45, 116.06, 207.07, 240.23, 639.0, 5.54, 6.81, 17.52, 18.55, 404.73, 477.67, 477.67, 0.0, 0.0, 0.0, 0.0, '', 0.0, datetime.datetime(2022, 8, 15, 0, 0), Timestamp('2022-03-07 00:00:00'), '1008.1003', datetime.datetime(2022, 4, 22, 0, 0)), (2, datetime.datetime(2016, 11, 6, 0, 0), 1, 'A001', 'AMHERST LCD MAIN', '', 'AMHERST LCD MAIN', '   LC0013', 'C', '1', 1.0, 1.0, 1.0, None, None, 58.35, 0.0, 0.0, 0.0, 11.92, 0.0, 0.0, 786.0, 2.2, 0.88, 0.0,
0.0, 271.6, 97.58, 222.1, 249.43, 786.0, 5.68, 8.91, 18.42, 21.0, 401.02, 474.4, 474.4, 0.0, 0.0, 0.0, 0.0, '', 0.0, datetime.datetime(2022, 8, 15, 0, 0), Timestamp('2022-03-07 00:00:00'), '1008.1003', datetime.datetime(2022, 4, 22, 0, 0)), (3, datetime.datetime(2016, 11, 6, 0, 0), 1, 'A001', 'AMHERST LCD MAIN', '', 'AMHERST LCD MAIN', '   LC0014', 'C', '1', 1.0, 1.0, 1.0, None, None, 58.35, 0.0, 0.0, 0.0, 11.3, 0.0, 0.0, 767.0, 2.26, 0.0, 0.0,
0.0, 267.46, 93.79, 237.31, 258.7, 767.0, 5.61, 7.41, 17.8, 19.83, 403.15, 475.16, 475.16, 0.0, 0.0, 0.0, 0.0, '', 0.0, datetime.datetime(2022, 8, 15, 0, 0), Timestamp('2022-03-07 00:00:00'), '1008.1003', datetime.datetime(2022, 4, 22, 0, 0)), (4, datetime.datetime(2016, 11, 6, 0, 0), 1, 'A001', 'AMHERST LCD MAIN', '', 'AMHERST LCD MAIN', '   LC0015', 'C', '1', 1.0, 1.0, 1.0, None, None, 58.35, 0.0, 0.0, 0.0, 5.93, 0.0, 0.0, 813.0, 1.39, 0.88, 0.0,
0.0, 247.64, 82.66, 223.86, 269.57, 813.0, 5.71, 9.39, 18.73, 21.18, 407.24, 473.89, 473.89, 0.0, 0.0, 0.0, 0.0, '', 0.0, datetime.datetime(2022, 8, 15, 0, 0), Timestamp('2022-03-07 00:00:00'), '1008.1003', datetime.datetime(2022, 4, 22, 0, 0)), (5, datetime.datetime(2016, 11, 6, 0, 0), 1, 'A001', 'AMHERST LCD MAIN', '', 'AMHERST LCD MAIN', '   LC0016', 'C', '1', 1.0, 1.0, 1.0, None, None, 58.35, 0.0, 0.0, 0.0, 7.09, 0.0, 0.0, 723.0, 2.09, 0.97, 0.0,
0.0, 303.54, 115.84, 208.27, 238.81, 723.0, 5.72, 8.4, 18.82, 21.47, 409.05, 477.57, 477.57, 0.0, 0.0, 0.0, 0.0, '', 0.0, datetime.datetime(2022, 8, 15, 0, 0), Timestamp('2022-03-07 00:00:00'), '1008.1003', datetime.datetime(2022, 4, 22, 0, 0)), (6, datetime.datetime(2016, 11, 6, 0, 0), 1, 'A001', 'AMHERST LCD MAIN', '', 'AMHERST LCD MAIN', '   LC0017', 'C', '1', 12.0, 2.0, 1.0, None, None, 13.35, 0.0, 0.0, 0.0, 3.42, 0.0, 0.0, 345.0, 2.24, 0.0, 0.0,
0.0, 164.48, 69.26, 115.8, 130.57, 345.0, 5.24, 4.49, 13.23, 12.0, 234.79, 253.83, 253.83, 0.0, 0.0, 0.0, 0.0, '', 0.0, datetime.datetime(2022, 8, 15, 0, 0), Timestamp('2022-03-07 00:00:00'), '1008.1003', datetime.datetime(2022, 4, 22, 0, 0)), (7, datetime.datetime(2016, 11, 6, 0, 0), 1, 'A001', 'AMHERST LCD MAIN', '', 'AMHERST LCD MAIN', '   LC0018', 'C', '1', 12.0, 2.0, 1.0, None, None, 13.35, 0.0, 0.0, 0.0, 5.07, 0.0, 0.0, 366.0, 2.78, 1.58, 0.0,
0.0, 182.13, 80.95, 108.57, 123.68, 366.0, 5.33, 4.47, 13.02, 13.71, 241.15, 263.96, 263.96, 0.0, 0.0, 0.0, 0.0, '', 0.0, datetime.datetime(2022, 8, 15, 0, 0), Timestamp('2022-03-07 00:00:00'), '1008.1003', datetime.datetime(2022, 4, 22, 0, 0))  ... displaying 10 of 13310 total bound parameter sets ...  (13308, datetime.datetime(2016, 11, 6, 0, 0), 5, 'E084', 'BURNABY LCD NORTH FRASER 2', '', 'BURNABY LCD NORTH FRASER 2', '   LC0244', 'C', '1', None, 1.0, 2.0, None, 'TWT', 58.35, 34.46, 0.0, 0.0, 26.49, 0.0, 0.0,
858.0, 14.17, 47.62, 0.0, 0.0, 251.82, 129.76, 104.33, 138.2, 858.0, 0.0, 9.27, 16.33, 0.0, 294.63, 474.65, 474.65, 0.0, 0.0, 0.0, 0.0, '', 0.0, datetime.datetime(2022, 8, 15, 0, 0), Timestamp('2022-03-07 00:00:00'), '3503.3501', datetime.datetime(2022, 5, 6, 0, 0)), (13309, datetime.datetime(2016, 11, 6, 0, 0), 5, 'E084', 'BURNABY LCD NORTH FRASER 2', '', 'BURNABY LCD NORTH FRASER 2', '   LC0246', 'C', '1', None, 2.0, 2.0, None, 'TWT', 13.35, 34.46, 0.0, 0.0, 25.7, 0.0, 0.0,
285.0, 5.24, 23.69, 0.0, 0.0, 111.31, 70.52, 62.88, 94.1, 285.0, 0.0, 2.85, 4.24, 0.0, 171.7, 274.15, 274.15, 0.0, 0.0, 0.0, 0.0, '', 0.0, datetime.datetime(2022, 8, 15, 0, 0), Timestamp('2022-03-07 00:00:00'), '3503.3501', datetime.datetime(2022, 5, 6, 0, 0))]

2023-11-27 19:03:43,360 INFO sqlalchemy.engine.Engine COMMIT

Comment: Can you turn `echo=True` on for that engine and then include the log?  Might be that it is being set within a transaction and then reset before the actual insert.
Comment: @IanWilson i've realized that i was missing the constant "myDate" column. So i added this: df.insert(0, 'myDate', pandas.Timestamp('2016-11-06')) and see the echo on the engine edited in the question. Thnks!!
Answer: I think the problem might be that you are using engine2 instead of the connection you made so you are probably working on 2 diff connections.  Ie.
df.to_sql("tblsummary", engine2, should be df.to_sql("tblsummary", sqlcon,.  But can you try an explicit transaction like this?
engine2 = sa.create_engine(connection_url, fast_executemany=True)

with engine2.begin() as sqlcon:

    sqlcon.execute(sa.sql.text("SET IDENTITY_INSERT tblsummary ON;"))

    #need to rename those two field as Django not accepting it in Models.py
    df.rename(columns={'CLASS': 'myclass', 'TYPE': 'mytype'}, inplace=True)

    t0 = perf_counter()
    df.to_sql("tblsummary", sqlcon, index = True, index_label="id", if_exists="append")
    print(f"{perf_counter() - t0} seconds")

    sqlcon.execute(sa.sql.text(f"SET IDENTITY_INSERT  tblsummary OFF;"))

    # transaction is committed and connection returned to engine

Here is the documentation explaining this usage:
connect-and-begin-once-from-the-engine
If you really wanted to fully understand what went wrong you could also turn on the engine pool echo flag, sqlalchemy.pool.Pool.params.echo.  I think two connections that each have their own transaction.
Comment: That did the trick perfectly! And it's way faster then the previous method. Thank you so much!
Comment: Oups. Still got an error on the second append. How can i have "id" to autoincrement so that i don't have a primary key violation?
Comment: Sorry you are inserting the ID value from the old db OR you want new id values automatically created when you insert the other non-id columns?


Need someone to clear up my mind about the CP of Pokemon

Question: After playing for a few days, i have some questions about the CP of Pokemons. My friends and i did some tests and here what we got:

Im lv18 and  catched a magikarp 100CP. My friend is lv18 too, and he catched one with 120CP. We max CP of each one and evolve them. Then the result is my Gyrados has 1469CP and his Gyrados is 1462CP. Only 7CP different not too much..
-> So i think that each lv has a limit CP for each pokemon. That means 2 players with the same level will have the same CP cap. Even if the beginning CP of 2 pokemons is different they still will have the same amount of CP when we max them?
On the otherside, another friend of mine catched 2 magikarp. One is 130CP, one is 120CP. He is lvl20. He max the one with 130CP and evolve it into a 1695CP Gyrados. The one with 120CP, he power up it to 130CP, evolve and max it, reach only 1665CP.
-> So my idea about the CP cap of each player is wrong? Cuz if my theory is right these 2 gyrados should have the same CP (maybe theres a distance but not too much like this).

Any idea here?
Comment: I believe that XS and XL also affect the CP/Health growth of a pokemon. This might be a relevant factor in this case.
Comment: Actually theres not much differences between their size i have some screenshot here but dunno how to up it.
Answer: I'll have to check myself, but according to some people, extra size and weight (XL or XS) do affect HP and CP
Check the size of your thow maxed out pokemons.
Also, the upgrade work steps by step. So if the next upgrade gives +10% (of max CP) and your pokemon is at 81%, it will got at 91% then blocked while starting at 89% you will end up at 99%.
Comment: I have checked the weight and height, an eevee with xl in both weight and height has 459cp and 59hp. Meanwhile, an eevee with normal size has 424cp and 61hp. So i think size doesnt effect cp nor hp.
Comment: U mean the upgrading system is random. I thought that it will auto adjust the cp so u can reach the same max CP for 2 pokemons of each kind. So if what u say is right then i can understand the difference in CP now. In the test 1 when power up i got more CP than my friend so that even we started with a far distance but we still ended up with same cp amount ! Thanks for that info !


My new electric kitchen stove stopped working

Question: I have a house that was built in the fifties,it has heavy wiring that comes from behind a cabinet for the stove. The plug in is on heavy wiring, is a three plug and matches the one that comes out from the stove.The bottom on plug that attaches to the big wiring feels loose. I had taped the plug with electrical tape and it worked when the new stove was put in but now stove has quit working,can you attach a new plug to this type of wiring?
Comment: Yes both the plug can be replaced.  One problem is it sounds like the old NEMA 10 type that was banned in the 90s for being unsafe.  Replacing with the safer NEMA 14 type might not be that hard.
Comment: Pictures would help. Also model # of the new stove.
Answer: It sounds as if you're describing the old-style 10-50 receptacle. One looks like this:

Though these have been banned for new installations for decades, and they're somewhat dangerous, they are still manufactured and allowed as replacements. If the one you have is so loose that you needed to tape the plug in, a new receptacle will be significantly safer. The ideal case, of course, is to retrofit the outlet with ground and replace the receptacle with a 14-50, but even a proper 10-50 replacement has a benefit over a worn out one.
If you're comfortable replacing receptacles and have done it before yourself, you can replace this in most jurisdictions without an electrician. It's bigger than a standard receptacle, and less forgiving of failure, but it's not typically that complicated of an installation. If you're not comfortable, this is a straightforward replacement for any electrician.
One caveat: if the wiring going to the outlet right now is cloth-covered, you should probably get a pro in to do the replacement or quote an upgrade.


Asp.Net MVC Inserting Same Data Into All Models

Question: I have more than 40 models in my application, and now i am trying to implement logging system. For the first phase, i want to keep the information of "Created By" and "Created Date" information for all the rows in all the tables.
I think i can create a base class which includes the attributes"CRDATE" and "CRBY", and create all of my models from this base class. But how can i write a generic method, to insert CRDATE and CRBY, and also deleted boo information ?
Here is my base-model:
<code> public class BaseModel
    {
        public DateTime CrDate { get; set; }

        public int UserId { get; set; }
        public ApplicationUser User { get; set; }

        public bool IsDeleted { get; set; }
    }
</code>
Should i use generic repository actions ?
Regards
Answer: Have your base class inherit from an Interface (such as IBaseModel) that has contains CrDate and CrBy (maybe name as well, for logging purposes), but not the specialized information from your other classes.
It would look something like:
<code>public class BaseModel: IBaseModel
{
    public DateTime CrDate { get; set; }

    public int UserId { get; set; }
    public ApplicationUser User { get; set; }

    public bool IsDeleted { get; set; }
}

public interface IBaseModel
    {
        DateTime CrDate { get; set; }
        ApplicationUser User { get; set; }
    }
</code>
Then your generic logging class can take IBaseModel as a parameter and get those two properties.
<code> public void LogWhatever(IBaseModel logModel)
 {
    //...
 }
</code>
Comment: Thank you for your help. But why i need to use interface ? I asked to learn. And ie, i have a model called, employee. How can i call the LogWhatEver() method ?
Comment: Interfaces allow you to pass around different objects that only have the subset of the signature you want.

You could call LogWhatever with and pass in anything that implements the interface.  For example:

BaseModel bm = new BaseModel(){CrDate=DateTime.Now,UserID=123,ApplicationUser = new ApplicationUser()};

or

AnotherModelThatImplementsIBaseModel abm = new AnotherModelThatImplementsIBaseModel() {...};

LogWhatever(bm);
LogWhatever(abm);
Comment: Still i have problems. If we dont have IBaseModel, i think , i can still call BaseModel bm = new BaseModel(){CrDate=DateTime.Now,UserID=123,ApplicationUser = new ApplicationUser()}; We are creating a basemodel and pass it into the method LogWhatever which is getting IBaseModel...
Comment: Also, after inherited all of my models from basemodel, should i use generic repository pattern ?


How to check if many-to-many list is empty with django-filter?

Question: I am using django-rest-framework with django-filter to implement filtering.
Let's say I have following result:
{
    "id": 13,
    "created": "2017-06-21T01:08:49.790254Z",
    "updated": "2017-07-21T10:25:51.706730Z",
    "toylist": [],
}

How do I implement filtering so I can check if the toylist array is empty? For example, something like: /toys/?toylist__isnull=True
Comment: Can you post your current view/viewset class?
Comment: Yes, here it is:
class ToysViewSet(viewsets.ModelViewSet):
        permission_classes = [permissions.IsAuthenticated]
 queryset = Toys.objects.all().order_by('-created')
 serializer_class = ToysSerializer
 filter_class = ToysFilter
Comment: And the `ToysFilter` class because that's the one handling the filtering
Comment: i do have toysfilter class
Answer: Ok, it was a relatively simple fix:
class ToysFilter(filters.FilterSet):
    toylist__isnull = filters.BooleanFilter(name='toylist', method='list_is_empty')

class Meta:
    model = Toys
    fields = {
        'id':['exact'],
        'created':'__all__',
        'updated':'__all__',
     }

def list_is_empty(self, qs, name, value):
    isnull = not value
    lookup_expr = LOOKUP_SEP.join([name, 'isnull'])

    return qs.filter(**{lookup_expr: isnull}).distinct()

Answer: It isn't necessary to use a method here. More simply, you could do the following:
class ToysFilter(filters.FilterSet):
    toylist__isnull = filters.BooleanFilter(name='toylist', lookup_expr='isnull', distinct=True)


Merge two sorted arrays in runtime faster than O(N)

Question: I think I have a solution but I am not completely sure.
My solution was to Convert Arrays to Linked Lists. Then Merge and sort the linked list recursively.
I've read that it will take O(1) space in memory. But I am not sure the runtime would be faster than linear time.
Any suggestions please?
Comment: Without the code, there is no way to say.  The only way to reduce the time complexity is you have a large number of duplicates.
Comment: How do you convert an array to a linked list in less than O(N)?
Comment: It's not possible to _read_ two sorted arrays faster than O(n), let alone do anything with them.  This is definitely 100% not possible.
Comment: by merge do you mean that there shouldn't be duplicate?
Comment: NO, it is NOT possible to merge 2 sorted arrays in less than O(n), n being the size of the biggest array
Comment: I wouldn't say that it is not possible in general. It depends on the use case. There are cases when you can say that statistically the merge will be faster than O(n).
Comment: "Not possible in general" means that in the general case it is not possible. There may be special cases where it is possible.
Comment: @DJClayworth if your comment is an answer to my comment, what I meant is more or less what you wrote, even though i wouldn't say that these are "special cases" if for special you mean also rare. They can be very common in some domains.
Comment: @Louis Wasserman Perhaps [quantum bogosort](http://c2.com/cgi/wiki?QuantumBogoSort)? O(1) ;-)
Comment: Are you looking for arrays only or any other data structure also.. as i think BST merging would be good and might do in <O(n)
Answer: There is a special case where you can merge 2 arrays in constant time:

The arrays are adjacent, that is they are slices of the same array and the last element of the first is just before the first element of the second.
The last element of the first array is less or equal to the first element of the second array.

The case can be checked with a single test.
This may seem ludicrous, but it is a very common case for mergesort and testing for this special case first increases mergesort performance significantly for arrays that are already fully or partially sorted.  A similar test can be used to handle arrays that are sorted in reverse order, and carefully crafted code can achieve O(N) sorting times for both sorted and reverse sorted arrays while keeping the same number of element comparisons for the general case.
Comment: Exactly what I was thinking!
Comment: it can also happen if the two lists are, for example, pixels of small segments : there could be a lot of pixels in each list, but you know that statistically there won't be overlap in most of the cases.
Comment: And even when there is an overlap, because they are sorted, you can use bisection to find the overlap and then check only the overlapped segment: operation that would take less than O(n)
Comment: LSNED about `mergesort()` implementations.
Answer:
My solution was to Convert Arrays to Linked Lists.

That takes O(N) time and memory.
Comment: @DJClayworth am I misinterpreting the question? I thought this pretty directly answered whether the OP's algorithm is faster than O(N).


Reference known property in (List)someObject

Question: have tried some searches. Probably my lack of knowledge that I'm not using the right search terms or perhaps just not understanding the answers.
I have a method that is being passed an object, which I want to output a particular value to a text file.
I already know the object will be a List< someClass > of a few different possible classes (customers/employees/items etc). But all of the classes contain the same string property (e.g.) string idNumber.
So something like this:
public static void OutputFile(object myInput)
{
  foreach (someGenericObject in (List<anyType>)myInput)
  {
    string textToOutput = someGenericObject.idNUmber;
    //output the text to somewhere else here
  }
}

I feel like as long as I know that it will always contain a this "idNumber" property regardless of the type, that I should be able to reference it somehow. But I just can't seem to get my head around it?
The error I typically get is something like:

Cannot cast List< Employee > to List< object > etc.

Thanks in advance
Comment: Do you have control over the definition of `Customer`, `Employee` and `Item`? As in, can you modify their definition? If so, you could have them all inherit from an interface with an `idNumber` property and change your method to be `public static void OutputFile(IEnumerable myInput)`.
Comment: Thank you! I think this is exactly what I was looking for.
Comment: Great. I've posted that as an answer below.
Answer: As I suggested in the comments, if you have the ability to modify these classes, you can have them all inherit from an interface IHasIdNumber with an idNumber property.
Your method would then become:
public static void OutputFile(IEnumerable<IHasIdNumber> myInput)
{
  foreach (var item in myInput)
  {
    string textToOutput = item.idNUmber;
    //output the text to somewhere else here
  }
}

Answer: There are a few ways you can solve this.
Recommended way: Implement common interface:
public interface INumberable { // I'm sure you can come up with a better name...
    string IDNumber { get; set; }
}

And then all the possible classes that can be passed into the method will implement INumberable. Your method can then look like this:
public static void OutputFile(List<INumerable> myInput)
{
  foreach (var someGenericObject in myInput)
  {
    string textToOutput = someGenericObject.idNUmber;
    //output the text to somewhere else here
  }
}

Not-so-recommended way: Reflection:
Type t = someGenericObject.GetType();
var p = t.GetProperty("idNumber");
string theStringYouWant = (string)p.GetValue(someGenericObject);

Note that this is not very safe.
Answer: You can use [dynamic].
foreach (var someGenericObject in (dynamic)myInput)
{
    //...
}

Comment: OP's list isn't a `List` so s/he can't use this method.
Answer: If all your classes have the same property you want to access in foreach loop you can do in via interface.
public interface ISmth {
        int MyProperty { get; set; }
    }

    public class Student : ISmth {
        public int MyProperty { get;  set; }
    }

    public class Employee : ISmth {
        public int MyProperty { get; set; }
    }

public static void DoSmth(object myObj) {
        foreach(ISmth item in (List<object>)myObj) {
            Console.Write(item.MyProperty);
        }
    }

List<Student> stdList = new List<Student>();

DoSmth(stdList.Cast<object>().ToList());

Comment: oops sorry try this:  foreach(ISmth item in (List)myObj) {
                Console.Write(item.MyProperty);
            }
Comment: That will also throw a runtime error. How about testing the code?
Comment: It works fine if the list is a `List`. If it's a `List` or `List` (like OP said it would be), it will throw a runtime error.
Comment: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/boxing-and-unboxing
Comment: I have no idea what you're trying to convey with that link, but here, look, runtime error: https://dotnetfiddle.net/VH8PkZ
Comment: Convert your lists of Employee/students to list of objects DoSmth(stdList.Cast().ToList());   (add using System.Linq;)
Comment: Yeah, you could do that, but there are much better ways to go about this that don't require a whole bunch of casting. See [my answer](https://stackoverflow.com/a/47279396/1945651) or [sweeper's answer](https://stackoverflow.com/a/47279418/1945651), for instance.


How to run a configuration script as soon as a Wacom graphics tablet is connected (via USB)?

Question: I'm using a Wacom graphics tablet under Ubuntu 18.04 (Kernel: 4.15.0-72-generic).
Unfortunately, I cannot configure it using the system settings because it is not recognized properly.
The configuration via xsetwacom works, but is not persistent. As soon as I restart the computer or replug the device, the default settings are loaded.

I assumed that the easiest solution would be to run a configuration script as soon as the tablet is recognized as a USB device.
According to my understanding, two steps would be necessary to accomplish this:

Create a udev rule
I've created a file /etc/udev/rules.d/99-config_wacom_intuos.rules with the content:
# "idVendor" and "idProduct" were derived from the output of the lsusb command.
ACTION=="add" \
, SUBSYSTEM=="input" \
, KERNEL=="mouse*" \
, ATTRS{idVendor}=="1234" \
, ATTRS{idProduct}=="5678" \
, RUN+="/bin/sh -c '/usr/local/bin/config_wacom_intuos.sh >> /var/log/custom_logs/config_wacom_intuos.log 2>&1'"

This file has the permissions:
-rw-r--r-- 1 root root    ...

(The dictionary /var/log/custom_logs were also created by me.)
Create a configuration script
I've created a file /usr/local/bin/config_wacom_intuos.sh with the content:
#!/bin/bash
#coding:utf8

# These were the missing statements as suggested by the answer.
#export DISPLAY=:1
#export XAUTHORITY=/run/user/1000/gdm/Xauthority

echo "`date '+%Y-%m-%dT%H:%M:%S'`, ShellPID $$, start"

sleep 1

if xsetwacom --list devices | grep -q "Wacom Intuos BT"
then
    main_screen="HEAD-0"
    bezier_args="0 20 80 100"
    positioning_mode="Absolute"
    raw_sample_lvl="9"
    suppress_lvl="10"

    # Maps the graphics tablet to the area of a specified screen (for multiple-screen environments).
    xsetwacom set "Wacom Intuos BT S Pen stylus" MapToOutput "$main_screen"
    xsetwacom set "Wacom Intuos BT S Pen eraser" MapToOutput "$main_screen"
    xsetwacom set "Wacom Intuos BT S Pen cursor" MapToOutput "$main_screen"

    # Changes the pressure sensitivity.
    xsetwacom set "Wacom Intuos BT S Pen stylus" PressureCurve "$bezier_args"
    xsetwacom set "Wacom Intuos BT S Pen eraser" PressureCurve "$bezier_args"

    # Smoothes drawn lines by reducing any quivering.
    xsetwacom set "Wacom Intuos BT S Pen stylus" RawSample "$raw_sample_lvl"
    xsetwacom set "Wacom Intuos BT S Pen stylus" Suppress "$suppress_lvl"
    xsetwacom set "Wacom Intuos BT S Pen eraser" RawSample "$raw_sample_lvl"
    xsetwacom set "Wacom Intuos BT S Pen eraser" Suppress "$suppress_lvl"
    xsetwacom set "Wacom Intuos BT S Pen cursor" RawSample "$raw_sample_lvl"
    xsetwacom set "Wacom Intuos BT S Pen cursor" Suppress "$suppress_lvl"

    # Specifies the positioning mode ("Absolute" / "Relative")
    xsetwacom set "Wacom Intuos BT S Pen stylus" Mode "$positioning_mode"
    xsetwacom set "Wacom Intuos BT S Pen eraser" Mode "$positioning_mode"
    xsetwacom set "Wacom Intuos BT S Pen cursor" Mode "$positioning_mode"

    # Assigns actions to the tablet buttons.
    xsetwacom set "Wacom Intuos BT S Pad pad" Button 1 "key +ctrl z -ctrl"
    xsetwacom set "Wacom Intuos BT S Pad pad" Button 2 "key +ctrl +shift z -ctrl -shift"
    xsetwacom set "Wacom Intuos BT S Pad pad" Button 3 "key 0xffab"
    xsetwacom set "Wacom Intuos BT S Pad pad" Button 8 "key 0xffad"

else
    echo "NO 'WACOM INTUOS BT' DEVICES FOUND."
fi

echo "`date '+%Y-%m-%dT%H:%M:%S'`, ShellPID $$, end"
echo -e "---\n"

exit 0

This file has the permissions:
-rwxr-xr-x 1 root root    ...

The script works just fine when I executed it manually from the terminal.
It is also executes when I plug in the device. Unfortunately, this doesn't seem to have any effect.
In addition, the script is executed several times in a row after plugging in the device.
I assume that this behavior occurs because of the udev rule, which is not restrictiv enough.
Can anyone tell me, what I'm doing wrong?
Comment: shebang should not contain any space ```#!/bin/bash```
Comment: I've updated the script. Thank you @bac0n
Answer: The X server tools usually affect only your current session (which is why you have to set them every time).
Since you are running that script in a shell that is not attached to any X session, the tool doesn't have any idea what X session those settings should be changed for (or more precisely, it doesn't have any idea that an X session even exists).
You can manually connect your shell to your current X session, but the solution might be a bit fragile on occasion.
You need to add two variable exports to your script, one for DISPLAY and XAUTHORITY. Those are used for identifying and accessing the correct X session. You can get the appropriate values by running env while logged in as your regular user.
In my case, the output looks like the following (parts marked by [...] are ommitted):
$ env
[...]
XAUTHORITY=/home/tim/.Xauthority
[...]
DISPLAY=:0.0
[...]

For those values, I would need to extend the script by the following lines:
export DISPLAY=:0.0
export XAUTHORITY=/home/tim/.Xauthority

Now, the script should work even while you are the root user.
The udev configuration itself seems fine.
Comment: I've followed your instructions, unfortunately the script still seems not to affect the current session.
The "what I've tried so far" section of my question was updated, to provide more details about my steps.
Nevertheless: Thank you!
Comment: Could you add a debug xmessage command (e.g. `xmessage "Test`) as the first command in your script? As soon as this is executed (and the connection is available), a pop-up should appear with the Text you set. This could tell us whether we are still stuck at connecting to the correct X session or whether the issue is somewhere else. Also, you could try to redirect the script's output to a file to check it afterwards: https://superuser.com/questions/1273148/writing-to-a-file-from-a-udev-run-command
Comment: I've implemented your recommendations and added a description of the resulting behavior to the original question. The problem seems to be that the tablet components are not yet registered at the runtime of the script.
Comment: Is the device still not configured correctly, even after udev triggered the script without issues? It appears that the udev rule is triggered by every component that is registered. One possible workaround for the errors would be to check the device list before changing settings. Another way would be to part the script so that we can trigger the sections seperately. This would only work if udev supports the necessary parameters. Could you run `udevinfo ` (should be `/dev/input/wacom*`) as outlined here and post the result: http://www.reactivated.net/writing_udev_rules.html#udevinfo
Comment: It happens that one of the triggered scripts (and all following) is / are running without errors. If so the device is correctly configured. I assume that this is mainly because of the delay produced by my input.
Comment: At least the script seems to be triggered only once, when I change `ATTRS` to`ATTR` in the udev rule ([Difference between ATTRS and ATTR in udev rules](https://unix.stackexchange.com/questions/424727/difference-between-attrs-and-attr-in-udev-rules)). But once again the script is not affecting the session (only `Cannot find device 'Wacom Intuos ..'` errors).
Comment: Unfortunately the command `udevinfo` is not installed on my system (nor is it installable via the default ubuntu repositories). I instead ran `udevadm info -q all -n [PATH]`. In order to not increase the length of the question even further, [I posted the result on codedump.io](https://codedump.io/share/KiL183zuDZTk/1/udev-output-for-debugging) (I hope that's ok).
Comment: Not having the script run 18 times is progress. However, I'm starting to get out of ideas. The only thing remaining that I can imagine to be the problem is that the device might not be initialized until after udev ran, so we probably want to try and delay the script. We can't outright `sleep`, since udev might execute those scripts synchronously, so I prepared a modified script that waits in the background and executes the commands after the device appears: https://pastebin.com/NLzfGSvX
Comment: I changed the udev rule so that the script only fires when the kernel `mouse*` is detected. Additionally a sleep command was added to the script.  Now there is a first execution of the script that always fails, but the second one always seems to be successful. Perhaps I later switch to a configuration via `xorg.conf.d` because it seems more reliable. Thank you very much for your help!


Is this wall load bearing? See photos

Question: I'm looking to tear down the wall between my kitchen and dining room, and I'm wondering if it's load bearing.  If so, it's a 9' section that I want to remove.  Would two 2x10s with 1/2" plywood between them be sufficient, or would I need to go with either 2x12s or LVLs?  See the pictures below.  And if you need, I can take a picture of the floor joists from the basement.  This is the first floor of a two story colonial.
Thanks!
Chris
Comment: See many other similar questions. To hazard even a guess we would need to know which direction the floor joists go, and even then the right answer is to have an expert look at the actual building.  You also need expert advice to tell you how large an LVL header will be required, if it is load bearing.
Comment: See [tag:load-bearing] for similar questions. [This answer](http://diy.stackexchange.com/a/37301/157) in particular has some good tips.
Answer: I wouldn't trust a random individual on the internet to correctly identify bearing walls. There are general guidelines for identifying bearing walls, but many exceptions to the rules.
Get a competent person in your kitchen to look at the structure. From there, you can figure out the engineering.
Comment: As a random individual on the internet, I'd say that the substantial headers over the openings on each side would point to it being load bearing.

Is this wall load bearing? See photos


Pair items from array in unique groups

Question: I have an array of numbers ([1,2,3,4,5,6,7,8,9,10]). These numbers represent players. I would like these players to each "play" each other exactly once.
I need to create "Rounds" for these games. These rounds will include a even number of matches, and each player can only play in a round, at most, once. If there's an odd number of matches, than a final round with irregular number of matches is okay.
The end result being an array of "Round" arrays. These round arrays will contain the matches between players. The end result being something like below, but complete:
[[[1,2],[3,4],[5,6],[7,8],[9,10]],[[1,3],[2,4],[5,7],[6,8],[9,1],[10,2]]]
I've found Array#combination for getting the matches created, but I can't seem to get the rounds to build properly.
Answer: That is called a round robin tournament. Wikipedia gives the following algorithm
Round 1. (1 plays 14, 2 plays 13, ... )
 1  2  3  4  5  6  7
 14 13 12 11 10 9  8

then fix one competitor (number one in this example) and rotate the others clockwise one position:
Round 2. (1 plays 13, 14 plays 12, ... )
 1  14 2  3  4  5  6
 13 12 11 10 9  8  7

And keep rotating:
Round 3. (1 plays 12, 13 plays 11, ... )
 1  13 14 2  3  4  5
 12 11 10 9  8  7  6

An odd number of players is handled by one player per round having no game (often implemented by adding a dummy player).

Pair items from array in unique groups


Cancelling needless freeze protection on pool filter

Question: For some reason the temperature sensor on my Paddock Aquatouch no longer reads the correct temperature.  It thinks my pool water temperature is in the range of 30F despite the fact that it is actually about 85F.  As a result, it keeps needlessly turning on my pump filter every 5 minutes!  How can I disable this?  I've Googled for my control system model but it is pretty old and all the results show newer models which have controls mine doesn't.  I assume there's a temp sensor somewhere I can disable it from listening to maybe?  How?
By playing around a bit with the buttons in all the combinations I could think of I did find that when I press "Program, Enter" I get the following message:
Press devices to activate for freeze protection - press enter when finished

Unfortunately, just hitting enter informed me that the filter pump was protected.  I tried adding and removing a couple other pumps, but while I was able to add them, I wasn't able to remove them!  When I hit enter it says:
Devices allocated to freeze protection are:
  Pump
  Aux7
  Pool Htr
  Spa Htr
Freeze protection is enabled

Implying there is a way to disable it.  But I haven't been able to find a combination to do that.
Update: Here is a picture of the controller.

I found what I think is the temperature sensor attached to the piping.

The circuit board (A Jandy Aqua Link 5574C) is shown here. I have circled in red where the temperature sensor wires appear to connect.  However, there are 4 wires instead of the expected two: green, yellow, red and black.

I have ohmed out these 4 wires with no power:
black and red: 1.2 ohms
black and green: 1.5k ohms
yellow and green: 1.5k ohms
Update: After I closed up the box and turned power back on after taking the bottom picture, the temperature reading went as high as 84F before dropping first to 75F and then 49F.
Comment: What is the exact make name and model number?  Paddock seems to be an OEM name.  Look at the specifications plate.
Comment: @wallyk I've added a picture to show the controller.  I'm not sure what specifications plate you are referring to - this unit is built into the wall so all I can see is the front.
Comment: If you can figure out where the temp sensor is connected, you can replace it with a quarter watt resistor, what I can't tell you is what value by I'd start with about 10k.  Bottom line you can also likely replace the thermistor for $20 if you find it and identify it.
Comment: Also if you can find "sensor calibration" or something like that in the programming menu's you can adjust that to have the sensor effectively lie about the current temp.
Comment: @Tyson I can't even find any menus...
Comment: I'm guessing the "program" button. But without a model number to google for a manual all I can do is guess.  There may be "user" program menu, and "setup" programming as well and for the latter you probably need to stand on it head and use a toe to press program 4 times while your other big toe holds some other button down....
Comment: @Tyson Since a thermistor's resistance goes down with temperature, I suppose if I just shorted it out it would appear to be very hot, although I don't know if the circuit would be designed to handle a short - I would assume the sensor has high resistance anyway, like into an op-amp or something, but who knows...
Answer: I suspect the 30°F reading is what the sensor indicates if it were disconnected.  Inspect the wiring between the controller and the sensor which is mechanically connected to the plumbing somewhere.  It could be a sensor failure, but is most likely a wiring problem.
Comment: I'll check the wiring... if it makes any difference, for some time before this happened it was inaccurately reading in the range of 110F, which of course made no difference to me because it had no effect on pool operation. :)
Comment: The wiring looks fine, I have added a couple of pictures.
Comment: Updated question to include resistances measured on the sensor wires... Maybe I'll see if I can find a suitable resistor and try paralleling it across the yellow/green wires.
Comment: Nope... paralleling 1k across yellow green did nothing.
Comment: Ok, I think with your help I managed to find a workaround.  I disconnected the sensor completely from the board and now (after a period of time where it started rising) seems to have stabilized at 113F and so far hasn't budged from that reading.  Given that the pool is going to be drained in the winter, I think that is probably acceptable.


Passing mat4 array to GLSL succeeding but producing GL_INVALID_OPERATION

Question: I'm currently passing an array of bone positions to GLSL for a skeletal animation shader; the positions are passing successfully but producing a GL_INVALID_OPERATION error.
I'm passing the matrices in the following line:
std::vector<glm::mat4x4> bpos;
...
glUniformMatrix4fv(shader.uniform("bpos"), 50, GL_FALSE, &bpos.at(0)[0][0]);

Where the shader.uniform("bpos") position has been assigned earlier as:
this->m_uniforms["bpos"] = glGetUniformLocation(this->m_program, "uniform_bpos");
I'm getting the following output:
GL CALLBACK: ** GL ERROR ** type = 0x824c, severity = 0x9146, message = GL_INVALID_OPERATION in glUniform3(uniform "uniform_bpos"@1 is matrix)
Has anyone here encountered this error or does anyone here see what I'm doing incorrectly?
EDIT:
The vertex shader:
#version 330 core

layout(location = 0) in vec3 vert_ms;
layout(location = 1) in vec3 norm_ms;
layout(location = 2) in ivec4 bone_ids;
layout(location = 3) in vec4 bone_weights;

out vec3 norm_ws;
out vec3 pos_ws;

uniform mat4 uniform_mvp;
uniform mat4 uniform_bpos[50];

void main(){
     mat4 bone = uniform_bpos[bone_ids[0]] * bone_weights[0];
     bone += uniform_bpos[bone_ids[1]] * bone_weights[1];
     bone += uniform_bpos[bone_ids[2]] * bone_weights[2];
     bone += uniform_bpos[bone_ids[3]] * bone_weights[3];

     gl_Position = uniform_mvp * bone * vec4(vert_ms, 1);
     norm_ws = (uniform_mvp * bone * vec4 (norm_ms, 0)).xyz;
     pos_ws = vec3(gl_Position);
}

the function getting the uniform locations:
Shader::Shader(GLuint shader_program)
{
  this->m_program = shader_program;

  this->m_uniforms["mvp"] = glGetUniformLocation(this->m_program, "uniform_mvp");
  this->m_uniforms["bpos"] = glGetUniformLocation(this->m_program, "uniform_bpos");
  this->m_uniforms["eye"] = glGetUniformLocation(this->m_program, "uniform_eye");
}

from this file: https://github.com/EricJIsaac/opengl-engine/blob/feature/pb-materials/src/graphics/shader.cpp
uploading the vertex data:
void SkeletonMeshBuffer::predraw()
{
  glEnableVertexAttribArray(0);
  glEnableVertexAttribArray(1);
  glEnableVertexAttribArray(2);
  glEnableVertexAttribArray(3);
  glBindBuffer(GL_ARRAY_BUFFER, this->m_vbo);

  // Vertices
  std::size_t stride = sizeof(graphics::data::SkeletonMesh_Vertex);
  glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, stride, (void*)0);

  // Normals
  char* offset = (char*)0 + 3 * sizeof(float);
  glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, stride, (void*)offset);

  // Bone Ids
  offset = (char*)0 + 6 * sizeof(float);
  glVertexAttribIPointer(2, 4, GL_UNSIGNED_SHORT, stride, (void*)offset);

  // Bone Weights
  offset = (char*)0 + 6 * sizeof(float) + 4 * sizeof(unsigned short);
  glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, stride, (void*)offset);

  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->m_ele);
}

void SkeletonMeshBuffer::draw(std::size_t id)
{
  if(id < 0 || id > this->m_entries.size())
  {
    printf("Invalid skeleton mesh id %lu requested\n", id);
    return;
  }

  char* offset = (char*)0 +
    this->m_entries[id].index_offset * sizeof(unsigned short);

  glDrawElementsBaseVertex(
    GL_TRIANGLES,
    this->m_entries[id].index_count,
    GL_UNSIGNED_SHORT,
    (void*)offset,
    this->m_entries[id].vertex_offset / 3);
}

void SkeletonMeshBuffer::postdraw()
{
    glDisableVertexAttribArray(0);
}

from this file: https://github.com/EricJIsaac/opengl-engine/blob/feature/pb-materials/src/graphics/skeleton_mesh_buffer.cpp
The meshes being loaded:
https://github.com/EricJIsaac/opengl-engine/tree/master/data/geometry/skeletonMeshes
Comment: "*the positions are passing successfully but producing a GL_INVALID_OPERATION error.*" How can something be "successful" while erroring? Also, how are "uniform buffer objects" involved; you don't use `glUniform*` calls to upload to UBOs.
Comment: To clarify, the animated meshes appear to be animating correctly but an error is being reported. My guess at the moment is that the matrices are accessible in the shader as expected but an error is being reported. My best guess is that I am either observing a bug or undefined behavior that happened to work.

So succeeding in the sense that the information seems to be making it to the hardware, but an error is still reported by the instruction that puts them there.
Comment: My mistake on the uniform-buffer-object tag, I just removed it.
Comment: Well, if the uniforms are uploaded correctly, are you sure the error is thrown by that exact function call and not some earlier or later code? It's also a bit confusing why the error message talks about `glUniform3`.
Comment: Please provide more code (shaders, uploading of the data, getting the uniform locations). As @ChristianRau mentioned, this part of the error message `glUniform3` looks suspicious. Throw an exception from your callback function if an error occurs. This way you can use your debugger to activate a breakpoint and traverse the call stack to find out which API call actually causes the error. It might be another function and not the one you expected.
Comment: I am not certain that the error was thrown by this exact function; I'll add the exception today to verify which function is throwing the error.
Answer: The eye position (a vec3) was being bound to the wrong shader, resulting in the glUniform3 error when OpenGL (mesa) checked the validity of the uniforms. The error was due to a typo; I named my simple-mesh and animated-mesh shaders similar things.
glUseProgram(smesh_shader.get());
      smb.predraw();
      glUniform3fv(mesh_shader.uniform("eye"), 1, &eye[0]); // <- Oops
      graphics::ogl::render(scene.getRoot(), smb, mv, smesh_shader);
      smb.postdraw();

Following @Christian Rau's and @wychmaster's suggestions, I was able to debug the issue. I also needed to build a debug version of the mesa library to make sense of the stack-trace in gdb.