text:
Q: Merge several Series with different indexes, summing over duplicated indexes Suppose I have three Series
s1 = pd.Series(data=np.arange(5))
s2 = pd.Series(data=np.arange(5),index=np.arange(2,7))
s3 = pd.Series(data=np.arange(5),index=np.arange(5,10))

Which is the most efficient method to merge them into a series which sums data values in duplicated indexes, and keeps values in non-duplicated indexes. In other words, for s1, s2, s3 we would expect the output:
0    0
1    1
2    2
3    4
4    6
5    3
6    5
7    2
8    3
9    4

In reality we could have a large number of series with a large number of data entries so looping is not efficient.

A: Let's use concat and sum here:
pd.concat([s1, s2, s3]).sum(level=0)

0    0
1    1
2    2
3    4
4    6
5    3
6    5
7    2
8    3
9    4
dtype: int64

Concatenation is an O(n) operation (linear complexity), recommended 99% of the time.

If you like method chaining, this one's for you.
s1.append(s2).append(s3).sum(level=0)

0    0
1    1
2    2
3    4
4    6
5    3
6    5
7    2
8    3
9    4
dtype: int64

Not recommended for more than 3 series. Appending two at a time turns out to be quadratic in complexity.

A: Here's one with NumPy tools -
def sum_series(L): # L is list of series
    aL = [list(l.index) for l in L]
    intL,unqL = pd.factorize(np.concatenate(aL))
    sums = np.bincount(intL,np.concatenate(L))
    return pd.Series(sums, index=unqL)

Sample run -
In [158]: L = [s1,s2,s3] # list of series

In [159]: sum_series(L)
Out[159]:
0    0.0
1    1.0
2    2.0
3    4.0
4    6.0
5    3.0
6    5.0
7    2.0
8    3.0
9    4.0
dtype: float64

With generic labels -
In [170]: L
Out[170]:
[Label0    0
 Label1    1
 Label2    2
 Label3    3
 Label4    4
 dtype: int64, Label2    0
 Label3    1
 Label4    2
 Label5    3
 Label6    4
 dtype: int64, Label5    0
 Label6    1
 Label7    2
 Label8    3
 Label9    4
 dtype: int64]

In [171]: sum_series(L)
Out[171]:
Label0    0.0
Label1    1.0
Label2    2.0
Label3    4.0
Label4    6.0
Label5    3.0
Label6    5.0
Label7    2.0
Label8    3.0
Label9    4.0
dtype: float64

Version #2
Using a concatenation on the array data and employing smart output dtype, probably a more desirable output could be obtained with something like this -
def sum_series_v2(L): # L is list of series
    aL = [list(l.index) for l in L]
    v = [l.values for l in L]
    intL,unqL = pd.factorize(np.concatenate(aL))
    sums = np.bincount(intL,np.concatenate(v))
    dtype = np.result_type(*[l.dtype for l in L])
    return pd.Series(sums.astype(dtype), index=unqL)

Sample run -
In [225]: sum_series_v2(L)
Out[225]:
Label0    0
Label1    1
Label2    2
Label3    4
Label4    6
Label5    3
Label6    5
Label7    2
Label8    3
Label9    4
dtype: int64


text:
Q: Center of gravity of the photon beam I have a conceptual question:
In singular optics the orbital angular momentum (OAM) is represented by two components: intrinsic (no relation to spin!) and extrinsic. The first one is associated to optical vortex structure of the beam. The second one - to the trajectory of motion of the center of gravity of the light beam.
So, how can we define a center of gravity of a beam if photons are massless? Any suggestions/guesses/ideas/links are appreciated. Thanks!

A: Okay, so:

Unfortunately, the word "mass" has been used in two different ways in physics. One was the way Einstein used it in E=mc^2, where mass is really just the same thing as energy (E) but measured in different units. This is the same "m" that you multiply velocity by to find momentum (p), and thus is sometimes called the inertial mass. It's also the mass that provides the source of gravitational effects. Light has this "m" because it has energy.

So basically, light has energy, which is really the same thing as mass according to Einstein's E=mc^2, and it is this that you use to calculate momentum.
There is a fuller explanation at https://van.physics.illinois.edu/qa/listing.php?id=1424 (where I got the quote).
Good question, and I hope this explanation helps!

redpajama_set_name: RedPajamaStackExchange


text:
Q: MIME/IMF error codes? I need to write php code to identify common e-mail errors, like "inbox full" or specially "invalid email name" from email messages, because we need to clear our databases from nonexistent emails.
I'm looking the MIME and IMF formats but I didn't find any kind of standard error code, does it exist?

A: This may help:
http://www.unixhub.com/docs/email/SMTPcodes.html
There are a lot of RFCs for email, and error codes.
The one you specified may be (550)


text:
Q: Importing QoH in Odoo 8 Documentation for the new version of Odoo (OpenERP) is nearly non-existent.  Apparently, the process for importing Quantity on Hand for products has changed, and I can't find anything that describes the new method. Anyone know how to import current stock levels into Odoo 8? In version 7, you created an inventory count record, then imported all your product quantities using the reference field from the manually created count record. This doesn't seem to work in v8.

A: It's finally solved,  simply follow the step
Step – 1 ;
1->   select product in warehouse module  (open in list view).
2->  select the product which you want to update the inventory  .
3-> click on more button and export  column
i-> product name and any other one if you needed .
you have file with name of product.temlate.csv .
4-> Add a column qty and enter the quantity of product .
Step – 2;
1-> select inventory adjustment in warehouse module  .
2-> if you already have any created inventory then  go to 3rd point if not then create a inventory and feel the detail . and select all product option in Inventory of - :
3-> now again click on inventory adjustment and select the inventory.
4-> click on more and export the following column
Inventories/location
Inventories/product
Invevtories/product Unit of Measure .
Now you have one more file with name stock.inventory.csv
Step -3 ->
1-> now add two column on stock.inventory.csv
First one is name and second is line_ids/product_qty.
2-> delete the value of column line_ids/product_id/id    of stock.inventory.csv  file .
now copy the values of id column from product.template.csv  and paste into the line_ids/product_id/id   column of stock.inventory.csv  .
3->  now copy the values of qty column from product.template.csv  and paste into the line_ids/product_qty column of stock.inventory.csv  .
4-> enter any value in name column for your reference .
Step – 4-
make sure your file look like this file:-
Click on following link to see file
This is a sample of the succesfully imported data
http://bit.ly/odoocsv
AFTER IMPORTING DONT FORGET START INVENTORY

A: I found that I had to do the import as before, but afterwards, I had to change the state to 'confirm' in the database manually, something like:

sudo -u postgres psql -c "UPDATE stock_inventory SET state = 'confirm' WHERE name like 'Inventory1234'" database_name

Otherwise, when I would press Start Inventory, the quantities would be lost.

A: What I figured out is that you have to have all of your stock locations set up first, so that you can import the quantity on hand per location in Odoo 8.  Set up your location hierarchy, then export the IDs.  Merge these with the product variant (product.template, not product.product) IDs.  I used FileMaker Pro to do this.  Next, create your inventory adjustment record and export the name and ID fields.  Use these on the first line only of your CSV file that contains the product quantity/location records to import.
If it helps, these are the column headers that I used in the import screen:

*

*"Inventories / Location / External ID"

*"Inventories / Checked Quantity"

*"Inventories / Product Unit of Measure"

*"Inventories / Product / Database ID"

*"Inventories / Product Name"

Hopefully, that will help someone out.  My notes are a couple months old, so I hope they are correct!


text:
Q: need to get data grouped by groupid I want to group the query data based on the groupid attribute, the following image is my table image
http://prntscr.com/g2qu7a
I want it to show it like a tree structure where i can show the data in this format:
Group1
    price
     length
      width
    price
     length
      width
    price
     length
      width

Group 2
   same as above

the 3 elements under each group can have 3 or less than 3 or just one or nothing, i want to get data so i can create textfields to update dat in my database, but that is not what i am trying
here is my query
select priceid,itemid,groupid,price,length,width from prices

A: Try using the following concept:
Insert data:
CREATE TABLE some_table (some_data VARCHAR(20), some_other_data VARCHAR(20), groupId VARCHAR(20));
INSERT INTO some_table (some_data, some_other_data, groupId) values ('a', '1', 'id1');
INSERT INTO some_table (some_data, some_other_data, groupId) values ('b', '2', 'id1');
INSERT INTO some_table (some_data, some_other_data, groupId) values ('c', '3', 'id2');

Execute the query:
SELECT '{"' + t.groupId + '": [{' + STUFF(
          (
            SELECT '{ "some_data":"' + td.some_data + '"', ', "some_other_data":' + td.some_other_data + '},'
            FROM some_table td
            WHERE t.groupId = td.groupId
            FOR XML PATH(''), TYPE
          ).value('.', 'NVARCHAR(MAX)'), 1, 1, '') + ']}'
FROM some_table t
GROUP BY t.groupId

Results:

{"id1": [{ "some_data":"a", "some_other_data":1},{ "some_data":"b","some_other_data":2},]}
{"id2": [{ "some_data":"c","some_other_data":3},]}

Note the trailing comma should not affect the validity of the data. My experience with SQL Server is limited, but this should get you started in a direction that can work.
Fiddle:
http://sqlfiddle.com/#!6/66b19/35


text:
Q: My chat client freezes up after beginning threads I made a better chat client following help from people:
They told me that if I didn't want to be blocked on .recv when waiting for messages,          I would need to use threads, classes, functions, and queues to do so.
So I followed some help a specific person gave me where I created a thread from a class and then defined a function that was supposed to read incoming messages and print them.
I also created a function that allows you to enter stuff to be sent off.
Thing is, when I run the program. Nothing happens.
Can somebody help point out what is wrong? (I've asked questions and researched for 3 days, without getting anywhere, so I did try)
from socket import *
import threading
import json
import select

print("Client Version 3")
HOST = input("Connect to: ")
PORT = int(input("On port: "))
# Create Socket

s = socket(AF_INET,SOCK_STREAM)
s.connect((HOST,PORT))
print("Connected to: ",HOST,)

#-------------------Need 2 threads for handling incoming and outgoing messages--

#       1: Create out_buffer:
Buffer = []

rlist,wlist,xlist = select.select([s],Buffer,[])

class Incoming(threading.Thread):
    # made a function a thread
    def Incoming_messages():
        while True:
            for i in rlist:
                data = i.recv(1024)
                if data:
                    print(data.decode())

# Now for outgoing data.
def Outgoing():
    while True:
        user_input=("Your message: ")
        if user_input is True:
            Buffer += [user_input.encode()]
        for i in wlist:
            s.sendall(Buffer)
            Buffer = []

Thanks for taking a look, thanks also to Tony The Lion for suggesting this

A: Take a look at this revised version of your code: (in python3.3)
from socket import *
import threading
import json
import select

print("client")
HOST = input("connect to: ")
PORT = int(input("on port: "))

# create the socket
s = socket(AF_INET, SOCK_STREAM)
s.connect((HOST, PORT))
print("connected to:", HOST)

#------------------- need 2 threads for handling incoming and outgoing messages--

#       1: create out_buffer:
out_buffer = []

# for incoming data
def incoming():
    rlist,wlist,xlist = select.select([s], out_buffer, [])
    while 1:
        for i in rlist:
            data = i.recv(1024)
            if data:
                print("\nreceived:", data.decode())

# now for outgoing data
def outgoing():
    global out_buffer
    while 1:
        user_input=input("your message: ")+"\n"
        if user_input:
            out_buffer += [user_input.encode()]
#       for i in wlist:
            s.send(out_buffer[0])
            out_buffer = []

thread_in = threading.Thread(target=incoming, args=())
thread_out = threading.Thread(target=outgoing, args=())
thread_in.start() # this causes the thread to run
thread_out.start()
thread_in.join()  # this waits until the thread has completed
thread_out.join()

*

*in your program you had various problems, namely you need to call the threads; to just define them isn't enough.

*you also had forgot the function input() in the line:            user_input=input("your message: ")+"\n".

*the "select()" function was blocking until you had something to read, so the program didn't arrive to the next sections of the code, so it's better to move it to the reading thread.

*the send function in python doesn't accept a list; in python 3.3 it accepts a group of bytes, as returned by the encoded() function, so that part of the code had to be adapted.


text:
Q: How to Align Everything to Centre Xcode I am trying to align all items to centre in Xcode as you can see here  but the problem is it looks un aligned in the other views
I have tried to do this using constraints but these do not seem to make any difference after updating frames.
All I am trying to achieve is for everything shown to be centred across all devices.
Thanks.

A: You can simply pin them using the horizontal center in container constraint in Storyboard.
Select all your views and assign it here:

A: I aligned Horizontal and Vertical centre in container from the Editor -> Align menu and then added constraints using the constraints editor for Height and Size. I also setup some top constraints (using I bars in constraints editor) so the items below my image all lined up with it correctly.
For more info, watch this Youtube video provided by Lennet.


text:
Q: Can I make SYSLINUX load a root fs from an image file on an NTFS partition? SYSLINUX allows me to boot from a FAT16 USB-stick by loading a kernel image and an initial ram-disk (initrd) image from there.
To get more space and a faster access, I can mount an NTFS partition from a hard disk after bootup, then use the loopback device to mount a file system image from there to replace /home or even chroot into it, but that is way after the bootup process, making system updates impossible.
Is there a way to make SYSLINUX itself mount the fs-image from the NTFS partition as root fs?
Or can I modify the initrd image to mount the new root fs way more early in the bootup process? I know how to mount and alter that image, but Iḿ lost in the scripts therein and don't know when and how they are executed.

A: Yes, that's possible. And it even works with built-in functions. Just edit your syslinux.cfg to include the following:
LABEL linux
LINUX /boot/vmlinuz
APPEND root=/dev/disk/by-label/data rootfstype=ntfs loop=images/linux_root.img loopfstype=ext4 rw
INITRD /boot/initrd.img

Obviously, you have to copy your kernel image (vmlinuz) and your initial RAM-disk image (initrd.img) to the FAT partition you want to boot off with SYSLINUX. (The path is relative to the partitions root.)
The root= parameter specifies the device and partition the root file system image lies on. You can of course also use the /dev/sda1 notation or the /dev/disk/by-UUID/SOMECRYPTYCNUMBER version.
The rootfstype specifies the file system of the partition the file system image lies on. NTFS and FAT are both supported out of the box. For more exotic formats you need to edit the initrd.img to include and load the appropriate kernel modules.
loop= gives the path to the root file system image relative to the base of the partition it lies on. loopfstype= specifies its internal type. It will, obviously, be mounted at / after boot. The partition the image was loaded from will me mounted at /host automatically if this folder exists. (You won't be able to mount it anywhere else if it is NOT mounted there atomatically. But you are able to move it to another mount point with mount -m if it is.)
Don't forget to copy and overwrite the kernel and the initrd.img on the FAT partition every time those get updated by a system update or strange things may happen on boot.
Unfortunately, there is no way of including a swap-partition in the same way. You have either to use a real partition for that or try to find a way to activate one after boot from the running system.
Expect approx. 10% CPU overhead for writing into the loop-device mounted through the NTFS-wrapper.


text:
Q: Haskell: Not in scope: type constructor or class 'Board' I'm trying to follow a tutorial in my Programming in Haskell book, but I get an error when I'm trying to run this directly copy pasted code from the book, can anyone see what's wrong?
error:
Not in scope: type constructor or class 'Board'
putBoard :: Board -> IO ()

putRow :: Int -> Int -> IO ()
putRow row num = do putStr (show row)
                    putStr ": "
                    putStrLn (concat (replicate num "* "))

putBoard :: Board -> IO ()
putBoard [a,b,c,d,e] = do putRow 1 a
                          putRow 2 b
                          putRow 3 c
                          putRow 4 d
                          putRow 5 e


text:
Q: 3D cross section of a 4D mesh First off, I'd like to note that I've seen the other topic trying to explain this.
I've read over the topic and tried to implement the math, but it doesn't seem to work. I'm probably doing something wrong.
For reference, I'm using C# in the Unity engine. I'm working on a game simmilar to Miegakure, in the fact that you "turn" to face the fourth dimension, seeing it in slices. This means that projecting 4D objects to 3D doesn't work. I need to get 3D Cross-sections.
I already have this working for my actual terrain itself, since it's voxels which makes it easy to change how the mesh generator iterates through the 4D world.
My current problem is non-voxel meshes. I want to have them in my world, for things like the player, and dynamic blocks that move from dimension to dimension (Therefore giving the effect of hypercubes)
In that post, they use some complicated vector math, which I don't think I understand.
So long story short, I just need a slightly better explanation. Does anyone have a link I can steal of an example from 3D>2D slicing, so I can try and extend it to 4D>3D?
Literally any help, even just a re-explanation of that previous post, or someone translating it to actual script, would be nice.
Thanks in advance!


text:
Q: About Entity Framework generated SQL and ViewModel I use ASP.MVC / EF in my project.
The domain model as below:
public class Post
{
     public int Id {get;set;}
     public string Abstract {get;set;}
     public string Content {get;set;}
}

and the view model is
public class PostListView
{
     public int Id {get;set;}
     public string Abstract {get;set;}
}

statemens in action to get model:
 db.Posts.Where(...).Select(p=>new PostListView
 {
       Id = p.Id,
       Abstract = p.Abstract
 });

When I check the SQL generated by Entity Framwork, the select statement includes all three columns. Is there some way to make EF generate more effective SQL statements that only select the fields needed by view model?
Thank you!

A: You can do like this
 var postQuery = from p in db.Posts
                                      select new { p.Id,p.Abstract};

And the enumerate collection
foreach (var p in postQuery  ){
// fill your view model here

}


text:
Q: Capture R output and replace with LaTeX code I'm trying to capture the output from some R code and replace it with latex code.
If you run this code:
library(stargazer)
x <- capture.output(stargazer(mtcars[1:5, 1:3], summary = FALSE, title="The main caption of the table."))

x

This is the output:
 [1] ""
 [2] "% Table created by stargazer v.5.1 by Marek Hlavac, Harvard University. E-mail: hlavac at fas.harvard.edu"
 [3] "% Date and time: Sat, Jun 27, 2015 - 11:36:07"
 [4] "\\begin{table}[!htbp] \\centering "
 [5] "  \\caption{The main caption of the table.} "
 [6] "  \\label{} "
 [7] "\\begin{tabular}{@{\\extracolsep{5pt}} cccc} "
 [8] "\\\\[-1.8ex]\\hline "
 [9] "\\hline \\\\[-1.8ex] "
[10] " & mpg & cyl & disp \\\\ "
[11] "\\hline \\\\[-1.8ex] "
[12] "Mazda RX4 & $21$ & $6$ & $160$ \\\\ "
[13] "Mazda RX4 Wag & $21$ & $6$ & $160$ \\\\ "
[14] "Datsun 710 & $22.800$ & $4$ & $108$ \\\\ "
[15] "Hornet 4 Drive & $21.400$ & $6$ & $258$ \\\\ "
[16] "Hornet Sportabout & $18.700$ & $8$ & $360$ \\\\ "
[17] "\\hline \\\\[-1.8ex] "
[18] "\\end{tabular} "
[19] "\\end{table} "

I need to replace line 5 with this:
"  \\caption[short caption]{The main caption of the table.} "

How can I do this?

A: Try:
x <- sub("\\caption{The main caption of the table.}",
         "\\caption[short caption]{The main caption of the table.}", fixed = TRUE, x)

A: This is a little different than what you had in mind, but perhaps you could just use xtable which has a caption.width argument, e.g.:
print.xtable(xtable(mtcars[1:5, 1:3],
                    caption="The main caption of the table"),
             caption.width="10cm",
             caption.placement="top")

The output will not port exactly to what you're going for, but maybe you could bend this to your purposes if you prefer the more concise code; from ?print.xtable:

The caption will be placed in a "parbox" of the specified width if caption.width is not NULL and type="latex". Default value is NULL.

Here's the output:
% latex table generated in R 3.1.3 by xtable 1.7-4 package
% Tue Jun 30 14:52:06 2015
\begin{table}[ht]
\centering
\parbox{5cm}{\caption{The main caption of the table}}
\begin{tabular}{rrrr}
  \hline
 & mpg & cyl & disp \\
  \hline
Mazda RX4 & 21.00 & 6.00 & 160.00 \\
  Mazda RX4 Wag & 21.00 & 6.00 & 160.00 \\
  Datsun 710 & 22.80 & 4.00 & 108.00 \\
  Hornet 4 Drive & 21.40 & 6.00 & 258.00 \\
  Hornet Sportabout & 18.70 & 8.00 & 360.00 \\
   \hline
\end{tabular}
\end{table}

You'll also have to mess around with the other options (e.g., digits) to get the exact formatting of the rest of the table to match that from stargazer, depending on what exactly the formatting is that you had in mind.


text: Q: More elegant way for solving $y(x) = y_{1}(x) + y_{2}(x)$ in $y'' - 10y' + 28y = 29xe^{-x}$ Is there a more elegant way for solving $y(x) = y_{1}(x) + y_{2}(x)$ in $y'' - 10y' + 28y = 29xe^{-x}$ than to use Euler's identity and get the general solution through brute computation?


text: Q: RDLC Report Downloading I have a project where we use downloads from reports which are made from the RDLC report designer(data taken from SQL Server). These downloads are in Word/Excel(97-2003) version. And If we open them from newer versions some alignments, spaces are changed. Can we change this download version from RDLC as Word/Excel versions(16-365)?


text:
Q: Number of ways of partitioning an array
Given an array of n elements, a k-partitioning of the array would be to split the array in k contiguous subarrays such that the maximums of the subarrays are non-increasing. Namely max(subarray1) >= max(subarray2) >= ... >= max(subarrayK).
In how many ways can an array be partitioned into valid partitions like the ones mentioned before?
Note: k isn't given as input or anything, I mereley used it to illustrate the general case. A partition could have any size from 1 to n, we just need to find all the valid ones.

Example, the array [3, 2, 1] can be partitioned in 4 ways, you can see them below:
The valid partitions :[3, 2, 1]; [3, [2, 1]]; [[3, 2], 1]; [[3], [2], [1]].
I've found a similar problem related to linear partitioning, but I couldn't find a way to adapt the thinking to this problem. I'm pretty sure this is dynamic programming, but I haven't been able to properly identify
how to model the problem using a recurrence relation.
How would you solve this?

A: Call an element of the input a tail-max if it is at least as great as all elements that follow. For example, in the following input:
5 9 3 3 1 2

the following elements are tail-maxes:
5 9 3 3 1 2
  ^ ^ ^   ^

In a valid partition, every subarray must contain the next tail-max at or after the subarray's starting position; otherwise, the next tail-max will be the max of some later subarray, and the condition of non-increasing subarray maximums will be violated.
On the other hand, if every subarray contains the next tail-max at or after the subarray's starting position, then the partition must be valid, as the definition of a tail-max ensures that the maximum of a later subarray cannot be greater.
If we identify the tail-maxes of an array, for example
1 1 9 2 1 6 5 1
. . X . . X X X

where X means tail-max and . means not, then we can't place any subarray boundaries before the first tail-max, because if we do, the first subarray won't contain a tail-max. We can place at most one subarray boundary between a tail-max and the next; if we place more, we get a subarray that doesn't contain a tail-max. The last tail-max must be the last element of the input, so we can't place a subarray boundary after the last tail-max.
If there are m non-tail-max elements between a tail-max and the next, that gives us m+2 options: m+1 places to put an array boundary, or we can choose not to place a boundary between these elements. These factors are multiplicative.
We can make one pass from the end of the input to the start, identifying the lengths of the gaps between tail-maxes and multiplying together the appropriate factors to solve the problem in O(n) time:
def partitions(array):
    tailmax = None
    factor = 1
    result = 1
    for i in reversed(array):
        if tailmax is None:
            tailmax = i
            continue
        factor += 1
        if i >= tailmax:
            # i is a new tail-max.
            # Multiply the result by a factor indicating how many options we
            # have for placing a boundary between i and the old tail-max.
            tailmax = i
            result *= factor
            factor = 1
    return result

A: Update: Sorry I misunderstanding the problem. In this case, split the arrays to sub-arrays where every tails is the max element in the array, then it will work in narrow cases. e.g. [2 4 5 9 6 8 3 1] would be split to [[2 4 5 9] 6 8 9 3 1] first. Then we can freely chose range 0 - 5 to decide whether following are included. You can use an array to record the result of DP. Our goal is res[0]. We already have res[0] = res[5] + res[6] + res[7] + res[8] + res[9] + res[10] in above example and res[10] = 1
def getnum(array):
    res = [-1 for x in range(len(array))]
    res[0] = valueAt(array, res, 0)
    return res[0]

def valueAt(array, res, i):
    m = array[i]
    idx = i
    for index in range(i, len(array), 1):
        if array[index] > m:
            idx = index
            m = array[index]
    value = 1;
    for index in range(idx + 1, len(array), 1):
        if res[index] == -1:
            res[index] = valueAt(array, res, index)
        value = value + res[index]
    return value;

Worse than the answer above in time consuming. DP always costs a lot.
Old Answer: If no duplicate elements in an array is allowed, the following way would work:
Notice that the number of sub-arrays is not depends on the values of elements if no duplicate. We can remark the number is N(n) if there is n elements in array.
The largest element must be in the first sub-arrays, other elements can be in or not in the first sub-array. Depends on whether they are in the first sub-array, the number of partitions for the remaining elements varies.
So,
N(n) = C(n-1, 1)N(n-1) + C(n-1, 2)N(n-2) + ... + C(n-1, n-1)N(0)
where C(n,k) means:

Then it can be solved by DP.
Hope this helps


text:
Q: Insert images in a table (rows = 1, columns = 2) docx python I generated multiple graphs based on the data provided in a csv file and saved the name in a list. Now, I want to loop through the list and insert those images in a table (rows = 1, cols = 2) in a docx file. It works with 2 images but not with more than 2. I want to insert all the images in a table of 2 columns.
 for i, image in enumerate(['1.jpg','2.jpg']):
    row_cells = table.add_row().cells
    paragraph = row_cells[i].paragraphs[0]
    run = paragraph.add_run()
    run.add_picture(image, width=Inches(3), height=Inches(3))

enter image description here


text:
Q: SQL Server Script to Iterate through servers Part 2 I am trying to create a script to obtain data from a multiple databases in a server and then I want it to continue to the next server and do the same. I already created a script to work with one server and all its databases. The script is the same for all databases, tables in all the servers.
My question, is how do I have the script recognize the linked servers that I linked to my current server and continue to obtain data from those servers? Is there a hidden stored procedure or command that someone may know?  I basically want to runs the below script through all my servers.  When its done iterating through all the databases in one server, I want it to continue to the next server and do the same.  I'm going to be saving all the data in a table.
Here is my script below, I want to have the script run through 5 servers which I currently have linked to one of my servers:
   SET NOCOUNT ON DECLARE @DBNAME NVARCHAR(MAX) DECLARE @DBNAME1 NVARCHAR(MAX) DECLARE @varSQL NVARCHAR(MAX)

DROP TABLE TEMPIMGCOUNTERSERVER3 CREATE TABLE TEMPIMGCOUNTERSERVER3 (DBname NVARCHAR(MAX), Images INT, FileSize INT, DBCreation DATETIME)

DECLARE DBNAME CURSOR FAST_FORWARD FOR select name from sys.databases where [NAME] LIKE 'Z%' AND create_date between '2011-02-06' and '2011-02-12' ORDER BY [create_date]

OPEN DBNAME

FETCH NEXT FROM DBNAME INTO @DBname WHILE (@@FETCH_STATUS=0) BEGIN

Set @varSQL='INSERT INTO TEMPIMGCOUNTERSERVER3 (DBNAME, IMAGES, FileSize, DBCreation)
SELECT ''['+@DBNAME+']'', SUM(PGCOUNT), sum(filesize/1024/1024), sys.databases.CREATE_DATE
    FROM SYS.DATABASES, ['+@DBNAME+'].dbo.tbldoc WHERE created between ''2011-02-06'' and ''2011-02-12''
    and sys.databases.name='''+@DBNAME+'''
    GROUP BY sys.databases.NAME, sys.databases.CREATE_DATE'
EXEC SP_EXECUTESQL @varSQL

FETCH NEXT FROM DBNAME
INTO @DBNAME
END

CLOSE DBNAME
DEALLOCATE DBNAME

INSERT TEMPIMGCOUNTERSERVER3 (DBNAME, IMAGES, FILESIZE)
SELECT @@SERVERNAME + ' ' +'TOTAL IMAGES AND FILE SIZE', SUM(IMAGES), SUM(FILESIZE) FROM TEMPIMGCOUNTERSERVER3

 SELECT DBNAME, IMAGES, FILESIZE, convert(VARCHAR(10),
DBCREATION, 101) AS DBCREATION FROM TEMPIMGCOUNTERSERVER3
GROUP BY DBNAME, IMAGES, FILESIZE, convert(VARCHAR(10), DBCREATION, 101)
HAVING SUM(IMAGES) is not null
ORDER BY DBCREATION

Should I add another cursor?  Something with this script:
select srvname from master..sysservers where srvname like 'sql%'

A: i would just nest your cursor in another cursor that runs on the linked servers.  filter the list of servers from master..sysservers on the srvproduct field where it equals "SQL Server".  if there's anything is that list you don't want put it in a not in clause.  then, modify your inner cursor to add the server name to the query, giving you a four part table name.


text:
Q: cannot get MySQL stored procedure into php The following SQL works 100% if I run it in phpMyAdmin, however if I try using it in a php prepare statement in a php file, using:
$stmt = $mysqli->prepare("...");
$stmt->execute();
$stmt->close();

I get an error. I need to know how to wrap this sql into php, because I must use a .php file
SELECT @myCommand := concat("SELECT UNIX_TIMESTAMP( TIMESTAMP( CURDATE( ) ,   HalfHourTime ) ), 0, 0, 0, 0
into OUTFILE 'C:/wamp/www/myApp/services/csv/filename-", DATE_FORMAT(now(),'%Y%m%d-%H%i%s'), '.csv' "'
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
FROM timeintervals_halfhours
");
PREPARE stmt FROM @myCommand;
EXECUTE stmt;

It's based on the post by Frank Flynn on October 6 2006 11:05pm where he said: "If you wish to use OUTFILE or DUMPFILE with a variable for the file name you cannot simply put it in place - MySQL will not resolve the name."
Thanks in advance.

A: The problem is mysqli does not support multi-statment execution in single call.
Take a look on http://php.net/manual/en/mysqli.multi-query.php


text:
Q: Highcharts not displaying tooltip title properly I'm using Highcharts (technically the Highstock .js file though) to display a chart on my site. Everything works perfectly except the tooltip. The API specifies that {series.name} should work for specifying the series name in the tooltip, but the chart actually displays "{series.name}" instead of the name itself. Here's a simplified jsFiddle that illustrates the issue. Switch the comments on the headerFormat: lines in the tooltip section and you'll see that {point.key} works as expected, but {series.name} does not.
What's wrong with the code to produce this problem?

A: It is known bug reported to our developers here.
Workaround: Use a tooltip formatter and print all informations which you need.


text:
Q: sencha architect doesnot allow to add plugins for catesianchart Am working with sencha archictect4.2.1. We need to use chart and on click of chart series or category it will go to drill down charts.(open a new window and show up charts there).  For chart click event we need to add following plugins:
   plugins : {
        ptype : 'chartitemevents',
        moveEvents : true
 }

how do I add above plugins into sencha Architect . I dont find any property with this name in cartesian chart component.
Regards,


text:
Q: java.lang.ClassNotFoundException: xsbt.CompilerInterface with PlayFramework What can i do with this? I try to create bot for telegram with deploy on heroky. But i got this exception, when i Run my project. I using IntelliJ IDEA Ultimate. PlayFramework with sbt. Database - MongoDB
 java.lang.ClassNotFoundException: xsbt.CompilerInterface
java.net.URLClassLoader.findClass(URLClassLoader.java:381)
java.lang.ClassLoader.loadClass(ClassLoader.java:424)
java.lang.ClassLoader.loadClass(ClassLoader.java:357)
java.lang.Class.forName0(Native Method)
java.lang.Class.forName(Class.java:348)
sbt.compiler.AnalyzingCompiler.getInterfaceClass(AnalyzingCompiler.scala:128)
sbt.compiler.AnalyzingCompiler.call(AnalyzingCompiler.scala:104)
sbt.compiler.AnalyzingCompiler.newCachedCompiler(AnalyzingCompiler.scala:62)
sbt.compiler.AnalyzingCompiler.newCachedCompiler(AnalyzingCompiler.scala:57)
sbt.compiler.CompilerCache$$anon$2.apply(CompilerCache.scala:47)
sbt.compiler.AnalyzingCompiler.compile(AnalyzingCompiler.scala:45)
sbt.compiler.MixedAnalyzingCompiler$$anonfun$compileScala$1$1.apply$mcV$sp(MixedAnalyzingCompiler.scala:50)
sbt.compiler.MixedAnalyzingCompiler$$anonfun$compileScala$1$1.apply(MixedAnalyzingCompiler.scala:50)
sbt.compiler.MixedAnalyzingCompiler$$anonfun$compileScala$1$1.apply(MixedAnalyzingCompiler.scala:50)
sbt.compiler.MixedAnalyzingCompiler.timed(MixedAnalyzingCompiler.scala:74)
sbt.compiler.MixedAnalyzingCompiler.compileScala$1(MixedAnalyzingCompiler.scala:49)
sbt.compiler.MixedAnalyzingCompiler.compile(MixedAnalyzingCompiler.scala:64)
sbt.compiler.IC$$anonfun$compileInternal$1.apply(IncrementalCompiler.scala:160)
sbt.compiler.IC$$anonfun$compileInternal$1.apply(IncrementalCompiler.scala:160)
sbt.inc.IncrementalCompile$$anonfun$doCompile$1.apply(Compile.scala:66)
sbt.inc.IncrementalCompile$$anonfun$doCompile$1.apply(Compile.scala:64)
sbt.inc.IncrementalCommon.cycle(IncrementalCommon.scala:32)
sbt.inc.Incremental$$anonfun$1.apply(Incremental.scala:72)
sbt.inc.Incremental$$anonfun$1.apply(Incremental.scala:71)
sbt.inc.Incremental$.manageClassfiles(Incremental.scala:99)
sbt.inc.Incremental$.compile(Incremental.scala:71)
sbt.inc.IncrementalCompile$.apply(Compile.scala:54)
sbt.compiler.IC$.compileInternal(IncrementalCompiler.scala:160)
sbt.compiler.IC$.incrementalCompile(IncrementalCompiler.scala:138)
sbt.Compiler$.compile(Compiler.scala:155)
sbt.Compiler$.compile(Compiler.scala:141)
sbt.Defaults$.sbt$Defaults$$compileIncrementalTaskImpl(Defaults.scala:886)
sbt.Defaults$$anonfun$compileIncrementalTask$1.apply(Defaults.scala:877)
sbt.Defaults$$anonfun$compileIncrementalTask$1.apply(Defaults.scala:875)
scala.Function1$$anonfun$compose$1.apply(Function1.scala:47)
sbt.$tilde$greater$$anonfun$$u2219$1.apply(TypeFunctions.scala:40)
sbt.std.Transform$$anon$4.work(System.scala:63)
sbt.Execute$$anonfun$submit$1$$anonfun$apply$1.apply(Execute.scala:228)
sbt.Execute$$anonfun$submit$1$$anonfun$apply$1.apply(Execute.scala:228)
sbt.ErrorHandling$.wideConvert(ErrorHandling.scala:17)
sbt.Execute.work(Execute.scala:237)
sbt.Execute$$anonfun$submit$1.apply(Execute.scala:228)
sbt.Execute$$anonfun$submit$1.apply(Execute.scala:228)
sbt.ConcurrentRestrictions$$anon$4$$anonfun$1.apply(ConcurrentRestrictions.scala:159)
sbt.CompletionService$$anon$2.call(CompletionService.scala:28)
java.util.concurrent.FutureTask.run(FutureTask.java:266)
java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
java.util.concurrent.FutureTask.run(FutureTask.java:266)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
java.lang.Thread.run(Thread.java:745)

A: As often, restarting the IDE did the trick in my case.

A: Delete .activator, .ivy2 and .sbt in your home directory and start again.

A: Deleting the .idea folder in the project and re-importing the sbt worked for me. (Deleting .ivy & .sbt in home folders did not).

A: Invalidating cache helped. File -> Invalidate Caches...


text:
Q: Get DateTime and the Difference JS I want to know how to get a Datetime and take the diffrence in Java Script, i know how to do it just in SQL,
I need this for a Employee point system. He will enter and starts the day, generating the date and time ( ex: 23/07/2020 08:00:00 ). After, he will end the day and take the date and time ( ex: 23/07/2020 18:00:00 ).
I need to take the Date and after the difference to give a time, like: "You worked 10:00:00".

A: you can do it easilly with momentjs
, it is a package that allows you to manage dates super easy and with no problems, you can add or subtract dates, and you can also show them with any format you want, this are only a few examples but you can do a lot more with it


text:
Q: Python inheritance from class/method I think the problem is with selfs/class methods etc.
first of all, I have that kind of code:
from locust import HttpUser, task, TaskSet, between, exception, events
import logging

alphabetic = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
              'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
              'u', 'w', 'x', 'y', 'z']

logins = [elem*3 for elem in alphabetic]

passwd = 'radio'

paths_in_dict = {"hard_path": "secure/izar.xhtml/",
                 "standard_analysis_path": "analysis/STANDARD/",
                 "smart_analysis_path": "analysis/SMART/"}

login_pass = [(elem, passwd) for elem in logins]

class MyUser(HttpUser):
    wait_time = between(5, 9)
    host = "https://localhost:9003/"

    def on_start(self):
        if len(login_pass) > 0:
            self.user, self.passwd = login_pass.pop()
        self.client.verify = False
        self.login()

    def on_stop(self):
        pass

    def login(self):
        default_headers = {'X-Username': self.user, 'X-Password': self.passwd}
        self.client.request(method="POST", url="login.xhtml", headers=default_headers,
                            name="---ON START---LOGIN")
        logging.info('Login with %s username and %s password', self.user, passwd)
    @task
    def delete_analysis(self):
        """DELETE will not be performed if Analysis does not exist"""
        default_headers = {'X-Username': self.user, 'X-Password': self.passwd}
        for number in range(101, 106):
            response = self.client.request(method="GET", url="api/analysis/%s" % number,
                                           headers=default_headers, catch_response=True,
                                           name="Check if Analysis %s exists" % number)
            if response.ok and number not in MyUser.deleted_number_analysis:
                MyUser.deleted_number_analysis[number] = True
                self.client.request(method="DELETE", url="api/analysis/%s" % number,
                                    headers=default_headers,
                                    name="Delete existing Analysis with ID %s" % number)
            else:
                response.failure(exc="Nothing to DELETE")

The next ones @tasks/methods are waiting for default_headers,
So my question is - how to make default headers for whole claas MyUser(HttpUser)?
I think I did some mistakes with selfs, methods, etc.
So how to declare default_headers for all of the methods in this class??
Could you please help me?

A: Instead of just declaring default_headers variable in the method, you should assign them as a property of the objects: 'self.default_headers = ...'
Also note that it's highly recommended to declare all parameters in the init method, like 'self.default_headers = {}'


text:
Q: SQL - Get previous amounts for each day I'm trying to write a query that is sort of like a running total but not really. I want to get the previous weight (kg) and keep outputting that for each day until another weight (kg) is recorded then continue to output that until next weight recorded. Below is example of what I'm trying to accomplish (see KG column).
Current results:
ENCOUNTER_ID | KG   | DATE_RECORDED | CALENDAR_DT
-----------------------------------------------
100            10     2019-01-01      2019-01-01
NULL           NULL   NULL            2019-01-02
100            12     2019-01-03      2019-01-03
NULL           NULL   NULL            2019-01-04
NULL           NULL   NULL            2019-01-05
NULL           NULL   NULL            2019-01-06
100            13     2019-01-07      2019-01-07
NULL           NULL   NULL            2019-01-08

Desired Results:
ENCOUNTER_ID | KG   | DATE_RECORDED | CALENDAR_DT
-----------------------------------------------
100            10     2019-01-01      2019-01-01
NULL           10     NULL            2019-01-02
100            12     2019-01-03      2019-01-03
NULL           12     NULL            2019-01-04
NULL           12     NULL            2019-01-05
NULL           12     NULL            2019-01-06
100            13     2019-01-07      2019-01-07
NULL           13     NULL            2019-01-08

A: In standard SQL, you would use lag() with the ignore nulls option:
select t.*,
       lag(kg ignore nulls) over (order by calendar_dt)
from t;

Not all databases support ignore nulls.  But it is standard SQL and you haven't specified the database you are using.

A: A solution can be achieved by combining a CASE with a subquery that will fetch the first valid value ordered by data.
See the below example using T-SQL.
create table dbo.WeightLog
(
  ENCOUNTER_ID int null,
  KG int null,
  DATE_RECORDED date null,
  CALENDAR_DT date not null
)
GO

insert into dbo.WeightLog values
(100 ,           10,     '2019-01-01',    '2019-01-01'),
(NULL,           NULL,   NULL,            '2019-01-02'),
(100 ,           12,     '2019-01-03',    '2019-01-03'),
(NULL,           NULL,   NULL,            '2019-01-04'),
(NULL,           NULL,   NULL,            '2019-01-05'),
(NULL,           NULL,   NULL,            '2019-01-06'),
(100 ,           13,     '2019-01-07',    '2019-01-07'),
(NULL,           NULL,   NULL,            '2019-01-08')
GO

select
wl.ENCOUNTER_ID,
case when wl.KG is null
then (select top 1 x.KG from dbo.WeightLog x where x.CALENDAR_DT < wl.CALENDAR_DT
        and x.KG is not null order by x.CALENDAR_DT desc)
else wl.KG end as [Kg],
wl.DATE_RECORDED,
wl.CALENDAR_DT
from dbo.WeightLog wl

Results in:

ENCOUNTER_ID Kg          DATE_RECORDED CALENDAR_DT
------------ ----------- ------------- -----------
100          10          2019-01-01    2019-01-01
NULL         10          NULL          2019-01-02
100          12          2019-01-03    2019-01-03
NULL         12          NULL          2019-01-04
NULL         12          NULL          2019-01-05
NULL         12          NULL          2019-01-06
100          13          2019-01-07    2019-01-07
NULL         13          NULL          2019-01-08

Note: it doesn't explore the particular case where a first record is null.


text:
Q: SSIS Package with CLR Trigger I am trying to run an SSIS package which calls a stored procedure that invokes a CLR trigger. I am getting the following error message:

Error: SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occurred. Error code: 0x80004005. An OLE DB record is available.
Source: "Microsoft SQL Server Native Client 11.0" HResult: 0x80004005
Description: "The metadata could not be determined because statement 'UPDATE blah SET field = value' in procedure 'sp_MyProc' invokes a CLR trigger.".
Error: Unable to retrieve destination column descriptions from the parameters of the SQL command.

I am running SQL Server 2014 but the package was created for 2005. We recently upgraded our servers and are migrating the old packages which is why we are seeing this issue now. The package was working fine before in SQL Server 2005.


text:
Q: trace execution path of python interpreter The following works nice to see what the interpreter does:
python -m trace --ignore-dir=$HOME/lib64:$HOME/lib:/usr -t path-to/script.py

But there are too many lines. I would like to hide the lines which happen during importing a file.
Example: I am not interested in lines like this:
saved_filter.py(9): class SavedFilter(models.Model):
saved_filter.py(10):     name = models.TextField(max_length=256)
saved_filter.py(11):     user = models.ForeignKey('auth.User', null=True, blank=True)

I could not find a solution in the docs:
https://docs.python.org/2/library/trace.html
Update
If there is a different way to get the result, for example a different python package (not trace), this would be a good solution, too.
Update 2
The tracing should be non-interactive.
Update 3
I tried the solution provided by Martin v. Löwis. It works in some cases, but not all.
file foo.py
import bar

def main():
    f=bar.Foo()
    f.my_func()

if __name__=='__main__':
    main()

file bar.py
class Foo(object):
    def my_func(self):
        def inner():
            print('#in inner')
            return 'inner'
        print('#in my_func()')
        inner()
        return 1

If I call foo.py, the wanted result looks similar to this:
foo.py: f=bar.Foo()
foo.py: f.my_func()
bar.py: print('#in my_func()')
bar.py: inner()
bar.py: print('#in inner')
bar.py: return 'inner'
bar.py: return 1
Result of trace2.py
> python tmp/trace2-orig.py --trace tmp/foo.py
 --- modulename: foo, funcname: <module>
 --- modulename: bar, funcname: <module>
 --- modulename: bar, funcname: Foo
bar.py(1): class Foo(object):               <======= Import lines
bar.py(2):     def my_func(self):
 --- modulename: foo, funcname: main
foo.py(4):     f=bar.Foo()
foo.py(5):     f.my_func()
 --- modulename: bar, funcname: my_func
bar.py(3):         def inner():
bar.py(6):         print('#in my_func()')
#in my_func()
bar.py(7):         inner()
 --- modulename: bar, funcname: inner
bar.py(4):             print('#in inner')
#in inner
bar.py(5):             return 'inner'
bar.py(8):         return 1
 --- modulename: trace, funcname: _unsettrace
trace.py(80):         sys.settrace(None)

Unfortunately there is still class Foo(object) which is something executed during import.
I guess the detection of code loading and executing does not cover all cases.

A: If you create a script trace2.py as
import trace

OrigTrace = trace.Trace
class Trace2(trace.Trace):
    def localtrace_trace(self, frame, why, arg):
        if why == "line" and frame.f_code.co_name == '<module>':
            return self.localtrace
        return OrigTrace.localtrace_trace(self, frame, why, arg)

trace.Trace=Trace2
trace.main()

and run python -m trace2 -t script.py you will not see trace output from lines that are on the module level.

A: you can use pdb library, by this library you can make breakpoint and/or inject python statements to the break point line by interactive console UI and doing more other actions.
;)

A: If you just want to hide code paths during import, just pipe it through a filter like this one:
import re
import sys

cur = None
skip_re = re.compile(r'^(?P<filename>.+)?\((\d*)\):\s*import')
for line in sys.stdin:
    if cur and not line.startswith(cur):
        continue
    cur = None
    match = skip_re.match(line)
    if match:
        cur = match.group('filename')
    sys.stdout.write(line)


text:
Q: Angular (v4) form data object not matching json data I have the following form set up in Angular (v4)
I'm pulling the following json data
db.json file contents
{
  "customer": {
    "title": "",
    "firstName": "D",
    "lastName": "",
    "address": {
        "line1": "",
        "line2": "",
        "town": "",
        "postcode": ""
    },
    "acceptData": false
  }
}

But when I display the form outputs
{{ form.value | json }}
 I get the following JSON data
FORM DATA
{
  "title": "",
  "firstName": "D",
  "lastName": "",
  "line1": "",
  "line2": "",
  "town": "",
  "postcode": "",
  "acceptData": false
}

You can see that the address object is missing, I'm sure I doing something wrong, quite simple but been staring at the code for hours and can't seam to fix it. I want the customer object to match that of the contents of db.json above.
FORM MARKUP
<form (ngSubmit)="handleSubmit(form.value, form.valid)" #form="ngForm" novalidate>

    <select
      id="title"
      name="title"
      [ngModel]="details?.title"
      (ngModelChange)="details.title=$event">
      <option value="" selected>Select</option>
      <option value="Mr">Mr</option>
      <option value="Mrs">Mrs</option>
    </select>

    First name
    <input
      type="text"
      name="firstName"
      id="firstName"
      maxlength="20"
      required
      #firstName="ngModel"
      [ngModel]="details?.firstName"
      (ngModelChange)="details.firstName=$event"
      [ngClass]="{ 'error': firstName.errors?.required && firstName.dirty }">

First name is required

    Last name
    <input
      type="text"
      name="lastName"
      id="lastName"
      maxlength="20"
      required
      #lastName="ngModel"
      [ngModel]="details?.lastName"
      (ngModelChange)="details.lastName=$event">

Last name is required

    Address
      <input
        type="text"
        name="line1"
        [ngModel]="details?.address.line1"
        (ngModelChange)="handleChange($event)"
        placeholder="Line1">
        <input
        type="text"
        name="line2"
        [ngModel]="details?.address.line2"
        (ngModelChange)="details.address.line2=$event"
        placeholder="Line2">
        <input
        type="text"
        name="town"
        [ngModel]="details?.address.town"
        (ngModelChange)="details.address.town=$event"
        placeholder="town">
        <input
        type="text"
        name="postcode"
        [ngModel]="details?.address.postcode"
        (ngModelChange)="details.address.postcode=$event"
        placeholder="postcode">

      <input
        type="checkbox"
        name="acceptData"
        [ngModel]="details?.acceptData"
        (ngModelChange)="details.acceptData=$event">

    <button
      type="submit"
      [disabled]="form.invalid">
      Submit
    </button>

      Form Data

{{ form.value | json }}

  </form>

Any help much appreciated

A: Just wrap the following form controls:
"line1": "",
"line2": "",
"town": "",
"postcode": ""

inside a div with ngModelGroup

DEMO
Seems you maybe also want to wrap everything inside customer to match the JSON? Then do the same, wrap everything with ngModelGroup="customer"


text:
Q: Sending tab key event? Is it possible to send a tab key press with calabash? I'm having difficulty selecting elements in a browser view on Android.
I've tried the following things:
enter_text("WebView css:'#Email'", "email@email.com")
enter_text("android.widget.EditText id:'#Email'", "email@email.com")

But they don't seem to be seen by calabash to select. I'm now wondering if I send certain number of tab presses, I should also end up in the field that I want. How do I send a tab key press though?
Additionally, is it possible to send text to an element that has the active focus, without specifying an id of the element?
Thanks in advance

A: "Is it possible to send a tab key press with calabash?"
Yes, it is.

press_user_action_button('next')

If you are using Cordova, you should change the Webview to cordovaWebView or SystemWebView.

enter_text("SystemWebView css:'#Email'", "email@email.com")

"Additionally, is it possible to send text to an element that has the active focus, without specifying an id of the element?"
Yes, it is.

keyboard_enter_text("text")


text:
Q: Unequal width binned histogram in python I have an array with probability values stored in it. Some values are 0. I need to plot a histogram such that there are equal number of elements in each bin. I tried using matplotlibs hist function but that lets me decide number of bins. How do I go about plotting this?(Normal plot and hist work but its not what is needed)
I have 10000 entries. Only 200 have values greater than 0 and lie between 0.0005 and 0.2. This distribution isnt even as 0.2 only one element has whereas 2000 approx have value 0.0005. So plotting it was an issue as the bins had to be of unequal width with equal number of elements

A: The task does not make much sense to me, but the following code does, what i understood as the thing to do.
I also think the last lines of the code are what you really wanted to do. Using different bin-widths to improve visualization (but don't target the distribution of equal amount of samples within each bin)! I used astroml's hist with method='blocks' (astropy supports this too)
Code
# Python 3 -> beware the // operator!

import numpy as np
import matplotlib.pyplot as plt
from astroML import plotting as amlp

N_VALUES = 1000
N_BINS = 100

# Create fake data
prob_array = np.random.randn(N_VALUES)
prob_array /= np.max(np.abs(prob_array),axis=0)  # scale a bit

# Sort array
prob_array = np.sort(prob_array)

# Calculate bin-borders,
bin_borders = [np.amin(prob_array)] + [prob_array[(N_VALUES // N_BINS) * i] for i in range(1, N_BINS)] + [np.amax(prob_array)]

print('SAMPLES: ', prob_array)
print('BIN-BORDERS: ', bin_borders)

# Plot hist
counts, x, y = plt.hist(prob_array, bins=bin_borders)
plt.xlim(bin_borders[0], bin_borders[-1] + 1e-2)
print('COUNTS: ', counts)
plt.show()

# And this is, what i think, what you really want

fig, (ax1, ax2) = plt.subplots(2)
left_blob = np.random.randn(N_VALUES/10) + 3
right_blob = np.random.randn(N_VALUES) + 110
both = np.hstack((left_blob, right_blob))  # data is hard to visualize with equal bin-widths

ax1.hist(both)
amlp.hist(both, bins='blocks', ax=ax2)
plt.show()

Output


text:
Q: Is python-oauth2 the right tool for my issue? I'm coding an app which has to use this api. So I want to do at a certain point a search on their database. Now I'm struggling with which python library is the right one to use in order to authenticate about oAuth2? I couldn't find any by now, where I was sure, it would offer the necessary functions.
I wonder if this library (python-oauth2) offers, what I need. But this isn't a library for the client, is it? It seems it is for the server...
I'd be really grateful, if someone could just give me an advice, with what I should work.

A: Method 1
You will need to use the following modules. No need to use oauth. Just need to get the token before performing any search using the api.

requests, json, urllib

Here's a short Example code for that
import requests, json, urllib

BASE_URL = "http://scoilnet.com/grants/apikey/"
r = requests.post(_BASE_URL+"user/token/", data={'username': username , 'password': password })
print r.getcontent

The above code will show you how to request a token from the api. Using that token you will be making get and post requests to the api which will give a json response. That json response will be shown as a Dictionary from which you will load you data in your program.
Method 2
You can also use urllib or urllib2 or urllib3


text:
Q: Is it possible to keep workspace on Amazon EC2 server between runs? We develop a software for Linux and Mac using C++ and python. So far we have installed all required packages into virtualenv using pip. Now 3rdParty libraries take substantial amount of time to compile. We want to speed up build process on the build servers.
One way is not to wipe out build agent workspace between builds. Is it possible when using Amazon EC2 servers?

A: After you can get instance to its base state, you can use that to create an AMI. Now if you launch with that AMI in the future, all the libraries should be in place. At that point you can do any additional bootstrapping you need.
It will use your existing key unless you prep the instance before creating an AMI to use the key provided at launch.

A: The following Jenkins plugin can be used to copy files into the slave workspace.

*

*https://wiki.jenkins-ci.org/display/JENKINS/Copy+To+Slave+Plugin


text:
Q: iOS simulator screen doesn't resize to actual device size even though used scaling in Xcode 6.4 I have recently upgraded Xcode 6.1.1 to 6.4. The simulators in 6.4 has large screen sizes. Even though I used scaling, the simulator become smaller as well as the screen also got small with respect to simulator. I have tried using different scaling sizes (75,50,33,25)% and also performed "Reset content and settings" option of iOS simulators.
Thanks in Advance.


text:
Q: High resolution image upload fails stream_copy_to_stream(): read of 8192 bytes I am using laravel + twill inside docker containers with php7.4.3-fpm + nginx. Everything works fine appart from when I am trying to upload images of high resolution. If I upload image of 3000x3000px there are no problem as soon as I try to do the same with higher resolution (4500x4500px) I get the following error,
message: "stream_copy_to_stream(): read of 8192 bytes failed with errno=21 Is a directory"
exception: "ErrorException"
file: "/var/www/backend/vendor/league/flysystem/src/Adapter/Local.php"
line: 159
trace: [{function: "handleError", class: "Illuminate\Foundation\Bootstrap\HandleExceptions", type: "->"},…]
0: {function: "handleError", class: "Illuminate\Foundation\Bootstrap\HandleExceptions", type: "->"}
function: "handleError"
class: "Illuminate\Foundation\Bootstrap\HandleExceptions"
type: "->"
1: {file: "/var/www/backend/vendor/league/flysystem/src/Adapter/Local.php", line: 159,…}
file: "/var/www/backend/vendor/league/flysystem/src/Adapter/Local.php"
line: 159
function: "stream_copy_to_stream"

Is it a php-fpm configuration issue? Is it problem with php? Has anyone had similar problems?

A: These steps solved the same issue for me!

*

*Open file /etc/php/7.*/fpm/php.ini

*Edit upload_max_filesize

*Edit post_max_size

*reload php7.*-fpm service

good luck!

A: I did find a solution, my problem was with php.ini setting, how lame of me to overlook it.
I fixed it by adding these to the docker entry file.
sed -i -e "s/upload_max_filesize = 2M/upload_max_filesize = 64M/g" $PHP_INI_DIR/php.ini
sed -i -e "s/post_max_size = 8M/post_max_size = 64M/g" $PHP_INI_DIR/php.ini
sed -i -e "s/memory_limit = 128M/memory_limit = 256M/g" $PHP_INI_DIR/php.ini


text:
Q: Can't find Powershell command to grant admin consent I have one Azure Ad app created via powershell.
I added permissions using Add-AzADAppPermission by following this document: Add-AzADAppPermission (Az.Resources) | Microsoft Docs
Now I want to grant admin consent for the added permissions via powershell but I can't find any related command or any ms doc.
Is there any command that I can use to grant admin consent from powershell?
Can anyone please shed light on this?

A: AFAIK, currently PowerShell don't have any command for granting admin consent.
Alternatively, you can make use of Azure CLI/Azure Portal to achieve your scenario as suggested by Joy Wang in this similar SO Thread.
I tried to reproduce the same in my environment like below:
I assigned the API permissions that need admin consent:

To grant the admin consent, execute the below command:
az login
az ad app permission admin-consent --id <application-id>

After executing the above command, admin consent for the API permissions granted successfully like below:

Reference:
az ad app permission | Microsoft Docs


text:
Q: (2D int array pointer to pointer) why is there a segmentation fault? I'm trying to print the elements of a 2D array but I keep getting a segmentation fault (I use my own printing function so i don't use printf)
the code:
(this is the main)
int main()
{

  int zArr[3][4]={1, 2, 3, 4};
  int *zPtr = *zArr;
  print2dArray(&zPtr, 3, 4);

  return 0;
}

(this is the function)
void print2dArray(int **arr, int rows, int cols)
{
  int a = 0;
  int b = 0;
  for(a = 0; a < rows; a++) {
    for(b = 0; b < cols; b++) {
      putNum(arr[a][b]);
    }
  }
}

(this is the output)
1
2
3
4
segmentation fault(core dumped)


text:
Q: Добавить блок в конец другого блока JQUERY Как добавить блок в конец другого блока JQUERY, если в блоке, куда добавляется, может быть пустой, а может иметь уже элемент div. В случае, если имеется, нужно добавить перед ним.
A: Проверяете количество div внутри блока и, если больше нуля, то prepend(), а если меньше - append(). В общем, как-то так.


text:
Q: Calculating total Balance of Particular Suburb C#    List<Customer> customers = new List<Customer>();
    int id = 0;
    int click = -1;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void AddButton_Click(object sender, EventArgs e)
    {
        Customer rec1 = new Customer("C0020", "Alfred", "Campbelltown", 1500, 2006);
        Customer rec2 = new Customer("C0021", "Ryder", "Liverpool", 2000, 2008);
        Customer rec3 = new Customer("C0022", "Alison", "Strathfield", 5500, 2012);
        Customer rec4 = new Customer("C0023", "Eliza", "Liverpool", 6000, 2012);
        Customer rec5 = new Customer("C0024", "Natsu", "Campbelltown", 2560, 2011);

        customers.Add(rec1);
        customers.Add(rec2);
        customers.Add(rec3);
        customers.Add(rec4);
        customers.Add(rec5);

        click = customers.Count - 1;

    }

How do i calculate the total balance by particular suburb? I can calculate the total balance of everything by using the code below:
        double total = 0;

        foreach (Customer Total in customers)
            total += Total.Balance; //Total Balance

Any Ideas? thanks

A: In C# >= 3.5 simplest way will be using LINQ:
customers.Where(c => c.Suburb == "whatever").Sum(c => c.Balance);

Sorry, you didn't describe your Customer props, so I've assumed them.

A: You can use LINQ's GroupBy and Sum each group:
var suburbGroups = customers
        .GroupBy(c => c.Suburb)
        .Select(g => new { Suburb = g.Key, Balance = g.Sum(c => c.Balance) })
        .OrderByDescending(x => x.Balance);

foreach(var grp in suburbGroups)
    Console.WriteLine("Suburb: {0}  Total-Balance: {1}", grp.Suburb, grp.Balance);

Note that you need to add using System.Linq;
Demo: http://ideone.com/TQcgE

A: Assuming you have Balance property in your Customer class
var bal = customers.Sum(c => c.Balance); // customers is the collection

A: Use Following Linq expression...
var balance=customers.GroupBy(g=>g.suburbname).Select(lg =>new { TotalBalance= lg.Sum(g => g.Balance)});


text:
Q: Simple LED display project not printing to the console how I want it to I've been tasked with creating a simple LED display that allows a user to input any non-negative integer and will print that number onto the console. I'm still learning and there are most likely better ways to do this but here's the code I came up with:

num = input('enter a number: ')

for i in num:

    if i == '1':
        row1 = '  #'
        row2 = '  #'
        row3 = '  #'
        row4 = '  #'
        row5 = '  #'

        fullnum1 = f' {row1} \n {row2} \n {row3} \n {row4} \n {row5} \n'
        ls.append(fullnum1)

    elif i == '2':
        row1 = '###'
        row2 = '  #'
        row3 = '###'
        row4 = '#  '
        row5 = '###'

        fullnum2 = f' {row1} \n {row2} \n {row3} \n {row4} \n {row5} \n'
        ls.append(fullnum2)

    elif i == '3':
        row1 = '###'
        row2 = '  #'
        row3 = '###'
        row4 = '  #'
        row5 = '###'

        fullnum3 = f' {row1} \n {row2} \n {row3} \n {row4} \n {row5} \n'
        ls.append(fullnum3)

    elif i == '4':
        row1 = '# #'
        row2 = '# #'
        row3 = '###'
        row4 = '  #'
        row5 = '  #'

        fullnum4 = f' {row1} \n {row2} \n {row3} \n {row4} \n {row5} \n'
        ls.append(fullnum4)

    elif i == '5':
        row1 = '###'
        row2 = '#  '
        row3 = '###'
        row4 = '  #'
        row5 = '###'

        fullnum5 = f' {row1} \n {row2} \n {row3} \n {row4} \n {row5} \n'
        ls.append(fullnum5)

    elif i == '6':
        row1 = '###'
        row2 = '#  '
        row3 = '###'
        row4 = '# #'
        row5 = '###'

        fullnum6 = f' {row1} \n {row2} \n {row3} \n {row4} \n {row5} \n'
        ls.append(fullnum6)

    elif i == '7':
        row1 = '###'
        row2 = '  #'
        row3 = '  #'
        row4 = '  #'
        row5 = '  #'

        fullnum7 = f' {row1} \n {row2} \n {row3} \n {row4} \n {row5} \n'
        ls.append(fullnum7)

    elif i == '8':
        row1 = '###'
        row2 = '# #'
        row3 = '###'
        row4 = '# #'
        row5 = '###'

        fullnum8 = f' {row1} \n {row2} \n {row3} \n {row4} \n {row5} \n'
        ls.append(fullnum8)

    elif i == '9':
        row1 = '###'
        row2 = '# #'
        row3 = '###'
        row4 = '  #'
        row5 = '###'

        fullnum9 = f' {row1} \n {row2} \n {row3} \n {row4} \n {row5} \n'
        ls.append(fullnum9)

    elif i == '0':
        row1 = '###'
        row2 = '# #'
        row3 = '# #'
        row4 = '# #'
        row5 = '###'

        fullnum0 = f' {row1} \n {row2} \n {row3} \n {row4} \n {row5} \n'
        ls.append(fullnum0)

for i in ls:
    print(i)

When the code is run, it prints the input vertically instead of each number side-by-side. I've tried this:
for i in num:
        print(i, end='')

But it doesn't work. Any help would be greatly appreciated.

A: For a more compact version, you can create the number lists in one line then split the line:
all = '''
  # ### ### # # ### ### ### ### ### ###
  #   #   # # # #   #     # # # # # # #
  # ### ### ### ### ###   # ### ### # #
  # #     #   #   # # #   # # #   # # #
  # ### ###   # ### ###   # ### ### ###
'''[1:-1]

dnum = {}
keys = '1234567890'
for k in keys:
   dnum[k] = []
lines = all.split('\n')
for ln in lines:
   for i,k in enumerate(keys):
       dnum[k].append(ln[i*4:i*4+4])

def shownum(num):
   for r in range(5):  # 5 rows tall
      for n in num:
         print(dnum[n][r], end='') # each digit
      print()  # next row

num = input('enter a number: ')
while num != '':
    shownum(num)
    num = input('enter a number: ')

Output
enter a number: 123
  # ### ###
  #   #   #
  # ### ###
  # #     #
  # ### ###

enter a number: 987
### ### ###
# # # #   #
### ###   #
  # # #   #
### ###   #

A: The following code does what you want:
# Create a dictionary, mapping each input character to an LED display representation
nums={
    '0':[
    "###",
    "# #",
    "# #",
    "# #",
    "###"
    ],
    '1':[
    "  #",
    "  #",
    "  #",
    "  #",
    "  #"
    ],
    '2':[
    "###",
    "  #",
    "###",
    "#  ",
    "###"
    ],
    '3':[
    "###",
    "  #",
    "###",
    "  #",
    "###"
    ],
    '4':[
    "# #",
    "# #",
    "###",
    "  #",
    "  #"
    ],
    '5':[
    "###",
    "#  ",
    "###",
    "  #",
    "###"
    ],
    '6':[
    "###",
    "#  ",
    "###",
    "# #",
    "###"
    ],
    '7':[
    "###",
    "  #",
    "  #",
    "  #",
    "  #"
    ],
    '8':[
    "###",
    "# #",
    "###",
    "# #",
    "###"
    ],
    '9':[
    "###",
    "# #",
    "###",
    "  #",
    "###"
    ]
}

while True:
    input_num=input("enter a number: ")
    print_str=""
    for i in range(5):  # because there are 5 rows per number
        for num in input_num:  # we have to fully build each row, so each input number has to be looped through
            print_str += nums[num][i] + "   "  # add a space separator between digits
        print_str += "\n"  # start the next row
    print(print_str)  # output the result at the end

Output:
enter a number: 56372
###   ###   ###   ###   ###
#     #       #     #     #
###   ###   ###     #   ###
  #   # #     #     #   #
###   ###   ###     #   ###

enter a number: 12345
  #   ###   ###   # #   ###
  #     #     #   # #   #
  #   ###   ###   ###   ###
  #   #       #     #     #
  #   ###   ###     #   ###

enter a number: 00101
###   ###     #   ###     #
# #   # #     #   # #     #
# #   # #     #   # #     #
# #   # #     #   # #     #
###   ###     #   ###     #

A: Finally got it. Others have posted solutions which are great. Here's mine if anyone's interested.
firstline = []
secondline = []
thirdline = []
fourthline =[]
fifthline = []

def concatenate_lines(firstline, secondline, thirdline, fourthline, fifthline):
    firstline.append(row1)
    secondline.append(row2)
    thirdline.append(row3)
    fourthline.append(row4)
    fifthline.append(row5)

num = input('enter a number: ')

for i in num:

    if i == '1':
        row1 = '  #'
        row2 = '  #'
        row3 = '  #'
        row4 = '  #'
        row5 = '  #'

        concatenate_lines(firstline, secondline, thirdline, fourthline, fifthline)

    elif i == '2':
        row1 = '###'
        row2 = '  #'
        row3 = '###'
        row4 = '#  '
        row5 = '###'

        concatenate_lines(firstline, secondline, thirdline, fourthline, fifthline)

    elif i == '3':
        row1 = '###'
        row2 = '  #'
        row3 = '###'
        row4 = '  #'
        row5 = '###'

        concatenate_lines(firstline, secondline, thirdline, fourthline, fifthline)

    elif i == '4':
        row1 = '# #'
        row2 = '# #'
        row3 = '###'
        row4 = '  #'
        row5 = '  #'

        concatenate_lines(firstline, secondline, thirdline, fourthline, fifthline)

    elif i == '5':
        row1 = '###'
        row2 = '#  '
        row3 = '###'
        row4 = '  #'
        row5 = '###'

        concatenate_lines(firstline, secondline, thirdline, fourthline, fifthline)

    elif i == '6':
        row1 = '###'
        row2 = '#  '
        row3 = '###'
        row4 = '# #'
        row5 = '###'

        concatenate_lines(firstline, secondline, thirdline, fourthline, fifthline)

    elif i == '7':
        row1 = '###'
        row2 = '  #'
        row3 = '  #'
        row4 = '  #'
        row5 = '  #'

        concatenate_lines(firstline, secondline, thirdline, fourthline, fifthline)

    elif i == '8':
        row1 = '###'
        row2 = '# #'
        row3 = '###'
        row4 = '# #'
        row5 = '###'

        concatenate_lines(firstline, secondline, thirdline, fourthline, fifthline)

    elif i == '9':
        row1 = '###'
        row2 = '# #'
        row3 = '###'
        row4 = '  #'
        row5 = '###'

        concatenate_lines(firstline, secondline, thirdline, fourthline, fifthline)

    elif i == '0':
        row1 = '###'
        row2 = '# #'
        row3 = '# #'
        row4 = '# #'
        row5 = '###'

        concatenate_lines(firstline, secondline, thirdline, fourthline, fifthline)

new1 = ' '.join(firstline)
new2 = ' '.join(secondline)
new3 = ' '.join(thirdline)
new4 = ' '.join(fourthline)
new5 = ' '.join(fifthline)

print(new1)
print(new2)
print(new3)
print(new4)
print(new5)

It has more lines compared to other solutions but I tried to keep it very readable.


text:
Q: regex to tokenize sentences python I have a task to tokenize sentences like
Python is good. C++ good as well. to Python is good. and C++ good as well.
My algorithm is doing this, but when it's Python is good.C++ good as well. (no space after dot) it doesn't work. By the way I need to consider that U.S.A. is 1 sentence. So my consideration is tokenize only if it's little character.BIG CHARACER.
I'm using something like
re.sub(r"/([.!?])([A-ZА-Я])/g", "/$1 /$2", 'Python is good.C++ is great')

but that doesn't help me.

A: My suggestion is to normalize the "old.New sentence" occurrences to "old. New sentence" by inserting a space, and then applying nltk.
The regex to insert the space could be
re.sub(r"\.([A-Z][a-zA-Z+#]* )", r". \1", 'Python is good.C++ is great.C# also')

'Python is good. C++ is great. C# also'

Now this text can be fed into nltk to tokenize it into sentences:
nltk.sent_tokenize('Python is good. C++ is great. C# also')

['Python is good.', 'C++ is great.', 'C# also']

A: If you really want to use regexp to split sentences, the easiest is to match punctuation instead of sentences,
>>> text = "Python is good. C++ is great. Another example: U.S.A."
>>> import re
>>> re.split('(?<=[!.?])', text)
['Python is good.', ' C++ is great.', ' Another example: U.', 'S.', 'A.', '']

this will not handle well all the edge cases though.
A better solution is to use either:

*

*nltk which implements the unsupervised Punkt sentence tokenizer with a pretrained model for English

*vtext which tokenizes sentences based on the Unicode Segmentation rules (language independent),

>>> from vtext.tokenize_sentence import UnicodeSentenceTokenizer
>>> tokenizer = UnicodeSentenceTokenizer()
>>> tokenizer.tokenize(text)
['Python is good. ', 'C++ is great. ', 'Another example: U.S.A.']


text:
Q: Calculate new position values in C# I have a document which containing some elements. The document is an INDD document. I am trying to show it in a webview but in a smaller size than the original size.
I am using ImageMapper (ASP.NET) to mark the different elements in the webview.
The problem is that I don´t get the correct positions in of the different spots in the webview.
I got the correct size of the new spots but not the position.
I made the calculations in the following way:
Original size (INDD document)
DocumentWidth = 768
DocumentHeight = 1024
New Size (Size of the webview)
Width = 522
Height = 696

percentW = newWidth(Webview)/DocumentWidth
percentH = newHeight(Webview)/DocumentHeight;

From these percent values I am calculating all the new values I will need in the ImageMapper (top,left,bottom,right).
Formula for that
myPrecent = (percentW/percentH) * 100;
        result =  myPrecent * ((top,left,right,bottom) / 100);

The result variable shall represent the new value which will be used in the spots within ImagMapper.
I suppose that I am thinking wrong in my calculation but I cant figured out what I´m doing wrong. So I will be appreciate if someone has any idea what I have doing wrong.

A: don't think of them as percentages, instead, think of them as scaling factors.
verticalScaling = Height/DocumentHeight
horizontalScaling = Width/DocumentWidth

newTop = Top * verticalScaling
newLeft = Left * horizontalScaling
newBottom = Bottom * verticalScaling
newRight = Right * horizontalScaling


text:
Q: If $\text{dim}(X \times X) = 2\text{dim}(X)$, does $\text{dim}(X^n) = n\text{dim}(X)$? I have been learning some (topological) dimension theory and have gotten through most of the basic material, at this point, and am about to start looking at papers.  In particular, I want to get familiar with the standard counterexamples regarding dimension of products, but I haven't noticed the question in the title addressed.
So my question would be what conditions on $X$ (e.g. separable metric, compact metric, continuum, homology manifold) are sufficient to ensure that if $\text{dim}(X \times X) = 2\text{dim}(X)$, then $\text{dim}(X^n) = n\text{dim}(X)$?  The initial assumption could also be weakened from $\text{dim}(X \times X) = 2\text{dim}(X)$ to $\text{dim}(X^m) = m\text{dim}(X)$ for some $1 < m < n$, or for various subsets of $\lbrace 2, 3, \dots, n - 1 \rbrace$.  The case $m = n - 1$ seems especially interesting.
In particular, have the dimensions of all the powers of the Pontryagin Surface been computed?
Edit after a couple of days: Dranishnikov (arguably the top living expert) says it is true for compact metric spaces.  He didn't mention any counterexample for more general spaces.  It was already known to Hurewicz in the 1930's to be true for compact metric spaces of dimension one.
As noted in the comments, it is known that for any compact Hausdorff or any metrizable space, the limit (called the stable dimension of $X$) $\lim \frac{\text{dim}(X^n)}{n}$ exists.  The quantity is positive if $X$ is compact metric and $\text{dim}(X) \geq 1$.  Thus to prove the titular proposition for compact metric spaces it's sufficient to prove the case $n = 4$, because we can then iterate and apply the uniqueness of the limit, using the fact that for reasonable spaces it is true that $\text{dim}(X \times Y) \leq \text{dim}(X) + \text{dim}(Y)$.  So if there was some pathology it would carry all the way to the limit.
This method assumes that if $\text{dim}(X) > 0$ then the stable dimension is positive; this is true for compact metric spaces, but is not true in general for separable metric spaces.  For example, let $E$ be Erdos Space.  It is known that $E = E \times E$ and $\text{dim}(E) = \text{dim}(E \times E) = 1$, so $\text{stabdim}(E) = 0$.  To see that it is true for (locally) compact metric spaces in dimension larger than $1$, use the small inductive dimension to obtain closed subspaces of dimension at least $1$ as boundaries of neighborhoods of a point, then apply the classical Hurewicz result mentioned above to see that in fact $\text{stabdim}(X) \geq 1$, since the product of these boundaries is closed and dimension is monotone wrt closed subsets.
This would extend the proof method to general compact Hausdorff spaces if we knew that the conjecture in the title were true for one-dimensional compact Hausdorff spaces (that it follows is due to the fact that for compact Hausdorff spaces $X$ we have $\text{dim}(X) \leq \text{ind}(X)$).  I am not sure if that is true or false, but I assume it's known.  Anybody have a reference?  Extending to LCH spaces is tricky in dimensions $0$ and $1$ so I have no idea about that, and I don't know if the stable dimension of LCH spaces is even well-defined.  That would also be good to know.

A: As John Samples noted in his comment, Dranishnikov's Theory of cohomological dimension implies the positive answer to this problem for compact (even $\sigma$-compact) metrizable spaces. Namely, according to a Definition on page 15 of the paper "Cohomological dimension theory of compact metric spaces" a compact metrizable space $X$ is called of basic type if $\dim X^2=2\dim X$ and of exceptional type if $\dim X^2=2\dim X-1$ (which is equivalent to $\dim X^2<2\dim X$ by Theorem 4.16). After this definition Dranishnikov writes that each compactum $X$ of basic type has $\dim X^n=n\dim X$ and each compactum $X$ of exceptional type has $\dim X^n=n\dim X-n+1$, for every $n\in\mathbb N$.
This implies that if some compactum $X$ has $\dim X^n=n\dim X$ for some $n\ge 2$, then it is of basic type and hence $\dim X^k=k\dim X$ for all $k\in\mathbb N$. Also the Dranishnikov's result implies that the stable dimension $\lim_{n\to\infty}\frac{\dim X^n}n$ of a compactum $X$ equals $\dim X$ if $X$ is of basic type and equals to $\dim X-1$ if it is of exceptional type.
In the first paragraph of Section 1 Dranishnikov writes: "Actually everywhere
in this paper one can replace compact spaces by σ-compact".


text:
Q: Need a date instead of datetime in SQL Server 2005 with dateadd I've got a query that get's a date of a field in a program. This date has to be modified with 10 years.
The query I made is
SELECT DATEADD(yy, +10, '"+thisfield.value+"')

where '"+thisfield.value+"' is coming from the program and is filled in like 01-08-2012.
The result of the query is 2022-07-31 00:00:00.000. The problem I have is that I just need 2022-08-01 but in the format of 01-08-2022 so that I can automatically fill an other field with this result.
In SQL Server 2005 the date function doesn't work only the datetime function and I just don't need that.
I hope this is clear (first time i post something). Can anyone help me?

A: You can either truncate the result, or cast it to DATE
CAST(DATEADD(yy, +10, '"+thisfield.value+"') AS DATE)"

CONVERT(VARCHAR, DATEADD(yy, +10, '"+thisfield.value+"'), 101)"

CONVERT using style 101 is in the format mm/dd/yyyy, which happens to be the format you want.  Keep in mind that you can format the result however you want in your application for display purposes which is better than returning strings from SQL Server.
Also note that you should look into parameterized queries and/or stored procedures.


text:
Q: Pygame sprites behaving incorrectly when moving left Alright so following up to my previous question I've made some progress, game has the addition of left and right movement and a simple jump script, evolution woo :D
My latest addition was an Idle animation and now the dude can't move left :D
I hope its not too silly I checked everything but can't point out the issue >.> ..
regardless here's the code, Thanks in advance, truly appreciative! (origination is awful srry >.<):
import pygame

pygame.init()

path = "C:/Users/user/Documents/Le game/"
win = pygame.display.set_mode((800, 700))
pygame.display.set_caption("Potato ultra")
bg = pygame.image.load(path + "BG.jpg")
walk_right = [pygame.image.load("C:/Users/user/Documents/Le game/R2.png"), pygame.image.load("C:/Users/user/Documents/Le game/R3.png"), pygame.image.load("C:/Users/user/Documents/Le game/R4.png"), pygame.image.load("C:/Users/user/Documents/Le game/R5.png"), pygame.image.load("C:/Users/user/Documents/Le game/R6.png"), pygame.image.load("C:/Users/user/Documents/Le game/R7.png"), pygame.image.load("C:/Users/user/Documents/Le game/R8.png"), pygame.image.load("C:/Users/user/Documents/Le game/R9.png")]
walk_left = [pygame.image.load("C:/Users/user/Documents/Le game/L2.png"), pygame.image.load("C:/Users/user/Documents/Le game/L3.png"), pygame.image.load("C:/Users/user/Documents/Le game/L4.png"), pygame.image.load("C:/Users/user/Documents/Le game/L5.png"), pygame.image.load("C:/Users/user/Documents/Le game/L6.png"), pygame.image.load("C:/Users/user/Documents/Le game/L7.png"), pygame.image.load("C:/Users/user/Documents/Le game/L8.png"), pygame.image.load("C:/Users/user/Documents/Le game/L9.png")]
Static = pygame.image.load("C:/Users/user/Documents/Le game/Idle.png")

SW = 800
SH = 700
x = 0
y = 480
width = 64
height = 64
vel = 20
isJump = False
MoveLeft = False
MoveRight = False
Idle = False
JumpCount = 10
walkCount = 0

def redrawGameWindow():

    win.blit(bg, (0,0))
    global walkCount
    if not Idle:
        if MoveRight:
            if walkCount <= 7:
                win.blit(walk_right[walkCount], (x, y))
            elif walkCount > 7:
                walkCount = 0
                win.blit(walk_right[walkCount], (x, y))
        if MoveLeft:
            if walkCount <= 7:
                win.blit(walk_left[walkCount], (x, y))
            elif walkCount > 7:
                walkCount = 0
                win.blit(walk_left[walkCount], (x, y))
    else:
        win.blit(Static, (x, y))

    pygame.display.update()

run = True
while run:
    pygame.time.delay(50)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()

    if keys[pygame.K_LEFT] and x > 0:
        Idle = False
        MoveRight = False
        MoveLeft = True
        x -= vel
        walkCount += 1
    if keys[pygame.K_RIGHT] and x < SW - width:
        Idle = False
        MoveRight = True
        MoveLeft = False
        x += vel
        walkCount += 1
    else:
        Idle = True

    if not isJump:
        if keys[pygame.K_UP] and y > 0:
            y -= vel
            if y < 0:
                y = 0
        if keys[pygame.K_DOWN] and y < SH - height:
            y += vel
            if y > 636:
                y = 636
        if keys[pygame.K_SPACE]:
            isJump = True
    else:
        if JumpCount >= -10:
            y -= (JumpCount * 4)
            if y < 0:
                y = 0
            JumpCount -= 2
        else:
            isJump = False
            JumpCount = 10

    redrawGameWindow()

pygame.quit()

A: Well, the first thing I would do would be to add the following code (before the final line below, which you already have):
print("DEBUG1 keyl =", keys[pygame.K_LEFT], "x =", x)
print("DEBUG2 keyr =", keys[pygame.K_RIGHT], "SW =", Sw, "wid =", width)
print("DEBUG3 mover =", MoveRight, "movel =", MoveLeft)
print("DEBUG4 vel =", vel, "walkc =", walkCount)
print("DEBUG5 ==========")
if keys[pygame.K_LEFT] and x > 0:

That way, you'll see all the variables that take part in deciding left and right moves, and it will hopefully become obvious what is preventing the left move from functioning.

Based on a slightly deeper look at your code, it appears to be this bit:
if keys[pygame.K_LEFT] and x > 0:
    Idle = False
    MoveRight = False
    MoveLeft = True
    x -= vel
    walkCount += 1
if keys[pygame.K_RIGHT] and x < SW - width:
    Idle = False
    MoveRight = True
    MoveLeft = False
    x += vel
    walkCount += 1
else:
    Idle = True

Since that else belongs only to the second if statement, it will fire whenever the right key is not being pressed, regardless of whether you're pressing the left key.
I suspect you can fix this simply by changing it from an if, if, else sequence to an if, elif, else sequence, so that the else fires only if neither of the keys are pressed.

A couple of possible improvements to your code:

*

*you can get rid of all that walkCount checking and adjusting in the redraw function by simply using walkCount = (walkCount + 1) % 8 in the event loop - this will ensure it wraps from seven to zero without further effort.

*you don't appear to have limiters on the x value. For example, if x == 5 and vel == 10, it's possible that a left move will set x = -5 which may not be desirable. You have more knowledge of the game play than me so I could be wrong, but it's worth checking.

*you may not need both MoveLeft and MoveRight. The Idle flag decides whether you're moving or not so, if you are moving, it's either left or right. So a Idle/MoveRight combo should be enough for the code to figure out what to do. Again, this is a gameplay issue, something to look at but I may be incorrect.

*not sure how your sprites look when they jump but you may be better off using constant acceleration formulae for calculating y position. I've answered similar questions before so you can have a look at this answer for guidance.


text:
Q: \expandafter usage and plain TeX programming Hello everybody out there using TeX,
Actually, I wanted to write a LaTeX macro in plain TeX in order to include source code examples with individual modifications like stripping off comments and the first 21 characters in LaTeX documents. My code so far looks as follows:
\documentclass{article}
\edef\hashmark{\string#}
\def\getfirst#1#2\getfirst{\string#1}
\def\gobble#1#2{\expandafter#2}
\newread\myread
\begin{document}
\openin\myread=complete.txt
  \newcount\linecount
  \global\linecount1
  \loop
    \unless\ifeof\myread
    \read\myread to \myinput
    \if\hashmark\expandafter\getfirst\detokenize\expandafter{\myinput}\getfirst
      \relax
    \else
      \newcount\position
      \global\position1
      {
        \loop
          \unless\ifnum\position>21
            \edef\myinput{\expandafter\gobble\myinput}
            \global\advance\position1
        \repeat
      }
    \fi
    \global\advance\linecount1
  \repeat
\closein\myread
\end{document}

This results in the error message ! Paragraph ended before \gobble was complete.
Unfortunately, this is already for the second time I have to ask for help here, because I'm lacking experience in developing TeX and interpreting the error messages.
All these difficulties in manipulating text input using TeX make me wonder, whether it makes really sense to use TeX to manipulate and trim my source code files instead of say sed, Perl, Python or any other programming language in which I have more experience and allowing for easy text manipulation.
Any contribution to this consideration is appreciated.

A: The origin of the problem were empty lines as well as the last line in the input file.
So, yes, I should have added a typical input file as a pointer towards this problem. Sorry for having missed that.
Checking for lines beginning with \par seems to fix that as far as I can see:
\documentclass{article}
\def\apar{\par}
\edef\hashmark{\string#}
\def\getfirst#1#2\getfirst{\string#1}
\def\gobble#1#2{\expandafter#2}
\newread\myread
\begin{document}
\openin\myread=complete.txt
  \newcount\linecount
  \global\linecount1
  \loop
    \unless\ifeof\myread
    \read\myread to \myinput
    \if\hashmark\expandafter\getfirst\detokenize\expandafter{\myinput}\getfirst
        \relax
      \else
        \xdef\mystring{\expandafter\myinput}
        \ifx\mystring\apar
            \relax
          \else
            \newcount\position
            \global\position1
            {
              \loop
                \unless\ifnum\position>1
                  \xdef\mystring{\expandafter\gobble\mystring}
                  \global\advance\position1
              \repeat
            }
          \fi
        \mystring
      \fi
    \global\advance\linecount1
  \repeat
\closein\myread
\end{document}


text:
Q: How do I run commands as a non-root user in a script started with root permissions? The problem
In a bash script, I am using the command...
sudo -u node bash

.. to switch from root to a non-sudo user, and this is failing.
The context
I am writing a provision.sh script for Vagrant, to set up a server running Ubuntu 16.04.3 with all the packages required to deliver an app with Meteor 1.6.
One required step is to install nvm as a non-root user. After nvm is installed, you need to log out and log back in again in order to activate nvm. I therefore create a non-sudo user named meteor, and want to switch to that when I download and install nvm.
Subsequently, I want to switch back to being root and log in gain immediately as meteor, in order to start using nvm to install Node.js.
You'll find a heavily commented script below. Vagrant runs this script each time I call vagrant reload --provision.
What command should I be using instead of sudo -u node bash?

echo "# whoami" && whoami && echo "^^^^ root expected"
echo "As root, create non-sudo user meteor:"
pass=$(perl -e 'print crypt($ARGV[0], "password")' $password)
useradd -m -p $pass meteor
echo "User meteor created. ls -al /home/meteor:"
ls -al /home/meteor
echo "Install curl as root:"
apt-get install -y curl
echo "Trying sudo -u meteor bash"
sudo -u meteor bash #### THIS IS THE LINE THAT FAILS ###

echo "$ whoami" && whoami && echo "^^^^^^ meteor expected"
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.6/install.sh | bash
echo "ls -al /home/meteor/.nvm # should be populated"
ls -al /home/meteor/.nvm

echo "ls -al /root/.nvm # should not exist"
ls -al /root/.nvm

echo "command -v nvm will fail silently until we log out and back in again"
#command -v nvm
exit

#### Because the script is still running as root, it halts here ####

echo "# whoami" && whoami && echo "^^^^ should be root"
sudo -u meteor bash
echo "$ whoami" && whoami && echo "^^^^^^ should be meteor"
echo "command -v nvm should work now"
command -v nvm

A: If you start your script with root permissions but need to run certain commands as a specific non-root user you can use sudo with the -u option to either run a single command with e.g.
sudo -u USERNAME whoami # outputs USERNAME's user name

or start a subshell and run your commands in it, e.g.:
sudo -u USERNAME bash -c 'whoami;echo $USER' # outputs USERNAME's user name twice

The line in your script doesn't fail actually, you just run only bash as user meteor, and as bash has nothing to do it just exits and the original root shell runs the rest of the script. What you actually want to do (I suppose) is:
…
echo "Trying sudo -u meteor bash"
sudo -u meteor bash -c '\
  echo "$ whoami" && whoami && echo "^^^^^^ meteor expected"
  curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.6/install.sh |\
  bash
'
echo "ls -al /home/meteor/.nvm # should be populated"
…

Another way to achieve the same is a here document:
…
echo "Trying sudo -u meteor bash"
sudo -u meteor bash <<EOF
  echo "$ whoami" && whoami && echo "^^^^^^ meteor expected"
  curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.6/install.sh |\
  bash
EOF
echo "ls -al /home/meteor/.nvm # should be populated"
…

A: If you're in a container environment, the gosu project could be of interest.  It is intended to solve the issue that su and sudo have very strange and often annoying TTY and signal-forwarding behavior.
A few nice alternatives are mentioned in the gosu project's README.md:

*

*chroot --userspec may already be installed

*su-exec https://github.com/ncopa/su-exec

*setpriv from the (Debian) util-linux package https://manpages.debian.org/buster/util-linux/setpriv.1.en.html

A: #! /bin/bash
#  (GPL3+) Alberto Salvia Novella (es20490446e)

execute () {
    function="${1}"
    command="${2}"
    error=$(eval "${command}" 2>&1 >"/dev/null")

    if [ ${?} -ne 0 ]; then
        echo "${function}: $error"
        exit 1
    fi
}

executeAsNonAdmin () {
    function="${1}"
    command="${2}"

    eval setPasswordAsker="SUDO_ASKPASS=/usr/libexec/openssh/ssh-askpass"
    run="runuser ${SUDO_USER} --session-command=\"${setPasswordAsker}\" --command=\"${command}\""
    execute "${function}" "${run}"
}

executeAsNonAdmin "" "${@}"


text:
Q: How to check if splitting fields of different polynomials share a subfield? First, some context: I'm working through the section on galois theory in Lang's Algebra in preparation for my qual. Exercise $1$ part $(j)$ asks us to compute the galois group of $(x^2 - 2)(x^2 - 3)(x^2 - 5)(x^2 - 7)$ over $\mathbb{Q}$.
Since each irreducible factor is of degree $2$, and the fields are obviously not equal, their pairwise intersections are all $\mathbb{Q}$ (since there's no room for the intersection to be anything else). This means we can apply the theorem on galois groups of composita to get the answer $C_2 \times C_2 \times C_2 \times C_2$.
However, I'm not sure how I would go about showing this in a more complicated example.
For instance, the galois group of $(x^2 + 3)(x^2 + x + 1)$ is just $C_2$, since $\mathbb{Q}\left ( \sqrt{-3} \right ) = \mathbb{Q}(\omega)$ (in $\mathbb{C}$, say). It's extremely non-obvious (at least to me) that these polynomials would be related, and if I didn't happen to know $\omega = \frac{-1 + \sqrt{-3}}{2}$ is a cube root of unity, I would have guessed that this polynomial had galois group $C_2 \times C_2$ (by an argument analogous to the previous one).
So the question, then:

If I'm asked to compute the galois group of a polynomial that factors into irreducibles as $f_1 f_2 \cdots f_n$, what are some strategies for checking that the roots don't "interact"? That is, if $E_j$ is the splitting field of $f_j$, how can we be sure that $E_i \cap E_j = \mathbb{Q}$? Conversely, if the roots do interact, is there a way of detecting this?

Thanks in advance! ^_^


text:
Q: Why does my font not appear on some computers? But i can look at other fonts on different websites that i don't have installed? Don't know if this is the right place to ask, but I am quite new to html, have made a complete site and uploaded to web server.
But i tried visiting the site on another device, and the font shows differently, but then when i go onto a website which has a different font it shows fine on their site.
Am i doing something wrong?
Cheers
Adam

A: Because the computer doesn't have that font, and you didn't include the font to download, just an instruction as to which one to use.
The CSS @fontface instruction lets you direct a browser to a file with a font.
A simpler and lighter approach, is to suggest back-ups. E.g. Instead of:
font-family: arial;

You could use:
font-family: arial, verdana, sans-serif;

The first will try to use Arial, and if it isn't available, will just use the default font for the browser (which could be a serif font like Times, for example).
The second will try to use Arial. If that's not available, it will try to use Verdana. If that's not available, it will try to use the default sans-serif font for the browser, which should at least be closer than a serif font.

A: Here is a great tutorial on how to create custom fonts on a website.
http://blog.themeforest.net/tutorials/how-to-achieve-cross-browser-font-face-support/
It will also explain which types of fonts are compatible on certain browsers


text:
Q: If a closed linear operator is one to one on a dense set, then is it one to one on the whole set? I am looking at the proof of the following proposition.
Here $A$ is a closed linear operator on $L$, that is, the graph of $A$ is closed subspace of $L \times L$. And $\lambda$ is said to belong to the resolvent set $\rho(A)$ of $A$, if $\lambda - A(\equiv \lambda I-A)$ is one-to-one, Range($\lambda - A)=L$, and $(\lambda - A)^{-1}$ is a bounded linear operator on $L$.

In the proof, as shown below, (2.6) shows that $\lambda-A$ is one-to-one on $\mathcal{D}(A)$, which is a dense subset of the vector space $L$ by a theorem preceding this. However, I don't see how this fact directly means that $\lambda - A$ is one-to-one on $L$. If a closed linear operator is one to one on a dense set, then is it one to one on the whole set? I would greatly appreciate any explanation on this line of the proof.

A: You have
$$D(\lambda - A)=\{x\in L:\lambda x - Ax \in L\} = \{x\in L : Ax\in L\}=D(A)$$
because $\lambda x - Ax$ lies in $L$ iff $Ax$ lies in $L$.
So you only need it to be injective on $D(A)$. $U_{\lambda}$ takes care of both its surjectivity and injectivity.
Finally, once that's done it is autumatically invertible. This is applies to slightly more general case:

Lemma: Suppose that $A$ is a closed linear operator on a Banach Space $X$, then it is invertible iff it is bijective onto $X$.

Clearly if it is invertible then it is bijective onto $X$. So the converse is interesting one;
Let $G(A)$ denote its graph, and suppose that $A$ is bijective onto $X$. Then its algebraic inverse exists, call it $B$. Then the map $(x,y)\mapsto (y,x)$ from $G(A)$ bijective onto $G(B)$ is a homeomorhpism, so $G(A)$ closed implies $G(B)$ is closed. Now as $X$ is complete, and $B$ is a bijection from $X$ onto $D(A)$, by closed graph theorem $B$ is bounded. So $A$ is invertible