Transferring files over home network WiFi

Question: I've got 2 PCs with Linux distributions installed (one has Ubuntu 17.04 the other Mint 17.3) and I'd like to know how to transfer files between one another over my WiFi-network.
I would like to do that without having to install programs or using GUIs;
I want to use the terminal.
Comment: You can do this with samba or any network protocol (http, ftp, ssh (scp), sshfs, etc). I thinks only samba requires no installation of packages, but I am not certain.
Comment: Use SCP - described here:
https://askubuntu.com/questions/560777/how-to-copy-files-between-two-computers-using-ssh https://askubuntu.com/questions/329370/using-scp-to-copy-files-from-remote-to-home-machine
Answer: Assuming, you want to transfer files from system A to system B

Find IP address of system A (wireless)

ifconfig

Go to the directory you have the files to share

cd /directory

Start that directory as HTTP server

python -m SimpleHTTPServer

Go to system B and install links (terminal browser) package

sudo apt-get install links

Start links with system A IP (assuming 192.168.2.1) and port which shows in third step (probably 8000)

links 192.168.2.1:8000

Download whatever files you want

If security is not your concern and simply want to transfer files without any configuration, this is perfect for you, I guess.
Comment: No such module looks like. Deprecated?
Comment: The SimpleHTTPServer module has been merged into http.server in Python 3.0. So, your command is python -m http.server, or depending on your installation, it can be: python3 -m http.server.
Answer: This is slightly beyond what you are asking for, but I would recommend that you install the program package openssh-server into one of the computers. I know that it is easy to install and works well in Ubuntu, because I use it.
Connect from the other computer via the program sftp to transfer files (or via ssh to log in and run programs remotely). This can be done completely via the command line (in a terminal which you wish now, or via GUI program if you wish later on).
These backup tools are designed to work well with an ssh server: rsync and Clonezilla.
The following links describe installing openssh-server and using sftp, ssh with more details,

help.ubuntu.com/14.04/serverguide/openssh-server.html
How do you send and receive data from one machine to another?
Filezilla crashes ubuntu 16.04 lts- Please suggest alternate
What is the simplest way to have remote GUI access to Ubuntu 16.04 "server" from Ubuntu 16.04 "desktop"?
Comment: @IDK, Please notice that the backup tools rsync and Clonezilla work well with an ssh server, if you wish to backup via the local [wireless] network.
Comment: thanks for the advice in the comment, I've actually done a local backup with tar  and I'd need a little help to figure some things out.                                                 I've edited my question  here : https://askubuntu.com/questions/954245/back-up-ubuntu-17-04


different partition size in parted and in df

Question: Can anyone explain the difference between partition size in parted and in df?
root@HOME:~# parted /dev/sda
GNU Parted 2.3
Using /dev/sda
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted) u s
(parted) p
Model: ATA Samsung SSD 850 (scsi)
Disk /dev/sda: 488397168s
Sector size (logical/physical): 512B/512B
Partition Table: gpt

Number  Start       End         Size        File system  Name                  Flags
 1      2048s       206847s     204800s     fat32        EFI                   boot
 2      206848s     468991s     262144s                                        msftres
 3      468992s     134686719s  134217728s  ntfs         Win10                 msftdata
 4      134686720s  268904447s  134217728s  ext4         ubuntu
 5      268904448s  436676942s  167772495s  ntfs         Basic data partition  msftdata

(parted) q
root@HOME:~# df -BG
Filesystem     1G-blocks  Used Available Use% Mounted on
/dev/sda4            63G    7G       53G  12% /
none                  1G    0G        1G   0% /sys/fs/cgroup
udev                  4G    1G        4G   1% /dev
tmpfs                 1G    1G        1G   1% /run
none                  1G    0G        1G   0% /run/lock
none                  4G    1G        4G   1% /run/shm
none                  1G    1G        1G   1% /run/user
/dev/sda1             1G    1G        1G  30% /boot/efi
root@HOME:~#

Size of /dev/sda4 is 134.217.728 sectors, which is 134.217.728*512 = 68.719.476.736 bytes.
It is EXACTLY 64GiB, as 64*1024*1024*1024 = 68.719.476.736
Why df shows "63G" ?
Comment: could be related to this http://superuser.com/questions/289678/du-vs-df-output
Comment: My question is not about the free size inside a partition, but about the overall partition size. I don't see any relation to that thread.
Comment: Have you tried `df -H`?  Tells it to use the powers of 1000 and not 1024.
Comment: `parted` with `u kib` shows 67108864kiB
It is correct: 67.108.864 / 1024 / 1024 = 64

`df -BK` shows 65922812K
It is wrong: 65922812 / 1024 / 1024 = 62.86889267
Comment: `df -H` shows 68G - totally wrong
`df -h` shows 63G - it is also wrong...
Comment: Take a look at this answer http://unix.stackexchange.com/a/10778/111521  Looks like a pretty good explanation of where the size goes.
Comment: Thank you, Terrance. That's really should be the answer...
Comment: You're very welcome!  =)
Answer: I assume that df shows the space available in the file system (without structures needed for the file system itself maybe?), whereas parted probably reports the outer size of the partition.
Other than that, the output of df -BG seems to be rounded down to full GigaBytes. I think that the sizes would differ less if you let df output smaller (optimally the same as parted i.e. 512 bytes) units.
Comment: df -BK (the smallest unit for df, I assume) shows
`root@HOME:~# df -BK
Filesystem     1K-blocks     Used Available Use% Mounted on
/dev/sda4      65922812K 7033496K 55517440K  12% /`
Which is also wrong:
65.922.812 / 1024 / 1024 = 62.86889267
Comment: `df -B512` shows 131.845.624

It is also wrong, according to `parted` is should be 134.217.728
Comment: @Tice As you're a reputation 6 user: If this answer helped you, don't forget to click the grey **☑** at the left of this text, which means [Yes, this answer is valid](http://askubuntu.com/help/accepted-answer)!  **;-)**


Projection problem interpretation

Question: Problem: Describe the projective transformations of $FP^n$ that preserve the $FP^{n−1}$ at infinity given by $x_0 = 0$.
My attempt: We have to preserve the points with first coordinate $0$, i.e. the transformation maps $[0, x_1, x_2...x_n]$ to $[0, y_1, ...y_n]$. I can see why we can represent $FP^n$ as the disjoint union of $F^n$ and $FP^{n-1}$ and the latter is basically what we want to preserve. Now I also know that a projective transformation is given by $v$   -> $[Tv]$, where $T:R^n$ -> $R^n$ is injective. I just can't seem to finalize the argument.
Thank you in advance
Rick M
Answer: Hint
Let's work with vector spaces : if $V = F^{n+1}$ with basis $B = (e_0, e_1, \dots, e_n)$ you are asking for matrices $g \in GL(V)$ such that $g(W) = W$ where $W$ has basis $(e_1, \dots, e_n)$. Do you agree ? Do you see how to finish ?
Comment: Hey, yup this is correct. What I found was that the first row of the matrix of transformation is $(a,0,0,....0)$. Also, that the right-down block matrix can't be 0 and needs to have determinant $\neq 0$.
Comment: Exactly. ${{{}}}$
Comment: Wait, is this actually what the question wants us to do? It is a lot simpler than expected. You are the best, really appreciate it! :)
Comment: Sure you're welcome, you did find by yourself :)

Projection problem interpretation


How to force scale_y_datetime scale to show 24:00 instead of 00:00 in R

Question: I have the following data.frame named qq.
head(qq)
  my_year  my_time
1    2004 20:08:04
2    2004 10:22:40
3    2004 15:55:26
4    2004 15:54:00
5    2004 07:29:26
6    2004 13:23:16

I want to plot my_time vs my_year (only one year in this toy example).
ggplot(qq, aes(factor(my_year),
                    as.POSIXct(my_time,
                    format = "%H:%M:%S"))) +
 ggbeeswarm::geom_quasirandom()+
 theme_bw() + xlab("")+
 ylab("Time of the day")+
 scale_y_datetime(breaks = "2 hour",
                  date_labels= "%H:%M")

QUESTION: How can I force the y axis to go from 0:00 to 24:00? In this case, data does not go to more than 23:00 but, when it does, the y axis shows 0:00 instead of 24:00.
You can also reproduce this issue with this data if you do
scale_y_datetime(breaks = "1 hour", ...)
Here's the data in case you want to reproduce the issue.
dput(qq)
structure(list(my_year = c(2004, 2004, 2004, 2004, 2004, 2004,
2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004,
2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004,
2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004,
2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004,
2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004,
2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004,
2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004,
2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004,
2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004), my_time = structure(c(72484L,
37360L, 57326L, 57240L, 26966L, 48196L, 48047L, 47931L, 71027L,
78931L, 32144L, 40831L, 31545L, 31092L, 73992L, 39895L, 76988L,
70303L, 52993L, 77522L, 53289L, 43273L, 52609L, 58788L, 69625L,
83071L, 60847L, 62218L, 75594L, 58615L, 38332L, 45811L, 75290L,
3063L, 67321L, 74520L, 74248L, 47665L, 54416L, 33803L, 32515L,
32428L, 40518L, 61085L, 63825L, 66352L, 73773L, 67165L, 37659L,
47710L, 49206L, 72484L, 37360L, 57326L, 57240L, 26966L, 48196L,
48047L, 47931L, 71027L, 78931L, 32144L, 40831L, 31545L, 31092L,
73992L, 39895L, 76988L, 70303L, 52993L, 77522L, 53289L, 43273L,
52609L, 58788L, 69625L, 83071L, 60847L, 62218L, 75594L, 58615L,
38332L, 45811L, 75290L, 3063L, 67321L, 74520L, 74248L, 47665L,
54416L, 33803L, 32515L, 32428L, 40518L, 61085L, 63825L, 66352L,
73773L, 67165L, 37659L, 47710L, 49206L), class = "ITime")), class = "data.frame", row.names = c(NA,
-102L), .Names = c("my_year", "my_time"))

Comment: Wouldn't your desired labels imply that there are 25 unique values for 'variable hour' ?
Comment: @markus Can we switch the labels without caring about the actual values?
Answer: One approach would be to move out of the ITime format and use a numeric scale with labels that look like hours:
qq %>%
  mutate(hour_num = my_time %>% as.integer() %>% `/` (60*60)) %>%
  ggplot(aes(factor(my_year), hour_num)) +
  ggbeeswarm::geom_quasirandom()+
  theme_bw() + xlab("")+
  ylab("Time of the day") +
  scale_y_continuous(breaks = 2*0:12,
                     labels = function(x) {paste0(floor(x),":00")})

Comment: Looks like I should accept this answer, but going to leave the question open for a little while just to see whether someone comes with another way of doing it.


Getting rid of cPanel's default page

Question: I've uploaded my site to my public_html folder, however I'm still getting the default cPanel page.
I've tried using both index.html and index.php files with no success. For some reason it's not realizing that I've got a valid home file in there.
Does anyone have any ideas on how to get this fixed?
Comment: Can you access index.html when you access the file through your domain? ex www.mysite.com/index.html
Answer: Make sure that your domain is configured to point to account IP address. Account IP address you can see in your cPanel user interface in the left info section. Finally, DNS A record of your domain should be equal to it.

Getting rid of cPanel's default page


Extract 14-bit values from an array of bytes in C

Question: In an arbitrary-sized array of bytes in C, I want to store 14-bit numbers (0-16,383) tightly packed. In other words, in the sequence:
0000000000000100000000000001

there are two numbers that I wish to be able to arbitrarily store and retrieve into a 16-bit integer. (in this case, both of them are 1, but could be anything in the given range) If I were to have the functions uint16_t 14bitarr_get(unsigned char* arr, unsigned int index) and void 14bitarr_set(unsigned char* arr, unsigned int index, uint16_t value), how would I implement those functions?
This is not for a homework project, merely my own curiosity. I have a specific project that this would be used for, and it is the key/center of the entire project.
I do not want an array of structs that have 14-bit values in them, as that generates waste bits for every struct that is stored. I want to be able to tightly pack as many 14-bit values as I possibly can into an array of bytes. (e.g.: in a comment I made, putting as many 14-bit values into a chunk of 64 bytes is desirable, with no waste bits. the way those 64 bytes work is completely tightly packed for a specific use case, such that even a single bit of waste would take away the ability to store another 14 bit value)
Comment: The technique you are describing is called "packing bits" or "bit packing." If you know that, finding information on how to do it is much easier.  In particular, http://www.catb.org/esr/structure-packing/
Comment: @RobertHarvey -  The article linked to seems mostly about ordering of structure members to avoid padding.
Comment: It's about word alignment.  You're going to need to know about that.  There are plenty of other articles I didn't link.
Comment: I don't think two 14-bit numbers will fit into a 16-bit integer. It should be array of 16-bit integers.
Comment: @MikeCAT: It is.  Read the question again.
Comment: Definitely an interesting problem.  But if you're doing this to save memory, think about how many more bytes of memory will have to be devoted to code to save those two bits of RAM from simply using `int64_t` or `uint16_t`.
Comment: @AndrewHenle: While you might be right, my basic idea is to limit the program's total working memory used to 20MB, where I have a 64 byte chunk of memory describing offsets into chunks of memory where a total of 16,000 items can be in those chunks, with 8 bytes reserved in the 64 bytes for a 64 bit "user data" pointer. This gives 32 "pointers" to items in a chunk of memory that can fit into a CPU L1 cache line, with theoretically zero malloc calls, and easy cache-friendly iteration with almost no memory being consumed by the program. (not including bytes spent on compiled code)
Answer: Well, this is bit fiddling at its best. Doing it with an array of bytes makes it more complicated than it would be with larger elements because a single 14 bit quantity can span 3 bytes, where uint16_t or anything bigger would require no more than two. But I'll take you at your word that this is what you want (no pun intended).  This code will actually work with the constant set to anything 8 or larger (but not over the size of an int; for that, additional type casts are needed). Of course the value type must be adjusted if larger than 16.
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#define W 14

uint16_t arr_get(unsigned char* arr, size_t index) {
  size_t bit_index = W * index;
  size_t byte_index = bit_index / 8;
  unsigned bit_in_byte_index = bit_index % 8;
  uint16_t result = arr[byte_index] >> bit_in_byte_index;
  for (unsigned n_bits = 8 - bit_in_byte_index; n_bits < W; n_bits += 8)
    result |= arr[++byte_index] << n_bits;
  return result & ~(~0u << W);
}

void arr_set(unsigned char* arr, size_t index, uint16_t value) {
  size_t bit_index = W * index;
  size_t byte_index = bit_index / 8;
  unsigned bit_in_byte_index = bit_index % 8;
  arr[byte_index] &= ~(0xff << bit_in_byte_index);
  arr[byte_index++] |= value << bit_in_byte_index;
  unsigned n_bits = 8 - bit_in_byte_index;
  value >>= n_bits;
  while (n_bits < W - 8) {
    arr[byte_index++] = value;
    value >>= 8;
    n_bits += 8;
  }
  arr[byte_index] &= 0xff << (W - n_bits);
  arr[byte_index] |= value;
}

int main(void) {
  int mod = 1 << W;
  int n = 50000;
  unsigned x[n];
  unsigned char b[2 * n];
  for (int tries = 0; tries < 10000; tries++) {
    for (int i = 0; i < n; i++) {
      x[i] = rand() % mod;
      arr_set(b, i, x[i]);
    }
    for (int i = 0; i < n; i++)
      if (arr_get(b, i) != x[i])
        printf("Err @%d: %d should be %d\n", i, arr_get(b, i), x[i]);
  }
  return 0;
}

Faster versions  Since you said in comments that performance is an issue: open coding the loops gives a roughly 10% speed improvement on my machine on the little test driver included in the original. This includes random number generation and testing, so perhaps the primitives are 20% faster. I'm confident that 16- or 32-bit array elements would give further improvements because byte access is expensive:
uint16_t arr_get(unsigned char* a, size_t i) {
  size_t ib = 14 * i;
  size_t iy = ib / 8;
  switch (ib % 8) {
  case 0:
    return (a[iy] | (a[iy+1] << 8)) & 0x3fff;
  case 2:
    return ((a[iy] >> 2) | (a[iy+1] << 6)) & 0x3fff;
  case 4:
    return ((a[iy] >> 4) | (a[iy+1] << 4) | (a[iy+2] << 12)) & 0x3fff;
  }
  return ((a[iy] >> 6) | (a[iy+1] << 2) | (a[iy+2] << 10)) & 0x3fff;
}

#define M(IB) (~0u << (IB))
#define SETLO(IY, IB, V) a[IY] = (a[IY] & M(IB)) | ((V) >> (14 - (IB)))
#define SETHI(IY, IB, V) a[IY] = (a[IY] & ~M(IB)) | ((V) << (IB))

void arr_set(unsigned char* a, size_t i, uint16_t val) {
  size_t ib = 14 * i;
  size_t iy = ib / 8;
  switch (ib % 8) {
  case 0:
    a[iy] = val;
    SETLO(iy+1, 6, val);
    return;
  case 2:
    SETHI(iy, 2, val);
    a[iy+1] = val >> 6;
    return;
  case 4:
    SETHI(iy, 4, val);
    a[iy+1] = val >> 4;
    SETLO(iy+2, 2, val);
    return;
  }
  SETHI(iy, 6, val);
  a[iy+1] = val >> 2;
  SETLO(iy+2, 4, val);
}

Another variation
This is quite a bit faster yet on my machine, about 20% better than above:
uint16_t arr_get2(unsigned char* a, size_t i) {
  size_t ib = i * 14;
  size_t iy = ib / 8;
  unsigned buf = a[iy] | (a[iy+1] << 8) | (a[iy+2] << 16);
  return (buf >> (ib % 8)) & 0x3fff;
}

void arr_set2(unsigned char* a, size_t i, unsigned val) {
  size_t ib = i * 14;
  size_t iy = ib / 8;
  unsigned buf = a[iy] | (a[iy+1] << 8) | (a[iy+2] << 16);
  unsigned io = ib % 8;
  buf = (buf & ~(0x3fff << io)) | (val << io);
  a[iy] = buf;
  a[iy+1] = buf >> 8;
  a[iy+2] = buf >> 16;
}

Note that for this code to be safe you should allocate one extra byte at the end of the packed array.  It always reads and writes 3 bytes even when the desired 14 bits are in the first 2.
One more variation Finally, this runs just a bit slower than the one above (again on my machine; YMMV), but you don't need the extra byte. It uses one comparison per operation:
uint16_t arr_get2(unsigned char* a, size_t i) {
  size_t ib = i * 14;
  size_t iy = ib / 8;
  unsigned io = ib % 8;
  unsigned buf = ib % 8 <= 2
      ? a[iy] | (a[iy+1] << 8)
      : a[iy] | (a[iy+1] << 8) | (a[iy+2] << 16);
  return (buf >> io) & 0x3fff;
}

void arr_set2(unsigned char* a, size_t i, unsigned val) {
  size_t ib = i * 14;
  size_t iy = ib / 8;
  unsigned io = ib % 8;
  if (io <= 2) {
    unsigned buf = a[iy] | (a[iy+1] << 8);
    buf = (buf & ~(0x3fff << io)) | (val << io);
    a[iy] = buf;
    a[iy+1] = buf >> 8;
  } else {
    unsigned buf = a[iy] | (a[iy+1] << 8) | (a[iy+2] << 16);
    buf = (buf & ~(0x3fff << io)) | (val << io);
    a[iy] = buf;
    a[iy+1] = buf >> 8;
    a[iy+2] = buf >> 16;
  }
}

Comment: I'd be interested in seeing a version that operates on an array of uint16_t. But as it is, this looks to be the best solution for my purposes as it seems to be the fastest solution. (though I wonder if operating on an array of uint16_t would be even faster)
Comment: @Freezerburn You didn't mention that speed was important.  There are probably somewhat faster ways (wild guess 10 to 50%) to code a 14-bit in byte custom solution. Here I was trying for generality.
Comment: Ah, sorry about that. Do you know of any resources that I could use to build a faster solution, if it becomes necessary? (as it is, under -O3, set takes ~11 nanoseconds and get is ~5 nanoseconds if my timing is correct, considering microbenchmarks are good at lying. this should be plenty for my purposes at least for now)
Comment: As mentioned before, the switch / case with fixed instruction sequences improves the performance. The example in my answer wasn't fully optimized (uses post increment instead of index + 1), but gives the idea. Array data could be read or written 32 bits at a time, but since much of the time it won't be aligned, I'm not sure that would help much with performance.
Comment: @Freezerburn I added another variation that is 20% faster still on my machine. It doesn't branch at all.
Comment: @rcgldr I only saw your remark and code after I posted. Great minds... ;-)
Comment: @Gene I have tried your code (1st version) to extract 37 bit . I have made necessary modifications for that. like W to 37 , data type of return value of arr_get,argument data type of arr_set etc... But its not working properly
Comment: @JissJ Works fine for me. The code wasn't intended to deal with `W>32`.  You probably didn't fix this line: `result |= arr[++byte_index] << n_bits;`. It will fail if `W > 32` because the shift operation is only 32 bits (on most machines). Extra bits are lost. Try `result |= ((uint64_t) arr[++byte_index]) << n_bits;`
Comment: @Gene OK.. Understood. Thanks
Answer: The easiest solution is to use a struct of eight bitfields:
typedef struct __attribute__((__packed__)) EightValues {
    uint16_t v0 : 14,
             v1 : 14,
             v2 : 14,
             v3 : 14,
             v4 : 14,
             v5 : 14,
             v6 : 14,
             v7 : 14;
} EightValues;

This struct has a size of 14*8 = 112 bits, which is 14 bytes (seven uint16_t). Now, all you need is to use the last three bits of the array index to select the right bitfield:
uint16_t 14bitarr_get(unsigned char* arr, unsigned int index) {
    EightValues* accessPointer = (EightValues*)arr;
    accessPointer += index >> 3;    //select the right structure in the array
    switch(index & 7) {    //use the last three bits of the index to access the right bitfield
        case 0: return accessPointer->v0;
        case 1: return accessPointer->v1;
        case 2: return accessPointer->v2;
        case 3: return accessPointer->v3;
        case 4: return accessPointer->v4;
        case 5: return accessPointer->v5;
        case 6: return accessPointer->v6;
        case 7: return accessPointer->v7;
    }
}

Your compiler will do the bit-fiddling for you.
Comment: Nice try, but this won't usually work by default because the overall structure typically gets extra padding to a word boundary (not guaranteed, but very very common). The safest approach is to expand the number of elements out to 16 (i.e. 14 words) as alignments are usually no stricter than that at the hardware level, even on 64-bit platforms (except when handling 64-bit values).
Comment: @DonalFellows The basic data type of the bitfields is `uint16_t` of which 7 will be allocated. As such, I assumed that the whole structure would be padded and aligned to a `uint16_t` boundary. But I agree that I may have been overconfident, the structure should be declared to be packed. I've added that now.
Answer: The Basis for Storage Issue
The biggest issue you are facing is the fundamental question of "What is my basis for storage going to be?" You know the basics, what you have available to you is char, short, int, etc... The smallest being 8-bits. No matter how you slice your storage scheme, it will ultimately have to rest in memory in a unit of memory based on this 8 bit per byte layout.
The only optimal, no bits wasted, memory allocation would be to declare an array of char in the least common multiple of 14-bits. It is the full 112-bits in this case (7-shorts or 14-chars). This may be the best option. Here, declaring an array of 7-shorts or 14-chars, would allow the exact storage of 8 14-bit values. Of course if you have no need for 8 of them, then it wouldn't be of much use anyway as it would waste more than the 4-bits lost on a single unsigned value.
Let me know if this is something you would like to further explore. If it is, I'm happy to help with the implementation.
Bitfield Struct
The comments regarding bitfield packing or bit packing are exactly what you need to do. This can involve a structure alone or in combination with a union, or by manually right/left shifting values directly as needed.
A short example applicable to your situation (if I understood correctly you want 2 14-bit areas in memory) would be:
#include <stdio.h>

typedef struct bitarr14 {
    unsigned n1 : 14,
             n2 : 14;
} bitarr14;

char *binstr (unsigned long n, size_t sz);

int main (void) {

    bitarr14 mybitfield;

    mybitfield.n1 = 1;
    mybitfield.n2 = 1;

    printf ("\n mybitfield in memory : %s\n\n",
            binstr (*(unsigned *)&mybitfield, 28));

    return 0;
}

char *binstr (unsigned long n, size_t sz)
{
    static char s[64 + 1] = {0};
    char *p = s + 64;
    register size_t i = 0;

    for (i = 0; i < sz; i++) {
        p--;
        *p = (n >> i & 1) ? '1' : '0';
    }

    return p;
}

Output
$ ./bin/bitfield14

 mybitfield in memory : 0000000000000100000000000001

Note: the dereference of mybitfield for purposes of printing the value in memory breaks strict aliasing and it is intentional just for the purpose of the output example.
The beauty, and purpose for using a struct in the manner provided is it will allow direct access to each 14-bit part of the struct directly, without having to manually shift, etc.
Comment: When someone offers help, if you want more, then the first thing you don't want to do is bite the hand that is feeding you. You were not clear, let's go from there, The easiest way to accomplish what you want without any waste would then be 2 short functions to set and retrieve the bits directly. I'll get an example of that if you can learn to be a bit more diplomatic.
Comment: I might have not made it clear what I was asking for: the ability to set/get an arbitrary 14 bits in an array. Unfortunately, this answer does not meet that need, as there is still waste bits (32-28=4) if I were to generate an array of them. If I were to shove as many of these into 64 bytes as I can, I would not want to waste 64 bits (which is 4 more possible 14-bit values). And yes, I do want to shove as many of these into 64 bytes as I can in the project I have in mind.
Comment: I am sincerely sorry if I sounded like I was being uncivil. I was attempting to clarify the original question (which I have edited into the question) while providing detail as to why your original answer did not fit the question. Unfortunately, text is a terrible medium for conveying tone :( I do appreciate the help, sincerely.
Comment: That's OK, I'm pretty sure I understood what you meant, it could have probably been worded a bit better. You mention a `short`, but you seem to really want to avoid the waste of `2` bits in each short, that is going to make things a bit more involved. Give me a bit and I'll amended the answer.
Answer: Update - assuming you want big endian bit packing. This is code meant for a fixed size code word. It's based on code I've used for data compression algorithms. The switch case and fixed logic helps with performance.
typedef unsigned short uint16_t;

void bit14arr_set(unsigned char* arr, unsigned int index, uint16_t value)
{
unsigned int bitofs = (index*14)%8;
    arr += (index*14)/8;
    switch(bitofs){
        case  0:   /* bit offset == 0 */
            *arr++  = (unsigned char)(value >>  6);
            *arr   &= 0x03;
            *arr   |= (unsigned char)(value <<  2);
            break;
        case  2:   /* bit offset == 2 */
            *arr   &= 0xc0;
            *arr++ |= (unsigned char)(value >>  8);
            *arr    = (unsigned char)(value <<  0);
            break;
        case  4:   /* bit offset == 4 */
            *arr   &= 0xf0;
            *arr++ |= (unsigned char)(value >> 10);
            *arr++  = (unsigned char)(value >>  2);
            *arr   &= 0x3f;
            *arr   |= (unsigned char)(value <<  6);
            break;
        case  6:   /* bit offset == 6 */
            *arr   &= 0xfc;
            *arr++ |= (unsigned char)(value >> 12);
            *arr++  = (unsigned char)(value >>  4);
            *arr   &= 0x0f;
            *arr   |= (unsigned char)(value <<  4);
            break;
    }
}

uint16_t bit14arr_get(unsigned char* arr, unsigned int index)
{
unsigned int bitofs = (index*14)%8;
unsigned short value;
    arr += (index*14)/8;
    switch(bitofs){
        case  0:   /* bit offset == 0 */
            value  = ((unsigned int)(*arr++)     ) <<  6;
            value |= ((unsigned int)(*arr  )     ) >>  2;
            break;
        case  2:   /* bit offset == 2 */
            value  = ((unsigned int)(*arr++)&0x3f) <<  8;
            value |= ((unsigned int)(*arr  )     ) >>  0;
            break;
        case  4:   /* bit offset == 4 */
            value  = ((unsigned int)(*arr++)&0x0f) << 10;
            value |= ((unsigned int)(*arr++)     ) <<  2;
            value |= ((unsigned int)(*arr  )     ) >>  6;
            break;
        case  6:   /* bit offset == 6 */
            value  = ((unsigned int)(*arr++)&0x03) << 12;
            value |= ((unsigned int)(*arr++)     ) <<  4;
            value |= ((unsigned int)(*arr  )     ) >>  4;
            break;
    }
    return value;
}

Comment: Added benchmarks for Gene's, mine, and yours to my answer.  Your code is the fastest.
Answer: Here's my version (updated to fix bugs):
#define PACKWID        14                    // number of bits in packed number
#define PACKMSK    ((1 << PACKWID) - 1)

#ifndef ARCHBYTEALIGN
#define ARCHBYTEALIGN    1                // align to 1=bytes, 2=words
#endif
#define ARCHBITALIGN    (ARCHBYTEALIGN * 8)

typedef unsigned char byte;
typedef unsigned short u16;
typedef unsigned int u32;
typedef long long s64;

typedef u16 pcknum_t;                    // container for packed number
typedef u32 acc_t;                        // working accumulator

#ifndef ARYOFF
#define ARYOFF long
#endif
#define PRT(_val)    ((unsigned long) _val)
typedef unsigned ARYOFF aryoff_t;            // bit offset

// packary -- access array of packed numbers
// RETURNS: old value
extern inline pcknum_t
packary(byte *ary,aryoff_t idx,int setflg,pcknum_t newval)
// ary -- byte array pointer
// idx -- index into array (packed number relative)
// setflg -- 1=set new value, 0=just get old value
// newval -- new value to set (if setflg set)
{
    aryoff_t absbitoff;
    aryoff_t bytoff;
    aryoff_t absbitlhs;
    acc_t acc;
    acc_t nval;
    int shf;
    acc_t curmsk;
    pcknum_t oldval;

    // get the absolute bit number for the given array index
    absbitoff = idx * PACKWID;

    // get the byte offset of the lowest byte containing the number
    bytoff = absbitoff / ARCHBITALIGN;

    // get absolute bit offset of first containing byte
    absbitlhs = bytoff * ARCHBITALIGN;

    // get amount we need to shift things by:
    // (1) our accumulator
    // (2) values to set/get
    shf = absbitoff - absbitlhs;

#ifdef MODSHOW
    do {
        static int modshow;

        if (modshow > 50)
            break;
        ++modshow;

        printf("packary: MODSHOW idx=%ld shf=%d bytoff=%ld absbitlhs=%ld absbitoff=%ld\n",
            PRT(idx),shf,PRT(bytoff),PRT(absbitlhs),PRT(absbitoff));
    } while (0);
#endif

    // adjust array pointer to the portion we want (guaranteed to span)
    ary += bytoff * ARCHBYTEALIGN;

    // fetch the number + some other bits
    acc = *(acc_t *) ary;

    // get the old value
    oldval = (acc >> shf) & PACKMSK;

    // set the new value
    if (setflg) {
        // get shifted mask for packed number
        curmsk = PACKMSK << shf;

        // remove the old value
        acc &= ~curmsk;

        // ensure caller doesn't pass us a bad value
        nval = newval;
#if 0
        nval &= PACKMSK;
#endif
        nval <<= shf;

        // add in the value
        acc |= nval;

        *(acc_t *) ary = acc;
    }

    return oldval;
}

pcknum_t
int_get(byte *ary,aryoff_t idx)
{

    return packary(ary,idx,0,0);
}

void
int_set(byte *ary,aryoff_t idx,pcknum_t newval)
{

    packary(ary,idx,1,newval);
}

Here are benchmarks:
set:    354740751        7.095 -- gene
set:    203407176        4.068 -- rcgldr
set:    298946533        5.979 -- craig

get:    268574627        5.371 -- gene
get:    166839767        3.337 -- rcgldr
get:    207764612        4.155 -- craig
Comment: This appears to be a little endian version of bit packing. The OP didn't mention if he wanted big endian or little endian bit packing. It also assumes 32 bit read / writes do not have to be aligned.
Comment: @rcgldr Yes.  On a BE arch, after int fetch and before store, just add an endian swap on acc [left off for brevity].  But, BE really only makes sense if an arch is BE [CPU's don't have vacuum tubes, either:-)] (still no problem, because the array may only be accessed via the access function).  Virtually all bigint packages do LE.  I've written my own from scratch.  I used to hate LE, until I compared it in detail--it makes everything much simpler.    And, int fetches haven't needed to be aligned on most arches since the 80's.  Even the venerable IBM/370 supported unaligned via the ICM inst.
Comment: I was thinking of standard compression formats, most of which are big endian (BE). I do recall that the backup DAT tape drives used a little endian (LE) compression format, but just about everything else I'm aware of uses big endian format. As for alignment issues, the 68000 series and older ARM series needed aligned data. For others reading this, BE reads sequential data into the low part of a working register and shifts left to get codes, LE reads sequential data into the high part of a working register and shifts right.
Comment: @rcgldr fixed bugs and added word align.  Two LEs:  arch LE for cell (e.g. int) and LE of bigint vector.  arch dictates cell.  But, always use LE for vec.  When mult n-digit num * m-digit num, you get (n+m) digit num.  With vec LE, it's easy to extend vec size via realloc, etc.


Connect 1/2" supply line to 3/8" outer diameter faucet line

Question: I bought from Home Depot a Glacier faucet that comes with 3/8 inch O.D. supply tubes. The supply lines from the wall have an outer diameter of 1/2 inches though. How do I connect the two?

This seems like a common enough question, but searching for "connector" I could only find this connector on Home Depot's site, which is from 3/8" to "M22". I'm not sure why "M22" is called that way, but its diameter is apparently 14mm, which isn't exactly 1/2".
Brass nipples on Home Depot's site seem to come only in the same diameter on both ends, e.g. 1/2".
(As you might suspect, I'm originally from Europe and have quite a bit of disdain for the imperial system and the US hanging on to it when the entire rest of the world uses metric.)
Answer: You need a brass connector. "1/2" female iron pipe" (1/2" FIP) is the size of the female connector on the end of the hose coming out of the sink plate in your picture; "3/8" female compression" is the size of the connector on the end of the hose coming out of the faucet in your picture. You need a 1/2" MIP (male iron pipe) X 3/8" male compression adapter. Super common at any hardware store, er... should I say "ironmonger shop"?

Comment: "Iron Pipe" sizes are also called National Pipe Taper (NPT), and male / female may be labeled MPT or FPT, respectively.
Comment: @Henry Jackson, thanks I should have thought to mention that. Very common to see the same size referenced with NPT. Also I should have noted that the picture shows the fitting with a compression nut and ferrule, which would be removed for the OPs purpose.
Comment: What is the rubber thing within the FIP?
Answer: I had the same issue.  Here is the part I used:  WATTS LFA-124.  Found it at Home Depot in the aisle with brass fittings.


Rendering transparent windows

Question: The only method I know for rendering transparent windows is call to UpdateLayeredWindows which is terribly slow in case when I need to render result of D3D9 Render target.
I have to read render target data into system memory by calling GetRenderTargetData and
then i have to render it on the screen by calling UpdateLayeredWindow.
Here http://msdn.microsoft.com/en-us/library/windows/desktop/ee890072(v=vs.85).aspx
there is a description of how to optimized rendering via "D3D9Ex Flip Mode Present to DWM".
Is there some kind of similar optimization for rendering top level transparent windows ?
Thanks
Comment: If you don't need per-pixel alpha, try using SetLayeredWindowAttributes (specifying either alpha or color key) instead and then paint/update as normal. I don't know how this will fare perf-wise compared to UpdateLayeredWindow, but worth a try perhaps.
Comment: [This article](http://www.codeproject.com/Articles/17727/Unmanaged-Vista-Power) seems to do what you want.  I haven't tried it though.
Comment: I think I need per-pixel alpha. I hore there should be something similar to WDM optimization
Comment: this is exactly correct solution. Thanks much.
Answer: I have found the answer in the comments:
This article seems to do what you want.
Thanks for user arx

Rendering transparent windows


How to disable IIS credentials in ASP.NET

Question: Is there a way to disable IIS default authentication in global.asax or somewhere else depending on passed parameters.
A client requests the same form would be secured using IIS authentication and by providing authentication information in POST variables
Answer: IIS authentication happens before the request is passed to the ASP.NET egine. Therefore, the answer to your question is "no".
However, by enabling anonymous access on IIS only, you can process any authentication (including Basic etc.) in your application without being "intercepted" by IIS.
Answer: This is not a complete answer, but may give you direction. If you are using IIS 7, then HttpModules are now native to IIS. That is, you can get an implementation of the IHttpModule interface to be used by IIS, regardless of what type of content is being served.
I suspect that you can wire such an HttpModule so that it will notice when IIS is failing a request due to a failure of Windows Authentication. If that is possible, then you might still be able to examine the POST variables and give the request a "second chance".
I also wonder if it might be possible with IIS 7 to turn this around - have the main site use anonymous authentication so that your code can check the form POST parameters. If that authentication fails, then redirect to the Windows Authentication site.
Comment: I have to do it foris IIS 5.1 :/


Android image download from server?

Question: my logcat---------::

09-07 19:55:51.623: DEBUG/skia(1680): --- SkImageDecoder::Factory returned null
09-07 19:55:51.634: DEBUG/skia(1680): --- SkImageDecoder::Factory returned null
09-07 19:55:52.033: DEBUG/dalvikvm(1680): GC_FOR_MALLOC freed 1896 objects / 518112 bytes in 97ms
09-07 19:55:52.364: DEBUG/skia(1680): --- SkImageDecoder::Factory returned null
09-07 19:55:53.254: DEBUG/dalvikvm(1680): GC_FOR_MALLOC freed 822 objects / 539696 bytes in 67ms
09-07 19:56:01.514: INFO/System.out(1680): ImageUrl :: http://www.heresmyparty.com/cms/components/com_chronocontact/uploads/add_event_form/20110805085124_wtpa.logo.png
09-07 19:56:01.584: INFO/System.out(1680): ImageUrl :: http://www.heresmyparty.com/cms/components/com_chronocontact/uploads/add_event_form/20110805084621_wtpa.logo.png
09-07 19:56:01.643: INFO/System.out(1680): ImageUrl :: http://www.heresmyparty.com/cms/components/com_chronocontact/uploads/add_event_form/20110805025050_chuckie liv.ashx.jpg
09-07 19:56:01.684: INFO/System.out(1680): ImageUrl :: http://www.heresmyparty.com/cms/components/com_chronocontact/uploads/add_event_form/20110805024007_space vegas.ashx.jpg
09-07 19:56:01.914: DEBUG/skia(1680): --- SkImageDecoder::Factory returned null
09-07 19:56:01.953: DEBUG/skia(1680): --- SkImageDecoder::Factory returned null
09-07 19:56:02.714: DEBUG/skia(1680): --- SkImageDecoder::Factory returned null
09-07 19:56:02.754: INFO/System.out(1680): ImageUrl :: http://www.heresmyparty.com/cms/components/com_chronocontact/uploads/add_event_form/20110805023407_blush vegas.ashx.jpg
09-07 19:56:02.834: INFO/System.out(1680): ImageUrl :: http://www.heresmyparty.com/cms/components/com_chronocontact/uploads/add_event_form/20110805022856_Savoy vegas.ashx.jpg
09-07 19:56:02.944: DEBUG/dalvikvm(1680): GC_FOR_MALLOC freed 1058 objects / 490016 bytes in 80ms
09-07 19:56:02.944: DEBUG/skia(1680): --- SkImageDecoder::Factory returned null
09-07 19:56:02.944: DEBUG/skia(1680): --- SkImageDecoder::Factory returned null
09-07 19:56:03.894: DEBUG/skia(1680): --- SkImageDecoder::Factory returned null
09-07 19:56:03.923: INFO/System.out(1680): ImageUrl :: http://www.heresmyparty.com/cms/components/com_chronocontact/uploads/add_event_form/20110808101519_DSC0028-Ti.jpg
09-07 19:56:04.104: INFO/System.out(1680): ImageUrl :: http://www.heresmyparty.com/cms/components/com_chronocontact/uploads/add_event_form/20110729152914_wtpa.logo.png
09-07 19:56:04.604: DEBUG/skia(1680): --- SkImageDecoder::Factory returned null
09-07 19:56:04.634: DEBUG/skia(1680): --- SkImageDecoder::Factory returned null
09-07 19:56:05.004: DEBUG/dalvikvm(1680): GC_FOR_MALLOC freed 966 objects / 515008 bytes in 80ms
09-07 19:56:05.404: DEBUG/skia(1680): --- SkImageDecoder::Factory returned null
09-07 19:56:05.434: DEBUG/skia(1680): --- SkImageDecoder::Factory returned null
09-07 19:56:05.464: DEBUG/skia(1680): --- SkImageDecoder::Factory returned null
09-07 19:56:06.194: DEBUG/skia(1680): --- SkImageDecoder::Factory returned null

my code is ::
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.Map;
import java.util.Stack;
import java.util.WeakHashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.EventLogTags.Description;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;

public class ImageLoader {

    MemoryCache memoryCache = new MemoryCache();
    FileCache fileCache;
    private Map<ImageView, String> imageViews = Collections
            .synchronizedMap(new WeakHashMap<ImageView, String>());
    private ProgressBar indicator;

    public ImageLoader(Context context) {

        photoLoaderThread.setPriority(Thread.NORM_PRIORITY - 1);
        fileCache = new FileCache(context);
    }

    public void DisplayImage(String url, Context activity, ImageView imageView,
            ProgressBar pbar) {

        imageViews.put(imageView, url);
        Bitmap bitmap = memoryCache.get(url);

        if (bitmap != null) {
            this.indicator = pbar;
            indicator.setVisibility(View.INVISIBLE);
            imageView.setImageBitmap(bitmap);
        } else {
            this.indicator = pbar;
            indicator.setVisibility(View.INVISIBLE);
            queuePhoto(url, activity, imageView);
            imageView.setImageBitmap(null);
        }
    }

    private void queuePhoto(String url, Context activity, ImageView imageView) {
        // This ImageView may be used for other images before. So there may be
        // some old tasks in the queue. We need to discard them.
        photosQueue.Clean(imageView);
        PhotoToLoad p = new PhotoToLoad(url, imageView);
        synchronized (photosQueue.photosToLoad) {
            photosQueue.photosToLoad.push(p);
            photosQueue.photosToLoad.notifyAll();
        }

        // start thread if it's not started yet
        if (photoLoaderThread.getState() == Thread.State.NEW)
            photoLoaderThread.start();
    }

    private Bitmap getBitmap(String url) {
        File f = fileCache.getFile(url);

        // from SD cache
        Bitmap b = decodeFile(f);
        if (b != null)
            return b;

        // from web
        try {

            HttpGet httpRequest = null;

            try {

                int pos = url.lastIndexOf('/') + 1;
                URI uri = new URI(url.substring(0, pos)
                        + URLEncoder.encode(url.substring(pos), "UTF-8"));
               //URL imgUrl = new URL(decodeUrl);
                httpRequest = new HttpGet(uri);
            } catch (URISyntaxException e) {
                System.out.println("Error ::" + e.toString());
                e.printStackTrace();
            }

            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = (HttpResponse) httpclient
                    .execute(httpRequest);

            HttpEntity entity = response.getEntity();
            BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
            InputStream instream = bufHttpEntity.getContent();
            Bitmap bm = BitmapFactory.decodeStream(instream);

            /*
             * Bitmap bitmap = null; URL imageUrl = new URL(url);
             * HttpURLConnection conn = (HttpURLConnection) imageUrl
             * .openConnection(); conn.connect(); conn.getDoOutput();
             *
             *
             * conn.setConnectTimeout(30000); conn.setReadTimeout(30000);
             *
             * InputStream is = conn.getInputStream();
             *
             * OutputStream os = new FileOutputStream(f); Utils.CopyStream(is,
             * os); os.close(); bitmap = decodeFile(f); return bitmap;
             */
            return bm;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    private Bitmap gonextUrl(String url) {
        Bitmap bm = null;
        try {

            URL imgUrl = new URL(url);
            HttpGet httpRequest = new HttpGet(imgUrl.toURI());

            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = (HttpResponse) httpclient
                    .execute(httpRequest);

            HttpEntity entity = response.getEntity();
            BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
            InputStream instream = bufHttpEntity.getContent();
            bm = BitmapFactory.decodeStream(instream);

            return bm;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bm;
    }

    // decodes image and scales it to reduce memory consumption
    private Bitmap decodeFile(File f) {
        try {
            // decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f), null, o);

            // Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE = 70;
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            while (true) {
                if (width_tmp / 2 < REQUIRED_SIZE
                        || height_tmp / 2 < REQUIRED_SIZE)
                    break;
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
            }

            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {
        }
        return null;
    }

    // Task for the queue
    private class PhotoToLoad {
        public String url;
        public ImageView imageView;

        public PhotoToLoad(String u, ImageView i) {
            url = u;
            imageView = i;
        }
    }

    PhotosQueue photosQueue = new PhotosQueue();

    public void stopThread() {
        photoLoaderThread.interrupt();
    }

    // stores list of photos to download
    class PhotosQueue {
        private Stack<PhotoToLoad> photosToLoad = new Stack<PhotoToLoad>();

        // removes all instances of this ImageView
        public void Clean(ImageView image) {
            for (int j = 0; j < photosToLoad.size();) {
                if (photosToLoad.get(j).imageView == image)
                    photosToLoad.remove(j);
                else
                    ++j;
            }
        }
    }

    class PhotosLoader extends Thread {
        public void run() {
            try {
                while (true) {

                    if (photosQueue.photosToLoad.size() == 0)
                        synchronized (photosQueue.photosToLoad) {
                            photosQueue.photosToLoad.wait();
                        }
                    if (photosQueue.photosToLoad.size() != 0) {
                        PhotoToLoad photoToLoad;
                        synchronized (photosQueue.photosToLoad) {
                            photoToLoad = photosQueue.photosToLoad.pop();
                        }
                        Bitmap bmp = getBitmap(photoToLoad.url);
                        memoryCache.put(photoToLoad.url, bmp);
                        String tag = imageViews.get(photoToLoad.imageView);
                        if (tag != null && tag.equals(photoToLoad.url)) {

                            BitmapDisplayer bd = new BitmapDisplayer(bmp,
                                    photoToLoad.imageView, indicator);
                            Activity a = (Activity) photoToLoad.imageView
                                    .getContext();
                            a.runOnUiThread(bd);
                        }
                    }
                    if (Thread.interrupted())
                        break;
                }
            } catch (InterruptedException e) {
                // allow thread to exit
            }
        }
    }

    PhotosLoader photoLoaderThread = new PhotosLoader();

    // Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable {
        Bitmap bitmap;
        ImageView imageView;

        // private ProgressBar indicator1;

        public BitmapDisplayer(Bitmap b, ImageView i, ProgressBar indicator) {
            this.bitmap = b;
            this.imageView = i;
            // this.indicator1 = indicator;
        }

        public void run() {
            if (bitmap != null) {
                // indicator1.setVisibility(View.INVISIBLE);
                imageView.setImageBitmap(bitmap);
            } else
                imageView.setImageBitmap(null);
        }
    }

    public void clearCache() {
        memoryCache.clear();
        fileCache.clear();
    }

}

Comment: Is there a question in all that?
Comment: no  in some url problem i have 15 image url out of 114 url ...There are prblm either url or bitmap idont know ????
Comment: or any way to download big image which size is 1000 * 1200 and size is more than 5 to 8 MB?? U have any application in android ...........
Answer: call this function loadImageFromUrl(" http://www.heresmyparty.com/cms/components/com_chronocontact/uploads/add_event_form/20110805085124_wtpa.logo.png")  to get image bitmap from imageurl
public static Bitmap loadImageFromUrl(String url) {
                InputStream inputStream;Bitmap b;
                try {
                        inputStream = (InputStream) new URL(url).getContent();
                        BitmapFactory.Options bpo=  new BitmapFactory.Options();
                        bpo.inSampleSize=2;
                       b=BitmapFactory.decodeStream(new PatchInputStream(inputStream), null,bpo );
                        return  b;
                } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
//                  return null;
        }

this is the class for PatchInputStream
public class PatchInputStream extends FilterInputStream {
          public PatchInputStream(InputStream in) {
            super(in);
          }
          public long skip(long n) throws IOException {
            long m = 0L;
            while (m < n) {
              long _m = in.skip(n-m);
              if (_m == 0L) break;
              m += _m;
            }
            return m;
          }
        }

You can also modify your code to prevent error.Just you need to add  PatchInputStream(inputStream) in BitmapFactory.decodeStream(new PatchInputStream(inputStream), null,bpo );
Comment: Got Exception and App force close_______________>>>>>>                     09-07 20:16:00.433: ERROR/AndroidRuntime(1729): FATAL EXCEPTION: Thread-9
09-07 20:16:00.433: ERROR/AndroidRuntime(1729): java.lang.RuntimeException: java.io.FileNotFoundException: http://www.heresmyparty.com/cms/components/com_chronocontact/uploads/add_event_form/20110729132422_wet rep every sun.jpg
Comment: what is the url you are passing in the method  loadImageFromUrl(String url)
Comment: http://www.heresmyparty.com/cms/components/com_chronocontact/uploads/add_event_form/20110722122552_mood%20fri.jpg
Comment: there is no such file for your url and that is why this   error java.io.FileNotFoundException: is coming
Comment: You can check it in the browser whether file is there or not .otherwise you are not passing the correct url.

Android image download from server?


When will an arithmetic progression contain a square number?

Question: Let $a,d \in \mathbb{N}$. When will the arithmetic sequence $(a+dn)_n$ contain a square number?
Obviously, we need to have that $a$ is a square $\mod d$. But is this a sufficient condition?
My try:
For example when $a =3$ and $d=11$, for finding a square in the sequence we get the diophantine equation
$$y^2-11x-3=0$$
which has solutions $x=11t^2+10t+2$ or $x=11t^2+12t+3$, $t\in\mathbb{Z}$. But I don't know how to solve the equation for general $a$ and $d$.
Answer: It is equivalent. If $m^2\equiv a\pmod d$, then $\exists n$ such that $m^2=a+dn$.
If you want $n>0$, replace $m$ by for example $m+ad$.


django rest framework and forms: How to do

Question: I have a model in my Django App as below. I am using ReactJs as frontend and pass data using Django Rest Framework.
class Ingredient(models.Model):
    MUNITS_CHOICES = (
        ('kg', 'Kilogram'),
        ('ltr', 'Liter'),
        ('pcs', 'Pieces'),
    )

    name = models.CharField(max_length=200,unique=True,null=False)
    slug = models.SlugField(unique=True)
    munit = models.CharField(max_length=10,choices=MUNITS_CHOICES,default=KILOGRAM)
    rate = models.DecimalField(max_digits=19, decimal_places=2,validators=[MinValueValidator(0)],default=0)
    typeofingredient = models.ForeignKey(TypeOfIngredient, related_name='typeof_ingredient',null=True, blank=True,on_delete=models.PROTECT)
    density_kg_per_lt = models.DecimalField(max_digits=19, decimal_places=2,verbose_name='Density (kg/lt)',null=True,blank=True,validators=[MinValueValidator(0)])
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)

As you see the model fields have lot of parameters like max_length, choices, ForeignKey(which is also kind of choices), DecimalField, CharField, DateTimeField etc
I was creating and rendering forms using Django Forms. Also the validaton is done in the Form class.
The advantage of this is the form is inserted very easily in the template using {{ form }}. and it takes care of all the parameters like max_length, choices, fieldtypes etc. Also we can validate the form and the errors are send back etc. So most the job is done automatically.
But since i am using DRF i created a serializer class to create or update:
class IngredientCreateUpdateSerializer(ModelSerializer):
    class Meta:
        model = Ingredient
        fields = [
            'name',
            'munit',
            'rate',
            'typeofingredient',
            'density_kg_per_lt',
        ]

Here again i have to write the validation logic which i have done in the form.
Now to create the HTML form in the reactjs i have to manually look at each form parameter (like fieldtype, required etc) and create the form, and then link the api endpoint to create/update on submit button.
Also the choices for select field have to passes as seperate endpoints.

Solution 1 Needed: Create form api

So is there a form api which will pass all the fields and their parameters like max_length, required, choices for select field, choices for foreignfields to the reactjs. So that i get some blueprint to create the form in reactJs. Later even if i change the model or parameters everything can be taken care of by the api.

Solution 2 Needed: Can validation logic be common for serializer and
  forms

Will i have to write the validation code for serializer class also or is there a way i can link with the form class which i have already used.

I am mainly looking for Solution 1

: Because solution 2 is more of typing the validation twice which is fine.
Answer: I read through your solution scenarios. I work with Django-reactjs. To make things simple for yourself,.
Make do with this templating https://github.com/Frojd/django-react-templatetags
You mention of model class parameters. It can suffix, since you are  interested  in passing the model parameters to the frontend.
Another option is : React, with the help of Webpack (module bundler) & Babel (transpiler), will bundle and transpile your Javascript into single or multiple files that will be placed in the entry HTML page. Learn Webpack, Babel, Javascript and React and Redux (a state container). I believe you won't use Django templating but
 instead allow React to render the front-end.
Should you have anyother questions do let me know
Comment: Recently i started using webpack, babel and react. I will check this,


Mobile broadband not connect without unplug and plug

Question: I have recently installed ubuntu 13.10 and I am still very new in this operating system. My problem is that when I start my computer, it detects all the wifi connections around but not my mobile broadband usb connection (huwaie).
After startup the network-manager doesn't display the mobile broadband section. The network-manager shows this section only after unplugging and then replugging my usb-modem. I don't like to unplug and then replug my device since it might ruin/loosen my USB-port. It's okay to have the modem always in, even when the laptop is shutdown.
The usb-modem should be auto-detected by ubuntu directly after startup. Can someone please help me? Thanks in advance.
Comment: did you install `huwaei broadband drivers for linux`?
Comment: Please guide me how to install huwaei drivers. I have downloaded drivers from my internet providers for linux but dont know how to install it as I am have installed ubuntu just two days before.
Comment: sir i am facing the same problem i got your point to install the huawei driver but the problem is when i plug my modem the system does not open its files allows me to connect net but doesn't show the drivers file like windows does.once i accidentally opened the driver but forgot how i had opened that.help me little bit here it must show mobilepartner upside computer.
Answer: Normally Linux distributions like Ubuntu,Debian,etc detect and mount modem as a CD/DVD drive.And the network manager applet does not show the service provider name on its list.For this problem you have to follow the simple steps given below.
1.Open the terminal and move to the directory where you extracted the huwaei datacard drivers for linux.(I extracted the drivers to the desktop)

2.run sudo chmod 777 install command to give executable permission to the file install.
3.run sudo ./install.After that the terminal shows Install NDIS driver failed.Skip that and press ENTER.

4.Finally restart your pc .
After that your network manager applet will surely detect your modem or you have to manually create a broadband connection.By,
1.Goto Network Connections and click on ADD Button.

2.Choose Connection Type as Mobile Broadband

3.Select HUAWEI Mobile from the dropdown list.And proceed through the installation steps by selecting APN,etc.
Comment: Thanks for your detailed answer. I tried it but no success. May be I am too new to understand commands in terminal. At the moment I can only put values someone gives me in terminal and enter, otherwise i dont know whats going on in terminal. anyway thank you for your time and answer.
Answer: 1) Just a hint to prevent unplug & plugin of modems,
try to restart network manager using terminal command
sudo service network-manager restart
& enter the password.
If nm is not at all find your modem, you may have to eject the CD within the modem from terminal or Disks.
Answer: i was also having the same problem with the tata photon wifi max ,i was able to connect to wifi but not lan so i tried this in terminal after plugging the device in terminal and it worked but every time i have tho run this command in terminal :
sudo usb_modeswitch -W -v 0x12d1 -p 0x1f01 -M "55534243123456780000000000000a11062000000000000100000000000000" -R
try this hope this works....
if it works then you can add a new internet connection in netwrok manager as mobile broadband and follow the steps like service provider etc etc
Answer: Though it is not for Huwaii devices, you could try the codes give in this thread.


Slideshow Pro - Flash loads but images do not. Why?

Question: I installed Slideshow pro, with swfobject here: http://globalhealth-dev.oit.duke.edu/whos-involved/alumni
The flash loads but the images do not. I have double checked the image paths to death and they appear to be correct.
Here is the html:
<object id="alumni" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="520" height="270">
<param name="movie" value="http://globalhealth-dev.oit.duke.edu/alumni-slideshow.swf" />

<object type="application/x-shockwave-flash" data="http://globalhealth-dev.oit.duke.edu/alumni-slideshow.swf" width="520" height="270">

Alternative content

</object>

</object>

Here is the swfobject code:

The images.xml file and the gallery are both in the root directory and the xml file code is:
<?xml version="1.0" encoding="UTF-8"?>
  <gallery>
   <album title="Alumni" description="Duke Global Health Institute Alumni" lgPath="gallery/album1/lg/">

   </album>
</gallery>

I would appreciate some help in resolving this! Thanks.
Answer: okay, are you ready, you putted all of them into root, and access now this url
http://globalhealth-dev.oit.duke.edu/alumni-slideshow.swf
end embed it where you want.
Comment: Hi Eugene, I tried that path and get the same results. The xml file and the gallery are in the same directory. This looks like it should make sense but shouldn't the ../../ be between the page and the .xml file? However, the connection is being made with the swf file. Any other thoughts?

Thanks!
Comment: I left that path intact so you can give it a try.
Comment: no it is not, http://globalhealth-dev.oit.duke.edu/whos-involved/alumni/image.xml returns 404
Comment: actually the xml path is: http://globalhealth-dev.oit.duke.edu/images.xml and the path to the photos is: http://globalhealth-dev.oit.duke.edu/gallery/album1/lg/
Comment: man, put your application into the root too, not two subfolders else, just root!
Comment: I like your style. All three are in the root folder. The images.xml, gallery and alumni-slideshow.swf. Is there anything else?
Comment: if its running enough well for you and you are like - then its all, if you need anything else - let me know. and don't forget to accept answer and rate the comments.
Comment: Eugene. Sorry I missed your comment there. The problem is that it is not working. The pictures still do not load.
Comment: stop, i saw your link with root swf file, where is it? I checked it and it works, what did you change? can you again past all data into the one folder?
Answer: With some help from the folks over at Slideshow Pro I finally figured out the solution:

Put the full url to the images.xml in the ssp preferences in Flash: http://www.myurl.com/images.xml
Put the full path to the gallery images folder in the xml file: http://www.myurl.com/gallery/lg/
Only put the name of the image in the img src link: img src="photo1.jpg"
Answer: For me it was an issue with crossdomain.xml and my Apache mod_rewrite rule which was directing all domain.com requests to www.domain.com.
I added this to my .htaccess file and it started working again:
RewriteRule ^/crossdomain\.xml$ - [L]
RewriteCond %{HTTP_HOST} ^domain\.com
RewriteRule ^(.*) http://www.domain.com%{REQUEST_URI} [redirect=permanent]


ssrs : box sneaking to the left side of the footer

Question: I'm creating a footer on my report, with 3 boxes. One on the left side, the second one in the middle and the last one on the right side.
The left box and right box are appearing on each page,  respectively with the timestamp info for the left box and for the number of pages for the right box.
Middle box is appearing , at the last page of the report only.
I've put the following line for my middle box
iif(Globals!PageNumber = Globals!TotalPages, False, True)

The script says the middle box will only appear at the last page of the report
Last page is fine. Three boxes, standing side by side.
Issue lies from the first page to the penultimate page.
As the middle box does not appear until the last page, the right box is shifting to the left side , taking over the place where the middle box should be.
I tried to fix this issue, by putting all the boxes in a rectangle. Alas no good news
I set the option Keep Together = True but I don't think it will help. I keep looking for a solution.
Any insights you may have , are more than welcome
Cheers
Update :
This is my last page

My second page to my penultimate page look like this

I want the third box to be on the extreme right side , like on my last page
Answer: If I'm interpreting your question correctly, then the middle textbox has the following two properties set:
Visibility (hidden):    =IIF(Globals!PageNumber = Globals!TotalPages, False, True)

The value is : "13779..." or some expression evaluating to this.
Try changing these properties to the following:
Visibility(hidden): False

Then
Value: =IIF(Globals!PageNumber <> Globals!TotalPages, Nothing, "13779...")

This way you are not hiding the textbox itself, just the text that it displays.  Doing so should cause the textbox to align the same horizontally on all pages.
Comment: Hi @wesley-marshall, your answer is unclear ... Can you please reformulate , especially the last part `try setting the visibility to always show the box, then change the value of the textbox to display nothing except on the last page`. Can you reformat your answer, please? Your help will have a real impact on my work ... Thanks for your understanding
Comment: Thanks for the help. It took me some time to understand your answer but I got it, finally! Cheers!
Answer: For the rightmost box make the right align the text.
Either by clicking on the menubar

OR
Change the textbox property TextAlign to Right

Another method will be to write an expression in Left padding for the rightmost text box.
Something Like
=iif(Globals!PageNumber = Globals!TotalPages, '2pt', '220pt')

Comment: Thanks for the help!
Comment: Hi @anup-agrawal, can it be that simple...? Checking
Comment: Hi @AndyK Added another way to solve the same issue.
Comment: @AndyK Also you can try middle box and right box overlap each other and make middle box left align and right box right align.
Comment: @anu-agrawal Both solutions are not doing the trick, alas. Please find a graphical update of my issue
Comment: Did you try the other solution of aligning the textboxes on top of each other?
Comment: what do you mean by aligning the textboxes on top of each other?
Comment: Make your right box start from the same location as your middle box and the end location of your right box will be the end of the report. Now right align the text.
Comment: Also the indent expression make it something like 200pt. `=iif(Globals!PageNumber = Globals!TotalPages, '2pt', '220pt')`


Conky Manager Installation Problem

Question: I've done
sudo apt install conky-all
cp /etc/conky/conky.conf ~/.conkyrc
sudo apt-add-repository -y ppa:teejee2008/ppa
sudo apt update

and then;
sudo apt install conky-manager

I get;
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package conky-manager

How can I overcome this problem?Why I am unable to locate the package?
Comment: Possible duplicate of [Ubuntu 18.04.1 LTS don't install Conky Manager](https://askubuntu.com/questions/1079596/ubuntu-18-04-1-lts-dont-install-conky-manager) and use [my other answer](https://askubuntu.com/a/1080007/66509) to set it up.
Comment: I found my answer here,  https://askubuntu.com/questions/1079596/ubuntu-18-04-1-lts-dont-install-conky-manager?noredirect=1&lq=1
Answer: Looking into the repository, it appears that there is no conky-manager package available for any version of Ubuntu over 16.04.
Thus, as a workaround, you can simply edit the file
/etc/apt/sources.list.d/teejee2008-ubuntu-ppa-$YOUR_DISTRO_NAME.list and change it to look like this:
deb http://ppa.launchpad.net/teejee2008/ppa/ubuntu xenial main
# deb-src http://ppa.launchpad.net/teejee2008/ppa/ubuntu xenial main

After that, just run sudo apt update one more time and you should be able to install it no problem after that.
Mind you, $YOUR_DISTRO_NAME in the file name above depends on the version you are currently running. You can find out what that is by running: lsb_release -c | awk '{print $2}'
Comment: I've done what you said and now I get this; sudo apt install conky-manager
(Reading and Building depen. tree all done)
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:
The following packages have unmet dependencies:
 conky-manager : Depends: realpath but it is not installable
E: Unable to correct problems, you have held broken packages.
Comment: By the way my distro name is bionic, if it helps

Conky Manager Installation Problem


Prove that $f\colon [a;\infty) \to \mathbb{R} $ is uniform continuous if $f$ is continuous.

Question: We have the continuous function $f\colon [a;\infty) \to \mathbb{R}$ .
 How can i prove that it is uniformly continuous?
 The function has a finite limit in $+\infty$.
I know that for a pair of $a,b \in \mathbb{R}$, $f\colon[a;b) \to\mathbb{R}$ is continuous if the $ \lim\limits_{\substack {x\to b \\x <b} }  f(x) $ is finite.
 I have absolutely no idea how to prove it. Can someone offer a step by step proof or an article to the proof?
Comment: But that is false. $f\colon x\mapsto x^2$ is not uniformly continuous on, say, $[1,\infty)$. Did you forget an assumption?
Comment: Not every continuous function $[a,\infty)\to\Bbb R$ is uniformly continuous, consider for example the function $x\mapsto x^2$. Do you have any conditions?
Comment: Hmm i understand, thank you for your fast and prompt answers!
Comment: https://en.wikipedia.org/wiki/Heine%E2%80%93Cantor_theorem ... continuous functions on compact are uniform continuous.
Comment: Wouldn't Heine - Cantor be impossible to use as $[1;+\infty)$ is not a compact set?
Comment: If you know that $f$ has a finite limit at $\infty$, then things are a bit different. Did you have that in mind? (and to refer to @rtybase comment: this indeed does *not* apply to $[a,\infty)$.)
Comment: Not really,can you elaborate?
Comment: Yes! That was the assumption that i did not write! I forgot to mention that $f(x)$ has a finite limit in $\infty$ !
Comment: If $\lim_\infty f = \ell \in\mathbb{R}$, then for every $\varepsilon>0$ you have a value $A$ such that $f(x)\in[\ell-\varepsilon,\ell+\varepsilon]$, and therefore $f(x)$ and $f(y)$ are very close whenever $x,y\in I=[A,\infty)$. Moreover, $[a,A]=J$ is a compact, so $f$ is uniformly continuous on $J$. Combining the two suitably, you'll get $f$ uniformly continuous. @Eduard6421
Comment: Thank you! Could you post it again as an answer? I would like to mark the question as answered!
Comment: @Eduard6421 Yes I know $[a;+\infty)$ is not compact and you can't apply that theorem unless you have more conditions over $f$ ;)
Answer: Following the exchange in the comments, posting what what there as answer.

This is false without further assumptions, as the example of $f\colon x\in[a,\infty)\mapsto x^2$ shows.
under the additional assumption that $\lim_\infty f$ exists (name it $\ell\in\mathbb{R}$), then this becomes a standard exercise (most likely asked several times on this website). The idea is to use

the fact that for $x,y$ "big", then $\lvert f(x) - f(y) \rvert \leq \lvert f(x)-\ell\rvert +  \lvert \ell - f(y)\rvert$ and both terms of the RHS are very small since $f\to_\infty \ell$;
and for $x,y$ "small", well they are both in a compact interval of the form $[a,A]$, and then anyway $f$ is uniformly continuous on this compact by the Heine—Cantor theorem.

More precisely, here is the outline:

for every $\varepsilon>0$ you have a value $A_\varepsilon$ such that $f(x)\in[\ell-\frac{\varepsilon}{2},\ell+\frac{\varepsilon}{2}]$, and therefore by the above $f(x)$ and $f(y)$ satisfy $\lvert f(x) - f(y) \rvert \leq \varepsilon$ whenever $x,y\in I=[A_\varepsilon,\infty)$.
But then, $[a,A_\varepsilon]=J$ is a compact, so $f$ is uniformly continuous on $J$, and there exists $\delta > 0$ such that for any $x,y\in J$ such that $\lvert x-y\rvert < \delta$ we have $\lvert f(x) - f(y) \rvert \leq \varepsilon$ as well.
The last case to deal with is when $x\in I,y\in J$: then, use continuity at $A_\varepsilon$.

Combining the three suitably, you'll prove (as $\varepsilon$ was arbitrary) that $f$ uniformly continuous on $[a,\infty)$.


Dolphin uses ftp not sftp when adding network folder

Question: I'm trying to connect to my server with sftp. The server is working just fine. I connected to it from FileZilla. Then I was able to connect to it using Dolphin by just typing in the address: sftp://username:password@domain/. This worked and I was even able to transfer files.
However, I would like to create a directory to save this for future use, so that I don't have to type that in every time. It seems that "Add Network Directory" uses ftp instead of sftp, making it so that I cannot connect to the server. I can find no way to make it use sftp, is there a way to do this?
Every time that I try to connect, it asks for the password, I enter it, and then I get this error:
  Server replied:
  530 Non-anonymous sessions must use encryption.
  Do you want to retry?

Answer: If it's your server and you have SSH access, than maybe setup a SSH connection instead and use fish://username@remotehost as the URI in dolphin.
There is a big difference between SFTP (FTP over SSH) vs FTPS which is FTP over TLS. It gets more complicated because FTPS has an implicit and explicit mode, implicit uses a dedicate port and connects using TLS, while the explicit mode uses the normal ftp port and switches to TLS with startTLS command.
Looking at the source:
https://github.com/KDE/dolphin/blob/c836cf010c12858a7f3a4943c06f9de2b9f31a14/doc/index.docbook#L609
The docs imply the dolphin supports SFTP and FISH, both of which use SSH. I can find no mention of FTPS, so perhaps it doesn't support that?
Comment: I made a typo, I used sftp to connect successfully. But in the `Add Network Folder -> FTP` there is not option for sftp, so it just kept refusing my connection. I assume there must be a way to use sftp for that.  However, I used ssh instead and it worked, so thanks a lot for the help.
Answer: You probably did something wrong. I've successfully created SFTP folder to my server by these steps

By the way, you probably shouldn't use fish:// protocol, it is fallback protocol for ssh servers which don't support sftp and it's not fast. Default sshd servers confugured with sftp enabled by default.
Comment: Yep, the answer above gave me the way to do that. I was using FTP in the first step.


Are the two starters for Pokémon Colosseum always exactly the same at start?

Question: I know this is an old game, but in the GameCube game Pokémon Colosseum, you start off with an Umbreon and an Espeon. Do they always have the same natures and starting stats for each new game? I know they are always boys. I would guess yes for stats, but are the natures random?
The reason this information would be useful is for trying to spawn favorable natures in those two Pokémon if they are indeed random.
Answer: Umbreon is Lv. 26 and Espeon is Level 25. Espeon is stronger overall, while Umbreon has more health and defenses, but weaker offensive stats. They also start out with different attacks as well.
In order to prevent breeding either of these two, Espeon
and Umbreon will always be male. Their IVs and Nature, however, will be
random.
Comment: I found the source here: http://www.gamefaqs.com/gamecube/914973-pokemon-colosseum/faqs/29532


Is My Load Bearing Beam Safe?

Question: I have been getting work done on my kitchen which involved removing a load bearing wall. To make a long story short, the contractor is a liar and now I can't trust him. It has been 2 months now of trying to get the beam approved by inspection. As a part of the permit process we did have to submit a plan from a structural engineer, which I have, but as far as I am aware, the structural engineer has never actually been to my house and has been contacted only by the contractor, not by me. I'm living about 2 hours away right now making things very difficult. Point is, I don't know enough about engineering to know if this is safe or not. How could an engineer calculate the load of my house without ever seeing it?
Any replies from any engineers with feedback would be great.
Comment: An engineer dies not have to see it. He/She just needs dimensions and a sketch.
Comment: This question isn't really appropriate here since it's ultimately about human nature, but if your contractor isn't providing accurate information to the engineer, how can the engineer's judgement be reliable? You knew that before you stopped by. FYI, engineers almost never visit jobsites in residential construction. They work from drawings almost exclusively from the comfort of their office chairs.
Comment: Did you see the Plan?  Did the plan look close enough to the house with the same dimensions?  Did the builder go by the plan?
Answer: This is actually pretty simple.
The work must be done according to the plan (drawings) made by the engineer.
The engineer does not have to go to your home.
Work that is done must pass inspection by your local building department.
If that work has not, or cannot pass inspection, you will have to speak with the local building department as to why.  They can tell you if the beam is not sufficient,( not built according to the engineered drawing) or if the attachment is not done correctly, or why they will not pass that part of the construction process.  Then you will have the correct information.
In the event that the inspector and the contractor have a disagreement, then schedule a meeting with them both and yourself at the home to discuss what will need to be done to make all parties satisfied so the project can move on.
Comment: 99% agree, except to say that the building department doesn't have the scope to have an opinion about a stamped engineered drawing. (In other words, if the engineer says a 2x6 is sufficient and the building inspector disagrees, the engineer wins every time.) Now, the building inspector has plenty of other pathways to make trouble for a job, so any sane GC works *with*, not against the inspector.
Comment: I edited the answer.  I agree the inspector does not opine about the beam other than if it is correct according to the drawing.
Comment: Also, having the inspector say "no, this isn't correct" gives the OP the firepower he needs to get the contractor to move or, worst case, to win in court. If it's just "Joe Average" homeowner against the contractor, the contractor is going to win 99.99% of the time.

Is My Load Bearing Beam Safe?


Angular + d3.js: Data binding with SVG text attr?

Question: I'm working on a visualization that involves updating a text element that appear inside of a circle. Something like:
<g>
    <circle></circle>
    <text>My text that needs updating</text>
</g>

Along with this small visual is a d3 brush being used as a slider. On brush/brushend, I need to <text>Update the text here</text>, based on data associated with a time scale along the slider's x-axis.
I have two Angular directives. One that contains the circle, the other that is the slider. In my slider directive I'm calling:
$rootScope.$emit('brushing'); and setting a rootScope variable according to my data, $rootScope.myNewValue = newValue; as sliding occurs
Then I'm listening for this in my other directive, and updating the text.attr to be the rootScope var:
$rootScope.$on('brushing', function () {
    myText.text($rootScope.myNewValue);
});
Where:
var myText = svg.append('text')
    .text('I'm trying to update this text..');

... in the d3 portion of the code
Doing things this way seems to work, but I'm wondering if there is a way to bind the data directly when initializing myText:
var myText = svg.append('text)
    .text($rootScope.myNewValue);

So that the value updates directly without having to $emit and listen. I've tried scope.$apply in the directive but that seems to have no effect.
Has anyone encountered a similar scenario when using d3 with Angular?
Comment: Have you tried just using angular binding to bind the text to a variable? Here is a good article on using SVG directly with angular: http://alexandros.resin.io/angular-d3-svg/
Answer: You can wrap up the D3JS code in a directive then use a property that is passed in and watch it to see if it changes to update the D3JS code accordingly (your saving a reference to the svg text is still probably the best bet).  For an example see my directive below where I use val to update the data used in a bar chart display (note I didn't deal with transitions here yet, and the codes a bit of a mess but hopefully you see the general point)
directive('barChart', function ( /* dependencies */ ) {
  // define constants and helpers used for the directive

  var width = 600,
    height = 80;

  return {
    restrict: 'E', // the directive can be invoked only by using <bar-chart></bar-chart> tag in the template
    scope: { // attributes bound to the scope of the directive
      val: '='
    },
    link: function (scope, element, attrs) {
      // initialization, done once per my-directive tag in template. If my-directive is within an
      // ng-repeat-ed template then it will be called every time ngRepeat creates a new copy of the template.

      // set up initial svg object
      var vis = d3.select(element[0])
        .append("svg")
          .attr("class", "chart")
          .attr("width", width)
          .attr("height", height);

      // whenever the bound 'exp' expression changes, execute this
      scope.$watch('val', function (newVal, oldVal) {

        // clear the elements inside of the directive
        vis.selectAll('*').remove();
        vis.attr("height", newVal.length*22);

        // if 'val' is undefined, exit
        if (!newVal) {
          return;
        }
        var totalDataSetSize = 0;

        for (var i = 0; i < newVal.length; i++) {
          totalDataSetSize += newVal[i].data.length
        };

        function calcBarWidth(d) {
          return (totalDataSetSize==0)?0:d.data.length/totalDataSetSize*420;
        }

        vis.selectAll("rect")
            .data(newVal)
          .enter().append("rect")
            .attr("y", function(d, i) { return i*20; })
            .attr("width", calcBarWidth)
            .attr("height", function(d) {return 20});

        vis.selectAll("text")
            .data(newVal)
          .enter().append("text")
            .attr("x", function(d) { return calcBarWidth(d)+10})
            .attr("y", function(d, i) { return (i+1)*20; })
            .attr("dy", "-.3em") // vertical-align: middle
            .style("font-size", ".7em")
            .attr("fill", "black")
            .attr("text-anchor", "beginning") // text-align: right
            .text(function(d,i){ return d.data.length.toString() + "  " + d.label})

      },true);
    }
  };
})

Comment: Thanks. This will probably work and I'll give it a try. I didn't think about setting up a watch. I'm currently passing in the value through an attr rather than a property of the isolate scope but I would anticipate similar results.
Comment: Yeah I think this will work for you, let me know if there's some issue as I plan to use this going forward :)
Comment: Will do. Haven't had a chance to try it out yet but will be back in the code this afternoon and will post an update.
Comment: We changed the approach of our application just slightly. What we are now doing is manipulating our slider, sending a XHR request based on the positioning, then updating our UI. However, this solution works for the new case and our previous approach. Thanks!


Get month name in Symfony

Question: Is it possible to get somehow name of given month (by its number) in Symfony's controller. And in current locale.
Form's date widget translates month to current locale automatically. I would like do the same but in my controller.
I know how get country translated but didn't found the same funtionality for month.
Thanks

Solution doesn't rely on Symfony components (except locale):
    setlocale(LC_ALL, $this->request->getLocale());
    $month = strftime("%B", mktime(0, 0, 0, $monthId, 1, 2000));

Comment: Not sure, but have a look to http://symfony.com/doc/current/components/intl.html
Comment: strftime has been DEPRECATED as of PHP 8.1.0. Relying on this function is highly discouraged.

See: https://www.php.net/manual/en/function.strftime.php
Answer: First, take a look at official ICU docs for date formatting. ICU is underlying component for Intl (mentioned by Yann in comments above).
So, given that variable $monthId contains the number of month, you could do:
$monthId = ....
$date = new \DateTime();

# Overwrite the date with first day in the month
$y = (int)$date->format('Y');
$date->setDate($y, $monthId, 1);

# Create a formatter
$fmt = new IntlDateFormatter(
    'en_US', // Your locale?
    "LLLL", // <--- This is the LONG MONTH format
    IntlDateFormatter::FULL,
    'America/Los_Angeles', // Time zone, not important in this case
    IntlDateFormatter::GREGORIAN
);

# Format the month
$monthName = $fmt->format($date);

Hope this helps...
Comment: And the solution is sooo simple: `setlocale(LC_ALL, $this->request->getLocale()); return strftime("%B", mktime(0, 0, 0, $monthId, 1, 2000));`
Comment: It should work but I got this error: `The Symfony\Component\Intl\DateFormatter\IntlDateFormatter::__construct() method's argument $locale value 'fr' behavior is not implemented. Only the locale "en" is supported. Please install the "intl" extension for full localization capabilities.`.
Comment: Oh, very simple indeed. Please include it as your own answer :) It certainly is much prettier than mine and should be upvoted :)
Comment: If y change the constructor call as following, it will work:
        $fmt = new IntlDateFormatter(
            'en_US',
            IntlDateFormatter::FULL,
            IntlDateFormatter::FULL,
            $dateTime->getTimezone(),
            IntlDateFormatter::GREGORIAN,
            'LLLL'
        );

Get month name in Symfony


How to turn off warning/error bars on APK build

Question: I am using a Hero animation in my App. During the transition, the text receives a thick yellow underline. I'm pretty sure this is a overflow warning (or something similar), but it persists even when I run flutter build apk and flutter install, i.e. it exists in production builds.
My app functions fine, so I'd like to hide these. How do I do so?
Answer:
During the transition, the text receives a thick yellow underline.

That is because Hero transition is done trough Overlay, which is rendered outside of Scaffold or other Material widgets.
The problem ? It means during transition, there's no widget that introduce a valid Theme (Scaffold, Dialog, Material do for example).
So it fallback to a default Theme. And that Theme has yellow underline with a big font.
The solution : Wrap your Hero child into a widget introducing Theme or in Theme itself.
Comment: Perfect! For future readers, I had to add `decoration: TextDecoration.none` to all my `Text` widgets, to revert the theme the hero transition widget recieved.
Answer: These bars are only shown in debug build.
For release builds use
flutter build apk --release

Comment: That's not the problem actually
Comment: I'm aware that the overflow should be fixed but he explicitely asked how to just get rid of the yellow bar :D As far as I know they are not shown in release builds.
Comment: Yeah but it's not overflow he's talking about. It's about text having a yellow underline during hero transition.
Comment: I think I see now what you mean
Comment: As @RémiRousselet stated, I confused the overflow warnings with the default Hero transition behavior. However, flutter gives faux-warnings (i.e. it thinks there are sub-pixel overflows due to rounding errors), and this helped quell them. Cheers!


What controls to fix this Filter?

Question: https://www.scic.com/schedule
I'm looking to replace the filters on the right side of the page and need to know some of the possiblities.
For the date selector, I'm looking at using: http://www.filamentgroup.com/lab/date_range_picker_using_jquery_ui_16_and_jquery_ui_css_framework/
Any other ideas as far as the other criteria is concerned? each of the criteria should also be multiselect.
Needs to be mobile friendly because we are moving that direction.
Comment: What problems are you seeing with the existing filters? What are the goals or requirements that the replacement filters need to address?
Comment: The user comments are that they are unwieldy and not easy to use, especially the Programs selector accordion at the bottom.
Answer: How about replacing the accordion with a multiselect box?
Comment: Don't think they're going to go for that one.
Comment: What, no other ideas?
Comment: I couldn't find anything that doesn't move items from the complete list to the selected list.
Comment: I don't quite understand what you are saying.

What controls to fix this Filter?


How can I find joists in my heavily-textured garage ceiling?

Question: I would like to install ceiling shelves in my garage. However I have a textured ceiling - it's not acoustical texture - more or less it looks like a wavy ceiling. It is also very thick so its nearly impossible to find a seam.
I had done research on this and a couple of ideas were- get a piece of cardboard and run your stud finder along the cardboard - the other idea is drill small holes in ceiling til you hit a stud- and lastly is to measure 16" from one side of the wall to the other. Has anyone ever tried any of these and what worked best for you?
Answer: Studfinders should work fine regardless of texture. Most have a deep scan mode for such situations, but I'd be surprised if that's even necessary.
If that's really not working, look for clues. Your overhead door is probably suspended from ceiling joists. You may have an outlet or light boxes attached to them as well. You may find nails in exterior fascia indicating rafter tail location.
Most modern truss systems are 24" on center. Older hand-framed roofs are likely 16" on center. Once you find one you should have them all.
Answer: Your curling is probably wavy because you have 1/2" drywall over 24" OC (on center) joists. The finished curling was not originally installed when your house was built. If it was planned for it would probably be 5/8" drywall over 16"OC joists. More support and more rigid drywall that way resists warping.
So to find your joists try using a magnet at on end of your ceiling. When it sticks to a nail or screw make a mark. Then go to the opposite end and do the same. Now snap a chalk line (a chalk box is an inexpensive hand tool found at any hardware store) or use a long straight edge to scribe a pencil line from your first mark to the second mark. As long as your mark the exact or close as possible location of the screws or nails under the mud or texture you will be marking the center of the stud and you won't have to worry about measuring 5/8"  out for edge of joist.
You can do this for all your joists or just the adjacent joist and hopefully the two joist locations will tell you the basic layout of your joists--either 24" OC or 16"OC. Then just measure over every 16 or 24 inches. This will give you most of your joist locations.
There may be an extra one here and there or a cross member you might be able to utilize in your installation. Remember the direction of your joists is usually in the direction of the shortest distance. It makes for a stronger structure if you have the shortest framing members rather than longer ones.


Calculation in Kivy with inputs from several widgets (and output to a different one)

Question: I'm trying to build an app with kivy that asks for some numbers and then returns a calculation, but I need the input numbers to be provided on different widgets. I've been searching for a way to do that, and it seems that it can be done with ObjectProperty() or NumericProperty(), but I can't figure the correct way. For a barebone example (not working, obviously), below is the code for an app where two numbers are introduced and it calculates the sum. The main.py is
    from kivy.app import App
    from kivy.uix.boxlayout import BoxLayout

    class SumRoot(BoxLayout):
        pass

    class FirstInput(BoxLayout):
        pass

    class SecondInput(BoxLayout):
        pass

    class OutputSlide(BoxLayout):
        def sum_of_inputs(self):
            self.resultado.text = str(float(self.first_input.text)+float(self.second_input.text))

    class SumApp(App):
        pass

    if __name__ == '__main__':
        SumApp().run()

and the sum.kv files is
    SumRoot:

    <SumRoot>:
        carousel: carousel
        first_slide: first_slide
        second_slide: second_slide
        third_slide: third_slide

        Carousel:
            id: carousel
            FirstInput:
                id: first_slide
            SecondInput:
                id: second_slide
            OutputSlide:
                id: third_slide

    <FirstInput>:
        orientation: "vertical"
        first: first_input
        TextInput:
            id: first_input
        Button:
            text: "Next"
            on_release: app.root.carousel.load_slide(app.root.second_slide)

    <SecondInput>:
        orientation: "vertical"
        second: second_input
        TextInput:
            id: second_input
        Button:
            text: "Sum"
            on_press: root.sum_of_inputs()
            on_release: app.root.carousel.load_slide(app.root.third_slide)

    <OutputSlide>:
        orientation: "vertical"
        result: result_output
        Label:
            id: result_output

The intended behavior is that when one presses the "sum" button it calculates the sum, goes to the next slide and displays the sum. All suggestions are welcomed.
Answer: 1) Pass references of the inputs to the OutputSlide, which does calculations:
OutputSlide:
    id: third_slide
    first_input: first_slide.first
    second_input: second_slide.second

2) Add object properties in py file, which will hold them:
from kivy.properties import ObjectProperty
...
class OutputSlide(BoxLayout):

    first_input = ObjectProperty()
    second_input = ObjectProperty()
    result = ObjectProperty()  # this one aswell, don't leave bare ids

3) Calculate the result on_press correctly:
<SecondInput>:
....
on_press: app.root.third_slide.sum_of_inputs()

Additionally, fix naming bugs in OutputScreen.


How can I create a cp932 encoded text file on Ubuntu?

Question: Is there a way to create a cp932 encoded file on Ubuntu?
Answer: gedit, "Save as" has an option to save it with a different encoding.

After that it should accept Japanese chars.
as seen here:

~/Desktop$ file test.txt
test.txt: DBase 3 data file with memo(s)

Command line

convert a file to cp933:
recode cp932 {filename}

or
iconv -f utf8 -t cp932 {filename} > {newfilename}

You probably need to install recode with sudo apt-get install recode
If you do
 touch {filename}
 recode cp932 {filename}

you create an empty file and should be able to add cp932 chars to the file.
If you use vim place the following in your /etc/vim/vimrc or ~/.vimrc file:
set encoding=cp932
set fileencoding=cp932

and the system will save the with cp932.
Comment: Thanks. Is there a way to create a cp932 encoded file from the command line? I don't have GUI access to Ubuntu
Comment: yes added those options.