text:
Q: Is this Simpson's Paradox on the Titanic data set? With the well known "Survival of passengers on the Titanic" data set I get a strange behaviour by plotting the fare vs. the age (see below). Without a constraint on Pclass the correlation is positive. In contrast for all Pclasses the correlations seems to be negative.
I assume that's a form of "Simpson's Paradox". But I am not sure. How can this behaviour best explained for this special case?
# df is a pandas dataframe with the titanic data set
# see https://www.kaggle.com/c/titanic

import seaborn as sns
sns.jointplot("Age", "Fare", df, kind='reg')

sns.lmplot("Age", "Fare", df, col="Pclass")

A: Although Simpson's paradox (or Simpson's reversal) is more often referred in 3-way contingency tables than in correlation between continuous variables, it's the same phenomenon.
Here, the explanation in simple words seems clear: Although inside each class there is a slight tendency of decreasing fares with age, people in lower classes tend to be younger. That is, younger people tend to travel in lower classes and therefore younger people tends to pay lower fares.
About the fact that people is younger in the lower classes, you can see in the plot that there are a lot of children (age<18) in 3rd class, less of them in 2nd class (clearly less people in 0-20 than in 20-40), and very few children in 1st class. Comparing the 40-60 and 60-80 bands with the 20-40 band would also show that people tend to be younger in lower classes.
In summary: Yes, it is an occurrence of the Simpson's paradox. Younger people tend to travel in lower classes and therefore younger people tend to pays lower fares, even if they tend to pay a little more than older people in the same class.
And just a as a side comment: this one is not the only occurrence of Simpson's paradox in the Titanic dataset. In https://select-statistics.co.uk/blog/hidden-data-and-surviving-a-sinking-ship-simpsons-paradox/ or https://www2.stat.duke.edu/courses/Fall12/sta611/SimpsonsParadox.pdf another one is noticed.


text:
Q: Carrying 10 liter dewar in elevator advisable? I am using liquid nitrogen a lot at university and frequently have to carry a 10 l dewar from the storage container into my lab. On this way I have to walk down 4 stories with the heavy dewar. Carrying gases and chemicals in elevators is strictly forbidden, which of course makes sense, since the elevator can always get stuck and then you would be stuck with those substances, posing fatal hazard in some cases.
Now I'm asking myself if a 10 l dewar would not infact be completely irrelevant in this regard. Large gas flasks are out of the question of course, but can the content of a 10 l dewar pose any real suffocation threat? The elevator I'm talking about can comfortably fit 8 people.
Side note: There is of course an elevator dedicated only to chemicals but it would mean quite a detour for me.

A:
but can the content of a 10 l dewar pose any real suffocation threat?

IN practice, probably not because the dewar has a lid and assuming the elevator is working properly (its been serviced recently) then there shouldn't be any problem. But these are assumptions of circumstance and cannot be trusted.
IN principle, there are tremendous safety risks for bringing a bunch of liquid nitrogen into a confined container, i.e. the elevator. The biggest threat is that if the dewar's lid gets removed or broken (or something) and it spills, then the liquid nitrogen could displace enough oxygen from the elevator carriage to cause suffocation - big no no! Especially since you might not be the only one riding the elevator, and if you are the only one then if something bad did happen then who would know about it to help you?
So, in the world of insurance liabilities and accidents, it's best to use the stairs, or the elevator that is specifically designed to transport chemicals. If the dewar is heavy, then enlist the help of an aspiring undergraduate to help you carry it :)
EDIT: and to the point made in the comments, the expansion ratio of liquid nitrogen is given here, so for every 1 liter of liquid nitrogen, in principle 696 liters of gaseous nitrogen can be produced (and liquid nitrogen turns into gaseous form at room temperature and atmo. pressure). So from this consideration, the risk is certainly non-insignificant.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to recursively scrape every link from a site using Scrapy? I'm trying to obtain every single link (and no other data) from a website using Scrapy. I want to do this by starting at the homepage, scraping all the links from there, then for each link found, follow the link and scrape all (unique) links from that page, and do this for all links found until there are no more to follow.
I also have to enter a username and password to get into each page on the site, so I've included a basic authentication component to my start_requests.
So far I have a spider which gives me the links on the homepage only, however I can't seem to figure out why it's not following the links and scraping other pages.
Here is my spider:
    from examplesite.items import ExamplesiteItem
    import scrapy
    from scrapy.linkextractor import LinkExtractor
    from scrapy.spiders import Rule, CrawlSpider
    from scrapy import Request
    from w3lib.http import basic_auth_header
    from scrapy.crawler import CrawlerProcess

    class ExampleSpider(CrawlSpider):
#name of crawler
name = "examplesite"

#only scrape on pages within the example.co.uk domain
allowed_domains = ["example.co.uk"]

#start scraping on the site homepage once credentials have been authenticated
def start_requests(self):
    url = str("https://example.co.uk")
    username = "*********"
    password = "*********"
    auth = basic_auth_header(username, password)
    yield scrapy.Request(url=url,headers={'Authorization': auth})

#rules for recursively scraping the URLS found
rules = [
    Rule(
        LinkExtractor(
            canonicalize=True,
            unique=True
        ),
        follow=True,
        callback="parse"
    )
]

#method to identify hyperlinks by xpath and extract hyperlinks as scrapy items
def parse(self, response):
    for element in response.xpath('//a'):
        item = ExamplesiteItem()
        oglink = element.xpath('@href').extract()
        #need to add on prefix as some hrefs are not full https URLs and thus cannot be followed for scraping
        if "http" not in str(oglink):
            item['link'] = "https://example.co.uk" + oglink[0]
        else:
            item['link'] = oglink

        yield item

Here is my items class:
    from scrapy import Field, Item

    class ExamplesiteItem(Item):
        link = Field()

I think the bit I'm going wrong is the "Rules", which I'm aware you need to follow the links, but I don't fully understand how it works (have tried reading several explanations online but still not sure).
Any help would be much appreciated!

A: Your rules are fine, the problem is overriding the parse method.
From the scrapy docs at https://doc.scrapy.org/en/latest/topics/spiders.html#crawling-rules

When writing crawl spider rules, avoid using parse as callback,
  since the CrawlSpider uses the parse method itself to implement
  its logic. So if you override the parse method, the crawl spider
  will no longer work.


text:
Q: Dice probability - amount of "hits" in a pool What I want is to calculate the probability of a minimum number of rolls with a minimum value for at given number of dice, e.g. "if I roll 20 dice, what is the probability of getting at least 3 dice with a value of 5 or more?"
I have a brute force setup, that creates the Cartesian product and just enumerates through that, but it completely explodes at 9 dice. So what I'm really looking for is some kind of function that does not require me to expand all possibilities, so that I can calculate for 20-30 dice.

A:
"if I roll 20 dice, what is the probability of getting at least 3 dice with a value of 5 or more".

Break it down into two stages:
a) if I roll 1 die, what is the probability of getting a value of 5 or more?
I assume these are 6-sided dice numbered 1-6. In which case $p=\frac{1}{3}$
You seem to call getting that result 'a hit'. I'll refer to it as "a success".
b) In 20 trials, what is the probability of at least 3 successes?
This is a binomial distribution question -
Given $X\sim \text{Bin}(n=20, p=\frac{1}{3})$, what is $P(X\geq 3)$?
By hand, that probability is relatively easily computed as $1-[P(X=0)+P(X=1)+P(X=2)]$
$=1-[(1-1/3)^{20}+ {{20}\choose{1}}(1/3)^1(1-1/3)^{19}+{{20}\choose{2}}(1/3)^2(1-1/3)^{18}]$
With bigger numbers of values to compute, this rapidly gets tedious.
These values can be obtained by tables or by computer programs (like R or Excel, for example). So let's look at some examples:
In R:
Calculated as if by hand:
> 1-((2/3)^20+20*(1/3)*(2/3)^19+20*19/2*(1/3)^2*(2/3)^18)
[1] 0.9824074

calculated using the inbuilt cdf:
> 1-pbinom(2,20,1/3)
[1] 0.9824074

So the probability of 3 or more successes in 20 dice is 0.9824
In Excel:
=1-BINOM.DIST(2,20,1/3,TRUE)

gives:
0.982407

(in older versions of Excel use BINOMDIST - with the same arguments - instead)

So how do we write it just as a single function?
In R you could do this:
poolprob <- function(target, dice, minhits) 1-pbinom(minhits-1,dice,1-(target-1)/6)

then:
> poolprob(5, 20, 3)
[1] 0.9824074

(there are one or two improvements that could be made, but this is just for illustration)
You could similarly set up an Excel spreadsheet that did the same kind of calculation.

So here it is for 3-30 dice:
> n=3:30
> data.frame(n,p=poolprob(5, n, 3))

which gives:
    n          p
1   3 0.03703704
2   4 0.11111111
3   5 0.20987654
4   6 0.31961591
5   7 0.42935528
6   8 0.53177869
7   9 0.62282172
8  10 0.70085861
9  11 0.76588935
10 12 0.81887735
11 13 0.86126776
12 14 0.89466626
13 15 0.92064288
14 16 0.94062489
15 17 0.95584927
16 18 0.96735214
17 19 0.97597930
18 20 0.98240737
19 21 0.98716891
20 22 0.99067741
21 23 0.99325031
22 24 0.99512894
23 25 0.99649521
24 26 0.99748526
25 27 0.99820030
26 28 0.99871513
27 29 0.99908475
28 30 0.99934942


text:
Q: PostGIS ST_Distance discrepancy between GeogFromText and Point SELECT t.coords, t2.coords,
  ST_Distance(ST_GeogFromText('SRID=4326;POINT(-115.83225 44.18711)'), ST_GeogFromText('SRID=4326;POINT(-105.83225 54.18711)')) AS d1,
  ST_Distance(ST_Point(t.coords[2], t.coords[1]), ST_Point(t2.coords[2], t2.coords[1])) AS d2
FROM locations
INNER JOIN locations t2 ON t2.id = 1
WHERE t.id = 2;

t.coords = "{44.18711,-115.83225}" and t2.coords = "{54.18711,-105.83225}"
d1 is returned as 1326899.86792105 and d2 as 14.142135623731.
Why is that? Thanks!

A: Seems I have to cast the ST_Point into a geography type, then it works.


text:
Q: VS Code custom run configuration for D Is there a way to add a custom run configuration that would run a current file in the terminal?
Currently no extensions exist for debugging .d files on Visual Studio Code. I still can manually enter the compile and run command with dmd in the terminal, though this gets tedious and the commands can be forgettable. I saw that it might be possible to do this more efficiently using tasks but I haven't found any sufficient examples on how to achieve it.

A: I use
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
        {
        "type": "code-d",
        "request": "launch",
        "name": "Debug D project",
        "cwd": "${workspaceFolder}",
        "program": "./darc-test-library"
        }
    ]
}

Together with CodeLLDB.


text:
Q: Ubuntu network file-sharing This couldn't be simpler, but I've failed to get it working, so I hope some Samba or Avahi experts can help me here.
I have a laptop and a desktop on a home network both running Ubuntu 19.10, along with a bunch of Android devices and an occasional Windows XP or Vista machine, or Virtual Windows 7. The laptop(s) may also be on other networks which I can control.
My objective is to share a partition from the Ubuntu laptop to the desktop. Principally so I can use Darktable, Digikam and the desktop's larger screen to view and edit images. This depends on name resolution and consistent network names.
How hard can it be?
I set up Samba on both machines (samba version 2:4.10.7+dfsg-0ubuntu2.3, samba-common, samba-common-bin), and nautilus-share. After much messing around I was able to connect to shared folders both ways using smb://ip-address/ in Nautilus and smbclient in the command terminal.
However I couldn't connect from the machine names; Nautilus returned the error:

'Unable to access location Failed to retrieve share list from server: Connection refused'

Command terminal:
$ smbclient -L ////JohnsMacBookPro//Pictures -U john
Unable to initialize messaging context
do_connect: Connection to JohnsMacBookPro failed (Error NT_STATUS_UNSUCCESSFUL)

For some reason the laptop was using NT1 and the desktop SMB3; I couldn't get to the bottom of this. And forcing versions by setting client and server min and max to SMB3 didn't change matters.
So, following @Morbius1's suggestion in this thread Bionic Beaver can not discover samba hosts - netbios, for simple Ubuntu networking, I:
1) Purged and reinstalled samba on both machines - samba, samba-common, samba-common-bin. I didn't edit the smb.conf.
2) Created an /etc/avahi/services/samba.service file on both machines:
<?xml version="1.0" standalone='no'?>
<!DOCTYPE service-group SYSTEM "avahi-service.dtd">
<service-group>
   <name replace-wildcards="yes">SMB %h</name> ## Display Name
   <service>
       <type>_smb._tcp</type>
       <port>445</port>
   </service>
</service-group>

3) Added and enabled samba users on both machines:
sudo smbpasswd -a john
sudo smbpasswd -e john

4) Used Nautilus to shared the Pictures partition and a sambashare folder from the laptop, and a sambashare folder from the desktop.
Now I can connect using the names - although there's duplication in Nautilus' network folders list. But the partition name has a number appended, which changes. This is a problem for an application like Digikam which expects to find resources in the same place every time it runs.
After rebooting the laptop, Nautilus on the desktop, 'Other locations', 'Network' shows 7 icons (possibly a reboot would clean this up):
Folder icon: 'pictures on johnsmacbookpro-15.local' which links
Folder icon: 'pictures on johnsmacbookpro-9.local' which linked yesterday, not today
Network drive icon: 'SMB JohnsMacBookPro-15' clicking on which generated the matching folder and mount point
Network drive icon: 'SMB Desktop01' which links to sambashare folder and print
Network drive icon: 'DESKTOP01 (File Sharing)' which links as above
Windows Network, leading to WORKGROUP and resources JOHNSMACBOOKPRO and DESKTOP01. Clicking on DESKTOP01 leads to the shared folders. JOHNSMACBOOKPRO generates the error message '**Unable to access location** Failed to retrieve share list from server: Connection refused' (as before from samba when accessing network resources)
Network drive icon: 'DESKTOP01 (File Sharing)' which links as above

The laptop's Other Locations - Networks list is simpler as whilst it shows 'SMB JohnsMacBookPro-15' it lists and links to 'DESKTOP01' and 'SMB Desktop01' without the appended numbers.
Output of testparm -s on both machines is the unaltered basic smb.conf:
$ testparm -s
Load smb config files from /etc/samba/smb.conf
Loaded services file OK.
Server role: ROLE_STANDALONE

# Global parameters
[global]
    log file = /var/log/samba/log.%m
    logging = file
    map to guest = Bad User
    max log size = 1000
    obey pam restrictions = Yes
    pam password change = Yes
    panic action = /usr/share/samba/panic-action %d
    passwd chat = *Enter\snew\s*\spassword:* %n\n *Retype\snew\s*\spassword:* %n\n *password\supdated\ssuccessfully* .
    passwd program = /usr/bin/passwd %u
    server role = standalone server
    server string = %h server (Samba, Ubuntu)
    unix password sync = Yes
    usershare allow guests = Yes
    idmap config * : backend = tdb

[printers]
    browseable = No
    comment = All Printers
    create mask = 0700
    path = /var/spool/samba
    printable = Yes

[print$]
    comment = Printer Drivers
    path = /var/lib/samba/printers

My immediate problems would be resolved if I can get a consistent name for the laptop, which I presume is from the Avahi / msdns packages?
Samba appears to have the same problems it always had. Not sure if those are soluble, might be a better solution in the long run.

A: I suspect this will be an iterative process.
The problem here is samba can resolve machines by name two different ways: By NetBIOS name and by its mDNS / Avahi name. Nautilus will display both by default if everyhing is working but it displays it with the same name followed by ( File Sharing ). NetBIOS is flaky so you may or may not be able to make a connection. Avahi is fairly consistent and is built into 19.10.
Here's the first thing I would do on both machine:
[1] Make sure you have the /etc/avahi/services/samba.service file on both machines.
[2] Edit /etc/samba/smb.conf on both machines and right under the workgroup = WORKGROUP line add this one:
multicast dns register = no

[3] Save smb.conf and restart smbd:
sudo service smbd restart

Your Linux machines will always appear as SMB hostname directly under "Other Locations" and not under "Windows Network". This is the Avahi way. There won't be any duplicates of the Avhai way since you've disabled it in smb.conf.
They may also show up under "Windows Network" but without the SMB prefix. This is the NetBIOS way. There is a way to disable this as well but then you mess with discovery from Windows machines.


text:
Q: Is there a max value for versioncode? We always have to increment versionCode by some arbitary number to publish it to google play.
Is there limit to that value and what will happen if it is reached?
defaultConfig {
        applicationId "my.app"
        minSdkVersion 15
        targetSdkVersion 22
        versionCode 65
        versionName "1.05"
        setProperty("archivesBaseName", "myapp-$versionCode")

    }

A: Starting at Android Pie (9), the version code will be a long (source). The max value of a long is 9,223,372,036,854,775,807 so you shouldn't run into any issues regarding length here.
Do note that it's still an int in older android versions, so long is only relevant to you when your minSdkVersion is 28 or higher.

A: The other responses are technically true but you should note that Google Play Store only accepts version codes up to 2100000000.

A: Update 08/11/2016 (UTC):
The docs has been updated. Not the old MAX_INT value nor the 2000000000.

Warning: The greatest value Google Play allows for versionCode is 2100000000.

Cross-post for visibility here.
It seems there was a recent change in Google, making the maximum versionCode up to 2000000000 only.
Reference post: Google Play Developer Console error: The version code of your APK is high and you risk not being able to update your APK

PS: For those who are planning to provide reference to the official documentation where the mentioned max value is 2147483647, please read the answer first in the post I referenced. It mentions that as of current date (08/10/2016), its still not updated.

A: According to android documentation and the gradle DSL documentation:
android:versionCode — An integer value that represents the version of the application code, relative to other versions.
Checking the java doc, by default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -2^31 and a maximum value of (2^31)-1.
Then the maximum value is 2^31-1.


text:
Q: Laplace transform for distributions The Fourier transform for tempered distributions is well-known. It's defined by $$\langle \mathcal{F}T , \phi\rangle = \langle T,\mathcal{F}\phi\rangle$$For any Schwartz function $\phi$. For ordinary functions, it's defined by $$\mathcal{F}f(s) = \int_{-\infty}^{+\infty}e^{-2\pi ist}f(t)dt$$On the other hand, the unilateral Laplace transform for the ordinary functions is $$\mathcal{L}f(s) = \int_{0^{-}}^{+\infty}e^{-st}f(t)dt$$Where $s \in \mathbb{C}$. Is it possible to take Laplace transform of distributions? How is it defined, then? It's known that $\mathcal{L}\delta(t) = 1$ but I don't know if it's rigorous since $\delta(t)$ is not an ordinary function.

A: If $T$ is a distribution with compact support then $\langle T(t), e^{-st} \rangle$ is well-defined. One can take $\rho \in C_c^\infty$ such that $\rho \equiv 1$ on a neighborhood of the support of $T$ and define $\langle T(t), e^{-st} \rangle = \langle T(t), \rho(t) e^{-st} \rangle$. The result doesn't depend on the choice of $\rho$.


text:
Q: Storing .dll files in SQL Server 2005 Where can I find information on storing ".dll" files in SQL Server 2005? Is it the same as storing Binary data?

A: You could use a binary or varbinary data type you can store any binary information including dlls.

A: Yes, it's just a file like a Word document or image...
Use varbinarx(max)


text:
Q: Data Analysis: Image Sharpening through Posterization I had this image, a picture of Jupiter:

I wanted to measure the pixel diameter of Jupiter. As evident, the image is quite blurry, and thus, many value of equally justified pixel diameters can be obtained. To eliminate this I posterised the image (which is technically, quote from Gimp, "designed to intelligently weigh the pixel colors of the selection or active layer and reduce the number of colors while maintaining a semblance of the original image characteristics"):

With the above result, I obtained three pixel diameters of Jupiter (one from each of the coloured circles), and with a little bit of calculation, realised that the yellow circle gave rise to the most accurate value of Jupiter's diameter (which was surprisingly off by less than one percent!).
My questions are:
1) Why is my original image like that? Is it due to some form of light scattering?
2) Is there a better method of obtaining an accurate pixel diameter than posterising the image
3) Is the posterised result expected? Are there names that can be given to the three distinct spherical objects (which seem to resemble shadows, like the umbra, prenunbra, antumbra, etc.)? Is there a reason why the middle posterised object gives the most accurate value?


text:
Q: How do I get the difference between 2 dates from a csv file? I have the Join Date and Left Date for multiple staff in a company in my csv file. I would like to calculate the difference for these 2 dates for each staff, and then find the total, average days, min and max. Not sure how to even get started...
Some Left Dates may be empty, and I would like to fill those empty dates with 1 May 2022, and then find the difference.
df[['Staff', 'JoinDate', 'LeftDate']]
df['LeftDate'].fillna(value = '1/05/2022')
I have tried to replace the NaN values with a set date but that doesn't work as well.

A: A rough draft of what I think you want. I use dateutil to make this easier.
cat dt_csv
id,dt_start,dt_end
1,2022-01-01,2022-06-30
2,2022-02-15,
3,2022-03-15,2022-07-31
4,2021-11-14,2022-04-15

import csv
from dateutil.parser import parse
from statistics import mean

with open('dt.csv') as csv_file:
    diff_list = []
    d_reader = csv.DictReader(csv_file)
    for row in d_reader:
        # Use strip() to reduce any values that are ' ' or more down  to '' so the or works.
        dt_start, dt_end = parse(row["dt_start"]), parse(row["dt_end"].strip() or "2022-05-01")
        dt_diff = dt_end - dt_start
        diff_list.append(dt_diff.days)
    # Sort the list to make it easier to get min and max.
    diff_list.sort()

diff_list
[75, 138, 152, 180]

avg_diff = mean(diff_list)
min_diff = diff_list[0]
max_diff = diff_list[-1]
total_diff = sum(diff_list)

avg_diff, min_diff, max_diff, total_diff
(136.25, 75, 180, 545)


text:
Q: assigning elements to buffer and specific position in buffer - how to speed up / why are the different implementations so slow? I'm trying to speed up the following code, where given a list of strings str_list I'm trying to convert the string into a number (unpack) and assign this number into the correct position of the nested list data. The dimensions of data are roughly data[4][20][1024]. Unfortunately, this function runs very slowly. Here's the code:
for abs_idx in range(nbr_elements):

    # get string
    this_element = str_list[abs_idx]

    # convert into number
    this_element = unpack('d', this_element)[0]

    # calculate the buffer number
    buffer_nbr = abs_idx / NBR_DATA_POINTS_PER_BUFFER_INT

    # calculate the position inside the buffer
    index_in_buffer = abs_idx % NBR_DATA_POINTS_PER_BUFFER_INT

    # write data into correct position
    data[file_idx][buffer_nbr][index_in_buffer] = this_element

I also tried the following alternative solution, which is even slower:
# convert each string into a number
unpacked_values = [unpack('d', str_list[j])[0] for j in range(nbr_elements)]
for abs_idx in range(nbr_elements):

    # calculate the buffer number
    buffer_nbr = abs_idx / NBR_DATA_POINTS_PER_BUFFER_INT

    # calculate the position inside the buffer
    index_in_buffer = abs_idx % NBR_DATA_POINTS_PER_BUFFER_INT

    # write data into correct position
    data[file_idx][buffer_nbr][index_in_buffer] = unpacked_values[abs_idx]

To my surprise, the next implementation is the slowest (I expected it to be the fastest):
# convert each string into a number
unpacked_values = [unpack('d', str_list[j])[0] for j in range(nbr_elements)]

# calculate all buffer numbers at once
buffer_ids = np.arange(nbr_elements) / NBR_DATA_POINTS_PER_BUFFER_INT

# calculate all positions inside the buffer at once
index_in_buffer_id = np.arange(nbr_elements) % NBR_DATA_POINTS_PER_BUFFER_INT

for abs_idx in range(nbr_elements):
    data[file_idx][buffer_ids[abs_idx]][index_in_buffer_id[abs_idx]] = unpacked_values[abs_idx]

Why are the successive implementations performing worse? Where are the individual bottlenecks? And how can I speed up my initial code?
EDIT: from my profiling tests, the following two steps are the bottleneck: running unpack and assigning the value to data. I don't know though how to speed-up these steps.
EDIT2: I need to use unpack because my strings are in hex.
EDIT3: values = unpack("d" * n, "".join(str_list)) solves the problem with unpack being slow. Still, the assignment to data with the triple (original) or double (modified) nested loop eats up 50% of the time. Is there a way to reduce this time?

A: Some optimizations:

*

*Unpack all stings at once

*Get item data[file_idx] before loop

Try it:
n = len(str_list)
values = unpack("d" * n, "".join(str_list))

a = data[file_idx]

# Just to shorten this code sample
q = NBR_DATA_POINTS_PER_BUFFER_INT

for i in xrange(n):
    a[i / q][i % q] = values[i]

Btw, did you profile what part of the code takes the most time?
UPDATE:
n = len(str_list)
values = unpack("d" * n, "".join(str_list))

# Just to shorten this code sample
q = NBR_DATA_POINTS_PER_BUFFER_INT

data[file_idx] = [values[i:i+q] for i in xrange(0, n, q)]

A: Is this any faster? It reduces some lookups and does not need to make an intermediate list with the numbers for all the strings?
df = data[file_idx]
index = 0
for value in str_list:
    # not sure what unpack does... is there a faster function
    # that does the same?
    number = unpack('d', value)[0]

    # calculate the buffer number
    buffer_nbr = index / NBR_DATA_POINTS_PER_BUFFER_INT

    # calculate the position inside the buffer
    index_in_buffer = index % NBR_DATA_POINTS_PER_BUFFER_INT

    # write data into correct position
    df[buffer_nbr][index_in_buffer] = number

    index += 1

A: How about this:
df = data[file_idx]
index = 0
bufnr = 0
buf = df[0]
for value in str_list:
    # not sure what unpack does... is there a faster function
    # that does the same?
    number = unpack('d', value)[0]

    buf[index] = number

    index += 1

    if index >= NBR_DATA_POINTS_PER_BUFFER_INT:
        index = 0
        bufnr += 1
        buf = df[bufnr]

Could it be that data is a dictionary instead of a list?


text:
Q: MySQL REPLACE doesn't work I use this to replace \" with " :
UPDATE wp_posts SET post_content = REPLACE (post_content, '\"', '"')

That query returns 0 row(s) affected and nothing happens.
What is wrong this this query?

A: You need to escape your backslash:
UPDATE wp_posts SET post_content = REPLACE (post_content, '\\"', '"')

A: The backslash charecter is escape character in MySQL so you need to escape it itself like this:
UPDATE wp_posts SET post_content = REPLACE(post_content, '\\"', '"')

A: use:
REPLACE(`post_content`, '\\"', '"')


text:
Q: How to find Latitude and longitude of Polygon shape edges? How to collect latitude and longitude of each edges of Polygon shape which we are drawing by google drawing API. Please help me by putting me in the perfect path to collect edges of Polygon.
<!DOCTYPE html>

    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title> Region Drawing System</title>

 Region Drawing System

            <input id="address" type="textbox" value="">
            <input type="button" value="Look UP" >

A: By The following code. Anyone can find the Lattitude and Longitude of the Polygon which we have drawn.
<!DOCTYPE html>

    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title> Region Drawing System</title>

 Region Drawing System

Have fun with the above code.


text:
Q: Why HIVE must split string with "\01"? [b4 0.11.0 is yes, after 0.11.0 you can specified] There is some string in a hive table, I use transform method that replace some char, my mapper script like this:
<?php
$strFrom = "\7";
$strTo = "\1"; // "|" it works well
$fd = fopen("php://stdin", "r");
while($line = fgets($fd)){
    $outStr = str_replace($strFrom, $strTo, $line);
    print $outStr;
}
fclose($fd);

my hive sql like this:
select transform (value)
using 'home/php/bin/php -c home/php/etc/php.ini replace.php'
as (v1 string)
from test_tbl

actually I try to replace string from "\7" to "\1", but I find it seems replace correctly, but it just output the first column. One input like this:
a\7b\7c\7d

then it output like this:
a

yeah, just one column!
If I replace it to "|", it output:
a|b|c|d

So I am confused, why must hive split string with "\1"? How can I forbid it? I just want to get:
a\1b\1c\1d

A: I found my answer in here.

*

*Data written to the filesystem is serialized as text with columns separated by ^A and rows separated by newlines.

*As of Hive 0.11.0 the separator used can be specified, in earlier versions it was always the ^A character (\001)
Thanks for all guys that seen this question.


text:
Q: Proof a series is coverges to a specific sum I need to prove that the sum of the following series is convergent to :   $1 \ge Sum$
$$\sum_{n=1}^\infty \ \left[\left(\frac{2n+1}{n}\right)\left(\frac{2n+2}{n}\right)\cdots\left(\frac{2n+n}{n}\right)\right]^{-1}$$
Well I succeed to compare it to another series but could only prove its   $2 \ge Sum$.
I would like to get a hint and explanation about the rationale of the solution.
Thanks!

A: Since $(2n+1)\ldots (2n+n)\geq (2n)^n=2^n n^n$,
$\displaystyle \sum_{n=1}^N \frac{n}{2n+1}\ldots\frac{n}{2n+n} \leq \sum_{n=1}^N \frac{1}{2^n} \leq \sum_{n=1}^\infty \frac{1} {2^n}=1$


text:
Q: Cannot install torch 1.7.0 in apple M1 I'm trying to install yolov5 on my Mac M1 using the followwing commands:
 git clone https://github.com/ultralytics/yolov5.git

then:
cd yolov5

But when I tried to install the requirmets from the requirments.txt file with below command:
pip install -r requirements.txt

The instllation complete but show below error at the end:
ERROR: Could not find a version that satisfies the requirement torch>=1.7.0 (from versions: none)
ERROR: No matching distribution found for torch>=1.7.0

I don't know which version of torch I have to use to complete the installation

A: Looks like this issue has been a regular for the latest python versions.
Could you please try downgrading your python version to 3.8 and retry your requirements.txt
https://github.com/pytorch/pytorch/issues/47354


text:
Q: How to import SQL file from input with PHP? I have a form with an input file, I want the user to upload a sql file, read it with php and import it to my database
My form code is

         <input type="file" accept=".sql" class="form-control" name="sql">

         <button type="submit" formaction="upload_sql.php" style="margin-top:8%" class="btn btn-primary" name="upload_sql">Upload</button>

But I don't know how to import that file into my database, I tried with "mysql -u root -p database < file.sql"

A: Mysql import SQL file with terminal
mysql -u username -p database_name < file.sql

With PHP
system('mysql -u username -p database_name < file.sql');


text:
Q: sql create columns from group by collection I have a table in the following form
chain   |branch
________|________|
    a   |UK
    a   |US
    b   |ISRAEL
    b   |UK
    b   |FRANCE
    b   |BELGIUM
    c   |NIGERIA

and i would like to create a new table in the following format
chain   |branch_1|branch_2|branch_3|branch_4
________|________|________|________|________|
    a   |  UK    |  US    |--------|--------|
    b   |  ISRAEL|  UK    | FRANCE |BELGIUM |
    c   | NIGERIA|--------|--------|--------|

For further clarification, imagine that you can do a group by (chain) where the aggregate function is the identity so that
group_1->(element1,element2,element3,..,elementM)
group_2->(element1,element2,element3,..,elementN)
...
group_X->(element1,element2,element3,..,elementZ)

so a new table will be created which will have
R+K columns where R are the number of columns that we group by (in our case that is the column 'chain' so R=1) and K is the max count of the groups (in our case that is four, corresponding to chain 'b')
I am sure that this must be a common question, so my apologies if this been answered before, but i could not find anything.
EDIT:
THIS IS NOT A PIVOT TABLE
A pivot table in that case would be
chain   |UK      |US      |ISRAEL  |FRANCE  |BELGIUM |NIGERIA |
________|________|________|________|________|________|________|
____a___|____1___|____1___|____0___|____0___|____0___|____0___|
____b___|____1___|____0___|____1___|____1___|____1___|____0___|
____c___|____0___|____0___|____0___|____0___|____0___|____1___|

Thanks!

A: You can do this with conditional aggregation and row_number():
select chain,
       max(case when seqnum = 1 then branch end) as branch_01,
       max(case when seqnum = 2 then branch end) as branch_02,
       max(case when seqnum = 3 then branch end) as branch_03,
       max(case when seqnum = 4 then branch end) as branch_04
from (select t.*,
             row_number() over (partition by chain order by branch) as seqnum
      from table t
     ) t
group by chain;

Note:  Your table doesn't have a column specifying the ordering of the rows.  SQL tables represent unordered sets.  Without such a column, there is no concept of one row being before or after another.  So, this version orders by the branch name.  You can order by whatever you like by changing the order by clause for row_number().


text:
Q: Qt Creator "Cannot create file (...) qtcreator.xml" (Mac) Qt Creator starts up with several error messages saying that:
"Cannot create file /Users/[username]/.config/Nokia/qtcreator.xml: Permission denied"
And when I exit:
"Cannot create file /Users/[username]/.config/Nokia/toolChains.xml: Permission denied"
The program runs fine, but I guess it won't be able to store any config. Anyone know how to fix this?

A: As has been mentioned in the comments, it looks like the Qt installer adds the configuration directories with root as the owner. To fix this, run:
sudo chown -R `id -un`:staff ~/.config/Nokia/

A: this command works great for me. found it in qtcenter forum
find ~/.config/Nokia -print0 | sudo xargs -0 chown $USER

i use this instead for version 2.6.1 Qt 5
find ~/.config/QtProject -print0 | sudo xargs -0 chown $USER


text:
Q: How to smooth a projected value obtained with a multiplicator in a time series? I have a time series chart where each bar interval = 600 seconds.
Each bar accumulates a number of transactions in a variable called 'volume'.
The goal is, while the current 10 mn bar is forming in real time, to anticipate the final volume value it will accumulate.
So I do a projection with a 'Multiplicator' that will multiply current intrabar volume in relation to remaining time in the bar.
So if 1mn has elapsed, I will project volume as x10, because 600/60 = 10.
Here is the calculation:
    SecondsPerBar = 600; // 10 mn
    TimeElapsed = 60; // 1mn... just an example, this is reevaluated each second.
    Multiplicator = SecondsPerBar / TimeElapsed;
    Projection = volume * Multiplicator;

This works fine, the problem is that in the beginning of the bar, the projection is usually much too strong, but it gets more accurate as the bar develops.
Is there a way to smooth the projection with inverse exponentiality, so at the beginning of the bar the projection will be less strong thus more smoothed, and the smoothness will loose intensity as the bar develops, and be nil at end of bar? What's the proper way to achieve this?


text:
Q: R color scatter plot points based on values I am able to plot a scatter plot and color the points based on one criteria, i.e. I can color all points >=3 as red and the remainder as black.
I would love to be able to color points in this fashion:

*

*

=3 color red

*<=1 color blue

*The rest as black

The code I have below completes step 1 and 3 but I am not sure how to incorporate the second argument of step 2
data<- read.table('sample_data.txtt', header=TRUE, row.name=1)
pos<- data$col_name1
cn<- data$col_name2
plot(pos,cn, ylim=c(0,5), col="blue")
plot(pos,cn, col=ifelse(cn>=3,"red","black"), ylim=c(0,10))

A: Best thing to do here is to add a column to the data object to represent the point colour.  Then update sections of it by filtering.
data<- read.table('sample_data.txtt', header=TRUE, row.name=1)
# Create new column filled with default colour
data$Colour="black"
# Set new column values to appropriate colours
data$Colour[data$col_name2>=3]="red"
data$Colour[data$col_name2<=1]="blue"
# Plot all points at once, using newly generated colours
plot(data$col_name1,data$col_name2, ylim=c(0,5), col=data$Colour, ylim=c(0,10))

It should be clear how to adapt this for plots with more colours & conditions.

A: It's better to create a new factor variable using cut(). I've added a few options using ggplot2 also.
df <- data.frame(
  X1=seq(0, 5, by=0.001),
  X2=rnorm(df$X1, mean = 3.5, sd = 1.5)
)

# Create new variable for plotting
df$Colour <- cut(df$X2, breaks = c(-Inf, 1, 3, +Inf),
                 labels = c("low", "medium", "high"),
                 right = FALSE)

### Base Graphics

plot(df$X1, df$X2,
     col = df$Colour, ylim = c(0, 10), xlab = "POS",
     ylab = "CS", main = "Plot Title", pch = 21)

plot(df$X1,df$X2,
     col = df$Colour, ylim = c(0, 10), xlab = "POS",
     ylab = "CS", main = "Plot Title", pch = 19, cex = 0.5)

# Using `with()`

with(df,
     plot(X1, X2, xlab="POS", ylab="CS", col = Colour, pch=21, cex=1.4)
     )

# Using ggplot2
library(ggplot2)

# qplot()
qplot(df$X1, df$X2, colour = df$Colour)

# ggplot()
p <- ggplot(df, aes(X1, X2, colour = Colour))
p <- p + geom_point() + xlab("POS") + ylab("CS")
p

p + facet_grid(Colour~., scales = "free")

A: Also it'd work to just specify ifelse() twice:
plot(pos,cn, col= ifelse(cn >= 3, "red", ifelse(cn <= 1,"blue", "black")), ylim = c(0, 10))

A: Here is a method using a lookup table of thresholds and associated colours to map the colours to the variable of interest.
 # make a grid 'Grd' of points and number points for side of square 'GrdD'
Grd <- expand.grid(seq(0.5,400.5,10),seq(0.5,400.5,10))
GrdD <- length(unique(Grd$Var1))

# Add z-values to the grid points
Grd$z <- rnorm(length(Grd$Var1), mean = 10, sd =2)

# Make a vector of thresholds 'Brks' to colour code z
Brks <- c(seq(0,18,3),Inf)

# Make a vector of labels 'Lbls' for the colour threhsolds
Lbls <- Lbls <- c('0-3','3-6','6-9','9-12','12-15','15-18','>18')

# Make a vector of colours 'Clrs' for to match each range
Clrs <- c("grey50","dodgerblue","forestgreen","orange","red","purple","magenta")

# Make up lookup dataframe 'LkUp' of the lables and colours
LkUp <- data.frame(cbind(Lbls,Clrs),stringsAsFactors = FALSE)

# Add a new variable 'Lbls' the grid dataframe mapping the labels based on z-value
Grd$Lbls <- as.character(cut(Grd$z, breaks = Brks, labels = Lbls))

# Add a new variable 'Clrs' to the grid dataframe based on the Lbls field in the grid and lookup table
Grd <- merge(Grd,LkUp, by.x = 'Lbls')

# Plot the grid using the 'Clrs' field for the colour of each point
plot(Grd$Var1,
     Grd$Var2,
     xlim = c(0,400),
     ylim = c(0,400),
     cex = 1.0,
     col = Grd$Clrs,
     pch = 20,
     xlab = 'mX',
     ylab = 'mY',
     main = 'My Grid',
     axes = FALSE,
     labels = FALSE,
     las = 1
)

axis(1,seq(0,400,100))
axis(2,seq(0,400,100),las = 1)
box(col = 'black')

legend("topleft", legend = Lbls, fill = Clrs, title = 'Z')


text:
Q: Get values from xml nodes within sql statement -- with string to xml manipulation I have string data with xml format in "Input" column from which I need specific values of nodes.
As an example:
I need every "error_text_1" value from each "error id".
{
 "xml" : "<?xml version='1.0'?>

 <error_protokoll xmlns:SOAP-ENV.....>

 <header>
 <source>machine</source>
 </header>

 <error_list>

 <error id='0'>
 <error_text_1>error0</error_text_1>
 </error>

 <error id='1'>
 <error_text_1>error1</error_text_1>
 </error>

 </error_list>

 </error_protokoll>"
}

The following sql statement returns only the "error_text_1" value of id=0.
SELECT top (10)

XML_INPUT.value('(error_protokoll/error_list/error/error_text_1)[1]', 'varchar(200)') error

FROM
(
 convert(xml, SUBSTRING( REPLACE(INPUT, '{
 "xml" : "<?xml version=''1.0''?>', ''), 0 , len(REPLACE(INPUT, '{
 "xml" : "<?xml version=''1.0''?>', ''))-3)) as XML_INPUT

  FROM  [Storage].[ods].[table]

) a

Please, see that I need to process first the "Input" column value to remove the "{}" brackets and the "xml" : ...xml version=''1.0..." part to have a correct xml structure.
This was the workaround to be able to get node value out of it.
Instead of only the first item, I'd like to have all of them.
Could you please help how to solve this?

A: I modified your xml syntax. I think he had a little problem. The following query fetches your information.
DECLARE @XML XML = '<?xml version="1.0"?>
<error_protokoll>
 <header>
 <source>machine</source>
 </header>
 <error_list>
   <error id="0">
      <error_text_1>error0</error_text_1>
   </error>
   <error id="1">
     <error_text_1>error1</error_text_1>
   </error>
 </error_list>
</error_protokoll>';

SELECT
      B.rec.value('(@id)[1]','int') AS id,
      B.rec.value('(error_text_1/text())[1]','nvarchar(100)') AS error_text_1
FROM @XML.nodes('/error_protokoll/error_list') A(evnt)
OUTER APPLY A.evnt.nodes('error') B(rec)

Demo in db<>fiddle
Or If you want to read the data from the table column
SELECT
      B.rec.value('(@id)[1]','int') AS id,
      B.rec.value('(error_text_1/text())[1]','nvarchar(100)') AS error_text_1

FROM tb
OUTER APPLY tb.xmlRec.nodes('/error_protokoll/error_list') A(evnt)
OUTER APPLY A.evnt.nodes('error') B(rec)

Demo in fiddle


text:
Q: Battery internal resistance calculation I am trying to figure out a simple, DC based way of approximating the internal resistance of the battery. I am familiar with the concept of instantaneous measurement, like here:
https://retrotechlab.com/how-to-measure-the-internal-resistance-of-a-battery/
But the problem with that is that this method does not specify the time after which the measurement has be taken after applying load. This makes me believe there should be a continuous method, in which we sample the voltage with load with time and draw a curve that would somehow help to estimate the resistance.
How can this be achieved?

A: That internal resistance reading was obtained "at this moment." If you want the internal resistance "at any moment," then you need to repeat the same steps "at any moment." There is no other way to go about it or any short cut.


text:
Q: Call external API until request is marked as complete I have following situation.
I have a service which runs jobs on a remote service and exposes API for calling the same.
I have an array of jobs which needs to be executed on remote server and it works fine, when used Promises.
The flow is as below
Inside main function I get a token. On .then() of the same, I initiate my for loop for jobs and pass the JobID and token. This second function returns me the execution_ID of each job. On the .then() of this second function I pass token and execution_id. This returns me the status of the job.
My problem is; when a job is executed, it send me queued, initiated and completed as status. When the status turns to 'completed' I get results of the job; which I need to display.
I tried using a setTimeOut() inside the last function, but I'm not sure when it will end as each job may take different time.
Is there a way I can call this third function multiple time unless the status changes to 'completed'?
Below is the code
app.get('/ExecuteJobs', function (req, res) {
var commandArraay = ["job1", "job2"]
var sTokenID;
getAuthToken()
    .then(function (token) {
        commandArraay.forEach(function (element) {
            getExecutionID(token, element)
                .then(function (executionResult) {
                    setTimeout(() => {
                        getExecutionResult(token, executionResult.id, executionResult)
                            .then(function (updateArray) {
                                console.log("Final Status " + "ID: " + executionResult.id + " Status: " + executionResult.status);
                                // if(executionResult.)
                            })
                    }, 10000)

                })
        })

    })
res.send('Done');
});

// Function to get the auth token
async function getAuthToken(token) {
    return new Promise(function (resolve, reject) {
        process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;
        var pUserID = 'uname'
        var pPwd = 'pwd'
        performhttpsRequest('/<remote_api>/tokens', 'POST', {
            sAuth: "Basic " + new Buffer(pUserID + ":" +    pPwd).toString("base64")
    }, "0", token,
        function (data1) {
            sTokenID = data1.token;
            resolve(sTokenID);
        })
})
}
// Function to post the command and get execution ID
async function getExecutionID(tokenID, command, executionID) {
    return new Promise(function (resolve, reject) {
        performhttpsRequest('/<remote_api>/executecommand', 'POST', {
        command: command
    }, "1", tokenID,
        function (data1) {
            var executionID = data1.execution_id;
            resolve(executionID);
        })
})
}
// Function to get the execution results for an ID
async function getExecutionResult(tokenID, executionID, result) {
return new Promise(function (resolve, reject) {
    performhttpsRequest('/<remote_api>/execution_result/' + executionID, 'GET', {

    }, "1", tokenID,
        function (result) {
            resolve(result.result);
        })
})

}

A: If you absolutely need a result after the enqueued job is settled, then I don't see how you can have any other choice other than retrying to check the status every n-seconds.
Here's how I would do it. A recursive function that retries a request n-times, each time waiting n-seconds:

// Mock request, resolves { status: 'completed' } 20% of the time.
const request = () => {
  return new Promise(resolve => {
    Math.random() < 0.2
      ? resolve({ status: 'completed', foo: 'bar' })
      : resolve({ status: 'pending' })
  })
}

const retryToCompletion = async ({ wait, retries }) => {
  console.log('Retries left:', retries)

  const result = await new Promise((resolve, reject) => {
    setTimeout(() => request().then(resolve).catch(reject), wait)
  })

  if (result.status === 'completed')
    return result

  if (retries)
    return retryToCompletion({ wait, retries: --retries })

  throw new Error('Retry attempts exhausted')
}

retryToCompletion({ wait: 1000, retries: 5 })
  .then(console.log)
  .catch(console.error)

That being said, some API's that work with BASE queues offer a handle to a WebSocket connection that notifies when a job is completed. If the API offers that, then you should ditch retrying and use the completed notification instead.

A: making GET calls until completion
/**
 * cbk be called when..complete execution ok
 */
function completeExecution(tokenID, executionID, result, callPeriod, cbk){
    return getExecutionResult(tokenID, executionID, result).then(res=>{

        if(res.completed){
            return cbk(null, res)
        }

        setTimeout(function(){
            return completeExecution(cbk); //reenqueue
        }, callPeriod)
    }).catch(cbk) //up to you to abort or insist
}

Then you can promisify completeExecution (with util.promisify or by yourself)


text:
Q: TextBox values are not updated from external method? I have a simple GUI with 6 textboxes.
I have a method that takes 7 parameters, 1 being a long string and the other 6 being the textboxes.  The method looks like this:
SetTextBoxesFromTokens(string s, string a, string b, string c, string d, string e, string f)
{
string[] tokens = s.Split('-');

a = tokens[0];
b = tokens[1];
c = tokens[2];
d = tokens[3];
e = tokens[4];
f = tokens[5];
}

I am calling the above method like so, but it is not updating the text boxes:
SetTextBoxesFromTokens("1-2-3-4-5-6",
        txtA.Text,txtB.Text,txtC.Text,txtD.Text,txtE.Text,txtF.Text);

A: The values are passed by value i.e. parameter passing of value types i.e a new variable is created for parameter and text of textbox is copied to it. Change of value of parameter is not supposed to be reflected in text boxes. If you want to change the value of textboxes in the function the pass the TextBoxes objects instead of Text.
SetTextBoxesFromTokens(string s, TextBox txta, TextBox txtb, TextBox txtc, TextBox txtd, TextBox txte, TextBox txtf)
{
  string[] tokens = s.Split('-');

  txta.Text = tokens[0];
  txtb.Text  = tokens[1];
  txtc.Text  = tokens[2];
  txtd.Text  = tokens[3];
  txte.Text  = tokens[4];
  txtf.Text  = tokens[5];
}

A: When calling your method, a copy of the string is created.  This means that you're not assigning your array of tokens to the .Text property of the respective TextBox controls.  You're just assigning values to things that'll fall out of scope at the end of the block.
You will be far better served with a more appropriate data structure for your requirement.
Consider instead:-
SetTextBoxesFromTokens(Dictionary<string,TextBox> tokenDict)
{
  tokenDict
    .Keys
    .ToList()
    .ForEach(k => tokenDict[k].Text = k);
}

Call it like so:-
// Define key value pair set containing
// token
// textbox to set
var dict = new Dictionary<string,TextBox>()
  {
    { "a", txtA },
    { "b", txtB },
    { "c", txtC },
    { "d", txtD },
    { "e", txtE },
    { "f", txtF }
  };

SetTextBoxesFromTokens(dict);

Using this approach, the Dictionary<string,TextBox> parameter ( and the TextBox objects within ) are passed by reference, and your method is no longer tied to a specific number of TextBox, or a coupled string.Split implementation which breaks if there aren't enough tokens.


text:
Q: top navbar on android kendoui mobile app I'm writing a KendoUI Mobile app for Android.
I add these style rules to put the navbar at the top of the screen.
/* visulaizza il titolo nella navbar */
.km-android .km-navbar .km-view-title {
    visibility: visible;
}

/* navbar in alto */
.km-android .km-view {
    -webkit-flex-direction: column;
}

Those work well when all run in browser preview but, after the app was build, on the device the navbar appears at the bottom.
Can someone help me?
Thanks!

A: Where do you place these CSS rules? Seems they don't get included in the build for some reason.

A: Your rule are incomplete. Use that:
.km-root .km-android .km-view {
    -webkit-box-direction: normal;
    -webkit-flex-direction: column;
}

You can watch other style tricks from this link
http://docs.kendoui.com/getting-started/mobile/application


text:
Q: A zmq subscriber unable to subscribe to the published messages if socket.send() was used only once A zmq subscriber fails to subscribe to the message if socket.send() is used only once in publisher.
Subscriber was able to subscribe to the messages when the following code is used in publisher:
var zmq = require('zmq')
  , sock = zmq.socket('pub')

sock.bindSync('tcp://127.0.0.1:3000');
var message = {"test" : true};
setInterval(function(){
    sock.send(['notify_anomaly', JSON.stringify(message)]);
},1000);

But it doesn't work if setInterval is removed in the publisher code, as follows:
var zmq = require('zmq')
  , sock = zmq.socket('pub')

sock.bindSync('tcp://127.0.0.1:3000');
var message = {"test" : true};
sock.send(['notify_anomaly', JSON.stringify(message)]);

A: This is a result of the "slow joiner" problem.
Here is a quote from the guide:

There is one more important thing to know about PUB-SUB sockets: you
  do not know precisely when a subscriber starts to get messages. Even
  if you start a subscriber, wait a while, and then start the publisher,
  the subscriber will always miss the first messages that the publisher
  sends. This is because as the subscriber connects to the publisher
  (something that takes a small but non-zero time), the publisher may
  already be sending messages out.

Basically, when the publisher runs, it has a handshake with the subscribers. Since that is asynchronous, the publisher may finish sending the messages before the handshake is complete. In that case the subscribers will miss the messages. To get the subscriber to get the first message, the publisher needs to wait to send until it is sure the subscriber is connected.
Here is a further quote:

In Chapter 2 - Sockets and Patterns we'll explain how to synchronize a
  publisher and subscribers so that you don't start to publish data
  until the subscribers really are connected and ready.

It shows how you can use another socket pair using REQ-REP to signal when the subscriber is ready to receive on the subscibe socket here.

A: Well, not exactly, Sir.
Historically, ZeroMQ used a SUB-side subscription ( topic-filtering ). That means two things. PUB-lisher has zero knowledge of who SUB'ed to what & spends Zero-effort on topic-filter processing. Plus, it pours and has to do so, all messages onto all diverse transport-class channels down the road, towards ( only down-there topic-filtering ) SUB-scribers ( which principally creates some level of inefficiency on the transport-layers resources ).
So, if your code uses "old" ZeroMQ wrapper / language-binding, your "PUB-lisher" is out of question not the root-cause of the problem, as it by-design does not care about any, including "late-SUBscriber", counterparties. The time-delay helps ( not the PUB.send(), but the
// unknown SUB code, a default SUB-state is TOPIC-FILTER throws everything, YES !
//                                                       THROWS EVERYTHING AWAY
SUB.setsockopt( zmq.SUBSCRIBE,
                "<some_TOPIC_FILTER_string_to_be_used_after_this_happens_in_time"
                );

So this has nothing to do with the code per-se on the PUB side, Q.E.D., but designers have to bear the timing-coincidences in mind, if designing robust app-architectures.
Next, the newer ZeroMQ versions have switched to PUB-side filtering. This seems as a major change, but it does not have any great implications into your example.
PUB-side filtering has just removed the transport-layer congestions by centralised topic-filtering on the PUB-side, at a cost of sum-of-(so-far-cheap-'cause-distributed)-workloads, that now reside, concentrated, on the PUB-side.
So, your observation still shows not receiving any message on SUB-side, so why going into such details? Well, now, in the case of the newer version, if the SUB did not manage to "tell & deliver" it's SUB-scription preferences to the PUB-side, before that one had already dispatched the PUB.send( aFirstMESSAGE_to_Those_whom_I_know_they_SUBed_to_this_TOPICFILTER )
there would be no music down the road at all, again, due to timing-coincidence of the distributed system events' propagation & delivery in time and not due to a PUB-side ( only ) code tweaking.
Epilogue:
In either case, ZeroMQ is a broker-less messaging framework. That means, persistence of messages is not even intended to create, nor provided. Each of the Scaleable Formal Communication Pattern's behavioural archetype node has clearly specified in API-documentation, buffer-management and message-{ retain | discard } and other rules. Be sure to check also the different versions of ZeroMQ low-level protocol, that is being used on all nodes of your distributed system realm ( typically one cannot control that, but may design version-aware behavioral policy enforcements to handle this sort of production ecosystem uncertainties ).
TheBestNextStep:

If one strives to remain some time in an area of a professional design of distributed systems, the best thing one can do is to read the fabulous book from one of the ZeroMQ fathers, Pieter HINTJENS ( may check other post on ZeroMQ and follow the direct link to the book's PDF-version ).


text:
Q: Prolog: Downcase all atoms in a list I'm trying to write a Prolog program that needs to take a user's natural language input and match it against a set of atoms.  I'm using SWI Prolog's readln/1 to get input and put it in a list of atoms, but I don't have any guarantee of the case of the user input, so I want to just downcase all of the input I get before I try matching.  What I have right now is:
downcase_list(AnyCase, LowerCase) :- dcl(AnyCase, X), flatten(X,LowerCase).

dcl([], List) :- List.
dcl([Head|Rest], []) :- downcase_atom(Head,X), dcl(Rest,X).
dcl([Head|Rest], List) :- downcase_atom(Head,X), dcl(Rest, [List|X]).

Appending using [List|X] seems to be my problem, but I don't know how to fix it, since I've already tried using append/3 and just got an infinite loop:
downcase_list([], List) :- List.
downcase_list([Head|Rest], []) :- downcase_atom(Head,X), downcase_list(Rest, X).
downcase_list([Head|Rest], NewList) :- downcase_atom(Head,X), append(NewList,X,Z), writeln(Z), downcase_list(Rest,Z).

I am very new to Prolog (I would classify myself as a Lisp programmer at this point), so it's very possible I'm missing something elementary.  Help?

A: If you already have a list of atoms, to downcase them you have to apply a mapping with maplist/3 and downcase_atom/2:
downcase_list(AnyCaseList, DownCaseList):-
  maplist(downcase_atom, AnyCaseList, DownCaseList).


text:
Q: Can I read a csv file inside of a Mongo Shell Javascript file? Basically I have a file of strings and I need to query against mongo to see if they exist in our database.
So I need to loop through a file and query mongo with a find query using the string from the file and then look at the results and increment some counters I have.
I am trying to do this using a shell script and calling mongo using --eval option but it's running slow.  It's been over an hour and hasn't finished a 120,000 queries.   I am thinking it would be faster if I could do it in a javascript file so it doesn't have to make the connection for each query.
Thanks for any suggestions!
Karen

A: Better option would be to use the native shell method cat().
Lets say, your file has following content and situated at /home/desktop/myfile.txt
row1
row2
row3
row4

Following code will let you get the file content as array in string var:
$> var string = cat('home/desktop/myfile.txt');
$> string = string.split('\n');
$> db.records.find({field: {$in: string}});

A: For bulk imports like this, you're usually better off with mongoimport. You may have to munge the CSV file to meet the requirements, but it will perform the final database operation over a single connection.


text:
Q: extract header info from a get request on a remote URL in asp.net? I want to perform a get request on a remote URL and then extract the headers returned.
Thanks for any help!

A: As MSDN Documentation
If you make any request, POST or GET like:
// Creates an HttpWebRequest for the specified URL.
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);

You will be getting always a Response object like:
// Sends the HttpWebRequest and waits for response.
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

And you can get all the headers with:
myHttpWebResponse.Headers

And iterate through them like:
for(int i=0; i < myHttpWebResponse.Headers.Count; ++i)
    Console.WriteLine("\nHeader Name:{0}, Value:1}",myHttpWebResponse.Headers.Keys[i],myHttpWebResponse.Headers[i]);


text: Q: Dual-boot 2 OS in different HDDs on the same PC I have a PC with Windows 10 Pre-installed. I want to install Ubuntu on a differnt drive, but I want to still be able to boot on both on startup. Can someone explain me how to do it? Thanks in advance!!


text:
Q: Subclassing UIControls for iPhone By which methods can UIControl properties be extended?

A: This should help things get rolling:
https://developer.apple.com/documentation/uikit/uicontrol#1968627

Override the sendAction(_:to:for:) method of an existing subclass to observe or modify the dispatching of action methods to the control's associated targets
Override the beginTracking(_:with:), continueTracking(_:with:), endTracking(_:with:), and cancelTracking(with:) methods to track touch events occurring in the control.


text:
Q: Lock orientation of a UIViewController on iOS 8 My app uses a view controller that should be locked into landscape mode. It works perfectly in iOS 6 and 7 but not in iOS 8. I was wondering if anyone heard or read anything about this not working anymore in iOS 8.
My code is calling - (NSUInteger)supportedInterfaceOrientations just fine but ignores the value returned and doesn't transition from portrait to landscape.
My code:
- (BOOL)shouldAutorotate {
    return YES;
}

- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskLandscape;
}


text:
Q: Is it possible to upload a image into server folder without using any severside scripting language Actually i wants to upload a image file into server folder using jquery/javascript and without using any severside scripting. is it possible? pls guide me

A: The absolute answer to that question is no.
A bit about those different sides: the client side languages (html, css, javascript) are all languages that gets executes by your browser. Meaning - on your own computer. You can't perform any operation on somebody else's with them. (accept sending and receiving certain requests).
The server side languages gets executed, not surprisingly, on the server computer! This means that they can execute code to do some operations on the server computer, like for example, save or change files.
This is why client side languages were not designed to do anything on the server, only send various requests (maybe to a server side script that will receive a file and save it locally on the server).
Another important point is security. Just think of the fact that client side scripts are completely exposed to the user. This means that if you could, by that alone, save files to your server from your website, i could copy your code to my own website and that way to save myself some files on your server without you even knowing.


text:
Q: Images slideshow with fade animation I am writing a theater mode section in music player. The requirements is to loop through a folder containing images of any type(png, jpeg, gif) and show in a picture box with 5 seconds delay for images of type (png,jpeg) and delay time for gif should be the actual gif time duration. Also there should be fade transition between images when switch from one image to another in a single picture box. All need to be done when software is idle lets say for 60 seconds
Problem

Currently the playing song directory has 'img' folder containing 3 png
images and 3 gif.   The first attempt to read
Helper.theaterImagesInfo.ToList() works pretty well

foreach (var img in Helper.theaterImagesInfo.ToList())

It starts to display 3 png images with 5 seconds delay and gif images
with the actual gif duration delay. but if i click picturebox to close theaterform as soon as the form is opened again after 60 seconds of idle state of software and loop continue
to iterate again. The default image is shown with
starting 2 png images from 'img' folder the 3rd png is skipped and then 4th gif starts
to play for few seconds not the actual gif duration and continued in wrong order as well as incorrect delay, Seems like while loop is always running in background. therfore it becomes choppy.

Desired Solution
Whenever i play song theaterform should be displayed and start to show images from folder ( in the same sequence and delay) even if the theaterform is opened again after 60 seconds if the song is still playing. Also if there is a way to show fade when changing image in a single picturebox
Code here
Program.cs
internal static class Program
{
  public static Timer IdleTimer = new Timer();
  readonly static int miliseconds =
  Convert.ToInt32(TimeSpan.FromSeconds(60).TotalMilliseconds);
  internal static MainForm f = null;
  static public TheaterForm tf;

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        MessageFilter limf = new MessageFilter();
        Application.AddMessageFilter(limf);
        Application.Idle += new EventHandler(Application_Idle);
        IdleTimer.Interval = miliseconds;
        IdleTimer.Tick += TimeDone;
        IdleTimer.Start();
        f = new MainForm();
        tf = new TheaterForm();
        var app = new MyApplication();
        app.Run(Environment.GetCommandLineArgs());
        Application.Idle -= new EventHandler(Application_Idle);
    }

    static private void Application_Idle(Object sender, EventArgs e)
    {
        if (!IdleTimer.Enabled)     // not yet idling?
            IdleTimer.Start();
    }

    static private void TimeDone(object sender, EventArgs e)
    {
        IdleTimer.Stop();

        if (MainForm.waveOut.PlaybackState == PlaybackState.Playing)
        {
            if (!Helper.IsTheaterOpen)
            {
                if (Form.ActiveForm == f)
                {
                   Helper.IsTheaterOpen = true;
                   tf.WindowState = FormWindowState.Maximized;
                   tf.Bounds = Screen.PrimaryScreen.Bounds;
                   tf.x = 1;
                   tf.ShowDialog(f);
                }
            }

        }
        else
        {
            if (!Helper.IsTheaterOpen)
            {
                if (Form.ActiveForm == f)
                {
                    Helper.IsTheaterOpen = true;
                    tf.WindowState = FormWindowState.Maximized;
                    tf.Bounds = Screen.PrimaryScreen.Bounds;
                    tf.x = 0;
                    tf.ShowDialog(f);
                 }
             }
         }
    }
}

public class MyApplication : WindowsFormsApplicationBase
{
    protected override void OnCreateMainForm()
    {
        MainForm = Program.f;
    }
    protected override void OnCreateSplashScreen()
    {
        SplashScreen = new SplashForm();
    }
}

Helper.cs
 internal class Helper
 {
     public static bool IsTheaterOpen { get; set; }

     public struct ImageInfo
     {
        public bool IsAnimated;
        public int durationInMilliseconds;
        public Image ImageHere;
     }

     public static List<ImageInfo> theaterImagesInfo = new List<ImageInfo>(10);
  }

MainForm.cs
/*
 * Every song directory has one folder named img that contains images and gif relevant
   to the song album
*/

  private int GetGifDuration(Image img)
  {
     int delay = 0, this_delay = 0, index = 0;
     FrameDimension frameDimension = new FrameDimension(img.FrameDimensionsList[0]);

     int frameCount = img.GetFrameCount(frameDimension);

     for (int f = 0; f < frameCount; f++)
     {
       this_delay = BitConverter.ToInt32(img.GetPropertyItem(20736).Value, index) * 10;

       delay += (this_delay < 100 ? 100 : this_delay);  // Minimum delay is 100 ms

       index += 4;
      }

     return delay;
   }

private void PlayAudio()
{

    // Getting images from folder and storing in struct on every song play
     if (Directory.Exists(Path.GetDirectoryName(CurrentPlayingMusicUrl) + "\\img"))
     {
        var files =
        Directory.EnumerateFiles(Path.GetDirectoryName(CurrentPlayingMusicUrl) +
        "\\img", "*", SearchOption.AllDirectories).Where(s => s.EndsWith(".png") ||
        s.EndsWith(".jpg") || s.EndsWith(".jpeg") || s.EndsWith(".gif"));

         Helper.theaterImagesInfo.Clear();
         foreach (var imagePath in files.ToArray())
         {
           using (System.Drawing.Image image = System.Drawing.Image.FromFile(imagePath))
           {
              if (image.RawFormat.Equals(ImageFormat.Gif))
              {
                  Helper.theaterImagesInfo.Add(new Helper.ImageInfo { IsAnimated = true, durationInMilliseconds = GetGifDuration(image), ImageHere = Image.FromFile(imagePath) });
              }
              else
              {
                  Helper.theaterImagesInfo.Add(new Helper.ImageInfo { IsAnimated = false, durationInMilliseconds = 5000, ImageHere = Image.FromFile(imagePath) });
              }
            }

          }
       }
       else
       {
           Helper.theaterImagesInfo.Clear();
           Program.tf.x = 0;
       }
}

TheaterForm.cs
public partial class TheaterForm : Form
{
    public TheaterForm()
    {
        InitializeComponent();
        SetDefaultImage();
    }

   /*
    * Getting Default image from top(root) directory ex. AllMusic. If no 'img' folder
      found in song album directory ex. AllMusic -> Justin Bieber -> (img folder not
      exist)song1, song2, song3 etc.
   */
    private async void SetDefaultImage()
    {
        string path = KJ_Player.Properties.Settings.Default["MusicFolder"] + "\\img";
        if (Directory.Exists(path))
        {
            var files = Directory.EnumerateFiles(path, "*",
            SearchOption.AllDirectories).Where(s => s.EndsWith(".png") ||
            s.EndsWith(".jpg") || s.EndsWith(".jpeg"));
            await Task.Run(() =>
            {
                if(files != null && files.Count()>0)
                {
                    PictureBox1.Image =  Image.FromFile(files.FirstOrDefault());
                }
            });
         }
     }

    public int x=1;
    private async void TheaterForm_Shown(object sender, EventArgs e)
    {
        if (this.PictureBox1.Image == null) SetDefaultImage();

        if (Helper.theaterImagesInfo != null && Helper.theaterImagesInfo.Count > 0)
        {
            while (x == 1)
            {
                foreach (var img in Helper.theaterImagesInfo.ToList())
                {
                    if (img.IsAnimated)
                    {
                        try
                        {
                            this.PictureBox1.Image = img.ImageHere;
                            await Task.Delay(img.durationInMilliseconds);
                        }
                        catch { }
                    }
                    else
                    {
                        try
                        {
                            await Task.Delay(img.durationInMilliseconds);
                            this.PictureBox1.Image = img.ImageHere;
                        }
                        catch { }
                    }
                }
            }

            SetDefaultImage();
        }
    }

    private void PictureBoxTheater_Click(object sender, EventArgs e)
    {
        this.x = 0;
        if (this.PictureBox1.Image != null) this.PictureBox1.Image=null;
        Helper.IsTheaterOpen = false;
        this.Close();
    }

}

A: Most likely you just need to break out of that foreach loop:
foreach (var img in Helper.theaterImagesInfo.ToList())
{
    if (img.IsAnimated)
    {
        try
        {
            this.PictureBox1.Image = img.ImageHere;
            await Task.Delay(img.durationInMilliseconds);
        }
        catch { }
    }
    else
    {
        try
        {
            await Task.Delay(img.durationInMilliseconds);
            if (this.x == 1) {
                this.PictureBox1.Image = img.ImageHere;
            }
        }
        catch { }
    }
    if (this.x == 0) {
        break; // exit the for loop early
    }
}


text:
Q: background image + media queries I am struggling with media queries right now. My project is stored here: http://colorfill.pl/clients/ratuszowa
as you see on the top there is a huge photo as one of the main top elements. What I would like to achieve is to have always image for 100%. I made a really dummy-method. Ive sliced the photo into several files (each has its own width). But the problem appear when i want to put it into media queries..
I prepared photos for such resolutions (showing right now only width of screen):
768
1024
1280
1360
1440
1600
1920
2048
2560
Just like I mention - each resolution will have own  img. I've tried with sth like that:
@media only screen and (max-width: 1024px) { }
@media only screen and (max-width: 1280px) { }
but the image display still the same - the smallest. What i am doing wrong?

A: I am sorry, I have less time to test such a thing because it has to be tested only then I can come to any conclusion, but try looking at these links in case you are using those images as a full page background and your css skills are falling short of what might be required.
1. http://css-tricks.com/perfect-full-page-background-image/
2. http://css-tricks.com/how-to-resizeable-background-image/


text:
Q: SQL Server Mirroring Removed Does anyone know how to tell when SQL Server mirroring was removed from a database? My log file is flooded with login failures but I can't find mention of removing of a mirror.
Is there any DMV way of finding this out?


text:
Q: login to sql fails when app is deployed to IIS I have a web application which calls a DLL, this DLL has a reference to another DLL which connects to an SQL Server. After doing some debugging i found out that the following error is being generated: Login failed for user 'DOMAIN\username'. This only happens when the web app is deployed to IIS, when debugging through Visual Studio everything works accordingly. Below is the connection string i'm using to connect:
string strConnectionString = "user id=" + strUsername +
                             ";password=" + strPassword +
                             ";server=" + strServer +
                             ";Trusted_Connection=false;database="
                             + strDatabaseName + ";connection timeout=30";

values are being retrieved from web.config. Any idea please?

A: Considering the error message, it appears that your application is not using the connection string provided by you at all. Instead it is using integrated windows security to log on to the database. This will work while you are on local machine and you have sql server installed locally but not on IIS as your account will not have permission to log on to sql server.
I suggest, try debugging the application and see if it is really using the connection string you supplied.
Further, you can use the connectionstring in web.config rather then providing values and re-construciting the connection string in the code.


text:
Q: unknow system variable: "new.id" is not recognized Let's say 6,7,8 are all taken, and l tried to insert data with id = 6. The purpose of the trigger is to find the next available number. However, MySQL does not recognize new.id
Or, can l alter auto_increment's value?
Why am l doing this? Because in OracleDB, the sequence generator will increment(and eventually find that available number) whereas MySQL's sequence generator won't increment if a duplicate primary key is generated somehow.
tried to replace "new.id = @valid" with "alter table wooster_brush_employee auto_increment = @valid" in trigger, but it did not work.

create table wooster_brush_employee(
    id int primary key auto_increment,
    first_name varchar(15),
    last_name varchar(20),
    username varchar(10),
    password varchar(15),
    email varchar(30)
);
delimiter //
create trigger validate_id before insert on wooster_brush_employee
    for each row
    set @old = last_insert_id();
    set @valid = last_insert_id();
    call wooster_brush_employee_id_validator(@old, @valid);
    set NEW.id = @valid;
    end;
delimiter;

A: I believe that your whole approach here is off kilter, and you don't even need to use this trigger.  The point of an auto increment column, in either MySQL or Oracle, is that the database handles the problem of finding the next available number in the sequence.  While the auto increment contract does not guarantee that the next value found will be greater than every value already in the column, it does guarantee that the next value will be unique.
So, if you want to make use of MySQL's auto increment functionality, then next time you insert, simply omit id from the column list:
INSERT INTO wooster_brush_employee (first_name, last_name, username, password, email)
VALUES
    ('Jon', 'Skeet', 'jonskeet', '*****", 'jon.skeet@google.com');

Since id was omitted, MySQL will automatically generate the next value in the sequence behind the scenes.


text:
Q: Запуск программы через sh файл Имеется программа, которая при запуске требует определенных библиотек, путь к которым устанавливается через LD_LIBRARY_PATH. Можно, конечно, вписать эту переменную в etc/profile, но я хотел бы, чтобы программа запускалась через bash скрипт, аля:
#!/bin/bash
appname="proga"

DIR="dir_with_libraries"

export LD_LIBRARY_PATH=$DIR

appname "$@"

Но тут две проблемы:
1) если я установливаю этот скрипт в директорию /usr/local/bin то не могу запустить его без sudo
2) при ноборе из командной строки нельзя автодополнить название, а в конце еще и разрешение "sh" указывать надо.


text:
Q: Java Private constructor in Junits I've a class with few constants declared, initialized and I also have a private constructor.
For some reasons I'm writing Junits to achieve the code coverage.
Here I have used constructor.setaccessible(true) and I have initialized the class.
In the assert statement I'm expecting the length of the constructor to be 1.
I've achieved 100% code coverage for this class. But I'm quite not sure how. Can anyone please throw some light on this?
public class CommonConstants {
  public static final String ABC= "ABC";
  public static final String XYZ= "XYZ";

  private CommonConstants() {}
}

@Test
public void stringTest() {
     final Constructor<?>[] constructors = CommonConstants.class.getDeclaredConstructors();
     constructors[0].setAccessible(true);
     try {
          CommonConstants cc = (CommonConstants) constructors[0].newInstance();
     } catch (InstantiationException e) {
          e.printStackTrace();
     } catch (IllegalAccessException e) {
          e.printStackTrace();
     } catch (InvocationTargetException e) {
          e.printStackTrace();
     }
     Assert.assertEquals(1, constructors.length);
  }


text:
Q: SP 2010 main area padding cut off I have custom CSS for my SP collaboration site so that it has a fixed width and it's centered.
This code does that:
#s4-bodyContainer {
    width: 950px !important;
    height: 100% !important;
    min-height:100% !important;
    margin-left:auto;
    margin-right:auto;
}

I have a grey background so I added this code to give the main area a bit of padding (so the content isn't flush against the edge of the main area)
#s4-mainarea {
    background-color: white;
    padding-left: 15px;
    padding-right: 15px;
    width: 920px !important;
    height: 100%;
}

It works great, but the height doesn't go 100%. It works for roughly 1000 pixels and then it seems like the main area just cuts off. How do I force the main area and it's padding to keep going?
Screens:

A: Well then.. I spent hours looking for the answer, decided to ask here after pulling all my hair out, and I found the answer by playing around with the CSS!
For anyone who googles this topic, rejoice for I have the answer and I'm going to actually share it!
ANSWER: Don't put padding in #s4-mainarea, put it in .s4-ca! Here's all my CSS:
#s4-bodyContainer {
width: 950px !important;
height: 100% !important;
min-height:100% !important;
margin-left:auto;
margin-right:auto; }

body #s4-ribbonrow {
background-color:#cccccc; }

body.v4master {
overflow: visible;
    background-color:#cccccc; }

.ms-cui-ribbonTopBars {
    width: 950px !important;
    margin-left:auto;
    margin-right:auto; }

.ms-cui-ribbonTopBars > div {
    border-bottom:1px solid transparent !important;
    width: 950px !important; }

body #s4-ribboncont {
padding:0px;
background: url("") repeat-x 0px -30px; }

#s4-mainarea {
background-color: white;
width: 950px !important;
height: 100%; }

#s4-leftpanel {
display: none !important;
visibility: hidden !important; }

.s4-ca {
margin-left: 0px !important;
padding-left: 15px;
padding-right: 15px; }


text:
Q: C string arrays
Possible Duplicates:
string literal in c
Assigning strings to arrays of characters

I got the following code:
char result[3][4];

result[0] = "horse";
result[1] = "pig";
result[2] = "chicken";

It won't compile saying Incompatible types in assignment. What am I doing wrong?

A: char is a single char, eg 'h'
What you want is string pointers.
 char *result[3];

Remember if you do it this way you won't be able to change the contents of an individual string (it is a constant and stored in a different place.)
You could also do something like this
 char *result[3];

 result[0] =  malloc(100 * sizeof(char));
 strcpy(result[0],"horse"); // or strncpy(result[0],5,"horse")
 etc

A: char result[3][10] = {
  "horse",
  "pig",
  "chicken",
}

or
char result[3][10];

strcpy_s(result[0], 10, "horse");
strcpy_s(result[1], 10, "pig");
strcpy_s(result[2], 10, "chicken");

A: The following works better:
char result[3][10] = {"horse", "pig", "chicken"};
Also, have in mind that "chicken" and "horse" have more that 4 characters and therefore result[3][4] (the [4] part) is not that right.

A: You probably wanted:
char* result[3];
result[0] = "horse";
result[1] = "pig";
result[2] = "chicken";

What you did was wrong for two reasons.
First, you can't "assign" a string to a char array like that, you'd have to use, for example, strcpy.
Second, your array dimension was also wrong, char array[4] obviously won't hold "horse" or "chicken", so it wouldn't work even if you corrected what I said above (it would compile, but you would be writing to memory you shouldn't be writing to).
What the corrected code does, is instead of storing the char array per se, it stores a pointer to the location in memory where "horse", etc., are stored. Therefore, it just stores an address, and you can then use the = operator.

A: Arrays are non-modifiable lvalues i.e you cannot assign to them.
You need to use array of pointers. Change char result[3][4]; to char * result[3]

A: This will not work because result declared as char result[3][4] and used as result[0] will result in something similar with: char * const result. Constant pointer doesn't admit any assignment, it already contains pointer to the array of columns "[4]".

A: You can assign a string literal (eg: "horse") to a char array only when you declare it, not after.
char array[4] = "str"; // is OK
char array2[4];
array2 = "str"; // is NOT OK.

You could do like this:
char result[3][4] = { "horse", "pig", "chicken" };

but warning: "horse" and "chicken" are longer than char[4].

If you want to assign a string literal to an already declared char array you'll have to use strcpy (or other similar functions).

The other solution, suggested by many is to declare result as an array of char pointers: char *result[3];, but if you do like this you won't be allowed to modify the content of the strings pointed by result[i].

A: You have to increase the size of the words and use strcpy():
char result[3][8];    // at least 8!

strcpy(result[0], "horse");
strcpy(result[1], "pig");
strcpy(result[2], "chicken");


text:
Q: Open a file using fgets result doesn't work I'm trying to open some files using open().
File names are stored in a temporary file (one filename in each row).
This is the code I'm using:
char strbuf[64];

while (fgets (strbuf, sizeof(strbuf), temp))
{
    printf("%s\n", strbuf);

    if((txt_fd = open(strbuf, O_RDWR | O_APPEND)) < 0)
    {
      printf("Open error!\n");
      exit(1);
    }
}

And this is the output:
Data1.txt
Open error!

The weird thing is that if i manually set the open() this way the open() works.
txt_fd = open("Data1.txt", O_RDWR | O_APPEND)

What's wrong with strbuf?
Thanks in advance.


text:
Q: Mp3 player - the "file not found" messagebox.showerror shows up every time I play a file The code below is a media player (mp3). It worked perfectly until I added the show_details() function which is supposed to show the length and timing of the song, the error message "file not found" appears when playing a file (The file does play! but the error message pops everytime). Once I take off the 3 lines consisting of 'a', 'total_length' and 'print' statements, the error stops to show up and the song of course plays normally. What is the problem with my code?
filelabel = Label(root, text="Let's make some noise!")
filelabel.pack(pady=10)

lengthlabel = Label(root, text="Total Length - 00:00")
lengthlabel.pack(pady=10)

def show_details():
    filelabel['text'] = 'Playing - ' + os.path.basename(filename)
    a = mixer.Sound(filename)
    total_length = a.get_length()
    print (total_length)

def play_music():
    global paused

    if paused:
        mixer.music.unpause()
        statusbar['text'] = 'Music Resumed: Playing ' + os.path.basename(filename)
        paused = False
    else:
        try:
            mixer.music.load(filename)
            mixer.music.play()
            statusbar['text'] = 'Playing - ' + os.path.basename(filename)
            show_details()
        except:
            tkinter.messagebox.showerror('FIle not found', 'Melody could not find the song, please check again')

A: I see you create a music and sound object at the same time. This might be a clue to your answer:
How can I play multiple sounds at the same time in pygame?
It seems that adding channels might fix your problem. But take out these three lines first to see if they are the cause:
a = mixer.Sound(filename)
total_length = a.get_length()
print (total_length)


text:
Q: billboard.js is not working in safari I have a billboard.js script running on a simple php file and for some reason it works fine in FF and IE but not Safari. I checked source code it and is pulling the content but the scrolling feature does not work when you click. Can someone please help me. Here is the link to try: www.luc.edu/test/cabplan/soc/test.php

A: it was an extra div tag


text:
Q: Getting error when attempting to remove hidden names in excel I'm trying to run a macro to clear my workbook of hidden names so when a tab is copied I don't have to hold down enter for 5 minutes because of all of the hidden names.
I looked around for some VBA code to accomplish this but am getting the error:

"Run-time error '1004': The syntax of this name isn't correct."

I assume it's running into an invalid name so it can't delete it?
Code below:
Sub Remove_Hidden_Names()

    Dim xName As Variant

    If MsgBox("Do you really want to delete all hidden names in this workbook?", vbQuestion + vbYesNoCancel, "Delete hidden names?") = vbYes Then

        For Each xName In ActiveWorkbook.Names
            If xName.Visible = False Then
                xName.Delete
            End If
        Next xName

        MsgBox "All hidden names in this workbook have been deleted.", vbInformation + vbOKOnly, "Hidden names deleted"
    End If

End Sub

A: Seems like there might be an invalid or corrupted name, the box shouldn't allow for dashe or hyphens. You could try to open the XML of the worksheet, find the invalid name and change it to a valid one.


text:
Q: Google+ Share Plugin - getting "Exception thrown and not caught" in IE, works fine in Firefox I'm just trying to add the Google+ share plugin to an application and it works fine in firefox but I get the following error in IE - "Exception thrown and not caught"
The following is the very basic code that I run on both firefox and IE, work fine in Firefox but dies in IE9:

Any help in this regard would be greatly appreciated or if you can redirect me to someone that can give me some insight would be very much appreciated.
Many thanks,
Mary O'Connor

A: The issue you're seeing is a bug. The share button is throwing an exception because your test page has no DTD.  Add this to the first line of your page:
<!DOCTYPE html>

Now your share button will work :)
I've filed this bug in the Google+ platform issue tracker. You can star it to subscribe to updates.


text:
Q: Where i have to add code to get instagram photos in home page in porto theme in magento 2 I want to display Instagram photos in my home page but problem is I don't know where I have to place code...
Could you please let me know where I have to place the code ?
Thanks in Advance.

A: First you should install Instagram Widget – Magento 2 Extension
Installation Process
Note: Please take a backup of your all Magento files and database before installing or updating any extension.
Download the extension file:

*

*Download the Instagram Widget extension .ZIP file from solwininfotech.com using your Solwin Infotech website account.

*Extract the .ZIP file which contains another .ZIP files.

*Now, you will see the extension .ZIP file for Magento 2.0.x, Magento 2.1.x,
Magento 2.2.x and Magento 2.3.x version.

Extension Installation:

*

*If you are using Magento 2.0.x then you need to extract solwin-instagram-m2-
2.0.x.zip file.
If you are using Magento 2.1.x then you need to extract solwin-instagram-m2-2.1.x.zip file.
If you are using Magento 2.2.x then you need to extract solwin-instagram-m2-
2.2.x.zip file.
If you are using Magento 2.3.x then you need to extract solwin-instagram-m2-
2.3.x.zip file.

*Copy the app folder and paste it into your magento ROOT directory.

*Run upgrade command as specified : php bin/magento setup:upgrade

*Run deploy command as specified : php bin/magento setup:static-content:deploy -f

*Clear the cache either from the admin panel or command line : php bin/magento cache:clean

*Now, you can see the Solwin menu in admin panel. Please go to Solwin -> Instagram Widget -> Configuration and select Enable to Yes.

*Change/Set all other options as per your requirements and save settings.

NOTE : Make sure the installation is done from under the FTP administrator account. Otherwise make sure to set 775 permissions to the store root directory after the extension is deployed.
Information :
Instagram Widget Magento 2 extension is an effective way to integrate Instagram with Magento 2 store. There is no any in-built feature in Magento for integration and display an Instagram feed. So, we have designed Instagram Widget Extension to equip this service on your store.
This extension will boost your products and helps you gain more customers to your store. At present, Instagram feed is a must-have for a successful online store. This will avail you to add new products by just taking photos of it. You can create gallery of your Instagram photos with a special tags.
Magento 2 Instagram Integration Extension will improve your store functionality. There is no Instagram authorization or permissions reviews are required to integrate. This is a powerful widget to take your customers to a new level.

A: Please try to use below example code.
{{block class="Smartwave\Porto\Block\Template" name="instagram" padding_item="10px" template="Smartwave_SocialFeed::instagramphotos.phtml"}}

Besides, you can config the Instagram Feed on Homepage by going to Admin Panel > Smartwave > SW EXTENSION > Social Feeds > Instagram
To get the Instagram Feed works, you need to insert the right AccessToken and UserID of your Instagram account.
Ahout how to get those info, please follow this guide.


text:
Q: How to sum tuple values outputted by an API in Python So a fairly simple problem which I'm trying to solve in the most efficient way possible.
I am querying an API which outputs a series of namedtuples, and I want to accumulate and sum the value of each outputted tuple.
i.e i'm doing something like the following:
for time_series in api_query:
    for ts_tuple in time_series.header:
        print(ts_tuple)

which would output something like:
Point(end_time='2017-07-05T12:12:24.471Z', start_time='2017-07-05T12:11:24.471Z', value=0)
Point(end_time='2017-07-05T12:13:24.471Z', start_time='2017-07-05T12:12:24.471Z', value=48)
Point(end_time='2017-07-05T12:14:24.471Z', start_time='2017-07-05T12:13:24.471Z', value=11)
Point(end_time='2017-07-05T12:15:24.471Z', start_time='2017-07-05T12:14:24.471Z', value=0)
Point(end_time='2017-07-05T11:52:24.471Z', start_time='2017-07-05T11:51:24.471Z', value=0)

I need to grab the value in each namedtuple, and sum the total.
What I've got is:
   total_foo = []

   for time_series in api_query:
        for ts_tuple in time_series.header:
            total_foo.append(ts_tuple.value)

then just call a sum on total_foo.
I was wondering whether anyone can suggest a more pythonic way? I'm trying to get away from just using for loops and appending to lists all the time.
NB: for some background the api is querying a Stackdriver metric via the google-cloud-python library.

A: You may use a generator expression with a nested loop, like this:
total = sum(ts_tuple.value for time_series in api_query for ts_tuple in time_series.header)

A: You can change your original loop to also do the sum:
total_foo = 0
for time_series in api_query:
    for ts_tuple in time_series.header:
        print(ts_tuple)
        total_foo += int(ts_tuple.value)


text:
Q: Htaccess rewriting url make slash(/) optionional I have this htaccess url rewrite.
RewriteCond %{HTTP_HOST} ^(.+?)\.mysite\.com$
RewriteRule ^/?login/?(.*)/(.*)$ /admin/index\.php?username=%1&m=$1&page=$2

These are the test cases I followed.
admin.mysite.com

admin.mysite.com/login

admin.mysite.com/login/

admin.mysite.com/login/0

admin.mysite.com/login/0/

admin.mysite.com/login/0/clients

In the above test cases, these were successful.
admin.mysite.com

admin.mysite.com/login/

admin.mysite.com/login/0/

admin.mysite.com/login/0/clients

Other URLs are displaying a 404 error. I realized "slash" is the reason for this error. How can I make it optional in my htaccess file?

A: Just separate the different cases which makes things much easier to read and therefor easier to maintain for later modifications:
RewriteEngine on

RewriteCond %{HTTP_HOST} ^(.+?)\.example\.com$
RewriteRule ^/?login/?$ /admin/index\.php?username=%1 [END]

RewriteCond %{HTTP_HOST} ^(.+?)\.example\.com$
RewriteRule ^/?login/(.*)/?$ /admin/index\.php?username=%1&m=$1 [END]

RewriteCond %{HTTP_HOST} ^(.+?)\.example\.com$
RewriteRule ^/?login/(.*)/(.*)/?$ /admin/index\.php?username=%1&m=$1&page=$2 [END]

In case you receive an internal server error (http status 500) using the rule above then chances are that you operate a very old version of the apache http server. You will see a definite hint to an unsupported [END] flag in your http servers error log file in that case. You can either try to upgrade or use the older [L] flag, it probably will work the same in this situation, though that depends a bit on your setup.
This implementation will work likewise in the http servers host configuration or inside a distributed configuration file (".htaccess" file). Obviously the rewriting module needs to be loaded inside the http server and enabled in the http host. In case you use a distributed configuration file you need to take care that it's interpretation is enabled at all in the host configuration and that it is located in the host's DOCUMENT_ROOT folder.
And a general remark: you should always prefer to place such rules in the http servers host configuration instead of using distributed configuration files (".htaccess"). Those distributed configuration files add complexity, are often a cause of unexpected behavior, hard to debug and they really slow down the http server. They are only provided as a last option for situations where you do not have access to the real http servers host configuration (read: really cheap service providers) or for applications insisting on writing their own rules (which is an obvious security nightmare).


text:
Q: How to make some pandas column values default to another value in a different column, but same row? I have a sample DataFrame that looks like this:
 ID        Product    UPC    Units Sold
 no link   cereal    3463    12
 2211      cereal    2211    13
 2211      cereal    8900    11
 2211      cereal    6754    14
 no link   cereal    9012    13
 3340      cereal    3340    12
 3340      cereal    5436    15

The 'ID' column identifies similar products into one product family ID. The ID is created by the first UPC number of that family. 'No link' identifies products that are the only member of their family. What I want is set the 'no link' values to default to the UPC number.
This is what I want my output to look like:
 ID        Product    UPC    Units Sold
 3463      cereal    3463    12
 2211      cereal    2211    13
 2211      cereal    8900    11
 2211      cereal    6754    14
 9012      cereal    9012    13
 3340      cereal    3340    12
 3340      cereal    5436    15

This is what I have so far:
 for row in product_families:
     if product_families.loc['Product Family Number'] == 'no link':

A: Use loc with boolean indexing and let Pandas assign with intrinsic data alignment:
df.loc[df.ID.eq('no link'),'ID'] = df.UPC

Output:
     ID Product   UPC  Units Sold
0  3463  cereal  3463          12
1  2211  cereal  2211          13
2  2211  cereal  8900          11
3  2211  cereal  6754          14
4  9012  cereal  9012          13
5  3340  cereal  3340          12
6  3340  cereal  5436          15

A: Scott Boston's solution should work.
Maybe worth trying a different approach using apply row wise.
df['ID']=df.apply(lambda x: x.UPC if x.ID=='no link' else x.ID, axis=1)