text:
Q: Why are most of the common processors' bit counts powers of 2? Most of the processors/CPUs widely used today, have a bit count that is a power of 2 (usually 32 and 64, but also 16, 8, and 4 bits).
Even though the meaning of bit count isn't consistent (some say it's the word size, the size of the registers, the instruction width, the data or address bus width etc.), all of these are almost always powers of 2.
I know there are some exceptions to this, for example the Intel 8086 had a 20 bit address bus, but as I said it is usually a power of 2.
Why does this happen, what are some exceptions, and why?

A: As RonJohn wrote, "computer industry, pushed by IBM, standardized on 8-bit bytes for General Purpose computers".
After that, there are internal advantages with using powers of 2 multiples of that - it allows for everything to be aligned when different size collections of bytes are used, and allows different bits of the address to be routed different places - e.g. which cache-line/block/page you want vs. where in the cache-line/block/page. That would require an ugly (and slow) division if anything other than a power of two was used.
For instance, you might have 32 or 64 bit registers, a 64 or 128 bit memory bus, 128 bit or 256 bit cache lines, 512 byte (=4096 bit) blocks on disk, 4096 byte (=32768 bit) pages in memory, etc. As long as these are all powers of two, the boundaries between them will as much as possible be in the same places, and the addresses all get split up bit-wise for addressing purposes, which leads to simpler hardware.
If for example you were to then throw a 25 bit or 48 bit structure in there and wanted to have an array of them, there would have to be either wasted space or you would end up having elements split across cache lines, memory pages etc. and it would take a division using all bits to determine which element an address was in.
The alignment part of this doesn't matter as much as it used to - for instance modern Intel/AMD chips don't have penalties for misaligned data at the byte level, but quite a bit of engineering has gone into that.
It also would work just fine if the lowest addressable unit was some number of bits as long as powers of 2 are used above that - for instance, if a byte was 7 bits, the other values would be 14, 28, 56, 112 ... . Indeed, many older architectures and some more specialized word addressable CPUs like DSPs use different word sizes, particularly if data and program memory is stored separately (Harvard Architecture).

A: I'd suggest that it is more a convention, less a technical issue.
Wikipedia's page on the word size choice in computer architecture has a nice table with a lot of older computer architectures with byte/word sizes which are not a power of two. On that page there is also a box in the upper right hand corner with links to individual pages for many unconventional word sizes (e.g., 12, 18, 24 but also 31, 36, 45 (!) etc.
One area where the byte/word size has significant impact is in compilers; i.e. your C compiler needs to know how many bits are available in the addressing registers (i.e. 16/24/32/64 bit), and many aspects flow from that (i.e., how arrays of integers are laid out in memory and how the code to access that is generated by the compiler).
Code built for one word size is then of course also usually incompatible with code built for other word sizes, even if the CPU in question would otherwise use exactly the same coding for their assembly language.
Also, if your data storage is binary - in the old days it was not unheard of to just dump a page of memory into a file and read that back in "as is" later - this completely breaks down if the two machines use different word sizes (even if other aspects, like endianess, are the same).
All of this leads to the industry converging on a smaller and smaller number of word sizes, just like many other technological aspects have converged over the years. As user alt-ctrl-delor has mentioned in his answer, one (maybe minor) aspect here could be that if you have some integer within your CPU, maybe even only internally/in hardware, where you wish to store the location of a bit within an register (i.e., a dynamic value ranging from 0 to the word size of your register), then having a register width that is a power of 2 avoids waste and some error states (i.e., addressing a bit past the non-power-of-two word size).

A: 8-bit bytes
Much of this grows out of the adoption of the 8-bit byte. That became popular with the introduction of the IBM 360 family of computers in 1964. In an issue that year of the IBM Technical Journal, an explanation of the choice was offered:

Character size, 6 vs 4/8: In character size, the fundamental problem is that decimal digits require 4 bits, the alphanumeric characters require 6 bits. Three obvious alternatives were considered - 6 bits for all, with 2 bits wasted on numeric data; 4 bits for digits, 8 for alphanumeric, with 2 bits wasted on alphanumeric; and 4 bits for digits, 6 for alphanumeric, which would require adoption of a 12-bit
module as the minimum addressable element. The 7-bit character, which
incorporated a binary recoding of decimal digit pairs, was also
briefly examined.
The 4/6 approach was rejected because (a) [it] was desired it to have the
versatility and power of manipulating character streams and addressing
individual characters, even in models where decimal arithmetic is not
used, (b) limiting the alphabetic character to 6 bits seemed
short-sighted, and (c) the engineering complexities of this approach
might well cost more than the wasted bits in the character.
The straight-6 approach, used in the IBM 702-7080 and 1401-7010
families, as well as in other manufacturers' systems, had the
advantages of familiar usage, existing I/O equipment, simple
specification field structure, and of commensurability with a 48-bit
floating-point word and a 24-bit instruction field.
The 4/8 approach, used in the IBM 650-7074 family and elsewhere, had
greater coding efficiency, spare bits in the alphabetic set (allowing
the set to grow), and commensurability with a 32/64-bit floating-point
word and a 16-bit instruction field. Most important of these factors
was coding efficiency, which arises from the fact that the use of
numeric data in business records is more than twice as frequent as
alphanumeric. This efficiency implies, for a given hardware
investment, better use of core storage, faster tapes, and more
capacious disks.

Overall, an 8-bit byte allowed a reasonably large character set, by the standards of the time, and also allowed two BCD digits per byte.
The move to byte addressing
The priority in the earliest computer designs was to process numbers as rapidly as possible. A number was typically stored in a machine word, and the desired numerical range determined the size of the word. Instructions were normally a single word, and there was often a single address as part of each instruction. The size of the address field in instructions determined the memory size. The IBM 704/709 is an example; it had a maximum of 4096 words of 36 bits, with six characters per word, each of 6 bits. Addresses are 12 bits.
As the range of uses for computers expanded, handling text data became more and more important. Doing that in a word-addressed machine is cumbersome, at best. A byte-addressed machine allows you to access individual characters easily, but demands a larger address field. At the same time, magnetic core memory allowed building much larger memories than vacuum tubes, electrostatic storage or delay lines.
These developments essentially forced computers to have larger address spaces, and ended the practice of having an address in each instruction.
Larger Data Items
It obviously makes things simpler to have a whole number of bytes per data item. Simplicity at this level is extremely worthwhile, because it's always been important to make a computer run as fast as possible within a limited budget of electronics parts (tubes early on, transistors since then). So two bytes (16 bits) becomes an obvious size.
For larger sizes, there are two factors that show up in the electronics design:
Counting things
Implementing instructions often requires counting through the bytes (or bits) of data items. Using powers of two makes the electronics of those counters simpler. To count through 4 bytes, you need a two-bit counter, which can hold values from 0 to 3. Counting through three bytes still needs a two-bit counter, but one of its values is meaningless and has to be treated as a special case in hardware.
Sending data over a serial line requires counting through the bits of each item, which is another benefit of 8-bit bytes. A 3-bit counter will handle them, without any need for special cases.
The IBM 360 picked 32-bit addresses (although it only allowed 24-bit memory addresses for its first decade), and once that was established, it was far easier to compete with IBM using 8-bit bytes and 32-bit addresses than if you wanted to do something different.
Memory fetches and data alignment
Fetching data from memory is simpler if data items are "aligned". This means that their addresses are a multiple of their size. So for a byte-addressed machine, like the IBM 360, a single byte can be at any address. A two-byte (16-bit) item as "aligned" if it is at an even-numbered address. A four-byte (32-bit) item is aligned if its address is a multiple of 4.
Many computer designs of the 1960s through 1990s had memories that could fetch 4 bytes in one operation, starting from an address that was a multiple of 4. If your data items are aligned, then you're guaranteed to be able to fetch any two- or four-byte item in a single read from memory. If they are not aligned, you sometimes need two fetches. That requires more complexity in the memory access system, to recognise that the operation is misaligned and generate the extra fetch. That complexity, and the extra fetch, slow things down.
Items bigger than four bytes will need two fetches, but life is simpler if your larger items are eight bytes, and aligned on 8-byte boundaries. Then you always need exactly two fetches. If you have 8-byte items that are not aligned, then you need three fetches.
In modern fast systems, fetches are always of complete cache lines, usually 32 or 64 bytes. These are always aligned, and aligned data items that fit inside them always arrive complete.
Quite a few computer designs regard a misaligned fetch as a program bug, and kill programs that execute one. x86-based systems don't do that, but have to pay the complexity price. They do run faster with aligned data, so that is normally used even though it is not compulsory.
24-bit systems
I've used a 24-bit system, an ICL 1900 mainframe. It used 6-bit bytes, four per 24-bit item. Those 6-bit bytes limited it to UPPERCASE text, and 24-bit pointers limited it to 16MB of RAM, which is tiny by today's standards.
A more modern 24-bit system with 8-bit bytes would still be limited to 16MB of easily addressable memory, and would be paying the costs of counters with unwanted states, and memory items that were either misaligned, or wasted a byte of memory for every 24-bit integer. A 32-bit system would be more capable, and can be built very cheaply in today's technology.
Lessons of history
There have ben a couple of influential computer systems that had 32-bit integers and pointers, but used 24-bit addressing. They're the Motorola 68000 and the IBM 360. In both cases, only the lowest 24 bits of an address were used, but addresses were stored in memory in 32 bits.
As those systems were limited to 16MB of RAM, programmers stored other data in the spare 8 bits. And when 16MB of RAM clearly wasn't enough and the designs were expanded to 32-bit addressing, that data stored in spare bits became a serious problem, if it was treated as part of the address.
On the 68000 family, existing programs had to be changed to stop using those no-longer-spare bits. This was most noticeable in the wider computer industry for Macintosh software in the late 1980s, when updating for 68020 compatibility, but the same thing happened on Amiga, and presumably other 68000-based systems.
On the successors of the IBM 360, 24-bit address programs could still be run, as could programs using larger addresses. But only 31 of the potential 32 address bits could be used; an address bit had been sacrificed to let the hardware tell the difference between the two kinds of code.
Everyone who designed a general-purpose architecture with addressing larger than 32 bits knew of those examples, and how much pain they'd caused. So let's look at the choices of address size:

*

*40-bit addressing involves electronic and alignment complexity, and clearly wasn't going to last very long. It only allows addressing 1024GB, and as of 2022, that would already have become a problem for some markets.

*48- or 56-bit addressing are about as complex as 40-bit, and while they probably would last rather longer, by the time you've gone this far, you might as well go all the way.

*64-bit is simpler to build than 40-, 48- or 56-bit. It will last longer. Its register size matches standard floating-point data sizes. It seems logical.
The first general-purpose post-32-bit microprocessor released was the DEC Alpha in 1992. The project had started in 1988, initially aiming to keep the 32-bit VAX architecture relevant in the long term. The designers rapidly realised that this was impractical, and designed a new architecture, intended to last at least 25 years. They therefore went for 64-bit addressing, to make sure that they didn't run out of address space.
Releasing a competitor to Alpha which wasn't 64-bit would obviously have a marketing problem with "why isn't it 64-bit?" questions. So 64-bit became the consensus. The much newer RISC-V architecture makes some provision for 128-bit addressing, although this has not yet been designed.
An important detail: no current 64-bit processor can actually have 64-bits worth of memory connected to it. None of them have enough address lines. This does not matter. Future implementations can be given more address lines. Programmers have to be discouraged from using the "spare" address bits, but that's practical to do, and operating systems can be designed to reject such usage.

A: It's coincidence, or just everyone copying everyone else. There is no deep technical reason that the number of bits should be a power of two. (There is a deep technical reason however that the number of possible values is a power of two).
A processor with 24, or 31, or 60 bit words would work just fine. Processors supporting extended precision have an 80 bit floating point type (that would be the x86 processors today and the 68k processors in the past).
When storing bit arrays, you need to divide integers by the number of bits in a word. There you have a slight advantage for powers of two, but an instruction dividing by one specific non-power of two integer is quite simple. When you want to pack small numbers into a bit array, it's nice if the number of bits in the small number divides the number of bits in a word, so a 60 bit word would allow you to store 60 bits, 30 x 2bits, 20x3 bits, 15x4 bits, 12x5 bits, or 10x6 bits in a word.
For character encodings, having 12 bit bytes instead of 8 would make it possible to store all unicode code points into two bytes instead of 1, 2, 3 or 4, which would make lots of text processing code faster.
BTW: "RAM chips will have a size that is a (power of 2) bits". Until Apple ships computers with 12GB RAM chips... Again no technical reason for a power of 2. I actually expected 10GB per chip :-)
CDC (the company that Cray left to build Cray computers) had sixty bit words. Very nice to fit four 15-bit, two 15 and one 30-bit, or two 30-bit instructions into one word.

A: Because the computer industry, pushed by IBM, standardized on 8-bit bytes for General Purpose computers.
The consequence of this is that it's more convenient for registers to have bit counts in multiples of 8:

*

*8 - 1 byte per register

*16 - 2 bytes per register

*24 - 3 bytes per register

*32 - 4 bytes per register

*40 - 5 bytes per register

*48 - 6 bytes per register

*56 - 7 bytes per register

*64 - 8 bytes per register
As you can see, 8- and 16-bit counts are obvious.
Why not 24 bits?  Because Moore's Law meant that transistor counts were growing fast enough that designers could go straight from 16 to 32 bits.
After 32 bits, why not 48 bits?
Well, we did, but for the address bus.  In the registers, they bit the bullet and went for 64 bits.
If computers ever need more than 256TB of RAM, then chip and motherboard makers easily increase the address bus from 48 to 64 bits while leaving the registers untouched.

A: Having 2ⁿ bit registers, allows bits in the registers to be addressed with an integer number of bits:
Addressing a bit in an 8 bit register will need 3 bits. Addressing a bit in a 16 bit register will need 4 bits. But, addressing a bit in a 12 bit register will need 3.58… bits. You would have to round it up to 4, thus wasting ≈0.4 of a bit.
Example

*

*Immediate shift: the shift distance is stored in the instruction.

*Immediate read bit: reads a bit for a register, the bit number is specified in the instruction.

*Reading or writing a bit from a large memory field: Mask (bit wise and) to get upper bits of the address and use these as the byte address, mask (bit wise and) to get lower bits of the address and use these as the bit offset.

We don't always use registers to specify the bit. We often use immediate addressing (the address is in the instruction). Even arm does this, and it does not have immediate addressing (at byte level). When we have the address in a register, then we are often dealing with more than 32 bits, so have to mask the address to get the byte number and the bit number. This only works because of the power of 2.

A: The most common reason is because computers use the binary system, where
a bit can be either a zero or one.
If computers used ternary values for the bits, then we'd have everything in powers of 3.
As regarding RAM/memory:
A number N of bits in an address bus (used to select an address)
can address 2^N bytes.
Whenever the number of address bits increases to N+1, automatically
the addressable space increases by a factor of 2.
The manufacturers will naturally use the maximum address capacity
when including memory chips in the design, so memory size will naturally
be in powers of two.
As regarding register sizes:
The same reasoning applies, since internally the hardware may address
a bit in the register using its number, which again is in binary
notation.
(All this is just a supposition and an enormous simplification of the
real situation. I'm sure that an electrical engineer will be able to
demonstrate why circuits based on the binary logic will naturally
use a power-two. As the Intel 8086 has shown, other numbers are possible,
but may be costlier to manufacture.)

A: I think some of the arguments missing is that it is convenient that a register can be divided into two parts which are easy to work with, for instance with smaller registers. Hence, for the intel architecture, you initially had 16 bits registers that were subdivided into two 8-bit subregisters, and then these registers were extended to 32 bits, keeping the least significant digits addressable as 16 bits register, and then to 64 bits. If you had a 48 bits register, it would leave an awkward 16 most significant bits part, and you would have to play with 16 bits and 32 bits subregisters... What a pain !
Moreover, when you multiply the contents of two registers, you need a register of twice that size (or two registers of the initial size) to contain the result. Having registers that cannot be combined two by two would make things complicated for arithmetic.
I guess this view is supported by the fact that, for addressing (and not arithmetic), the processors internally use other numbers of bits.

A: Generally, processors are referred to as x-bit, where x is the width of the data bus.
In rough terms, increasing the data bus size offers primarily speed as a reward...twice the bits, twice the data access speed.  This is the ideal; some inefficiencies are involved (e.g., fetching 1 byte still takes 1 cycle on a 32-bit system, same as fetching 4 bytes).
As ctrl-alt-delor points out, there are some logistical advantages to stick with a bus width of 2**N.  The only restriction of following this pattern is that you have to double the width every time you introduce a wider architecture, giving a max access speed increase of 2.
And in the end, it's hard to justify a new architecture if it's not at least twice as fast as the old one.
Note that low end microcontrollers offer many exceptions to this rule, and the properties of audio and human perception have made 12 bits a popular width for DSPs.

A: CPU register width tends to grow faster than the ability to cheaply get RAM to fill it all.
You can save money on developing and manufacturing your CPU by not adding pins, such as address pins, that will never be used.
Furthermore the 8086 was really weird - addresses were expressed using segments.  20 bits address lines made sense for that.
A segment was basically a value shifted 4 bits, and it was combined with an offset to get the real address.  E.g 0000h:1000h and 0001h:0100h referred to the same address. This allowed some interesting tricks with making code relocatable I think, but did make C-style pointers complicated.
386 and other CPU architectures with MMUs change the game up a bit.
Physical addresses only matter if

*

*your MMU is "identity mapped" and your mapping is 1:1 from virtual->physical.

*you're in the "ring 0" or kernel/supervisor mode that allows access to all memory.

When you are in the "ring 3" or user mode, your access is constrained by the MMU - accessing pages that are marked specially will cause a fault to kernel mode.
Now of course, this can be used to limit a user process to a specific amount of memory.  But it can also be used to implement swap files and mmap - a UNIX system call that essentially leverages the MMU to make it look like a file is mapped to memory.  This simplifies access to it for programs that need to deal with large amounts of data and random access, such as databases.
So, 64 address bits is a lot of room to map files in and some random high address in the 64-bit space might be chosen - but it's never meant to reach actual RAM in the first place.
I can't really find good pinouts of any modern CPU but I doubt they physically bring out 64 address lines for each of the RAM channels.  But there is still value in having all registers that refer to memory be 64 bit due to the above.

A: If I remember the math theory correctly, ideal numerical system has e numbers, where 3 is the closest integer number to it. That means that 3 would be better from a theory point of view, then a binary system, but the implementation in hardware is easier to do with two numbers then 3.
For a bit more details, see this: https://math.stackexchange.com/questions/446664/what-is-the-most-efficient-numerical-base-system


text:
Q: SQL Server : Recursive Advanced Query on two conditional logics Not showing hierarchy relationship Recently I got a challenge to resolve in SQL Server 2012. This is the background of the problem.
We are maintaining a self referencing entity (hierarchy) in our product entity. Each product is having parent and child relationship.
Product is having special grouping called master products which derive based on the following logic.
If there is only one product available on hierarchy with regardless of IsMasterProdcut flag it consider master account.
For other products which its immediate parent product tagged as master product or top most product which comes first consider as master product.
Graphical representation is as follow ,

This is the DDL
-- Create Table
CREATE TABLE Product
(
    ProductID int PRIMARY KEY,
    Name      VARCHAR(30) NOT NULL,
    ParentId  int,
    IsMasterProdcut bit NOT NULL
)

-- Insert the data to the table
-- Senario where top most product is the master product
INSERT INTO Product (ProductID,Name,ParentId,IsMasterProdcut) VALUES (1,'Prodcut 1',NULL,0); -- <-- this is the master prodcut as non of the child as flaged
INSERT INTO Product (ProductID,Name,ParentId,IsMasterProdcut) VALUES (2,'Prodcut 2',1,0);
INSERT INTO Product (ProductID,Name,ParentId,IsMasterProdcut) VALUES (3,'Prodcut 3',2,0);

-- Senario two where in middnle account has flag as master product
INSERT INTO Product (ProductID,name,ParentId,IsMasterProdcut) VALUES (4,'Prodcut 4',NULL,0); -- <-- this is the master prodcut as this is top most in hirerachy . So 4 will be master prodcut of 4 and 5 , 6 and 7 will not master product
INSERT INTO Product (ProductID,Name,ParentId,IsMasterProdcut) VALUES (5,'Prodcut 5',4,0);
INSERT INTO Product (ProductID,Name,ParentId,IsMasterProdcut) VALUES (6,'Prodcut 6',5,1); -- < -- this a a master prodcut as it is flagged as master product , So account 7 and 6 master product with be 6
INSERT INTO Product (ProductID,Name,ParentId,IsMasterProdcut) VALUES (7,'Prodcut 7',6,0);

-- Senario three where it has one product
INSERT INTO Product (ProductID,Name,ParentId,IsMasterProdcut) VALUES (8,'Prodcut 8',0,0);
INSERT INTO Product (ProductID,Name,ParentId,IsMasterProdcut) VALUES (9,'Prodcut 9',0,1);

-- Senario 4 Complex product

INSERT INTO Product (ProductID,Name,ParentId,IsMasterProdcut) VALUES (10,'Prodcut 10',0,0);
INSERT INTO Product (ProductID,Name,ParentId,IsMasterProdcut) VALUES (11,'Prodcut 11',10,0);
INSERT INTO Product (ProductID,Name,ParentId,IsMasterProdcut) VALUES (12,'Prodcut 12',11,1);
INSERT INTO Product (ProductID,Name,ParentId,IsMasterProdcut) VALUES (13,'Prodcut 13',12,0);
INSERT INTO Product (ProductID,Name,ParentId,IsMasterProdcut) VALUES (14,'Prodcut 14',10,0);
INSERT INTO Product (ProductID,Name,ParentId,IsMasterProdcut) VALUES (15,'Prodcut 15',14,0);
INSERT INTO Product (ProductID,Name,ParentId,IsMasterProdcut) VALUES (16,'Prodcut 16',15,0);
INSERT INTO Product (ProductID,Name,ParentId,IsMasterProdcut) VALUES (17,'Prodcut 17',10,0);

Expected Result
Master Product ID   Master Product Name Product ID  Product Name
1                    Product 1          1            Product 1
1                    Product 1          2            Product 2
1                    Product 1          3            Product 3
4                    Product 4          4            Product 4
4                    Product 4          5            Product 5
6                    Product 6          6            Product 6
6                    Product 6          7            Product 7
8                    Product 8          8            Product 8
9                    Product 9          9            Product 9
10                   Product 10        10            Product 10
10                   Product 10        11            Product 11
12                   Product 12        12            Product 12
12                   Product 12        13            Product 13
10                   Product 10        14            Product 14
10                   Product 10        15            Product 15
10                   Product 10        16            Product 16
10                   Product 10        17            Product 17

Working solution: this is the solution that I have got so far:
      BEGIN

    CREATE TABLE #TmpMasterProduct
    (
       ProductId nvarchar(50)
    )

    INSERT INTO #TmpMasterProduct
    SELECT ProductId

    FROM (
        -- Get master accounts which are flagged as master product
        SELECT MA.ProductId
        FROm [dbo].[Product] AS MA WITH (NOLOCK)
        WHERE MA.[IsMasterProdcut] = 1

        UNION
        -- Get top most prodcut which will be automatically consider as master product.

        SELECT MAT.ProductId
        FROM DBO.[Product] As MAT WITH (NOLOCK)
        WHERE MAT.[ParentId] IS NULL
    ) AS MasterProdcuts;

    WITH Mapping as
    (
      SELECT A.ProductId , A.ParentId
      FROM DBO.[Product] A
      WHERE  A.ProductId IN
      (
        SELECT ProductId
        FROM #TmpMasterProduct
      )

      UNION ALL

      SELECT A.ProductId , A.ParentId
      FROM DBO.[Product]  A
      INNER JOIN Mapping M
      ON M.ProductId = A.ParentID
     )

    SELECT  M.ParentId As MasterProductId ,  MP.Name As MasterProductName , M.ProductId As ProdcutId , CP.Name As ProductName
    From Mapping As M
    LEFT OUTER JOIN DBO.Product As MP ON MP.ProductId = M.ParentId
    LEFT OUTER JOIN DBO.Product As CP On CP.ProductId = M.ProductId

    DROP TABLE #TmpMasterProduct

END

But I'm deviating form the result that I want. This is the current out put I'm getting.
MasterProductId MasterProductName   ProdcutId   ProductName
NULL               NULL               1           Prodcut 1
NULL               NULL               4           Prodcut 4
5                  Prodcut 5          6           Prodcut 6
0                  NULL               9           Prodcut 9
11                 Prodcut 11         12          Prodcut 12
12                 Prodcut 12         13          Prodcut 13
6                  Prodcut 6          7           Prodcut 7
4                  Prodcut 4          5           Prodcut 5
5                  Prodcut 5          6           Prodcut 6
6                  Prodcut 6          7           Prodcut 7
1                  Prodcut 1          2           Prodcut 2
2                  Prodcut 2          3           Prodcut 3

Basically this query I wrote does not goes to deeper level. It terminates form the parent. And second observation I had is this does pick up parents nodes which are not master product.
Is my approach wrong? What is the best way I can get this done except cursors.

A: You are on the right track :) Some fixes:
You are inserting zero, not null, as ParentId into products 8 and 10 - this is why they are never picked up in your initial #TmpMasterProduct query - you'll need to change these back to NULL  e.g.
INSERT INTO Product (ProductID,Name,ParentId,IsMasterProdcut)
VALUES (8,'Prodcut 8',NULL,0);

(Also, if you were enforcing referential integrity with a Foreign Key from ParentId -> ProductId on the self-join, this kind of issue would be prevented)
You don't need the UNION on the master product prefilter - you can just use OR, i.e.:
INSERT INTO #TmpMasterProduct
SELECT MA.ProductId
FROM
    [dbo].[Product] AS MA
WHERE MA.[IsMasterProdcut] = 1 OR MA.[ParentId] IS NULL;

In your recursive CTE, you'll need to keep remembering the actual MasterProductId, not necessarily the ParentId for each Master product tree, to allow for hierarchies greater than 1 deep, i.e.
WITH Mapping as
(
  SELECT A.ProductId as MasterProductId, A.ProductId , A.ParentId ...

  UNION ALL

  SELECT M.MasterProductId, A.ProductId , A.ParentId ...

You'll need to introduce a termination condition on navigating a tree, which terminates when there is a node which is itself a Master Product (this will be listed separately).
AND A.IsMasterProdcut = 0

You'll want to order the items by MasterProductId to print them out nicely.
SqlFiddle here

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does 'python --version' not print string I was trying to write a bash script to test the python version. However, I found python --version behave weirdly for python 2, as I can't process its output using any tool. I have tested the same script on Mac OS (10.13.5) and AWS Linux (GUN/Linux #1 SMP Fri Feb 16 00:18:48 UTC 2018). So I think the problem is related to python 2.
The script and corresponding output are:
$ echo $(python --version) | awk '{print $2}'
> Python 2.7.10

But the output should be 2.7.10.
$ echo $(python --version) > weird.txt
> Python 2.7.10
$ cat weird.txt
>

So the output cannot be written into a file as well.
The same script to test for python3 has a totally different result
$ echo $(python3 --version) | awk '{print $2}'
> 3.6.5

But python3's output can be written into a file.
$ echo $(python3 --version) > weird.txt
$ cat weird.txt
> Python 3.6.5

I have found the reason for this difference is that python --version does not output a normal string or whatsoever. Maybe it calls another command to output the result for it??? Thus the result cannot be caught by current process?? (just pure guess here)
Can anyone help me to figure out why there is the difference here? There are probably of million ways to test for python version. But I'm just super curious about what is happening here.
Thanks for all the replies. Just found a useful answer explaining that why python -V outputs to stderr:
Why does python print version info to stderr?

A: Python outputs the version to standard error (stderr) up to version 3.3 according to issue 18338 and as noted here, so redirect accordingly:
$ echo $(python --version 2>&1) | awk '{print $2}'
2.7.14

The command substitution is unnecessary and this could be written as:
$ python --version 2>&1 | awk '{print $2}'

A: How about using Python command itself using platform library of it(which is a very common in use).
python -c 'import platform; print(platform.python_version())'

When I run it I get Python's exact version.


text:
Q: How to compare two columns with thousands of rows I need a quick help please. I have two columns in excel with thousands of rows. They are supposed to be the same, that is a1 =b1, a2 =b2, a3=b3 and so on. But i need to confirm that is in fact true. So how do i verify that quickly without having to create a third column of thousands of rows. (several ways that i discarded are using the "=and(exact..." formula or color coding where there are differences. Because those methods would again require me to check the new third row or check all the rows manually for color difference). The values in the rows that i have are alphanumeric.I appreciate any help. Thanks.

A: I have just seen a very similar thread here suggesting using an Array Formula. You would need to enter the formula below and press ctrl+shift+enter, you can tell it is being handled as an array formula if curly braces are shown around it when you go back to the cell:
=AND(Sheet1!A1:A10000=Sheet2!B1:B10000)

Note that the ranges in the formula above can be adjusted as required, I have assumed from your question that 10k rows will be enough to compare and that you want to compare column A in sheet1 to column B in sheet2.


text: Q: Difference between IEC60309 2P + E and P + N + E From my understanding the 2P + E contain 1 wire for the line 1 wire for neutral and another line for ground. Then what's the difference between these 2 plug? Are they compatible with each other?


text:
Q: find all $m$,$n$ such that $\varphi(m) + \varphi(n) = \varphi(mn)$. We have to find all $m,n$ belongs to natural numbers such that $\varphi(m) + \varphi(n) = \varphi(mn)$.
I know if $(m,n)=1$, then $ \varphi(m)\varphi(n) = \varphi(mn)$.
but, I am confused how I can use this fact here.

A: Let $d=\gcd(m,n)$, $D=\varphi(d)$, $M=\varphi(m)$, $N=\varphi(n)$.
Then $D(M+N)=MNd$, because $\varphi(d) \varphi(mn) = \varphi(m) \varphi(n) d$.
Also, $\varphi(n)$ divides $\varphi(kn)$. Therefore, $M=AD$ and $N=BD$.
Thus, $D^2(A+B)=ABD^2d$ and so $A+B=ABd$. This implies $A \mid B \mid A$ and so $A=B$. Then, $2A=A^2d$ implies $d=1$ or $d=2$.
If $d=1$, then $M+N=MN$, which implies $M=N=2$. Therefore, $(m,n)=(3,4)$ or $(m,n)=(4,3)$, because $\varphi(x)=2$ iff $x\in\{3,4,6\}$.
If $d=2$, then $M+N=2MN$, which implies $M=N=1$. Therefore, $(m,n)=(2,2)$.


text:
Q: Foreground detection without an image sequence I need to detect the foreground object on an image and cut it off from that image. There are lots of background/foreground subtraction or object recognition algorithms but these algorithms are working on the videos or image sequences. I have only an image (it can be a picture of a man in front of a white wall. ) as an input. Do you know any useful approaches that can be applicable on a single image file instead of video or image sequences.

A: What you are looking for is a figure-ground segmentation algorithm. Does it have to be fully automatic? If you can draw an initial contour of the object by hand, you can use a class of algorithms called "active contours". If you need this to be fully automatic, you can use an algorithm called N-cuts.
If you are using MATLAB, and you are ok with semi-automatic segmentation, try the Image Segmenter App in the Image Processing Toolbox.

A: search as an "saliency detection"
like
"Global contrast based salient region detection"
http://mmcheng.net/salobj/


text:
Q: Too many values to unpack robotframework ,rest api Can someone tell me what is wrong with the following code . I am trying to get the details of a policy with id 5 .
*** Settings ***
Library           RequestsLibrary
Library           Collections
Library           strings

*** Test Cases ***
Get_Policy_Details
    [Documentation]    This is for getting the list of policies
    ${auth}=    Create List    admin    admin123
    ${session}=    Create Session    cam_session   https://host132.camb.com:7771    ${auth}    debug=3
    Log    cam_session
    ${resp}=    Get Request    cam_session    /policies/5
    ${result}=   To JSON      ${resp.content}
    Log    ${result}

Following is the response when URL is requested .I am trying to get the values(Firstname,lastname) from the below json .
{
  "submittedDT": null,
  "submittedBy": null,
  "id": 5,
  "createdBy": {
    "id": 5,
    "firstName": "Commence",
    "password": null,
    "lastName": "Architect",
    "loginName": "compliancearchitect",
    "organization": {
      "id": 1,
      "name": "public"
    },
    "roles": null,
    "emailAddr": null,
    "enabled": true
  },
  "modifiedBy": {
    "id": 2,
    "firstName": "Madhu",
    "password": null,
    "lastName": "RAJU",
    "loginName": "MSRAJU",
    "organization": {
      "id": 1,
      "name": "public"
    },
    "roles": null,
    "emailAddr": null,
    "enabled": true
  },
  "complianceScore": null,
  "organization": {
    "id": 1,
    "name": "public"
  }
}

report.html
TEST CASE: Get_Policy_Details Expand All
    Full Name:  ITOC Tests.Get_Policy_Details
    Documentation:
    This is for getting the list of policies in ITOC server
    Start / End / Elapsed:  20170313 15:13:08.999 / 20170313 15:13:09.013 / 00:00:00.014
    Status: FAIL (critical)
    Message:    ValueError: too many values to unpack
    KEYWORD: ${auth} = BuiltIn.Create List itocadmin, opsware Expand All
    Documentation:
    Returns a list containing given items.
    Start / End / Elapsed:  20170313 15:13:09.003 / 20170313 15:13:09.004 / 00:00:00.001
    15:13:09.004    INFO    ${auth} = [u'itocadmin', u'opsware']
    KEYWORD: ${session} = RequestsLibrary.Create Session cam_session, https://host132.camb.com:7771  ${auth}, debug=3 Expand All
    Documentation:
    Create Session: create a HTTP session to a server
    Start / End / Elapsed:  20170313 15:13:09.005 / 20170313 15:13:09.012 / 00:00:00.007
    15:13:09.006    INFO    Creating Session using : alias=cam_session, url=https://host132.camb.com:7771   headers=[u'admin', u'admin123'],                     cookies=None, auth=None, timeout=None, proxies=None, verify=False,                     debug=3
    15:13:09.011    FAIL    ValueError: too many values to unpack

A: Here is the way I log JSONs:
Get Request and Log
    [Arguments]    ${alias}    ${uri}    ${params}=${EMPTY}
    ${resp}=    Get Request    alias=${alias}    uri=${uri}    params=${params}
    Run Keyword And Ignore Error    Log    ${resp.text}
    [Return]    ${resp}

So there should be no reason to unpack JSON in your case, just feel free to read from that as you wish:
${id} =    Set Variable    ${resp.json().get("id")}
...


text:
Q: Cannot upgrade pip on Windows I have Windows 10, Python 3.6 and want to upgrade pip. I get the following error:
C:\Users\Acer Aspire E15>python -m pip install -U pip
Collecting pip
  Using cached https://files.pythonhosted.org/packages/00/b6/9cfa56b4081ad13874b0c6f96af8ce16cfbc1cb06bedf8e9164ce5551ec1/pip-19.3.1-py2.py3-none-any.whl
Installing collected packages: pip
  Found existing installation: pip 9.0.1
    Uninstalling pip-9.0.1:
Exception:
Traceback (most recent call last):
  File "C:\Program Files (x86)\Python36-32\lib\shutil.py", line 538, in move
    os.rename(src, real_dst)
PermissionError: [WinError 5] Access is denied: 'c:\\program files (x86)\\python36-32\\lib\\site-packages\\pip-9.0.1.dist-info\\description.rst' -> 'C:\\Users\\ACERAS~1\\AppData\\Local\\Temp\\pip-y05m24ex-uninstall\\program files (x86)\\python36-32\\lib\\site-packages\\pip-9.0.1.dist-info\\description.rst'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\pip\basecommand.py", line 215, in main
    status = self.run(options, args)
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\pip\commands\install.py", line 342, in run
    prefix=options.prefix_path,
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\pip\req\req_set.py", line 778, in install
    requirement.uninstall(auto_confirm=True)
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\pip\req\req_install.py", line 754, in uninstall
    paths_to_remove.remove(auto_confirm)
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\pip\req\req_uninstall.py", line 115, in remove
    renames(path, new_path)
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\pip\utils\__init__.py", line 267, in renames
    shutil.move(old, new)
  File "C:\Program Files (x86)\Python36-32\lib\shutil.py", line 553, in move
    os.unlink(src)
PermissionError: [WinError 5] Access is denied: 'c:\\program files (x86)\\python36-32\\lib\\site-packages\\pip-9.0.1.dist-info\\description.rst'
You are using pip version 9.0.1, however version 19.3.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

I do not know what more details to add. Can you help me find a way to upgrade the pip?

A: I believe the culprit is PermissionError: [WinError 5] Access is denied: 'c:\\program files (x86)\\python36-32\\....
Please, launch the command prompt as administrator or edit permissions of the python36-32 folder.
Duplicate of
Python 3.5 pip install not working on Windows 7 - PermissionError


text:
Q: I have a custom edittext I made with XML only that in the KITKAT version it gets with the black background This is the custom edittext XML code
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke android:width="1dp" android:color="@android:color/darker_gray"/>
    <corners android:radius="90dp"/>
    <padding android:top="5dp" android:bottom="5dp" android:left="5dp" android:right="5dp"/>
</shape>

edittext xml code
 <EditText
      android:id="@+id/txtRegistration"
      style="@style/editText_style"
      android:textColor="@color/colorText"
      android:inputType="textEmailAddress" />

follows the style being used in edittext
<style name="editText_style">
       <item name="android:gravity">center</item>
        <item name="android:background">@drawable/edittext_text_login</item>
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:ems">10</item>
        <item name="android:layout_marginRight">30dp</item>
        <item name="android:layout_marginLeft">30dp</item>
        <item name="android:layout_marginBottom">10dp</item>
        <item name="android:textColor">#100</item>
        <item name="android:textColorHint">#6F7A8B</item>
        <item name="android:padding">20dp</item>
</style>

Above the Android Lollipop it stays as it has to be, like this:click here to see the image

In android kitkat it gets all bugged the edittext bakground turns black:click here to see the image

A: <shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@null"/>
    <stroke android:width="1dp" android:color="@android:color/darker_gray" />
    <corners android:radius="90dp"/>
    <padding android:top="5dp" android:bottom="5dp" android:left="5dp" android:right="5dp"/>
</shape>

use this code for the drawable background, this may works.


text:
Q: html form submits prematurely on validation subroutine using jquery dialog box I am using the jquery dialog box to display messages during form completion. All but the last dialog box seem to work. The last one displays briefly, but the "X" does not appear, the box dismisses automatically, and the form is submitted prematurely.
Sample of the incomplete dialog box is here:
http://www.bbhq.com/dbox.htm
(The form must submit before the "X" image has time to display.)
I am using jquery-1.10.1.
I think it might be a jquery issue. When I replace the jquery dialog box with a simple "alert," it works.
Here is the JavaScript:
  function valdata() {
    alert ("watch closely; dialog box will pop up; dismiss automatically; and form will submit")
      $("
made simple b4 submit
").dialog();
  return

here is the html:
  <FORM NAME="mainform" METHOD="POST" ACTION="http://www.bbhq.com/dummy.htm"
      onSubmit="return valdata()"  >

      test dialog box here

  1. this is question 1.
    <input type=text name=ques1>

  2. this is question 1.
    <input type=text name=ques2>

  3. this is question 1.
      <input type=text name=ques3>

  <INPUT TYPE="submit" VALUE="  Click here to submit the form   ">

  </FORM>

In the onSubmit code, I have tried it with and without a "return."
I tried removing the onsubmit, and replacing the input submit with a button which calls the function and then submits the form. The result was the same.
My sample is here: http://www.bbhq.com/tmp-form.htm
(Sorry; I could not make jsfiddle work for me.)
I am a newbie with jquery, but I have designed dozens of forms. Am I missing something obvious here?
Thank you,

A: instead of having an onsubmit attribute on the form add this to your page:
$(document).ready(function() {

    $('form[name="mainform"]').submit(function(e) {
       e.preventDefault();
       e.stopImmediatePropagation();

       valdata();
       return false;
    });
});

What it does:
1) wait for the dom to load:
$(document).ready(function() {

2) bind a submit handler to the form:
$('form[name="mainform"]').submit(function(e) {

3) stop the default browser behavior from occuring (ie: following the attribute action on the form
e.preventDefault();

4) stop the event from bubbling up the call stack
e.stopImmediatePropagation();

5) call your function
valdata();

6) return false to prevent form from submitting (return true to allow the form to submit)
return false;


text:
Q: Query help need in finding missing numbers I have a table that looks something like this:
ID         | GROUP
-------------------
1000001    | 0
1000001    | 1
1000001    | 2
1000002    | 0
1000002    | 2
1000002    | 3
1000003    | 1
1000003    | 2
1000003    | 3
1000004    | 0

I need to list all the ids where there is a group missing in the sequence.
So for the above example i would only need back 1000002 & 1000003.
Thanks in advance

A: select distinct id
from
(
    SELECT Id, Group, LAG(Group, 1, -1) over (partition by Id order by Group) prevGroup
 FROM Table
 )
 WHERe Group -1 <> PrevGroup

A: As we don need the information about the missing group number we can compare that over all count of elements is lower or equal for specific group
SELECT ID FROM YOUR_TABLE
GROUP BY ID
HAVING COUNT(ID) <= max(GROUP);

A: Maybe this:
SELECT
  id
FROM mytable m
GROUP BY id
HAVING (MAX(group) + 1) > COUNT(DISTINCT group);

(I've written the keys in lowercase). If you have a unique key on (ID, GROUP), you can leave out the DISTINCT.

A: What I'm getting from your comments is that the ID must start with a group of 0 and the group should always increment only by 1.  From that, I get this:
SELECT id
FROM (
        SELECT  id, count(*) as cnt, max(group) as mx, min(group) as mn
        FROM    myTable
        GROUP BY group
     ) A
WHERE NOT mx = cnt - 1
AND NOT mn = 0

Hope this helps.  It's probably not the cleanest or most effective, but hope it will help.
EDIT:  Actually, after re-looking over the answer before mine and thinking about HAVING, it probably would be cleaner like this.
SELECT ID
FROM   myTable
GROUP BY ID
HAVING MAX(group) >= COUNT(DISTINCT group)


text:
Q: Unit Tests on V3 fails with Exception in thread "FiberTimedScheduler-Same thread scheduler" java.lang.OutOfMemoryError: Java heap space I ran the gradlew with
./gradlew -Dorg.gradle.jvmargs="-Xmx2048m" test

and also make the following entry in the build.gradle
test {
    jvmArgs('-XX:+UseG1GC', '-Xmx2048m')
    maxHeapSize = "2048m"
}

and I am getting the following error
Exception in thread "FiberTimedScheduler-Same thread scheduler" java.lang.OutOfMemoryError: Java heap space
    at co.paralleluniverse.fibers.FiberTimedScheduler.findProblemFibers(FiberTimedScheduler.java:402)
    at co.paralleluniverse.fibers.FiberTimedScheduler.work(FiberTimedScheduler.java:140)
    at co.paralleluniverse.fibers.FiberTimedScheduler.access$000(FiberTimedScheduler.java:45)
    at co.paralleluniverse.fibers.FiberTimedScheduler$1.run(FiberTimedScheduler.java:81)
    at java.lang.Thread.run(Thread.java:748)
Exception in thread "FiberTimedScheduler-Same thread scheduler" java.lang.OutOfMemoryError: Java heap space
Exception in thread "FiberTimedScheduler-Same thread scheduler" java.lang.OutOfMemoryError: Java heap space
Exception in thread "FiberTimedScheduler-Same thread scheduler" java.lang.OutOfMemoryError: Java heap space

A: This might resolve the issue. Try Configuring JVM properties as per the instructions here


text:
Q: QSettings with different types I'm trying to store some parameters with different type using QSettings (ini file, Linux).
When I'm reading values from this using settings.value() I just get QStrings.
Are there any way to store type of QVariant inside this settings file or should I use other storage instead?
Thanks in advance!

A: According to the docs, the QSettings::value() function returns a QVariant.  This should then be converted to whatever type you want.
You can use QVariant::type() to find the type you stored in the QSettings.
This is how QSettings should work, and does, using the NativeFormat on Windows.
However, when using an ini file and for most simple types - including strings and integers - QSettings uses the same simple representation in the ini file and therefore merges these types.  They all come back as QString type in the QVariant.
More complex types are properly encoded in the ini file and so these types are preserved.

A: As noted in QSettings does not differentiate between string and int values

Every value of QVariant which is read from a .ini file by QSettings has string type.

There is also proposed solution to manually append type information to stored strings. So, if during reading the special postfix is not found it is possible to manually decide regarding conversion to int or to bool.
By the way, for more complex types (like QSize) the type information is stored, so QVariat type is correct.


text:
Q: load jQuery charset I hava 2 php files. index.php and preview.php
in the top of index.php I have this code
<meta http-equiv='Content-Type' content='Type=text/html; charset=utf-8'>

When I try to load content to index.php from preview.php using:
function preview_content(id)
{

    var thebutton = '#previewButton';
    $(thebutton).hide();
    $('#preview_area').load('preview.php?id='+id);
}

the content loaded with characters like this M�laga CF
I tried to put the same utf-8 code in the top of preview.php but nothing changed. Is there any way to retrieve the content with UTF-8 charset?

A: Please be sure about preview.php's encoding is UTF-8. Your editor's default encoding applies newly created files but if you copied preview.php from somewhere else it's encoding might be different. Also adding header('charset=utf-8'); as first line to preview.php might help. Like this;
<?php
header('charset=utf-8');
// your code below here
.
.
.

You can also use .ajax() and specify contentType instead of .load();
function preview_content(id)
{

    var thebutton = '#previewButton';
    $(thebutton).hide();
    $.ajax({
        data: { "id" : id },
        type: "GET",
        url: "preview.php",
        contentType: "application/x-www-form-urlencoded;charset=UTF-8",
        success: function(output) {
            $('#preview_area').html(output);
        }
    });
}

A: The meta content attribute doesn't have a "Type=" part
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

A: The Emre Erkan's solution was right, but it needed "echo" before "header('...')"
Add this lines in the top of preview.php:
<?php
echo header('Content-Type: text/html; charset=utf-8');
?>

It worked in my website


text:
Q: Manipulating parent's array prop - Reactjs This question may sound a little complicated. But i am stuck here, so i am throwing it here.
I am rendering a child component multiple times in parent with different properties and an array.
Parent contains an array of headings, i am passing it to child components and mapping select options with that array. If an heading is selected from any of the child components, that heading should display as disabled in other child components.
Child:
{
  this.props.xarray.map((heading, index) => {
    if (heading.headingis.toLowerCase().indexOf(this.state.field) != -1) {
      this.setcheckstate(); //ignore this function
      this.props.actionis(index, 'disabled');  //Using this function (passed from parent) to disable selected option
      return <option value={heading.headingis} key={index} selected disabled={heading.disabled}>{heading.headingis}</option>
    }else{

        return <option value={heading.headingis} key={index} disabled={heading.disabled}>{heading.headingis}</option>
    }

  })
}

Parent's actionis function:
handlerHeading(index, disabled) {
   xarray[index]['disabled'] = disabled;
}

It's working somehow BUT problem is

*

*If first component is rendered, it will disable that value

*Then 2nd component is rendered, it will disable that value
along with previous one.

and so on...
But in first component, only one value is disabled, in 2nd component 2 values are disabled and in 3rd component 3 values are disabled. And so on...
But i want if one value is disabled in component 6, it should get disabled in all previous components.
Have a look at following images for example.
Component #1 Rendered:

Component #4 Rendered:

A: I have resolved this, by changing xarray to state of parent.
This:
state = {xarray: xarray}

And:
handlerHeading(index, disabled) {
   xarray[index]['disabled'] = disabled;
   this.setState({ xarray: xarray });
}

For some reason you cannot change Props as you desire. See This Question


text:
Q: Ruby-On-Rails and PostgreSQL - Decimal error causing an import of a CSV file to fail I'm having a big problem with Ruby-On-Rails and PostgreSQL. I'm using geokit gem to locate my Store model. This morning before I added geokit gem, my model had a longitude and a latitude column, both of :string type. After adding the gem, I realized that I needed my column to be :float type so I created the migration and modified my columns. I then added all my records (from a csv file) to the database.
Everything seemed to work well because I could locate my records from an address thanks to geokit. Then during my tests, I realized that one of my records didn't have all the decimal places in its coordinates. I then thought that it had to come from float which I know how to create problems so many decimal places.
I recreated a migration to transform my colones into :decimal like HERE.
Since then, nothing gets imported, I have relaunched the parsing of the csv and all my records are now only 1 decimal (example: 0.2,4.1) I wanted to go backwards but that's impossible. Now that I use float or decimal in my database it's the same: it's impossible to have more than one number after the comma.
I created a new project and relaunch, nothing to do I can't have more than 1 decimal. I'm worried about having created a bug, but I have no idea how to fix it.


text:
Q: Persistent Cookie is not working in cross browser's I am trying to set a persistent cookie from my asp.net application. when i try to store a value using IE browser and tries to get the value from Mozilla or chrome browser and it is not working.

*

*Is it possible to get the same persistent cookie value across all browsers?

*Is persistent cookie is browser independent?

I have used the below URL for persistent cookie.
URL:
http://www.codeproject.com/Articles/31914/Beginner-s-Guide-To-ASP-NET-Cookies#9
and is  I've been using the below code :
public void SetPersistentCookies(string name, string value){
    HttpCookie cookie = new HttpCookie(name);
    cookie.Value = value;
    cookie.Expires = DateTime.Now.AddHours(12);
    Response.Cookies.Add(cookie);
}
 public void GetPersistentCookies(string name)
{
    //Retrive Cookie by cookies name
    HttpCookie cookie  = Request.Cookies[name];
    Response.Write(cookie.Value);
}

can you guys help me to resolve this issue with a sample?
Thanks,
Anbu

A: No, cookie is not accessible across browsers. Persistent cookie is a cookie that doesn't disappear when browser is closed. Browser is responsible for managing cookies it stores, and each browser can have independent way of storing them.
What is more - I think this article is a bit outdated, check following link for 'fresher' info - MSDN

A: Cookies are browser dependent. Main purpose of cookies is to store some data on client end or for specific client.
1.Is it possible to get the same persistent cookie value across all browsers?
No, If you want to access some value on different browsers then you should go server side.
2.Is persistent cookie is browser independent?
No, They are browser dependent. They will persist only on the browser where you had visited your page. I think you are confused about persistent.
Persistent means you are defining some time duration for cookie to exist. After this time it will deleted by browser.


text:
Q: Java client and a C++ server send and receive via TCP Socket I have a C++ server and two clients (ruby and java).
Everything is running on a 64-bit linux-machine (java 1.7.0_17)
The ruby client is fully working, but the java version makes problems.
In Java I tried to send a String from the client to the server. Actually the Server received the entire String, but the server thinks there is still something more to receive.
The ruby client looks a little bit like this:
socket = TCPSocket.open(@options[:host],@options[:port])
test = "Hello, World"
socket.puts test
socket.shutdown 1
response = socket.gets

Everything here is working fine. The ruby client sends a string. The server receives that string and sends a reply.
The Java Version looks like:
String ip = "127.0.0.1";
int port = 6686;
java.net.Socket socket = new java.net.Socket(ip,port);
OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream());
InputStreamReader in = new InputStreamReader(socket.getInputStream());

String msg = "Hello, world!";

//send
PrintWriter pw = new PrintWriter(out, true);
pw.print(msg);
pw.flush();
// I also tried: out.write(msg); out.flush(); nothing changed

//receive the reply
BufferedReader br = new BufferedReader(in);
char[] buffer = new char[300];
int count = br.read(buffer, 0, 300);
String reply = new String(buffer, 0, count);
System.out.println(reply);

socket.close();

On the other side there is a C++ Server:
string receive(int SocketFD) {
   char buffer[SOCKET_BUFFER_SIZE];
   int recv_count;

   // empty messagestring
   string message = "";

   // empty buffer
   memset(buffer, 0, sizeof(buffer));

   while ((recv_count = recv(SocketFD, buffer, sizeof(buffer) - 1, 0)) > 0) {
      /*if (recv_count == -1) {
         cout << "failed." << endl;
         break;
      }*/
      cout << recv_count << endl;
      if (ECHO_SOCKETS) cout << "received: " << buffer << endl;

      message.append(buffer);
      memset(buffer, 0, sizeof(buffer));

      if (ECHO_SOCKETS) cout << "message is now: " << message << endl;

   }
   return message;
}

The server output from the Java-message is:
13
received: Hello, world!
message is now: Hello, world!

and then nothing happens.
The problem is that:
recv(SocketFD, buffer, sizeof(buffer) - 1, 0)

is catched in an endless loop (or something like that).
If I kill the Java-client process or I type something like:
pw.print(msg);
out.close();

the output on the server side is:
_sending reply: "Request unrecognized/invalid" request="Hello, world!"
send reply success
now close connection

This output is right (except "send reply success"), but in case of adding:
out.close();

the client can't receive the reply of the server. Because the Socket is closed.
java.net.SocketException: Socket is closed
at java.net.Socket.getInputStream(Socket.java:864)
at MyServer.writeMessage(MyServer.java:56)
at MyServer.test(MyServer.java:42)
at MyServer.main(MyServer.java:30)

Edit
I tried to call pw.flush(); and different delimiters like "\n", "\r", "\r\n" and "\n\r" but the server still thinks there is still something to read. I also tried to use DatagramSockets:
java.net.DatagramSocket dSocket = new java.net.DatagramSocket();
InetAddress address = InetAddress.getByName("localhost");
String msg = "Hello, world!";
byte[] buf = msg.getBytes();
java.net.DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 6686);

But the server can't accept the packet.
Solution
The ruby-client does something like a socket.shutdownOutput(); (ruby: socket.shutdown 1) after the call of puts. I changed the java-client-code:
out.write(msg);
socket.shutdownOutput();

and it works!
As @Charly said: I have to define a "protocol". In my case I'm not allowed to change any communication related code (in the server and the ruby-client) because this functionality is used by a another group of researchers. So I've to modify my java-client in that way, that it does the exact same things at the exact same time as the ruby-client (something like a protocol).

A: PrintWriter buffer (when autoflush is true) is only flushed by calling println or printf. Calling print may not flush the buffer (Javadoc). Try calling println or use a OutputStreamWriter directly and flush().
Be aware of using the right charset (You can set it up in OutputStreamWriter constructor).

A: Close the stream respectively flush it in a way like this:
DataOutputStream dataOut = new DataOutputStream(socket.getOutputStream());
dataOut.writeUTF(s);
dataOut.flush();

A: while ((recv_count = recv(SocketFD, buffer, sizeof(buffer) - 1, 0)) > 0) {
      if (recv_count == -1) {

I don't know what your problem is but this code is certainly nonsense. It is impossible for the inner test ever to succeed.


text:
Q: How to onClick in Ajax Process I have added html code in ajax process,but I have faced problem when using onclick function in there.

The expected result will show "12".
But,the problem I got "undefined" val.
function getValue(){
     var val= $(this).find('.imageClass').val();
     alert(val);
  }

function getImage(){
    $.ajax({
        type: "GET",
        url: 'image.php?id='+ID,
        async: false,
        beforeSend: function(x) {
            if(x && x.overrideMimeType) {
                x.overrideMimeType("application/j-son;charset=UTF-8");
            }
        },
        dataType: "json",
            success: function(data){
            var html = '';
            }

            html+='
<input class="imageClass" type="hidden" value="12"/>'+
                      '
'+
                   '
';

                $('.content').html(html);
            }
        });
}

A: You could create a custom function with even delegation like:
$(document).on(".ToClick",function getValue() {

//action to do here

});

Your HTML
html+='
<input class="imageClass" type="hidden" value="12"/>'+
                      '
'+
                   '
';

Or send this into HTML function
 html+='
<input class="imageClass" type="hidden" value="12"/>'+
                      '
'+
                   '
';

And the function should be:
function getValue(e){
     var val= $(e).find('.imageClass').val();
     alert(val);
  }

Note: the inline function is not recomemded, use event delegation instead.

A: You must attach an eventhandler dinamically using on
$("selector").on("event",function getValue() {

//action to do here

});

A: You should use the jQuery Deferred Object and outsource the success function.
That onclick Event is not being parsed.
function getValue(){
     var val= $(this).find('.imageClass').val();
     alert(val);
  }

function getImage(){
    $.ajax({
       type: "GET",
        url: 'image.php?id='+ID, //Wherever that ID comes from
        async: false,
        beforeSend: function(x) {
            if(x && x.overrideMimeType) {
                x.overrideMimeType("application/j-son;charset=UTF-8");
           }
       },
       dataType: "json"
       }).done(
       function(data){
        var html = $('
<input class="imageClass" type="hidden"    value="12"/>'+
                      '
'+
                  '
');
            html.find('input').on('click', getValue);
                $('.content').html(html);

        };

A: This may not be the only problem, but it is a problem: your onclick handler looks like this:
onClick="getValue()"

Within getValue you are assuming that this is set to the div that was clicked, but this is not the case.  Within the context of the code in onclick, this is set to that div, but once the function is called, that context is lost.  This would work:
onClick="getValue.call(this)"


text:
Q: Is it possible to rename an SQL Server 2005 instance I would like to change the name of my SQL Server instance.  Is there a simple way of doing this or is a significant effort required?  Note, this is a named instance - not the default instance.

A: The only way is a reinstall. See this similar thread for more info: SQL Server, convert a named instance to default instance?

A: Or you could try this method:
http://groups.google.com/group/microsoft.public.sqlserver.server/browse_thread/thread/544c4eaf43ddfaf3/f1bdcd1ec9cab158#f1bdcd1ec9cab158

A: I have seen a few makeshift ways of doing this, but I don't have confidence in any of them.  I think I will simply install a new instance and transfer my information over.

A: Renaming does't work well on the registry. Install a new isntance.

A: Although there is no simple way of renaming a SQL Server instance, one can create SQL aliases.


text:
Q: How to know who is changing database data in mysql Some changes made in my database which is in server how to know who changes the data and what changes they made?

A: I'm not sure if it is possible in MySQL but in Oracle you can create system triggers to check who has logged in, which values have been changed etc.
I recommend you to surf in the MySQL triggers website and see if there's something that you need.
https://dev.mysql.com/doc/refman/8.0/en/triggers.html


text:
Q: Have a listen vs have listens vs have listen
*

*Have a listen to the CD.

*Have listens to the CD.

*Have listen to the CD.

Are they correct?
Can countable nouns take plural forms with this kind of delexical verbs?

A: This kind of usage is common for sensory verbs. If you look at this Oxford Dictionary entry for Listen, you will find this definition for the noun form:

listen
   noun
     [in singular] An act of listening to something:
radio plays are definitely worth a listen

The [in singular] bit means that the noun is only valid as a singular noun- not plural. Looking at your three sentences:

Have a listen to the CD.

This is valid, because a listen is singular, and listen can be a singular noun.

Have listens to the CD.

This is not valid, because listens is a plural noun, and listen cannot be a plural noun, only singular.

Have listen to the CD.

This is not valid, because there is no determiner (a or the). You can only omit the determiner for non-count nouns like peace and sugar, and listen cannot be a non-count noun, only singular.
The following words are documented as working in the same way: watch, read, think and sniff. Other sensory words seem to work the same way, for example smell, taste, feel and shufti, but they are not marked as singular-only for this usage.


text:
Q: MaxStartups and MaxSessions configurations parameter for ssh connections? I am copying the files from machineB and machineC into machineA as I am running my below shell script on machineA.
If the files is not there in machineB then it should be there in machineC for sure so I will try copying the files from machineB first, if it is not there in machineB then I will try copying the same files from machineC.
I am copying the files in parallel using GNU Parallel library and it is working fine. Currently I am copying 10 files in parallel.
Below is my shell script which I have -
#!/bin/bash

export PRIMARY=/test01/primary
export SECONDARY=/test02/secondary
readonly FILERS_LOCATION=(machineB machineC)
export FILERS_LOCATION_1=${FILERS_LOCATION[0]}
export FILERS_LOCATION_2=${FILERS_LOCATION[1]}
PRIMARY_PARTITION=(550 274 2 546 278) # this will have more file numbers
SECONDARY_PARTITION=(1643 1103 1372 1096 1369 1568) # this will have more file numbers

export dir3=/testing/snapshot/20140103

find "$PRIMARY" -mindepth 1 -delete
find "$SECONDARY" -mindepth 1 -delete

do_Copy() {
  el=$1
  PRIMSEC=$2
  scp david@$FILERS_LOCATION_1:$dir3/new_weekly_2014_"$el"_200003_5.data $PRIMSEC/. || scp david@$FILERS_LOCATION_2:$dir3/new_weekly_2014_"$el"_200003_5.data $PRIMSEC/.
}
export -f do_Copy

parallel --retries 10 -j 10 do_Copy {} $PRIMARY ::: "${PRIMARY_PARTITION[@]}" &
parallel --retries 10 -j 10 do_Copy {} $SECONDARY ::: "${SECONDARY_PARTITION[@]}" &
wait

echo "All files copied."

Problem Statement:-
With the above script at some point I am getting this exception -
ssh_exchange_identification: Connection closed by remote host
ssh_exchange_identification: Connection closed by remote host
ssh_exchange_identification: Connection closed by remote host

And I guess the error is typically caused by too many ssh/scp starting at the same time. That leads me to believe /etc/ssh/sshd_config:MaxStartups and MaxSessions is set too low.
But my question is on which server it is pretty low? machineB and machineC or machineA? And on what machines I need to increase the number?
On machineA this is what I can find -
root@machineA:/home/david# grep MaxStartups /etc/ssh/sshd_config
#MaxStartups 10:30:60

root@machineA:/home/david# grep MaxSessions /etc/ssh/sshd_config

And on machineB and machineC this is what I can find -
[root@machineB ~]$ grep MaxStartups /etc/ssh/sshd_config
#MaxStartups 10

[root@machineB ~]$ grep MaxSessions /etc/ssh/sshd_config
#MaxSessions 10

A: i do not think load of 10 parallel connection is high for ssh.
i assume you have passwordless access, check if there is a key issue
for i in `echo MachineA MachineB MachineC`
   do
    echo testing $i
    ssh -v $i exit
  done

Check /etc/hosts.deny and /etc/hosts.allow on MachineB and MachineC & see if connection from MachineA are allowed


text:
Q: How to have Page Navigation programmatically in ReportViewer? I'm writing a report in ASP.NET using Reporting Services. I want to hide the Toolbar of the ReportViewer and have my own "Next Page" and "Previous Page" buttons. Is there a way to programmatically navigate through ReportViewer pages? Does it have methods such as "NextPage" and "PreviousPage"?

A: If you hide the toolbar and have your own controls for page navigation you could set the ReportViewer's CurrentPage property in your code.

A: I just thought I'd add to this as I've been doing similar things and have built a little set of JavaScript (using JQuery) functions where you can pass the ReportViewerID and it'll allow you to add next, previous, first last and so on to your own custom toolbar buttons. Just hide the toolbar using the ReportViewer_HideToolbar function on document ready. Thought it was worth sharing as I couldn't find anything on this when searching for hours yesterday. Even if it's just a starting point for someone, atleast it's that bit closer and of help :-)
p.s. I'm using ReportViewer 10, others may be different and not work.
function ReportViewer_FirstPage(ReportViewerID) {
    var ReportViewer = $("span[id$='" + ReportViewerID + "_ReportViewer'")
    ReportViewer.find("input[title='First Page']").first().click()
}

function ReportViewer_NextPage(ReportViewerID) {
    var ReportViewer = $("span[id$='" + ReportViewerID + "_ReportViewer'")
    ReportViewer.find("input[title='Next Page']").first().click()
}

function ReportViewer_PreviousPage(ReportViewerID) {
    var ReportViewer = $("span[id$='" + ReportViewerID + "_ReportViewer'")
    ReportViewer.find("input[title='Previous Page']").first().click()
}

function ReportViewer_LastPage(ReportViewerID) {
    var ReportViewer = $("span[id$='" + ReportViewerID + "_ReportViewer'")
    ReportViewer.find("input[title='Last Page']").first().click()
}

var tReportViewerLastFindText = ""
function ReportViewer_Set_SearchText(ReportViewerID, tText) {
    var ReportViewer = $("div[id$='MainPlaceHolder_" + ReportViewerID + "'")
    ReportViewer.find("input[title='Find Text in Report']").val(tText)
    var m_reportViewer = $find($(ReportViewer).attr('id'))
    if (tReportViewerLastFindText != tText) {
        m_reportViewer.find(tText)
        tReportViewerLastFindText = tText
    } else {
        m_reportViewer.findNext()
    }
}

function ReportViewer_Set_PageNumber(ReportViewerID, tPageNumber) {
    var ReportViewer = $("span[id$='" + ReportViewerID + "_ReportViewer'")
    var CurrentPage = ReportViewer.find("input[title='Current Page']")
    $(CurrentPage).val(tPageNumber)
    __doPostBack(CurrentPage.attr("name"), '')
}

function ReportViewer_Print(ReportViewerID) {
    var ReportViewer = $("div[id$='MainPlaceHolder_" + ReportViewerID + "'")
    var m_reportViewer = $find($(ReportViewer).attr('id'))
    m_reportViewer.invokePrintDialog()
}

function ReportViewer_HideToolbar(ReportViewerID) {
    var ReportViewer = $("span[id$='" + ReportViewerID + "_ReportViewer'")
    $(ReportViewer).find("div[style$='toolbar_bk.png);']").hide()
}

Regards
Liam


text:
Q: How to format date in SSRS? In SSRS report query is generating date as a column in the format of :
Sales   ID20200331      ID20200430      ID20200531
To remove the ID i used following expression:
=Right( Fields!ID20210331.Value, len(Fields!ID20210331.Value) - 2)
This gives me 84, instead of removing ID.
How can I remove ID and format date as 2020 Mar etc.
Thanks

A: If your fields values are "ID20200430" etc then in SSRS you can use something like this..
=DateSerial(
MID(Fields!IDDate.Value, 3, 4),
MID(Fields!IDDate.Value, 7, 2),
RIGHT(Fields!IDDate.Value, 2)
)

However It appears that it's your column [names] that represent dates is this correct?
If this is true, then you would have to UNPIVOT the columns in SQL then convert the resulting values into a real date format.
Here' some sample data to show how to do this.
DECLARE @t TABLE (Sales varchar(10), ID20200331 int, ID20200430 int, ID20200531 int)

INSERT INTO @t VALUES
('A', 1,2,3),
('B', 4,5,6),
('C', 7,8,9)

SELECT
        Sales, IdDate, SomeNumber
        , MyDate = DATEFROMPARTS(SUBSTRING(IdDate, 3, 4), SUBSTRING(IdDate, 7, 2), SUBSTRING(IdDate, 9, 2))
    FROM @t
    UNPIVOT(
            SomeNumber FOR IdDate IN ([ID20200331],[ID20200430],[ID20200531])
    ) unpvt

Which gives us this including the myDate column which is the correct date type

You could then use this in a matrix control in SSRS to get the data back into a pivoted view


text:
Q: How can I read multiple COM ports? I have two Arduino Pro mini projects. These two Arduino's are sending data to me simultaneously. I don't send to data. I want to read these ports on Python(PC or Raspberry Pi). My baundrate is 9600. What kind of path should I follow?

A: Try using Putty to monitor the different Com ports.
Run two instances of Putty at the same time and monitor the com ports.


text:
Q: How to generate a Zip from a set of streams and producing a stream with the Zip data? I have an app with manages a set of files, but those files are actually stored in Rackspace's CloudFiles, because most of the files will be ~100GB. I'm using the Cloudfile's TempURL feature to allow individual files, but sometimes, the user will want to download a set of files. But downloading all those files and generating a local Zip file is impossible since the server only have 40GB of disk space.
From the user view, I want to implement it the way GMail does when you get an email with several pictures: It gives you a link to download a Zip file with all the images in it, and the download is immediate.
How to accomplish this with Python/Django? I have found ZipStream and looks promising because of the iterator output, but it still only accepts filepaths as arguments, and the writestr method would need to fetch all the file data at once (~100GB).

A: Since Python 3.5 it is possible to create zip chunks stream of huge files/folders. You can use the unseekable stream. So no need to use ZipStream now.
See my answer here.
And live example here: https://repl.it/@IvanErgunov/zipfilegenerator
If you don't have filepath, but have chunks of bytes you can exclude open(path, 'rb') as entry from example and replace iter(lambda: entry.read(16384), b'') with your iterable of bytes. And prepare ZipInfo manually:
zinfo = ZipInfo(filename='any-name-of-your-non-existent-file', date_time=time.localtime(time.time())[:6])
zinfo.compress_type = zipfile.ZIP_STORED
# permissions:
if zinfo.filename[-1] == '/':
   # directory
   zinfo.external_attr = 0o40775 << 16   # drwxrwxr-x
   zinfo.external_attr |= 0x10           # MS-DOS directory flag
else:
   # file
   zinfo.external_attr = 0o600 << 16     # ?rw-------

You should also remember that the zipfile module writes chunks of its zipfile own size. So, if you send a piece of 512 bytes the stream will receive a piece of data only when and only with size the zipfile module decides to do it. It depends on the compression algorithm, but I think it is not a problem, because the zipfile module makes small chunks <= 16384.

A: You can use https://pypi.python.org/pypi/tubing. Here's an example using s3, you could pretty easily create a rackspace clouldfile Source. Create a customer Writer (instead of sinks.Objects) to stream the data some where else and custom Transformers to transform the stream.
from tubing.ext import s3
from tubing import pipes, sinks
output = s3.S3Source(bucket, key) \
    | pipes.Gunzip() \
    | pipes.Split(on=b'\n') \
    | sinks.Objects()
print len(output)

A: Check this out - it's part of the Python Standard Library:
http://docs.python.org/3/library/zipfile.html#zipfile-objects
You can give it an open file or file-like-object.


text:
Q: Regex problem - missing matches Here's a short regex example:
preg_match_all('~(\s+|/)(\d{2})?\s*–\s*(\d{2})?$~u', 'i love regex  00– /   03–08', $matches);
print_r($matches);

The regex only matches '03–08', but my intention was matching '00–' as well. What is the problem? Anyone could explain?

A: The portion at the end:
-\s*(\d{2})?$~u

Means that you can only have spaces and/or optionally two digits between your match and the end of the string.  This means 00- can't match since there's other stuff between it and the end of the string.
If you remove the $, it should work as you intend.


text:
Q: Using optionRenderer with Select.Aysnc (react-select) I can't find in the documentations how to use optionRenderer prop with react-select async (Select.Async)
here is a question that already been answered, but the renderOptions is not being called at all
here is my a snippet of my code:
renderOption = (option) => {
    return (

            // for example:
            {option.label}: {option.value}

    )
}

<Select.Async
    placeholder={placeholder}
    loadOptions={(inputValue) => this.asyncLoadOptions(inputValue)}
    isClearable
    onChange={(value, e) => {
      this.onDropDownFilterChange(value, e)
    }}
    onMenuScrollToBottom={this.fetchDropDownNextPage}
    defaultOptions={defaultOptions}
    defaultValue={defaultValue}
    styles={this.props.hasError ? customStyles : undefined}
    optionRenderer={this.renderOption}

/>

Here I want to keep the functioality and styles for each dropDown item as is (e.g onMouseOver and so on) I just want to format how the items are shown in the list, so is this the right way to do it? or there no other option than using the components prop.
I was able to achieve the formatting right using the components prop, but I lost the styles, and all the mouse events.

A: so for those who are looking for the answer, this is what I ended up using and it does the job: (unrelated code has been removed to keep the snippet concise)
import AsyncSelect  from 'react-select/async';
import { components } from 'react-select';

const Option = props => {
    return (
        <components.Option {...props} >
            {props.data.label}

                {props.data.manufacturerName || 'Unknown'} | {props.data.assetGroupDescription || 'Unknown'}

        </components.Option>
    )};

class FilterDropDownMenu extends Component {

render() {
    return (
        <>
            {translate(placeholder)}
            <AsyncSelect
                {...this.props}
                isClearable
                onChange={(value, e) => {
                    this.onDropDownFilterChange(value, e)
                }}
                onMenuScrollToBottom={this.fetchDropDownNextPage}
                defaultOptions={defaultOptions}
                defaultValue={defaultValue}
                styles={hasError ? customStyles : undefined}
                components={{ Option }}
            />
        </>
    )
   }
}

This way, I get the formatting that I want, And I don't loose the built in functionality of react-select (mouse events and styling and so on).


text:
Q: Django Javascript append options In my class in models.py I have a field:
names = models.TextField(max_length=40, choices=sektor, default="Adam", verbose_name="Name")

sektor = (
    ("Adam", "Adam"),
    ("Tom", "Tom"),
)

When I change an option in my page, I run the following script
<script type="text/javascript">
        var endpoint = '/call_jquery_sektor/'
        var sektor = []
        $.ajax({
            method: "GET",
            url: endpoint,
            success: function(data){
                sektor = data.sektor
                //loop
                $(sektor).each(function(i) {
                $("#id_names").append("<option>" + sektor[i] + "</option>") //append options
                })
                },
            error: function(error_data){
                console.log("error")
                console.log(error_data)
                }
        })
    </script>

I get all data, writen as two elements of each tuple, in one row. I would like to clear all previous options and when I run script I would get list of all names, each name single time and only 1 in 1 row.
I get:
Adam, Adam, Tom, Tom

I would like to get:
Adam
Tom

A: You can do that simply by adding this line in your code!
<script type="text/javascript">
    var endpoint = '/call_jquery_sektor/'
    $.ajax({
        method: "GET",
        url: endpoint,
        success: function(data){
            var sektor = []
            sektor = data.sektor
            //loop
            $(sektor).each(function(i) {
            $("#id_names").append("<option>" + sektor[i] + "</option>") //append options
            })
            },
        error: function(error_data){
            console.log("error")
            console.log(error_data)
            }
    })
</script>


text:
Q: binary operator '/' cannot be applied to two 'Double' operands While trying to execute this block of code in Swift 3, I encountered the error: binary operator '/' cannot be applied to two 'Double' operands
var array2 = [8, 7, 19, 20]

for (index, value) in array2.enumerated() {
    array2[index] = Double(value) / 2.0
}

Yet this works
var array2 = [Double]()
array2 = [8, 7, 19, 20]

for (index, value) in array2.enumerated() {
    array2[index] = value / 2.0
}

Why doesn't the first block of code work?

A: The error is a bit misleading.
In the first set of code, array2 is implicitly declared as an array of Int. So any attempt to assign a value to an index of array2 will require an Int value.
The problem is that Double(value) / 2.0 results in a Double value, not an Int. So the compiler is looking for a version of / that returns an Int. And that version expects two Int parameters. Since you are supplying two Double parameters, you get the error mentioned in your question.
The solution is to either cast the result to an Int or use two Int parameters to /.
var array2 = [8, 7, 19, 20]

for (index, value) in array2.enumerated() {
    array2[index] = Int(Double(value) / 2.0) // cast to Int
}

or
var array2 = [8, 7, 19, 20]

for (index, value) in array2.enumerated() {
    array2[index] = value / 2 // Use two Int
}

The result will be the same in this case. 8 will be replaced with 4. 7 will be replaced with 3, etc.
The second set of code works as-is because you declare the array to be filled with Double so everything matches up with the correct type.

A: For the first one, your array is of type Int hence doing array2.enumerated() gives you value as an Int. When you do this to it, Double(value) / 2.0, the final result returned is of type Double which is incompatible with your array type.
For the second one though, you explicitly declared an array of Double hence array2.enumerated() returns value as a Double so performing the operation works just fine.

A: rmaddy's answer is correct as to why you are seeing the issue, the implicit Int declaration.  For the sake of completeness. There are a couple ways to fix this, casting is one;  another not yet mentioned here is to extend Double to include this case, if you need to do this enough you can simply define your own version of Double / Int and control how Swift handles it within your own function.
extension Double {
    static func / (left: Double, right: Int) -> Double {
        return left / Double(right)
    }
}

You can always add another function handling the reverse case an Int / Double, etc...


text:
Q: Generate the schema.rb from Rails Models (without Database) I have a Rails project that has an outdated schema.rb file. I also have an empty database. How do I generate the schema.rb from the Rails Models?

A: You shouldn't be generating a schema from your models, but rather your database or migration files. If your migrations are up to date and reflect the state of your database, you can run:
bundle exec rake db:schema:dump

It should generate the schema.rb file from your database.
This is what Rails runs after the db:migrate task has executed:
Rake::Task["db:schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby

A: You can try;
rake db:schema:load

A: The ActiveRecord models don't store any information about the database schema. The schema is stored in the schema.rb file.
The file is generated from the database, at the end of every migration. Therefore, if you have an up-to-date database, simply run:
$ rake db:migrate

to sync the schema. If you have an empty database, then there is no way to update the schema (actually, at that point I wonder what your Rails models are using).
The only thing you can do is:

*

*load the current schema and migrate from that

*reuse the migrations, assuming they are up to date