text:
Q: Processing .ELF with multiple headers for ARM Dissembler I'm writing a simple ARM dissembler which takes an ELF file and reverts it back to its ARM instructions.
I'm having an issue with processing the ELF files which contain multiple program headers I have an example .elf file to demonstrate this but I'm unsure where to upload it.
I think the issue is that I'm passing the wrong start address into the Dissemble() function.
Anyone have any thoughts about this?
MAIN.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

#include "elf.h"

void Disassemble(unsigned int *armI, int count, unsigned int startAddress);
void DecodeInstruction(unsigned int instr, unsigned int Address);
void HexToBinary(int *bits, unsigned int hex);
int SignExtend(unsigned int x, int bits);
int Rotate(unsigned int rotatee, int amount);
void PrintASCII(unsigned int instr);
void ProcessSWI(int *bits, unsigned int instr, char *instructionPtr);
void ProcessBranch(int *bits, unsigned int instr, unsigned int currentAddress, char *instructionPtr);
void ProcessDP(int *bits, unsigned int instr, char *instructionPtr);
void ProcessLDR(int *bits, unsigned int instr, char *instructionPtr);
void ProcessMUL (int *bits, unsigned int instr, char *instructionPtr);
void ProcessLDM(int *bits, unsigned int instr, char *instructionPtr);

int main(int argc, const char * argv[])
{
    FILE *fp;
    ELFHEADER elfhead;
    int i;
    unsigned int *armInstructions = NULL;

    if(argc < 2)
    {
        fprintf(stderr, "Usage: DisARM <filename>\n");
        return 1;
    }

    /* Open ELF file for binary reading */
   if((fp = fopen(argv[1], "rb")) == NULL)
    {
      fprintf(stderr, "%s\n", argv[1]);
      exit(EXIT_FAILURE);
    }
    /* Read in the header */
    fread(&elfhead, 1, sizeof(ELFHEADER), fp);
    if(!(elfhead.magic[0] == 0177 && elfhead.magic[1] == 'E' && elfhead.magic[2] == 'L' && elfhead.magic[3] == 'F'))
    {
        fprintf(stderr, "%s is not an ELF file\n", argv[1]);
        return 2;
    }
    printf("\nFile-type: %d\n",elfhead.filetype);
    printf("Arch-type: %d\n",elfhead.archtype);
    printf("Entry: %x\n", elfhead.entry);
    printf("Prog-Header: %x\n", elfhead.phdrpos);
    printf("Prog-Header-count: %d\n", elfhead.phdrcnt);
    printf("Section-Header: %x\n", elfhead.shdrpos);

    /* Find and read program headers */
    ELFPROGHDR *prgHdr[elfhead.phdrcnt];
    for(i = 0; i < elfhead.phdrcnt; i++)
      {
    fseek(fp, elfhead.phdrpos*(i+1), SEEK_SET);
    prgHdr[i] = (ELFPROGHDR*)malloc(sizeof(ELFPROGHDR));
    if(!prgHdr)
      {
        fprintf(fp, "Out of Memory\n");
        fclose(fp);
        return 3;
      }

    fread(prgHdr[i], 1, sizeof(ELFPROGHDR), fp);
    printf("Segment-Offset: %x\n", prgHdr[i]->offset);
    printf("File-size: %d\n", prgHdr[i]->filesize);
    printf("Align: %d\n", prgHdr[i]->align);

        /* allocate memory and read in ARM instructions */
        armInstructions = (unsigned int *)malloc(prgHdr[i]->filesize + 3 & ~3);
        if(armInstructions == NULL)
        {
            fclose(fp);
            free(prgHdr[elfhead.phdrcnt]);
            fprintf(stderr, "Out of Memory\n");
            return 3;
        }
        fseek(fp, prgHdr[i]->offset, SEEK_SET);
        fread(armInstructions, 1, prgHdr[i]->filesize, fp);

        /* Disassemble */
        printf("\nInstructions\n\n");

        Disassemble(armInstructions, (prgHdr[i]->filesize + 3 & ~3) /4, prgHdr[i]->virtaddr);
        printf("\n");
        free(armInstructions);
    free(prgHdr[i]);
      }
    fclose(fp);

    return 0;
}

void Disassemble(unsigned int *armI, int count, unsigned int startAddress)
{
    int i;
    printf("Address   Hex       ASCII\tDisassembly\n");
    printf("=============================================\n");
    for(i = 0; i < count; i++)
    {
        printf("%08X  %08X", startAddress + i*4, armI[i]);
        DecodeInstruction(armI[i], startAddress + i*4);
        printf("\n");
    }

}

void DecodeInstruction(unsigned int instr, unsigned int Address)
{
  int bits[32];
  char instruction[100];

  sprintf(instruction, "\0");

  HexToBinary(bits, instr);
  printf("  ");
  PrintASCII(instr);
  printf("\t");

  if (bits[27] && bits[26] && bits[25] && bits[24])
    ProcessSWI(bits, instr, instruction);
  else if (bits[27] && !bits[26] && bits[25])
    ProcessBranch(bits, instr, Address, instruction);
  else if (!bits[27] && bits[26])
    {
    if (!bits[25])
      ProcessLDR(bits, instr, instruction);
    else if (bits[4])
      strcat(instruction, "Undefined Instruction.");
    else if (!bits[4])
      ProcessLDR(bits, instr, instruction);
    }
  else if (bits[27] && !bits[26] && !bits[25])
    ProcessLDM(bits, instr, instruction);
  else if (!(bits[27] || bits[26] || bits[25] || bits[24] || bits[23] || bits[22]) && (bits[7] && !bits[6] && !bits[5] && bits[4]))
    ProcessMUL(bits, instr, instruction);
  else if (!bits[27] && !bits[26])
    ProcessDP(bits, instr, instruction);
  else
    strcat(instruction, "Undefined Instruction.");

  printf("%s", instruction);

  /* DEBUG PRINT BINARY */
  /*printf("\t\t");
    for(int i=31;i>=0;i--)
    {
    printf("%d", bits[i]);
    }*/
}

int SignExtend(unsigned int x, int bits)
{
    int r;
    int m = 1U << (bits - 1);
    x = x & ((1U << bits) - 1);
    r = (x ^ m) - m;
    return r;
}

int Rotate(unsigned int rotatee, int amount)
{
    unsigned int mask, lo, hi;

    mask = (1 << amount) - 1;
    lo = rotatee & mask;
    hi = rotatee >> amount;

    rotatee = (lo << (32 - amount)) | hi;

    return rotatee;
}

void HexToBinary(int *bits, unsigned int hex)
{
  int i;
  for (i = 0; i < 32; i++)
    {
      bits[i] = (hex >> i) & 1;
    }
}

void PrintCCode(unsigned int instr, char *instructionPtr)
{
  switch((instr & 0xF0000000) >> 28)
    {
    case(13): strcat(instructionPtr, "LE"); break;
    case(12): strcat(instructionPtr, "GT"); break;
    case(11): strcat(instructionPtr, "LT"); break;
    case(10): strcat(instructionPtr, "GE"); break;
    case(9): strcat(instructionPtr, "LS"); break;
    case(8): strcat(instructionPtr, "HI"); break;
    case(7): strcat(instructionPtr, "VC"); break;
    case(6): strcat(instructionPtr, "VS"); break;
    case(5): strcat(instructionPtr, "PL"); break;
    case(4): strcat(instructionPtr, "MI"); break;
    case(3): strcat(instructionPtr, "CC/LO"); break;
    case(2): strcat(instructionPtr, "CS/HS"); break;
    case(1): strcat(instructionPtr, "NE"); break;
    case(0): strcat(instructionPtr, "EQ"); break;
    }
}

void PrintASCII(unsigned int instr)
{
  char c[5];
  int i;

  c[0] = (instr & 0x000000FF);
  c[1] = (instr & 0x0000FF00) >> 8;
  c[2] = (instr & 0x00FF0000) >> 16;
  c[3] = (instr & 0xFF000000) >> 24;

  for(i = 0; i < 4; i++)
    {
      if(isalpha(c[i]) || ispunct(c[i]))
    printf("%c", c[i]);
      else
    printf("*");
    }
}

void ProcessSWI(int *bits, unsigned int instr, char *instructionPtr)
{
  strcat(instructionPtr, "SWI");
  PrintCCode(instr, instructionPtr);
  sprintf(instructionPtr + strlen(instructionPtr), "\t%X", instr & 0x00FFFFFF);
}

void ProcessBranch(int *bits, unsigned int instr, unsigned int currentAddress, char *instructionPtr)
{
  if ( bits[24] )
    strcat(instructionPtr, "BL");
  else
    strcat(instructionPtr, "B");
  PrintCCode(instr, instructionPtr);
  sprintf(instructionPtr + strlen(instructionPtr), "\t&%X", (SignExtend((instr & 0x00FFFFFF) << 2, 26)) + currentAddress + 8);
}

void ProcessDP(int *bits, unsigned int instr, char *instructionPtr)
{
  int DP = (instr & 0x01E00000) >> 21;
  int Rd = (instr & 0x0000F000) >> 12;
  int Rn = (instr & 0x000F0000) >> 16;
  int Rot = (instr & 0x00000F00) >> 8;
  int Op = (instr & 0x000000FF);
  int Rm = (instr & 0x0000000F);
  int Sh = (instr & 0x00000060) >> 5;
  int Shift;

  switch(DP)
    {
    case(15): strcat(instructionPtr, "MVN"); break;
    case(14): strcat(instructionPtr, "BIC"); break;
    case(13): strcat(instructionPtr, "MOV"); break;
    case(12): strcat(instructionPtr, "ORR"); break;
    case(11): strcat(instructionPtr, "CMN"); break;
    case(10): strcat(instructionPtr, "CMP"); break;
    case(9): strcat(instructionPtr, "TEQ"); break;
    case(8): strcat(instructionPtr, "TST"); break;
    case(7): strcat(instructionPtr, "RSC"); break;
    case(6): strcat(instructionPtr, "SBC"); break;
    case(5): strcat(instructionPtr, "ADC"); break;
    case(4): strcat(instructionPtr, "ADD"); break;
    case(3): strcat(instructionPtr, "RSB"); break;
    case(2): strcat(instructionPtr, "SUB"); break;
    case(1): strcat(instructionPtr, "EOR"); break;
    case(0): strcat(instructionPtr, "AND"); break;
    }

  PrintCCode(instr, instructionPtr);
  if (bits[20] && DP != 10 && DP != 11)
    strcat(instructionPtr, "S");

  if (DP != 11 && DP != 10)
    sprintf(instructionPtr + strlen(instructionPtr), "\tR%d, ", Rd);
  else
    strcat(instructionPtr, "\t");

  if (DP != 13 && DP != 15)
    sprintf(instructionPtr + strlen(instructionPtr), "R%d, ", Rn);

  if (bits[25])
    {
      if (!(bits[11] || bits[10] || bits[9] || bits[8]))
    sprintf(instructionPtr + strlen(instructionPtr), "#&%X", Op);
      else
    sprintf(instructionPtr + strlen(instructionPtr), "#&%X", Rotate(Op, Rot*2));
    }
  else
    {
      if (bits[4])
    Shift = (instr & 0x00000F00) >> 8;
      else
    Shift = (instr & 0x00000F80) >> 7;
      sprintf(instructionPtr + strlen(instructionPtr), "R%d", Rm);
      if (Shift > 0)
    {
      switch(Sh)
        {
        case(3): if(Shift == 0) strcat(instructionPtr, ", RRX"); else strcat(instructionPtr, ", ROR "); break;
        case(2): strcat(instructionPtr, ", ASR "); break;
        case(1): strcat(instructionPtr, ", LSR "); break;
        case(0): strcat(instructionPtr, ", LSL "); break;
        }
      sprintf(instructionPtr + strlen(instructionPtr), "#&%X", Shift);
    }
    }
}

void ProcessLDR(int *bits, unsigned int instr, char *instructionPtr)
{
    int sourceReg = (instr & 0x0000F000) >> 12;
    int baseReg = (instr & 0x000F0000) >> 16;
    int Rm = (instr & 0x0000000F);
    int immediate = (instr & 0x00000FFF);
    int Shift = (instr & 0x00000F80) >> 7;
    int Sh = (instr & 0x00000060) >> 5;

    if (bits[20])
      strcat(instructionPtr, "LDR");
    else
      strcat(instructionPtr, "STR");

    PrintCCode(instr, instructionPtr);
    if (bits[22])
      strcat(instructionPtr, "B");

    sprintf(instructionPtr + strlen(instructionPtr), "\tR%d", sourceReg);

    if (bits[24]) // Pre incremented
      {
        sprintf(instructionPtr + strlen(instructionPtr), ", [R%d", baseReg);
    if (bits[25])
      sprintf(instructionPtr + strlen(instructionPtr), ", R%d]", Rm);
    else
      {
        if (immediate > 0)
          sprintf(instructionPtr + strlen(instructionPtr), ", #%d]", immediate);
        else
          strcat(instructionPtr, "]");
      }
    if (bits[21])
      strcat(instructionPtr, "!");
      }
    else // Post incremented
      {
    if (bits[21])
      strcat(instructionPtr, "!");
        sprintf(instructionPtr + strlen(instructionPtr), ", [R%d]", baseReg);
    if (bits[25])
      {
        if(bits[23])
          sprintf(instructionPtr + strlen(instructionPtr), ", R%d", Rm);
        else
          sprintf(instructionPtr + strlen(instructionPtr), ", -R%x", Rm);

        if (Shift > 0)
          {
        switch(Sh)
          {
          case(3): if(Shift == 0) strcat(instructionPtr, ", RRX"); else strcat(instructionPtr, ", ROR "); break;
          case(2): strcat(instructionPtr, ", ASR "); break;
          case(1): strcat(instructionPtr, ", LSR "); break;
          case(0): strcat(instructionPtr, ", LSL "); break;
          }
            sprintf(instructionPtr + strlen(instructionPtr), "#&%X", Shift*2); //DOUBLED..
          }
      }
    else
      {
        if (bits[23])
          sprintf(instructionPtr + strlen(instructionPtr), ", #&%x", immediate);
        else
          sprintf(instructionPtr + strlen(instructionPtr), ", #-&%x", immediate);
      }
      }
}

void ProcessMUL (int *bits, unsigned int instr, char *instructionPtr)
{
  int Rd = (instr & 0x000F0000) >> 16;
  int Rm = instr & 0x0000000F;
  int Rs = (instr & 0x00000F00) >> 8;
  int Rn = (instr & 0x0000F000) >> 12;

  if (bits[21])
    strcat(instructionPtr, "MLA");
  else
    strcat(instructionPtr, "MUL");
  PrintCCode(instr, instructionPtr);
  if(bits[20])
    strcat(instructionPtr, "S");
  sprintf(instructionPtr + strlen(instructionPtr), "\tR%d, R%d, R%d", Rd, Rm, Rs);
  if(bits[21])
    printf(", R%d", Rn);
}

void ProcessLDM(int *bits, unsigned int instr, char *instructionPtr)
{
  char regList[256] = { 0 };
  int listState = 0;
  int Rn = (instr & 0x000F0000) >> 16;
  int i;

    if (bits[20])
      strcat(instructionPtr, "LDM");
    else
      strcat(instructionPtr, "STM");

    PrintCCode(instr, instructionPtr);

    sprintf(instructionPtr + strlen(instructionPtr), "\tR%d", Rn);
    if (bits[21])
      strcat(instructionPtr, "!");
    strcat(instructionPtr, ", ");
    strcat(regList, "{");
    for (i = 0; i<16; i++)
      {
    if (bits[i] && !bits[i+1])
      {
        sprintf(regList + strlen(regList), "R%d, ", i);
        listState = 0;
      }
    else if (bits[i] && bits[i+1] && !listState)
      {
        sprintf(regList + strlen(regList), "R%d-", i);
        listState = 1;
      }
      }
    strcat(regList, "\b\b}");
    strcat(instructionPtr, regList);
    if(bits[22])
      strcat(instructionPtr, "^");
}

elf.h
#ifndef DisARM_elf_h
#define DisARM_elf_h

typedef struct _elfHeader
{
    char magic[4];
    char class;
    char byteorder;
    char hversion;
    char pad[9];

    short filetype;
    short archtype;

    int fversion;
    int entry;
    int phdrpos;
    int shdrpos;
    int flags;

    short hdrsize;
    short phdrent;
    short phdrcnt;
    short shdrent;
    short shdrcnt;
    short strsec;

} ELFHEADER;

typedef struct _elfProgHeader
{
    int type;
    int offset;
    int virtaddr;
    int physaddr;
    int filesize;
    int memsize;
    int flags;
    int align;

} ELFPROGHDR;

#endif

Any other general constructive criticism and tips are also greatly welcome.
Please let me know if I need to add additional info to help identify the issues.


text:
Q: OSX Change Sublime Text 3 App Icon I can't seem to change the icon of Sublime Text 3 like I did with 2. When I drag the image to the preview window, Sublime opens the image instead of the icon being replaced. Any ideas how to make this happen?

A: Drag the desired to the top left image in the info, not the preview image.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why should faithfully flat descent preserve so many properties? This question is based on the following proposition (EGA IV, 2.7.1)
Let $f: X \rightarrow Y$ be a $S$-morphism of $S$-schemes, $g: S'\rightarrow S$ a faithfully flat and quasi-compact morphism. Denote $X \times_S S'$ by $X'$, and denote $Y \times_S S'$ by $Y.$ We have a natural morphism $f': X\rightarrow Y.$ Consider the following properties of morphisms:
(i) separated
(ii) quasiseparated
(iii) locally of finite type
(iv) locally of finite presentation
(v) finite type
(vi) finite presentation
(vii) proper
(viii) isomorphism
(ix) monomorphism
(x) open immersion
(xi) quasi-compact immersion
(xii) closed immersion
(xiii) affine
(xiv) quasi-affine
(xv) finite
(xvi) quasi-finite
(xvii) entire (I'm not sure exactly what a "morphisme entier" is, but some reading of the french wikipedia gave me the impression that it's an integral morphism)
If $P$ is one of the preceding properties, then $f$ has property $P$ if and only if $f'$ has property $P.$
My impression of the proof is that there are quite a few ingredients needed to prove this proposition, where different ingredients are needed for different properties, and it surprises me that there seems to be no "unifying principle" that covers all the proofs.
What I would like is something like this theorem: Let $P$ be a property closed under composition and base change. Then, if $f:X \rightarrow Y$ is a map of $Z$-schemes, such that the structure morphism $X \rightarrow Z$ is in $P$ and the diagonal morphism of the structure morphism $Y \rightarrow Z$ is in $P$, then $f$ is in $P$. I like this theorem because it explicitly states the conditions the property needs to satisfy, and the conditions are fairly loose. Then, you have essentially the same proof of this theorem for every such property $P$.
Is there any such unification of the proofs for this result? To me, it seems like this result is some incredibly mysterious miracle. I would appreciate any intuition behind this result.

A: Just to add a little to Akhil's nice answer:
Akhil's answer explains that a faithfully flat morphism is analogous to a surjective map of sets.  This shouldn't be a complete surprise, because the faithful part of faithful flatness is precisely that the morphism be surjective.
There is another analogy that is also intuitively useful, in which we make a comparison not with the category of sets, but with a slightly more geometric category, the category of topological spaces:
Namely, a faithfully flat morphism in algebraic geometry is roughly analogous
to a quotient morphism of topogical spaces (i.e. a surjective morphism in which
the target is given the quotient topology induced by the topology on the source).  Again, this should seem quite natural once you recall that a faithfully flat morphism of schemes is a quotient map when we pass to underlying topological spaces.  (See the wikipedia article for the citation to EGA IV.)
So the idea is that the target of a faithfully flat morphism can be obtained as the quotient of its source just by imposing an appropriate equivalence relation, and hence many properties downstairs can instead be checked upstairs.

A: I think that a "faithfully flat" morphism in algebraic geometry can be thought of as analogous to a surjective map of sets (maybe more accurately as something like a fibration with surjective image). A lot of elementary properties one might formulate about a map of sets can be tested after base-change by a surjection. For instance, if $f: X \to Y$ is a function, then $f$ is surjective (resp. injective) if and only if the base change of $f$ along a surjection $Y' \to Y$ is. There is more to this analogy: one can recover the function $f$ from its base-change along $Y' \to Y$ (under the condition that the two base-changes to $Y' \times_Y Y'$ agree); the analog of this for schemes is (a special case of) faithfully flat descent, explained for instance in Vistoli's article.
I don't know of a general categorical set up relevant here. However, to demystify this result, you might try proving the analogs in commutative algebra, for instance, the following: given an $A$-module $M$ (for $A$ a ring) and a faithfully flat extension $A \to B$, then $M$ is finitely generated if and only if $M \otimes_A B$ is finitely generated.


text:
Q: PHP Cron jobs return "-: error while loading shared libraries: libc.so.6: ELF load command past end of file" I would like to run a few PHP cron jobs on my server.
Scheduler notification is set and the result would be sent to my email.
However, they fail to run, and I keep receiving emails with following contents:
-: error while loading shared libraries: libc.so.6: ELF load command past end of file

Environment:

CentOS Linux 7.0.1406 (Core)
  with Plesk

Cron job commands that I have tried in Plesk, but same result:
/usr/bin/php /var/www/vhosts/domain.com/httpdocs/cron/file.php
php /var/www/vhosts/domain.com/httpdocs/cron/file.php

Checked that the PHP file runs normally without error via HTTP request.
But I would like to use php instead of wget
The cron job command runs without error via SSH to the server.
whereis php
php: /usr/bin/php /usr/lib64/php /etc/php.d /etc/php.ini /usr/share/php /usr/share/man/man1/php.1.gz

whereis libc.so.6
libc.so: /usr/lib64/libc.so.6 /usr/lib64/libc.so

It seems the library is corrupted.
May I know how to reinstall or overwrite the corrupted library?
Not having much knowledge on server management, please suggest me ways to solve the problem.
Thank you.

A: Try something like:
yum resinstall glibc


text:
Q: How to write nested if statements in haskell? I have this function "path" that takes 3 arguments:
path::String->String->String->IO()
path place1 dir place2 =
  if place1 == "bedroom" && d == 'n' && place2 == "den"
    then do
      putStrLn "You are in a bedroom with a large, comfortable bed. It has  been a long, tiresome day, and you would like nothing better than to go to sleep."
  else
    if place1 == "bedroom" && d == 'd' && place2 == "bed"
      then describe "bed"
    else
      if place1 == "den" && d == 's' && place2 == "bedroom"
        then describe "bedroom"
      else
        if place1 == "bed" && d == 'u' && place2 == "bedroom"
          then describe "bedroom"
        else  putStrLn "Cannot go there!"

I want to know how if this is the correct way of having multiple conditions and multiple if statements?

A: Consider using guards, e.g.:
path :: String -> String -> String -> IO ()
path place1 d place2
      | place1 == "bedroom" && d == "n" && place2 == "den"
         = putStrLn "You are in a bedroom ..."
      | place1 == "bedroom" && d == "d" && place2 == "bed"
         = describe "bed"
      | place1 == "den" && d == "s" && place2 == "bedroom"
         = describe "bedroom"
      | place1 == "bed" && d == "u" && place2 == "bedroom"
         = describe "bedroom"
      | otherwise = putStrLn "Cannot go there!"

Note that String literals an enclosed in double quotes.

A: It's not incorrect, but it is not idiomatic (i.e. customary style).  Usually we prefer guards to if-then-else, like in @user5402's answer.  However in your case you are also just comparing to constant literals with ==, which means the best way is to take it one step further and use pattern matching (I formatted it a bit prettier too):
path :: String -> String -> String -> IO ()
path "bedroom" "n" "den"     = putStrLn "You are in a bedroom with a large, comfortable bed. It has  been a long, tiresome day, and you would like nothing better than to go to sleep."
path "bedroom" "d" "bed"     = describe "bed"
path "den"     "s" "bedroom" = describe "bedroom"
path "bed"     "u" "bedroom" = describe "bedroom"
path _         _   _         = putStrLn "Cannot go there!"


text:
Q: Dynamic Facebook open graph tags - javascript I want to read the URL and set og tags according to the result I get.
I'm trying document.write but Facebook doesn't see them
Example:
<head>
  <script>
    if(a==b){
      document.write('<meta property="og:title" content="Wow... A equals B, who knew!" />');
    }
  </script>
</head>

Is there a better way to do this?

A: Open Graph tags should not be used dynamically, Facebook caches those tags. That being said, the Facebook scraper ignores JavaScript, you would have to add them with a server language. For example, with PHP:
<meta property="og:title" content="<?php echo $title; ?>" />


text:
Q: python os.walk() problems I faced some problems when I used os.walk()
Here is my code:
import os

premise_source_dir = 'C:/Users/xujia_000/Desktop/Final_data/eclipse_data/test/test_premise/'
for (premise_root,premise_subdirs,premise_files) in os.walk(premise_source_dir):
    print premise_root
    print premise_subdirs
    print premise_files

The result is:

It doesn't really get the premise_root and premise_files.
So, maybe there is something wrong with my code?

A: If you join premise_root and a filename in premise_files, you will get the absolute path of that file.
import os

premise_source_dir = 'C:/Users/xujia_000/Desktop/Final_data/eclipse_data/test/test_premise/'
for (premise_root,premise_subdirs,premise_files) in os.walk(premise_source_dir):
    for f in premise_files:
        print os.path.join(premise_root, f)

The above code will print the absolute path of every file in premise_source_dir, recursively.


text:
Q: StreamWriting XML in any encoding I've been trying to write XML as output using javax.xml.stream.XMLOutputFactory.createXMLStreamWriter(). Getting stuck on the XML Declaration when not using UTF-8.
   String encoding = "ISO-8859-1";
   File testFile = new File(xmlOutFile);
   OutputStream ops = new FileOutputStream(testFile);
   xmlWriter = factory.createXMLStreamWriter(ops,encoding);

  ...
  String version = "1.0";
  String encoding = "ISO-8859-1";
  xmlWriter.writeStartDocument(encoding, version);

XML input file being re-written;
<?xml version="1.0" encoding="ISO-8859-1"?>
<definition attr1="toady"></definition>

No error is thrown, the file is created, but it's empty.
If I set the xmlWriter to UTF-8, the file is written.

A: The only problem here turned out to be lack of a file close statement: xmlWriter.close().
It wasn't obvious because in my real code, the process starts with an END_DOCUMENT in the first parser that must make it to the END_DOCUMENT handler that generates the XML.
I was thrown off by the fact that UTF-8 worked anyway.


text:
Q: Send small amounts to PayPal API I'm using the PayPal API to handle payments on my website. A product has the following prices :

*

*exclusive of tax : 0.083€

*vat rate : 20%

*all taxes included : 0.10€

In the API, we have to send the items of an order with the exclusive of tax unit price and the vat rate.
Here is my request :
{
  "intent": "sale",
  "payer": {
    "payment_method": "paypal"
  },
  "transactions": [
    {
      "amount": {
        "currency": "EUR",
        "total": "99.60",
        "details": {
          "subtotal": "83.00",
          "tax": "16.60"
        }
      },
      "item_list": {
        "items": [
          {
            "quantity": "1000",
            "name": "My product",
            "price": "0.08",
            "currency": "EUR",
            "sku": "1-20140407123511492"
          }
        ]
      }
    }
  ]
}

As you can see, since PayPal accepts only prices with a maximum of 2 decimals, there is an error in the final calculation (0.003€ multiplied by the quantity).
In the end, I have the following error :
{"name":"VALIDATION_ERROR","details":[{"field":"transactions","issue":"Item amount must add up to specified amount subtotal (or total if amount details not specified)"}],"message":"Invalid request - see details","information_link":"https://developer.paypal.com/webapps/developer/docs/api/#VALIDATION_ERROR","debug_id":"132eaa3f14cce"}

So, how can we handle small prices with the PayPal API ?
Thanks.


text:
Q: How to find computer specs in Python? I am somewhat a beginner in Python, and want to make a script that would evaluate how much the users PC is worth. For this, I need to have a way to find out what the users computer specs would be.
Some things that I need to know about would be:
CPU
GPU
How much RAM
How much Storage
I have heard that there is a way to find the cpu, but how about a way to find out any of the remaining parts.

A: Check this question:
How to get current CPU and RAM usage in Python?
Specs is a really general question. You're better off searching for each specific thing you want to find. I think psutil will give you some of what you need.


text:
Q: How to get information from a Java Process? So, say I have multiple instances of a java program running, and I need to get information from each instance, ie if the program is performing its function correctly and if its not I need to get information to the process on what to do, I essentially need to open a tunnel. How would I do so? I hope this question isn't to vague.
I'm basically writing a manager, the manager loads a bunch of clients and I need a way to communicate between the manager and each client.

A: Have you looked into Java Management Extensions?  It's built-in and made for monitoring java processes:
http://openjdk.java.net/groups/jmx/
if you need to look at custom info for your processes (some state of execution, or some special log info), you can create your own info-providers (aka "MBeans"):
https://blogs.oracle.com/WebLogicServer/entry/developing_custom_mbeans_to_ma
hope that helps


text:
Q: Animation Button with plotly R - customize "hover" color I'd like to change the background color of the button when hovering over it - so eg. if not hovering over the button it should be blue and if hovering it should change to red.
What I tried: animation_button(color = "red) and (based on the options for animation_slider) animation_button(activebgcolor = "red"). Both didn't work - Moreover, I searched for the css options but couldn't find it either. Do you have an idea how to access the buttons 'hover' color and maybe also the 'hover' font color? Thanks!
df <- data.frame(
  x = c(1, 2, 2, 1, 1, 2),
  y = c(1, 2, 2, 1, 1, 2),
  z = c(1, 1, 2, 2, 3, 3)
)
plot_ly(df) %>%
  add_markers(x = 1.5, y = 1.5) %>%
  add_markers(x = ~x, y = ~y, frame = ~z) %>%
  animation_button(font = list(color = "white",
                               family = "Aldhabi"),
                   bgcolor = "blue",
                   bordercolor = "blue",
                   # color = "red"
                   # activebgcolor = "red"
                   )

Edit:
As suggested here I tried this command but it didn't help either.
btn:hover {
  color:"red";
}

A: In CSS you just do:
 .classname:hover{
      background-color: red;
 }


text:
Q: Issue to insert record with datetime to SQL Server 2014 via ODBC C++ I have a simple c++ code to insert a record in SQL Server 2014 via ODBC. It works fine with varchar fields, but it does not work with datetime field.
SQLCHAR buf[64];
SQLLEN len;
SQLCHAR buf2[255];
SQLLEN len2;
SQLLEN len3;
double f;
rc = SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_TYPE_TIMESTAMP, 19, 0, (SQLCHAR*)buf, 0, &len);
rc = SQLBindParameter(hstmt, 2, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_VARCHAR, 255, 0, (SQLCHAR*)buf2, 0, &len2);
rc = SQLBindParameter(hstmt, 3, SQL_PARAM_INPUT, SQL_C_FLOAT, SQL_FLOAT, 15, 0, &f, 0, &len3);
rc = SQLPrepare(hstmt, (SQLCHAR*)"insert into test(timepoint,strvalue,floatvalue) values (?,?,?)", SQL_NTS);

strcpy((char*)buf,"20171010 00:08:14");
len=strlen("20171017 00:08:14");
strcpy((char*)buf2,"simple string");
len2=strlen("simple string");
f=1.34e+8;

SQLSMALLINT NumParams;
SQLNumParams(hstmt, &NumParams);
rc = SQLExecute(hstmt);

Can anybody help to understand that is wrong?
I've got always:
"22018:1:0:[Microsoft][ODBC SQL Server Driver]Invalid character value for cast specification\n"
If I'm wrong here with my question, please give a hint which forum fits better. I've spent some days, but can't find the solution. For any help would be very appreciate.

A: SQL Server can cast various strings in different date formats to a real date implicitly, but you must be very careful how to use them:
There is the unseparated date format "yyyyMMdd", which cannot carry a time!
SELECT CAST('20170102' AS DATETIME) --2017-01-02 00:00:00.000

The most universal format is ISO8601, which is yyyy-MM-ddTHH:mm:ss (beware of the the T in the middle and the usage of 24 hours format!)
SELECT CAST('2017-01-02T12:23:59' AS DATETIME) --2017-01-02 12:23:59.000

And - last but not least - there are three ODBC formats:
SELECT CAST({d'2017-01-02'} AS DATETIME)           --2017-01-02 00:00:00.000
SELECT CAST({t'23:35:51'} AS DATETIME)             --2018-01-19 23:35:51.000 (today!)
SELECT CAST({ts'2017-01-02 23:35:51'} AS DATETIME) --2017-01-02 23:35:51.000

And a last - important! - hint: Some formats work, but depend on the system's settings. This can work for you and pass all internal tests, but might break on a customer's machine:
SET LANGUAGE ENGLISH;
SELECT CAST('2017-01-02 23:35:51' AS DATETIME) -- Jan 2
SET LANGUAGE GERMAN;
SELECT CAST('2017-01-02 23:35:51' AS DATETIME) -- Feb 1


text:
Q: Seed for reproducible results is not working (Tensorflow) I'm having a problem that concern the reproducibility of my results using Tensorflow (v1.15.3). I set all the seeds (os, random, numpy and tensorflow) but the results of a convolutional neural networks changes always between executions (even if similar).
I set my seeds in this way:
seed_value = 1234

import os
os.environ['PYTHONHASHSEED'] = str(seed_value)
import random
random.seed(seed_value)
import numpy as np
np.random.seed(seed_value)
import tensorflow as tf
tf.compat.v1.set_random_seed(seed_value)
tf.set_random_seed(seed_value)

Next I define the weights of the net like this:
weights = {
    'conv1/conv2d': tf.get_variable('conv1/weights', shape=[3,3,512,1024], initializer=tf.contrib.layers.xavier_initializer()),
    # and more ...
}

(things doesn't change if I use or not the initializer for the weights)
after that I define the graph with convolution operations using the weights initialised before (I omit that because there is no way to set seed to the tf.nn.conv2d operation in Tensorflow and because only the weights are the dynamic part of the model that could affect the results).
Any idea how to get always the same results after defining a model in this way using Tensorflow?
Thank you.

A: I suggest, after
weights = {
    'conv1/conv2d': tf.get_variable('conv1/weights', shape=[3,3,512,1024], initializer=tf.contrib.layers.xavier_initializer()),
    # and more ...
}

store the weight externally in a file, for example, then next time you run, do not go through that previous line and load the weight from the external file.


text:
Q: Scala best way of turning a Collection into a Map-by-key? (2nd variant) (This is a variant to this Q&A)
Say I have this:
List( "foo", "bar", "spam" )

I want to create a Map for which the key is the length of the String and the value is a Collection of all the Strings that have that length. In other words, given the about List, we'd get:
Map( 3 -> List(foo, bar), 4 -> List(spam) )

The code I've written to do this is:
list.foldLeft(Map[Long, List[String]]()) {
  (m, s) => m(s.length) = s ::
     ( if ( m.contains(s.length) ) m(s.length)
       else Nil )
}

This works, but it adds a lot of ugliness to the elegant answer Daniel Spiewak provided to the original question (referenced above).
Any ideas how to improve the solution for my variant?
Thanks!
Sean

A: If you don't mind lousy performance:
val list = List( "foo", "bar", "spam" )
val keyValue = for (length <- list map (_ length) removeDuplicates;
                    strings = list filter (_.length == length))
               yield (length -> strings)
val map = Map(keyValue: _*)

The problem is that the list is read again for each different length.
Now, about the uglyness of your version, perhaps this helps:
list.foldLeft(Map[Long, List[String]]()) {
  (m, s) => m(s.length) = s :: m.getOrElse(s.length, Nil)
}

Better? It's still not quite good because you get the length twice. This one doesn't have this problem, but it's slightly uglier:
list.foldLeft(Map[Long, List[String]]()) {
  (m, s) => val length = s.length; m(length) = s :: m.getOrElse(length, Nil)
}

A: With Scala 2.8.0:
list.groupBy(_.length)

It can not get any simpler than that!


text:
Q: Typescript: iterate through checkbox (made by ngfor) and print value of each checkbox I want to get value (console.log(somevalue))  from each of my checkbox generated by ngfor . My form is displaying OK.
Here is code :
<form>

    {{firstColumn}}

        <input name="checkbox{{i}}" id="checkbox{{i+'_'+j}}" type="checkbox" class="custom-control-input"
          value={{secondColumn}}>
        {{secondColumn}}

      <button name="submit" type="submit" class="btn btn-primary">Submit</button>

</form>

Here is design :

I need to iterate though all of my checkbox and console.log() each check box value. Please help me
(Note that : see how I generated Id and Name - it is like :
when name 1 id is 1_1 , 1_2 ..
when name 2 id is 2_1, 2_2, 2_3, ...
Should I change my id , name implementation for this purpose ? If so please tell me about it.)

A: A possible solution would be to use Reactive Forms. First create a FormGroup in the component based on the first and second columns in your arrays like so:
 buildReactiveForm() {
    this.form = new FormGroup({});
    this.mapMenusFirstColumn.forEach((firstColumnItem, firstIndex) => {
      this.getSecondColumn(this.mapMenu, firstColumnItem).forEach(
        (secondColumnItem, secondIndex) => {
          this.form.addControl(
            "checkbox" + firstIndex + "_" + secondIndex,
            new FormControl(false)
          );
        }
      );
    });
  }

And in your HTML file add another attribute for the  tag specifying the form control name
<input name="checkbox{{i}}" id="checkbox{{i+'_'+j}}" formControlName="checkbox{{i+'_'+j}}" type="checkbox" class="custom-control-input">

And, finally, you can log the values of the checkboxes by simply logging the form's value
console.log(this.form.value)

Which will have the following output

Stackblitz: https://stackblitz.com/edit/questions63098875?file=src/app/app.component.ts


text:
Q: How to communicate between threads I have 3 classes 1. main 2. Master 3. Clients ( three instance). Master and client have a function increment where they keep increment a value and periodically clients (say every 2 secs) send that increment value to master and at random time each client should send message to other client which it choose randomly (say client1 send to client 2) . and when the maser receives the message it will do some calculation and broadcast the value to all cilents.
Main -------->
public class Sample_one{

public static final int PORT = 4444;
public static void main(String[] args) throws IOException{

ServerSocket server = new ServerSocket(PORT);
Socket socket =server.accept();

Thread m1=  new Master(socket);
m1.start();

Client c1 = new Client();
Client c2 = new Client();
Client c3 = new Client();
c1.start();
c2.start();
c3.start();

}
}

Master ----->
public class Master extends Thread  {
private int inc= 0;
long start = System.currentTimeMillis();
long end = start + 10*1000;
Socket socket;

Master(Socket socket){
    this.socket = socket;
}

@Override

public void run() {

    while(System.currentTimeMillis() < end){
        increment();

    //Method to read input from the client

      }

}

private void increment(){
    inc++;
    System.out.println("counter"+ inc);
}

}

Client -- >
    public class Client extends Thread  {

    private int inc= 0;
    long start = System.currentTimeMillis();
    long end = start + 10*1000;

     public void run() {

    while(System.currentTimeMillis() < end){
        increment();

    //Method to send the value to the Master or other clients

      }

      }

     private void increment(){
    inc++;
    System.out.println("counter"+ inc);
    }

     }

Am I going in current path?? How do I connect the master and client and client with other clients?? Whether Socket are the only way?? I am new Threads.

A: Probably the best thing would be to use pipes. Look at PipedInputStream and PipedOutputStream classes for example. Once you open the pipes, to receive data you would do something like this:
//establish the pipe connection

while (pipe) //assuming someone will eventually close the connection
{
   while (pipe.available() > 0)
      buffer.addByte(pipe.read())

   //Do some other processing
}


text:
Q: Explain this awk command Please explain what exactly this awk command does:
awk '$0!~/^$/{print $0}'

A: It removes blank lines.  The condition is $0 (the whole line) does not match !~ the regexp /^$/ (the beginning of the line immediately followed by the end of the line).
Similar to grep -v '^$'

A: It prints non-empty input lines. Note: "Empty" does not mean "blank", in this case.

A: Your example could be rewritten as simply:
awk '!/^$/'

or
sed '/^$/d'

A: Like Ben Jackson and the others said, it removes completely empty lines. Not the ones with one ore more whitespaces, but the zero character long ones. We will never know if this was the intended behaviour.
I'd like to remark, that the code is at least redundant if not even triple redundant depending on what it's used for.
What it does is that it prints the input line to the output if the input line is not the empty line.
Since the standard behaviour of awk is, that the input line is printed if a condition without a following program block is met, this would suffice:
awk '$0!~/^$/' or even shorter awk '$0!=""'

If you could be sure, that no line would be parsed to zero, even a
awk'$0'

could do the trick.

A: Make it readable first...

echo '$0!~/^$/{print $0}' | a2p
==>
$, = ' ';
$\ = "\n";

while (<>) {
    chomp;
    if ($_ !~ /^$/) {
        print $_;
    }
}

And the interpret. In this case, don't print empty lines.


text:
Q: reading xlsx with multi sheets into lists c# I have a code where i read a file (.csv) and store its columns in lists.
var pathskill = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory.ToString(), "skill.csv");

using (var fs1 = File.OpenRead(pathskill))
using (var reader1 = new StreamReader(fs1))

while (!reader1.EndOfStream)
{
    var line = reader1.ReadLine();
    var values = line.Split(',');

    list_MainId.Add(Convert.ToDouble(values[0]));
    list_MainName.Add(values[1]);
    list_AmountMade.Add(Convert.ToInt32(values[2]));
    list_Level.Add(Convert.ToDouble(values[3]));
    list_Exp.Add(Convert.ToDouble(values[4]));
    list_MadeFrom_One_Id.Add(Convert.ToDouble(values[5]));
    list_Amount_MadeFrom_One.Add(Convert.ToInt32(values[6]));
    list_MadeFrom_Two_Id.Add(Convert.ToDouble(values[7]));
    list_Amount_MadeFrom_Two.Add(Convert.ToInt32(values[8]));

}

This code works great and i get 9 lists with values.
However, i have many .csv files and i think it will be better that each will be like a sheet in xlsx file and i can choose which one to read by its name.
For example to have a sheet called skill1, skill2 and so on.
Is there a way to read a specific sheet from xlsx by its name and store it columns into lists?
Thank you

A: There are a lot of ways to do this. You could unzip xlsx files and read sheet XMLs directly, or you may use some library that can work with xlsx (e.g. EPPLUS that is freeware).


text:
Q: Laravel manual login function I use manual login function in Laravel 5.5. Stuck in login. and check all(5 relevant ) Stack links and didn't find any clue on it.

Achievement  is once user get registered, automatically sign in that user.

Error is

"Type error: Argument 1 passed to Illuminate\Auth\SessionGuard::login() must implement interface Illuminate\Contracts\Auth\Authenticatable, string given, called in Server/vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php on line 294 ◀"

if ($validator->fails()) {

//            $messages = $validator->messages();

            return Redirect::to('register')
                ->withErrors($validator)
                ->withInput();

        } else {

            $email = Input::get('email');
            $user = new user;
            $user->name     = Input::get('name');
            $user->email    = Input::get('email');
            $user->password = Hash::make(Input::get('password'));

            $user->save();
//            $userMail = $user->find($email);
            $userMail = User::where('email','=',$email)->first();
            Auth::login($userMail->email, TRUE);

am i doing anything wrong. Please guide me.

A: Login function needs user of type Authenticatable and you just given email which is string thats why you get this error, Either use Auth::loginUsingId($id);
 $user = User::where('email','=',$email)->first();
 Auth::loginUsingId($user->id, TRUE);

Or just
Auth::login($user);

A:
Instead of this

Auth::login($userMail->email, TRUE);

Use this

Auth::login($user->id, TRUE);

A: $email = $request->email;
    $password = md5($request->password);

    if ($request->remember_me == 1) {
        $cookie =  Cookie::queue('username', $email, time() + 31536000);
    } else {
        $cookie =  Cookie::queue('username', '', time() - 100);
    }

    $user = DB::table('tbl_adminuser')->where('email_address', $email)->where('password', $password)->first();
    $request->session()->put('userData', $user);

=> You can manual login like this in laravel

A: The Auth::login() function expects an Authenticable object. If you have not messed with the User class, this will be what you need to pass in.
Auth::login($user, true);
Reference: https://laravel.com/api/5.5/Illuminate/Auth/SessionGuard.html#method_login

A: Just use Auth::login($userMail, TRUE); instead of Auth::login($userMail->email, TRUE);
For more info check: https://laravel.com/api/5.5/Illuminate/Auth/SessionGuard.html#method_login

A: For Laravel 7.
Manual Login
Use this method for login.
public function check_login(Request $request)
{
    $credentials = $request->only('username', 'password');
    if (Auth::attempt($credentials)) {
        return redirect('/dashboard');
    } else {
        return redirect('/login')->with('error', 'Invalid Email address or Password');
    }
}

If you are using a different model class other than the default('User'), then -> navigate to config/auth.php and edit this
 'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],

to
 'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Staff::class,
        ],

Note: I have replaced User with my model class Staff.
Finally go to your model class and instead of extending Model, extend User. ie
From
class Staff extends Model
{

to
class Staff extends \Illuminate\Foundation\Auth\User
{

That's it.

A: You need to pass/return the $user like this
if ($validator->fails()) {

//            $messages = $validator->messages();

            return Redirect::to('register')
                ->withErrors($validator)
                ->withInput();

        } else {

            $email = Input::get('email');
            $user = new user;
            $user->name     = Input::get('name');
            $user->email    = Input::get('email');
            $user->password = Hash::make(Input::get('password'));

            $user->save();
//

            Auth::login($user);

OR
Auth::loginUsingId($user->id, TRUE);

A: According to the doc, you may need to regenerate the session after manually login an user:
        $user = User::firstOrCreate([
            // ...
        ], [
            // ...
        ]);

        Auth::login($user);
        $request->session()->regenerate();

        return redirect()->route('dashboard');


text:
Q: Obtener en tiempo real el valor de un select en php-js-ajax Tengo un pequeño problema que no se como resolver. Tengo un desplegable para seleccionar entre 3 opciones y al lado un input para escribir y realizar busquedas.
Cuando empiezas a escribir en el input va mostrando los datos que coinciden de la bbdd, pero los datos que muestra siempre son de la misma tabla. (En la query esta puesto el nombre de la tabla en vez de una variable)
Lo que quiero conseguir es que dependiendo que opción selecciones en el desplegable, luego cuando escribas muestre los datos de una u otra tabla.
El input es como autocompletar automáticamente en tiempo real.
Como puedo pasar en tiempo real el valor del desplegable a una variable para ponerlo en la query?
actualizacion
En mi pagina principal tengo esto:
<select required name="name" id="name" class="form-control" onchange="send(this.value);">
<option value="name1">name1</option>
<option value="name2">name2</option>
</select>

<script>
  function send(name) {
     //var dataString = "name" + name;
      $.ajax({
      type: 'POST',
      url: 'ajax.php',
      data: {name: name},
      });
   }
</script>

Y en la otra pagina trato de recoger el valor de esta forma, pero devuelve null.
$name =$_post['name'];
var_dump($name);
die();


text:
Q: Gitlab CI/CD running pipeline only on tag push and only if specific files changed I have a monorepository with a lot of things that needs to be deployed seperately.
Now i wonder if it is possible to run a task only if a tag is pushed and if there are changes in a certain directory.
I've tried the following:
.components:
  only:
    changes:
      - source/packages/components/**/*
  except:
    - branches

.components:
  only:
    refs:
      - tags
    changes:
      - source/packages/components/**/*

.components:
  rules:
    - if: $CI_COMMIT_TAG
    changes:
      - source/packages/components/**/*

.components:
  rules:
    - if: $CI_COMMIT_TAG
      changes:
        - source/packages/components/**/*
      when: always
    - when: never

This is one of the .gitlab-ci.yml files i use. Each of then looks the same except of a few things.
.components:
  rules:
    - if: '$CI_COMMIT_TAG'
      changes:
        - source/packages/components/**/*

build_componets:
  stage: build
  extends: .components
  needs: []
  script:
    - echo "Compiling the components code..."

test_componets:
  stage: test
  extends: .components
  needs: ["build_componets"]
  script:
    - echo "Compiling the components code..."

deploy_componets:
  stage: deploy
  extends: .components
  needs: ["test_componets"]
  script:
    - echo "Compiling the components code..."

Currently behavior: Every pipeline runs... regardless of this configurations but only when I'm pushing a tag.
All of those files are imported to a main file at the project root.
stages:
  - build
  - test
  - deploy

include:
  - source/packages/business-logic/.gitlab-ci.yml
  - source/packages/components/.gitlab-ci.yml
  - source/applications/native/.gitlab-ci.yml
  - source/services/user-service/.gitlab-ci.yml

And the merged YAML looks like this.
---
".business-logic":
  rules:
  - if: "$CI_COMMIT_TAG"
    changes:
    - source/packages/business-logic/**/*
    when: always
  - when: never
build_business_logic:
  rules:
  - if: "$CI_COMMIT_TAG"
    changes:
    - source/packages/business-logic/**/*
    when: always
  - when: never
  stage: build
  extends: ".business-logic"
  needs: []
  script:
  - yarn install
  - yarn workspace @zeou/business-logic build
test_business_logic:
  rules:
  - if: "$CI_COMMIT_TAG"
    changes:
    - source/packages/business-logic/**/*
    when: always
  - when: never
  stage: test
  extends: ".business-logic"
  needs:
  - build_business_logic
  script:
  - echo "Compiling the business-logics code..."
deploy_business_logic:
  rules:
  - if: "$CI_COMMIT_TAG"
    changes:
    - source/packages/business-logic/**/*
    when: always
  - when: never
  stage: deploy
  extends: ".business-logic"
  needs:
  - test_business_logic
  script:
  - echo "Compiling the business-logics code..."
".components":
  rules:
  - if: "$CI_COMMIT_TAG"
    changes:
    - source/packages/components/**/*
    when: always
  - when: never
build_components:
  rules:
  - if: "$CI_COMMIT_TAG"
    changes:
    - source/packages/components/**/*
    when: always
  - when: never
  stage: build
  extends: ".components"
  needs: []
  script:
  - echo "Compiling the components code..."
test_components:
  rules:
  - if: "$CI_COMMIT_TAG"
    changes:
    - source/packages/components/**/*
    when: always
  - when: never
  stage: test
  extends: ".components"
  needs:
  - build_components
  script:
  - echo "Compiling the components code..."
deploy_components:
  rules:
  - if: "$CI_COMMIT_TAG"
    changes:
    - source/packages/components/**/*
    when: always
  - when: never
  stage: deploy
  extends: ".components"
  script:
  - echo "Compiling the components code..."
stages:
- ".pre"
- build
- test
- deploy
- ".post"
before_script:

Can someone tell me what i'm doing wrong ?
Thanks 100 times :D

A: Use rules: in this case to combine a changes: clause with an if: rule to check if there is a tag.
myjob:
  rules:
    - if: "$CI_COMMIT_TAG"
      changes:
        - source/services/user-service/**/*
   # ...


text:
Q: From where to start such a question?
13 equal charges, q , are placed at the corners of a 13 sided regular polygon. What is the force on a test charge Q at the centre?

I couldn't figure out from where to start solving it. It would be very messy to do vector addition of 13 forces. So I think, there must be some trick behind it? Can you please help me?

A: You can take the vertices to be the roots of $x^{13}-1$.  The sum of those roots is minus the coefficient of $x^{12}$, which is zero.


text:
Q: Emacs org-mode totals table I have an org file, describing a project:
* task1
** task1-1
     :PROPERTIES:
     :price: 10
     :given: <2012-11-08 Thu>
     :END:
** task1-2
     :PROPERTIES:
     :price: 11
     :given: <2012-11-08 Thu>
     :END:

* task2
** task2-1
     :PROPERTIES:
     :price: 20
     :given: <2012-11-08 Thu>
     :END:
** task2-2
     :PROPERTIES:
     :price: 21
     :given: <2012-11-08 Thu>
     :END:

I used org-collector to produce a totals table:
#+BEGIN: propview :id global :conds ((not (= price 0))) :cols (ITEM price)
| ITEM      | price |
|-----------+-------|
| "task1-1" |    10 |
| "task1-2" |    11 |
| "task2-1" |    20 |
| "task2-2" |    21 |
|-----------+-------|
|           |    62 |
#+TBLFM: @6$2=vsum(@2$2..@5$2)
#+END:

But I want to have something like this:
| ITEM      | price |
|-----------+-------|
| "task1-1" |    10 |
| "task1-2" |    11 |
| "task2-1" |    20 |
| "task2-2" |    21 |
|-----------+-------|
| Total     |    62 |

How to do it?

A: For the "Total" line, you can add a line |Total| |, press C-u C-c = in the empty cell (to define a formula for it), and enter the formula vsum(@1$2..@4$2). (If you wanna recalc, that's C-u C-c C-c for all.)
I don't know about org-collector, so can't help you with this part. Run it on the entire document (is :id global working?), or shift everything by one level to the right for it to be inside a single tree, maybe.

A: I just figured this one out this morning.  The answer you're looking for with Org-Collector is straightforward.  Just put the table formulae two blank lines beneath the beginning of the property view and it'll be calculated automatically when the property view is evaluated (with C-c C-c).
#+BEGIN: propview :scope tree :cols (ITEM CLOCKSUM EFFORT) :match "TODO=\"TODO\"" :noquote ALL

#+TBLFM: @>$1=Totals::@>$2=vsum(@I..@II);t::@>$3=vsum(@I..@II);t
#+END:

If you want to turn this into a generic yasnippet, you need to escape the $ and the \:
#+BEGIN: propview :scope tree :cols (ITEM CLOCKSUM EFFORT) :match "TODO=\\"TODO\\"" :noquote ALL

#+TBLFM: @>\$1=Totals::@>\$2=vsum(@I..@II);t::@>\$3=vsum(@I..@II);t
#+END:

Now, you can add a generic property view that calculates the time so far and effort remaining for each step of a project, as well as the total time overall.


text:
Q: Posting 'object' to WebApi works, but ViewModel comes in null, and string throws up a big mess I send "TargetViewModel" down using WebAPI (v2.2). At the top of the ViewModel I have [JsonObject] and this now works OK: I get my object down to the client and it renders fine.
However, I want to send the object back. So I've got a Post method in my ApiController-derived controller. The method starts:
    [Route]
    [HttpPost]
    [AllowAnonymous]
    public DataPostResponse Post(TargetViewModel PostBack)
    {

If I post to this I get a null object.
If I change "TargetViewModel" in the method signature to simply 'object' I get a populated object. Same if I use JObject as the type.
If I change "TargetViewModel" to type 'string' I instead get: No action was found on the controller that matches the request...
... but there is, because it finds it when it's set to 'TargetViewModel' or 'object'.
So I was wondering why this might be.

A: For anyone else having this kind of issue, here's how I found out what was going on:
I tried changing the method signature to expect a JObject instead and then later on de-serialize it to my complex ViewModel.  This then threw up the error that was the root of it all: No parameterless constructor existed for my Complex View Model. A silly mistake, but I was going around for hours on this one until I finally got an error that pointed me in the right direction.
Always check you have a parameterless constructor.


text:
Q: Counterexamples of second mean value theorem of integral Recently I am having trouble understanding Bonnet's mean value theorem. I looked back and forth on the proof, and find that the condition of $\phi$ being decreasing is essential. However, I am unable to find an example to illustrate how the theorem fails when $\phi$ is NOT decreasing.
Can anyone give an example?

A: DO NOT LEAVE a comment before even reading the question. The question is asking for an example where the theorem FAILS. It is NOT asking for an example where the theorem applies properly. It is irresponsible to vote or comment before even understanding the question properly.
Let $\phi(x)=x$, $G(x)=1$, and $[a,b]=[0,1]$. Then
$$
\int_0^1 G(x)\phi(x)dx=0.5
$$
But for any $c\in[0,1]$,
$$
\phi(0) \int_0^c G(x)dx=0.
$$
So the theorem fails.


text:
Q: Taxonomy structure help I have been struggling with Taxonomies and Post Types for a while and could really use help understanding what would be the best implementation for my situation.
Have a look here: http://shaulzofef.com/netivyah/resources/audio-lessons/
I setup a few post types; Books, Magazines, Articles and Audiolessons.
I setup a few Taxonomies: Language, Author, Teacher.
Teacher is associated to one post type only, Audiolessons, but Language is associated to all post types.
I made a submenu on the audio page that has English, Hebrew and Russian at parent level and underneath a list of teachers in each language.
I have a few problems:
1 - Some teachers teach in more than one language, so if I click on Joseph under English how will I make it list only the posts with taxonomy term Joseph AND taxonomy term English?
2 - When I click on English it lists the English Audiolessons AND other posts associated with taxonomy term English (articles, books and so on). How would I list only the Audiolessons?
I realize I can code a Wordpress query for posts related to post type and taxonomy, however that will require a file for each combination..
I could create separate taxonomies for each post type, 'Audio-Language' for instance, then I could easily list them, but that doesn't seem right.. then what if I do want an option to list all English resources together.
Should I create hierarchical taxonomies instead?..
I'm getting confused.
Any help much appreciated.

A: If you want to filter your audio lessons post archive you could borrow from the article I linked you to and add a custom rewrite rule:
function wpa_add_rewrite_rules() {
    global $wp_rewrite;

    $new_rules = array(
        'audio-lessons/language/(.+)/?$' => 'index.php?post_type=audio-lesson&language=' . $wp_rewrite->preg_index(1)
    );
    $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}
add_action( 'generate_rewrite_rules', 'wpa_add_rewrite_rules' );

After re-saving your permalinks, something like http://example.com/audio-lessons/language/english would show all the English audio lessons.
However, I am not sure the URL you provided is a post type archive and not a custom page template.
If it is a page template and you are running multiple Wp_Query() calls you could register a new query variable and build your tax_query up from that.
function wpa_add_new_query_vars($vars) {
    $vars[] = 'language'; // name of variable you want to add
    return $vars;
}
add_filter( 'query_vars', 'wpa_add_new_query_vars', 10, 1 );

You may not even need this part as I think the query var is registered when you register the taxonomy.
Then you could query posts like so:
$args = array(
    'post_type' => 'audio-lesson'
);

if( $lang = get_query_var( 'language' ) ){
    $args['tax_query'] = array( array(
            'taxonomy' => 'language',
            'field' => 'slug',
            'terms' => '$lang'
        ));
}

$my_posts = new WP_Query( $args );

I can't really test this and the tax_query can sometimes trip me up with its array of arrays so I'm not 100% sure it will work.
Then anywhere you wanted to make a link to a specific language section you could use add_query_arg()


text:
Q: Twilio API ApiConnectionException "A Task Was Canceled" I'm using the Twilio C# API to send batches of messages to the Twilio API (typically small amounts, but can grow to several thousand at a time), and in an effort to make the process faster, I started switching everything over to asynchronous calls (as well as some parallel foreaches).
The Twilio API works most of the time when it's completely synchronous, but when I change the request to be asynchronous, I start to get heaps of errors. They all essentially say:
Connection Error: POST and the internal error is A task was canceled.
After doing some digging, I've determined that the Twilio API is built on top of the HttpClient, and it uses the client to send all its requests. However, I can't figure out how to make it all work properly. On average, when sending batches with over 3,000 messages, roughly 20% of them fail.
My sending code is pretty basic
// async SendTextNotificationsAsync
try
{
    var result = MessageResource.Create(
        to,
        from: new PhoneNumber(PhoneNumber),
        body: message);

    return result;
}
catch (ApiException ex) // API exception, probably an invalid number.
{
    LogTwilioBadNumber(ex, phone);

    return null;
}
catch (ApiConnectionException ex) // Connection error, let's reattempt
{
    if (tryAttempt < 3)
    {
        System.Threading.Thread.Sleep(500);
        // failed call again
        return await SendTextNotificationsAsync(phone, message, tryAttempt + 1);
    }
    if (tryAttempt >= 3)
    {
        LogTwilioConnectionException(ex, phone, patientId, tryAttempt);
    }

    return null;
}

The above is called from another method that looks something like:
// async void CompleteCampaignsAsync
await Task.Run(() => Parallel.ForEach(campaign.Details, async n =>
{
    await com.SendTextNotificationsAsync(to, message);
}));

And finally, the controller simply calls something like so:
// Don't wait for this to finish, internal processes handle logging
// Will get a time-out error if we wait for this.
await Task.Run(() => cl.CompleteCampaignsAsync()).ConfigureAwait(false);

There are several other steps and layers, so the above is massively simplified. Everything is asynchronous and everything is awaited. The only real exception is the main controller due to it being a long running process that needs to just get kicked off.
In the first method, I've tried both MessageResource.Create and MessageResource.CreateAsync. In the latter, I get through about 80 messages before its an unending stream of task cancelled errors. In the former, the process runs to completion, but roughly 20%-50% of the tasks fail.
Is there anything immediately obviously wrong that would allow me to correct this?


text:
Q: Why bluez removal also removes almost all system settings? I wanted to change bluez 4 to bluez 5.
Moving through the procedure I found that bluez removal also removes ubuntu-desktop, unity-control-center and some other packages. Do you really think I do not need so set up my system any more if I've removed bluetooth support? That's funny!
Update with details:
Ubuntu 14.04.
Run sudo apt-get purge bluez.
It removes ubuntu-desktop, unity-control-center and other packages, and informs that they will be removed. Of course, I can install them back (as I did), but the usability of such approach is doubtful.
So, for example, if I do not want to have bluetooth support in my computer and remove it, why do I lose system settings in addition?

A: If you want bluez 5, I recommend you upgrade to Ubuntu 16.04 LTS which includes bluez 5.


text:
Q: How to count no of rows and column in csv file using c programming #include <stdio.h>

int main()
{
    FILE *fileptr;
    int count_lines = 0;
    char filechar[40], chr;

    printf("Enter file name: ");
    scanf("%s", filechar);
    fileptr = fopen(filechar, "r");
    chr = getc(fileptr);
    while (chr != EOF)
    {
        if (chr == 'n')
        {
            count_lines = count_lines + 1;
        }
            chr = getc(fileptr);
    }
    fclose(fileptr); //close file.
    printf("There are %d lines in %s  in a file\n", count_lines, filechar);
    return 0;
}

here i am able to count the no of row but i dont know how to count the no of col please help me out
the  main is i not am able to count no of comma in csv file so if i am able to count no of comma then it easy to know how much column in csv file


text:
Q: Visual Express installation aborted at KB2999226 update I have windows 8.1 installed on my computer. I tried to install Visual Express 2015 on it and the installation get aborted when it tries to install KB2999226 update.
Then I tried to install that update manually. But it says that the update is not applicable to my computer.
Why is this? Does that KB2999226 update needs any other update to to be installed beforehand?

A: Does the KB2999226 update need any other update to to be installed beforehand?

Prerequisites
To install this update, you must have April 2014 update rollup for
  Windows RT 8.1, Windows 8.1, and Windows Server 2012 R2 (2919355)
  installed in Windows 8.1 or Windows Server 2012 R2. Or, install
  Service Pack 1 for Windows 7 or Windows Server 2008 R2. Or,
  install Service Pack 2 for Windows Vista and for Windows Server
  2008.

Source KB2999226 - Update for Universal C Runtime in Windows

A: I would like to give you a background on Universal CRT this would help you in understanding as to why the system should be updated before installing vc_redist.x64.exe.
A large portion of the C-runtime moved into the OS in Windows 10 (ucrtbase.dll) and is serviced just like any other OS DLL (e.g. kernel32.dll). It is no longer serviced by Visual Studio directly. MSU packages are the file type for Windows Updates.
In order to get the Windows 10 Universal CRT to earlier OSes, Windows Update packages were created to bring this OS component downlevel. KB2999226 brings the Windows 10 RTM Universal CRT to downlevel platforms (Windows Vista through Windows 8.1). KB3118401 brings Windows 10 November Update to the Universal CRT to downlevel platforms.
Windows XP (latest SP) is an exception here. Windows Servicing does not provide downlevel packages for that OS, so Visual Studio (Visual C++) provides a mechanism to install the UCRT into System32 via the VCRedist and MSMs.

*

*The Windows Universal Runtime is included in the VC Redist exe package as it has dependency on the Windows Universal Runtime (KB2999226).
Windows 10 is the only OS that ships the UCRT in-box.  All prior OSes obtain the UCRT via Windows Update only. This applies to all Vista → 8.1 and associated Server SKUs.
For Windows 7, 8, and 8.1 the Windows Universal Runtime must be installed via KB2999226. However it has a prerequisite update KB2919355 which contains updates that facilitate installing the KB2999226 package.

*Why does KB2999226 not always install when the runtime is installed from the redistributable?  What could prevent KB2999226 from installing as part of the runtime?
The UCRT MSU included in the VCRedist is installed by making a call into the Windows Update service and the KB can fail to install based upon Windows Update service activity/state:

*

*If the machine has not updated to the required servicing baseline, the UCRT MSU will be viewed as being "Not Applicable".
Ensure KB2919355 is installed. Also, there were known issues with KB2919355  so before this the following hotfix should be installed: KB2939087, KB2975061.

*If the Windows Update service is installing other updates when the VCRedist installs, you can either see long delays or errors indicating the machine is busy.
This one can be resolved by waiting and trying again later (which may be why installing via Windows Update UI at a later time succeeds).

*If the Windows Update service is in a non-ready state, you can see errors reflecting that.
We recently investigated a failure with an error code indicating the WUSA service was shutting down.

*To identify if the prerequisite KB2919355 is installed there are 2 options:
Registry key:
64bit hive
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\Packages\Package_for_KB2919355~31bf3856ad364e35~amd64~~6.3.1.14
CurrentState = 112

32bit hive
HKLM\SOFTWARE\[WOW6432Node\]Microsoft\Windows\CurrentVersion\Component Based Servicing\Packages\Package_for_KB2919355~31bf3856ad364e35~x86~~6.3.1.14
CurrentState = 112

Or check the file version of:
C:\Windows\SysWOW64\wuaueng.dll
C:\Windows\System32\wuaueng.dll

7.9.9600.17031  or later.


text:
Q: php like concat get userid with username I am creating PHP user details display script I have added userid to Like Conact method but i want to add userid and username to it's two parameters
Here is my code
if(isset($_GET["user_id"]))
{
$uid = $_GET["user_id"];
}
if ($stmt = $con->prepare("SELECT p.*, c.cat_title,u.username,u.profile_pic,u.
content_details,u.web_link,u.fb_page,
u.github,u.twit_link,title,desc1,time,img,
views,id FROM products AS p
JOIN users AS u ON u.user_id= p.user_id
JOIN category AS c ON c.cat_id = p.cat_id
WHERE u.user_id LIKE CONCAT('%',?,'%')  ")){
$stmt->bind_param("s", $uid);
$stmt->execute();
}

A: WHERE u.user_id LIKE CONCAT('%',?,?,'%')")){
$stmt->bind_param("ss", $uid, $username);

Is this what you were asking for? Based on your question this would do it. If you're trying to do LIKE by either or then you'll have to use OR and do another LIKE comparison.


text:
Q: How to initialize 'attr_accessor' attribute values?
Possible Duplicate:
attr_accessor default values

I am using Ruby on Rails 3.0.9 and I would like to initialize some attr_accessor attribute values in my class\model that inherits from ActiveRecord::Base. That is,
... in my module I have:
class User < ActiveRecord::Base
  attr_accessor :attribute_name1,
                :attribute_name2,
                :attribute_name3,
                ...
end

and I would like to set to true all attr_accessor attribute values. How can I do that?
P.S.: Of course I would like to solve the above issue approaching "à la Ruby on Rails Way". I know about the after_initialize callback but by using that method I should repeat each attribute_name<N> statement for which I would like to set the value to true inside that after_initialize statement (... and this is not DRY - Don't Repeat Yourself). Maybe there is a better way to achieve this. Is there a way to set attr_accessor attribute values "on the fly" when you state those attributes? That is, I expect to declare and set attr_accessor attributes at once!

A: For Rails 3.2 or earlier, you could use attr_accessor_with_default:
class User < ActiveRecord::Base
  attr_accessor_with_default :attribute_name1, true
  attr_accessor_with_default :attribute_name2, true
  attr_accessor_with_default :attribute_name3, true
  ...
end

Since your default value is an immutable type (boolean), this form of the method is safe to use here.  But don't use it if the default value is a mutable object, including an array or  string, because all of your new model objects will share the exact same instance, which is probably not what you want.
Instead, attr_accessor_with_default will accept a block, where you can return a new instance each time:
attr_accessor_with_default(:attribute_name) { FizzBuzz.new }

A: I would just define a getter that lazily loads the value you are interested in, and use attr_writer to define the setter. For instance,
class Cat
  attr_writer :amount_of_feet
  def amount_of_feet; @amount_of_feet ||= 4; end # usually true
end

Which, if you really mean it, can be rewritten with some meta-programming:
class Cat
  # The below method could be defined in Module directly
  def self.defaulted_attributes(attributes)
    attributes.each do |attr, default|
      attr_writer attr

      define_method(attr) do
        instance_variable_get("@#{attr}") ||
          instance_variable_set("@#{attr}", default)
      end
    end
  end

  defaulted_attributes :amount_of_feet => 4
end

calin = Cat.new
print "calin had #{calin.amount_of_feet} feet... "
calin.amount_of_feet -= 1
puts "but I cut one of them, he now has #{calin.amount_of_feet}"

This works because, usually, computing the default value won't have any side effect making the order matter and it won't be needed to compute the value until you first try to access it.
(Câlin is my cat; he's doing well, and still has the four of his feet)

A: Brutal solution
class User < ActiveRecord::Base
  @@attr_accessible = [:attribute_name1, :attribute_name2, :attribute_name3]
  attr_accessor *@@attr_accessible
  after_initialize :set_them_all
  def set_them_all
    @@attr_accessible.each do |a|
      instance_variable_set "@#{a}", true
    end
  end
end

or little more conceptual: Ruby: attr_accessor generated methods - how to iterate them (in to_s - custom format)?

A: Did you try:
class User < ActiveRecord::Base
  attr_accessor :attribute_name1,
                :attribute_name2,
                :attribute_name3,
                ...

  after_initialize :set_attr

  def set_attr
    @attribute_name1 = true
    ...
  end
end


text:
Q: Need help pivot columns to rows SQL Server with count This is what I am trying to achieve in SQL Server but no luck.
I have table as below
ID  Start Dt    End Dt  Count
1   3/1/2016    6/1/2016    3

This is what I need, If Count column is 3 then I need to generate three rows
ID  Start Dt    End Dt  Count
1   3/1/2016    4/1/2016    1
1   4/1/2016    5/1/2016    1
1   5/1/2016    6/1/2016    1

Appreciate your help..

A: I use a UDF to create dynamic date ranges (see below).  I added another row in the sample data to illustrate the many-to-many.
Declare @Table table (ID int,StartDt Date,EndDate Date,Count int)
Insert into @Table values
(1,'2016-03-01','2016-06-01',3),
(2,'2016-02-01','2016-07-01',22)

Declare @MinDate Date,@MaxDate Date
Select @MinDate=min(StartDt),@MaxDate=max(EndDate) from @Table

Select ID,DateR1,DateR2,Count=cast((Count+0.0)/DateDiff(MM,StartDt,EndDate) as money)
  From @Table A
  Join (Select DateR1=RetVal,DateR2=DateAdd(MM,1,RetVal)  From [dbo].[udf-Create-Range-Date](@MinDate,@MaxDate,'MM',1)) B
    on DateR1 Between StartDt and EndDate and DateR1<EndDate

Returns
ID  DateR1      DateR2      Count
1   2016-03-01  2016-04-01  1.00
1   2016-04-01  2016-05-01  1.00
1   2016-05-01  2016-06-01  1.00
2   2016-02-01  2016-03-01  4.40
2   2016-03-01  2016-04-01  4.40
2   2016-04-01  2016-05-01  4.40
2   2016-05-01  2016-06-01  4.40
2   2016-06-01  2016-07-01  4.40

The UDF
CREATE FUNCTION [dbo].[udf-Create-Range-Date] (@DateFrom datetime,@DateTo datetime,@DatePart varchar(10),@Incr int)

Returns
@ReturnVal Table (RetVal datetime)

As
Begin
    With DateTable As (
        Select DateFrom = @DateFrom
        Union All
        Select Case @DatePart
               When 'YY' then DateAdd(YY, @Incr, df.dateFrom)
               When 'QQ' then DateAdd(QQ, @Incr, df.dateFrom)
               When 'MM' then DateAdd(MM, @Incr, df.dateFrom)
               When 'WK' then DateAdd(WK, @Incr, df.dateFrom)
               When 'DD' then DateAdd(DD, @Incr, df.dateFrom)
               When 'HH' then DateAdd(HH, @Incr, df.dateFrom)
               When 'MI' then DateAdd(MI, @Incr, df.dateFrom)
               When 'SS' then DateAdd(SS, @Incr, df.dateFrom)
               End
        From DateTable DF
        Where DF.DateFrom < @DateTo
    )

    Insert into @ReturnVal(RetVal) Select DateFrom From DateTable option (maxrecursion 32767)

    Return
End

-- Syntax Select * from [dbo].[udf-Create-Range-Date]('2016-10-01','2020-10-01','YY',1)
-- Syntax Select * from [dbo].[udf-Create-Range-Date]('2016-10-01','2020-10-01','DD',1)
-- Syntax Select * from [dbo].[udf-Create-Range-Date]('2016-10-01','2016-10-31','MI',15)
-- Syntax Select * from [dbo].[udf-Create-Range-Date]('2016-10-01','2016-10-02','SS',1)

A: This is another method and it works.
declare @temp_table table (
        id int,
        start_date date,
        end_date date,
        count_no int
    )

    insert into @temp_table values (1,'3/1/2016','6/1/2016',3)

    select * from @temp_table

Above query will return your original results. And below query will return your expected results.
;with temp(count) as (
    select 1
    union all
    select count + 1
    from temp
    where count < (select count_no from @temp_table)
)
select tt.id,
    convert(char, dateadd(month,count -1 , tt.start_date), 101) as start_date,
    convert(char, dateadd(month,count,tt.start_date ) , 101) as end_date,
    count(*) as count

from temp as t cross join @temp_table as tt
group by tt.id,tt.start_date,t.count

HTH


text:
Q: Optimal way to chain reverse foreign key lookups in Django We have a DB model that looks something like this, where each arrow represents a many to one relationship in the direction of the arrow:
A --> B --> C --> D < -- E
For most models, we have a property called D. For C, that method returns D. For B, that method calls C.D() and so on. These we can use for FK lookup.
The problem arises for reverse lookups, since these chained properties are unavailable when generating SQL statements, meaning we would have to load the entire QuerySet into memory to filter on those properties. Ideally, we could do something like A.objects.filter(D=someD).
What we instead do is lookup based on relations and chain a bunch of joins. The syntax is nice for one join, but it quickly becomes hard to maintain.
If we want to get all A objects related (indirectly) to D, we have to doA.objects.filter(B__C__D=someD). Having to write code like this in multiple places is obviously not ideal.
We have looked into F annotations and a custom manager for each model without much luck.
TLDR: What's the optimal way to chain reverse lookups?
Thanks in advance!


text:
Q: Need help improving a Ruby DSL for controlling an Arduino controlled drink dispenser (bar monkey) I'm writing a DSL in Ruby to control an Arduino project I'm working on; Bardino.  It's a bar monkey that will be software controlled to serve drinks.  The Arduino takes commands via the serial port to tell the Arduino what pumps to turn on and for how long.
It currently reads a recipe (see below) and prints it back out.  The code for serial communications still need to be worked in as well as some other ideas that I have mentioned below.
This is my first DSL and I'm working off of a previous example so it's very rough around the edges.  Any critiques, code improvements (are there any good references for Ruby DSL best practices or idioms?) or any general comments.
I currently have a rough draft of the DSL so a drink recipe looks like the following (Github link):
desc "Simple glass of water"
recipe "water" do
  ingredients(
  "Water" => 2.ounces
  )
end

This in turn is interpreted and currently results with the following (Github link):
[mwilliams@Danzig barduino-tender]$ ruby barduino-tender.rb examples/water.rb
Preparing: Simple glass of water

Ingredients:
 Water: 2 ounces

This is a good start for the DSL, however, I do think it could be implemented a little bit better.  Some ideas I had below:

*

*Defining what "ingredients" are available using the name of the ingredient and the number pump that it's connected to.  Maybe using a hash?  ingredients = {"water" => 1, "vodka" => 2}.  This way, when an ingredient is interpreted it can either a) send the pump number over the serial port followed by the number of ounces for the Arduino to dispense b) tell the user that ingredient does not exist and abort so nothing is dispensed c) easily have the capability to change or add new ingredients if they're changed.

*Making the recipe look less code like, which is the main purpose of a DSL, maybe build a recipe builder?  Using the available ingredients to prompt the user for a drink name, ingredients involved and how much?

The Github project is here, feel free to fork and make pull requests, or post your code suggestions and examples here for other users to see.  And if you're at all curious, the Arduino code, using the Ruby Arduino Development framework is here.
Update
I modified and cleaned things up a bit to reflect Orion Edwards suggestion for a recipe.  It now looks like the following.
description 'Screwdriver' do
  serve_in 'Highball Glass'
  ingredients do
    2.ounces :vodka
    5.ounces :orange_juice
  end
end

I also added a hash (key being the ingredient and the value the pump number it's hooked up to).  I think this provided much progress.  I'll leave the question open for any further suggestions for now, but will ultimately select Orion's answer.  The updated DSL code is here.

A: Without looking into implementation details (or your github links), I'd try write a DSL like this:
(stealing from here: http://supercocktails.com/1310/Long-Island-Iced-Tea-)
describe "Long Island Iced Tea" do
  serve_in 'Highball Glass'

  ingredients do
    half.ounce.of :vodka
    half.ounce.of :tequila
    half.ounce.of :light_rum
    half.ounce.of :gin
    1.dash.of :coca_cola
    #ignoring lemon peel as how can a robot peel a lemon?
  end

  steps do
    add :vodka, :tequila, :light_rum, :gin
    stir :gently
    add :coca_cola
  end
end

Hope that helps!

A: If you want the recipe to look more natural, why not (from the same recipe Orion Ewards used, thanks!):
Recipe for Long Island Iced Tea #1
Ingredients:
  1/2 oz Vodka
  1/2 oz Tequila
  1/2 oz Light Rum
  1/2 oz Gin
  1 Dash Coca-Cola
  # ignored Twist of Lemon Peel (or Lime)

Then add Treetop to the mix. You could have rules such as:
grammar Cocktail
  rule cocktail
    title ingredients
  end

  rule title
    'Recipe for' S text:(.*) EOF
  end

  rule ingredients
    ingredient+
  end

  rule ingredient
    qty S liquid
  end
# ...
end

Which the treetop compiler will transform into a nice ruby module. Then:
parser = CocktailParser.new
r = parser.parse(recipe)

A: Orion's DSL looks very nice.
The only change  I'd possibly suggest from you "updated" code is

*

*Replace description  with recipe. It is a more descriptive term

*Since the set of ingredients and actions is fixed, bind the ingredients to variables rather than symbols i.e you have vodka = :vodka defined someplace. Its is easier to say
mix vodka, gin and triple_sec # instead of using :vodka, :gin and :triple_sec.
anyways that's a minor nit.


text:
Q: IE11 throwing "SCRIPT1014: invalid character" where all other browsers work Here's a new one, IE11 is throwing errors on code that works in every other browser.
Anyway, after a few hours of "fixing" code so that IE11 doesn't fall on its own face I have come across an error I just cannot seem to find a solution to. Here is the code in question:
$('input[name="messageAccount"]').change(function () {
    $aButton.show();
    var addedIds = $("#hdnfield").val();
    if (addedIds == null || addedIds === "") {
        $("#hdnfield").val(this.value);
    } else {
        $("#hdnfield").val(`${addedIds}${this.value}`);
    };
});

This is nested on the inside of the success call in an Ajax request. IE's debugger is saying the error is coming from the content of the else statement but it's also reading all the brackets wrong. For example the opening parenthesis on this function is being "closed" after the closing bracket for the Ajax request... (hopefully that made sense).
Has anyone else had a similar issue with IE before? I've got a number of other bugs to fix so if there are any replies I will post back as soon as I can. Thanks in advance.
EDIT: just for reference I am currently running this locally and is part of what will become an internally hosted web app.

A: It's because "`" (template strings) is not supported by IE : http://caniuse.com/#search=string
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
See https://stackoverflow.com/a/27678299/2195875
To avoid this error you can either use a ES6 to ES5 transpiler, or just directly write valid ES5 javascript:
instead of

`string text ${expression} string text`

write

"string text "+expression+" string text"

A: You can also add polyfill to your html:

<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.26.0/polyfill.min.js"/>


text:
Q: Java registration simple checker I have a simple password and text area checker for a registration page. Here all the text area MUST be filled, otherwise a popup JOptionPane. AND the password and the re-entered password (confirm password) should be equal otherwise warning.
I don't know how to do this.
Code:
    private boolean check()  {
    boolean isEmpty=false;

    if(nickNametxt.getText().equals("") || pwdTxt.getText().equals("") ||
      logintxt.getText().equals("") || rePwdTxt.getText().equals("")){
        JOptionPane.showMessageDialog(null, "Please fill all the fields before proceeding");
    if (pwdTxt != rePwdTxt){
        JOptionPane.showMessageDialog(null, "Wrong Password");
    }
    isEmpty = true ;
    }

    return isEmpty ;
}

A: Try with the following code snippet. The second if condition has been modified from != to .equals as != will verify object reference.
private boolean check(){
    boolean isEmpty = false;
    String nickName = nickNametxt.getText();
    String login    = logintxt.getText();
    String pwd      = pwdTxt.getText();
    String rePwd    = nickNametxt.getText();

    isEmpty = true;
    if(!((null != nickName && !nickName.isEmpty()) && (null != login && !login.isEmpty())
            && (null != pwd && !pwd.isEmpty()) && (null != rePwd && !rePwd.isEmpty()))){
        JOptionPane.showMessageDialog(null, "Please fill all the fields before proceeding");
        isEmpty = true;
    }else if(!pwd.equals(rePwd)){
        JOptionPane.showMessageDialog(null, "Wrong Password");
        //Depending on your usecase - place it here or not
        //isEmpty = true;
    }
    return isEmpty;
}


text:
Q: Calculation differences I have something like this in c#
        byte a;
        byte b;
        byte c;

        c = a + b;

and it gives an error for c = a + b and says "Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?). I don't understand why because everything is in bytes
Matlab is involved because I am translating an image processing program from matlab into c# where i take values from a picture which are uint8 and doing calculations with that value when it does it the unit8 takes over and during any calculations any number higher than 255 is set to 255. So in c# I just made all of my variables bytes since they are all under 255 anyways but just like in the example code when running the calculations the error pops up.

A: The arithmetic expression on the right-hand side of the assignment operator evaluates to int by default.
See byte - MSDN

The following assignment statement will produce a compilation error,
  because the arithmetic expression on the right-hand side of the
  assignment operator evaluates to int by default.

byte x = 10, y = 20;
byte z = x + y;   // Error: conversion from int to byte

By adding an explicit cast the error will go like:
byte z = (byte)(x + y);

A:
During any calculations any number higher than 255 is set to 255.

This is not supported natively in C#. Instead, the default behaviour of the (byte) cast is to take the least significant byte, giving an arithmetic result equivalent to modulo 256.
c = unchecked((byte)(200 + 200));

The result above will be 144, which is equivalent to 400 % 256.
If you want to clip results at 255, you need to specify this explicitly:
c = (byte)Math.Min(a + b, 255);


text:
Q: Angular 7 testing: "Can't bind to formGroup since it isn't a known property of form" The console logs error:

15 02 2019 14:50:24.868:INFO [Chrome 72.0.3626 (Windows 10.0.0)]:
  Connected on socket BiEioS9fHwq-QLg3AAAA with id 27946068 Chrome
  72.0.3626 (Windows 10.0.0) LoginComponent should create FAILED
          Can't bind to 'formGroup' since it isn't a known property of 'form'. ("
        <div class="row">

(etc)

I'm running it using command ng test. My spec file:
describe('LoginComponent', () => {

    let component: LoginComponent;
    let fixture: ComponentFixture<LoginComponent>;

    const fakeActivatedRoute = {
        snapshot: { data: {} }
    } as ActivatedRoute;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [
                LoginComponent
            ],
            imports: [
                RouterTestingModule,
                HttpClientModule,
                CommonModule,
                BrowserModule,
                BrowserAnimationsModule,
                ReactiveFormsModule,
                MessageModule,
                MatFormFieldModule,
                MatInputModule,
                MatButtonModule,
                MatCheckboxModule,
                MatProgressSpinnerModule,
                MatRadioModule,
                MatSliderModule,
                NgbModule
            ],
            providers: [
                {
                    provide: ActivatedRoute,
                    useValue: fakeActivatedRoute
                }
            ]
        })
            .compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(LoginComponent);
        component = fixture.debugElement.componentInstance;
        fixture.detectChanges();
    });

    it('should create', () => {
        expect(component).toBeTruthy();
    });

});

And the LoginModule file:
@NgModule({
  declarations: [LoginComponent],
  imports: [
    CommonModule,
    BrowserModule,
    BrowserAnimationsModule,
    FormsModule,
    ReactiveFormsModule,
    MatFormFieldModule,
    MatInputModule,
    MatButtonModule,
    MatCheckboxModule,
    MatProgressSpinnerModule,
    MatRadioModule,
    MatSliderModule,
    MessageModule,
    NgbModule.forRoot()
  ],
  providers: [],
  bootstrap: [
    LoginComponent,
    MessageComponent
  ]
})
export class LoginModule {}

What's missing?

A: It depends on which type of form you are using in your project. Angular provides Template-driven forms and Reactive forms. If you are using Reactive forms then, You need to import ReactiveFormsModule in your componentName.spec.ts file as
import { ReactiveFormsModule } from '@angular/forms';
beforeEach(async(() => {
TestBed.configureTestingModule({
  declarations: [ ContactUsFormComponent ],
  imports: [ReactiveFormsModule]
})
.compileComponents();}));

Otherwise, if you are using Template driven forms then, you need to import FormsModule.

A: Similar to Angular2 : Can't bind to 'formGroup' since it isn't a known property of 'form'
I think you are missing to import FormsModule in your configureTestingModule

A: I think that it´s the
FormsModule

and the
.forRoot()

in the NgbModule in your testing imports.

A: I had the same problem, solved it by importing ReactiveFormModule in configureTestingModule and removed the word 'export' from my testing host component.
like:
@Component({
    template: '<form [formGroup]="myTestForm"><input formControlName="test"></form>'
})
export class HostComponent {...}

to

@Component({
    template: '<form [formGroup]="myTestForm"><input formControlName="test"></form>'
})
class HostComponent {...}


text:
Q: HttpClient behaviour for persistent/continuous connections I'm trying to use the CouchDB change notifications API in continuous mode, so I want send this
_changes?feed=continuous?include_docs=true to my CouchDb server as a GET request. Easy so far, but to get HttpClient to send it I have to do this :-
_changesClient.openUrl('GET', uri)
      .then((HttpClientRequest request) {

        return request.close();
      })

This closes the connection which I don't want, I want to send the request and then just sit listening for incoming data i.e the changes that CouchDB is emitting. I can't seem to fathom this, it seems that HttpClient is geared towards a single shot send/receive model or I'v missed something.

A: OK resolved, see the bug link above for the outcome


text:
Q: SQL using table from join in subqueries I am writing a query to be used as databases view, it looks now like this:
SELECT
  contact.*,
  contact_users.names AS user_names,
  contact_status.status_id AS status_id,
  status_translation.name AS status_name,
  status_translation.lang_id AS lang_id
FROM contacts as contact
LEFT JOIN contact_status AS contact_status ON contact_status.status_id = contact.status
LEFT JOIN contact_status_translation AS status_translation ON status_translation.id = contact.status
LEFT JOIN (
    SELECT
    contacts_users.contact_id,
      string_agg(users.fullname || ', ' || users.id, ' | ') as names
  FROM v_contacts_users as contacts_users
  LEFT JOIN v_users as users on users.id = contacts_users.user_id
  WHERE users.lang_id = status_translation.lang_id
    GROUP BY contacts_users.contact_id
) AS contact_users ON contact_users.contact_id = contact.id
WHERE contact.deleted = FALSE

Everything works as expected except the WHERE condition in the last LEFT JOIN - the WHERE users.lang_id = status_translation.lang_id part says that status_translation cannot be referenced in this part of the query? Why is that? I tried to reference this table with various always but the result is still the same.Thing is that v_users is translated as well so I need to have only one result from this table.

A: Insert LATERAL between LEFT JOIN and the opening parenthesis if you want to reference previous FROM list entries.


text:
Q: How do I properly connect to a mysql database? Here is my code:
<?php
    require_once('config.php');
    $link = mysqli_connect($db_host, $db_user, $db_pass, $db_name) or die ('Your DB connection is misconfigured. Enter the correct values and try again.');
?>

I have stored my host, username, password and database name in the separate file config.php. I know that the information is correct because I can connect to my database via putty, but I keep getting the error:

Warning: mysqli_connect(): (HY000/1045): Access denied for user
  'blank'@'T9AF3.WPA.blank.Ca' (using password: YES) in
  C:\xampp\htdocs\temp2\index.php on line 3 Your DB connection is
  misconfigured. Enter the correct values and try again.

Note: 'blank' is there to protect my identity and is not a typing error.
Edit: I only used putty to test that my login information was correct. Putty has very little to do with my actual question.
Edit2:
<?php
    $db_host = 'host';
    $db_user = 'user';
    $db_pass = 'pass';
    $db_name = 'dbname';
?>

These are filers.

A: if you can login from putty, by that i think you mean localhost, and you can't from php file, which is i think trying to connect remotely, the problem most probably lies on your user not defined for your servers ip. your server, which you are trying to connect from is 'T9AF3.WPA.blank.Ca'
in mysql a username has a password and a location and mysql uses both to authenticate the user. you can have permission to connect locally but not remotely i.e. from another server. check with your system admin to make sure you have proper access defined from 'T9AF3.WPA.blank.Ca'.
Or you have not specified an IP Address for the server to listen to. It may only be listening on localhost of your server, instead of allowing remote connections. Check your mysql configuration and which IP address it is listening on.

A: Your mysql user must have proper rights on the database you are using