text:
Q: What's the purpose of including java.lang.Object in an interface's Constant Pool? Compiling the following interface:
package test;

public interface MyInterface {
    public void foo();
}

and checking the compiled code using javap -v -s test.MyInterface shows the following (-s prints member signatures):
  Compiled from "MyInterface.java"
public interface test.MyInterface
  SourceFile: "MyInterface.java"
  minor version: 0
  major version: 51
  flags: ACC_PUBLIC, ACC_INTERFACE, ACC_ABSTRACT
Constant pool:
  #1 = Class              #7              //  test/MyInterface
  #2 = Class              #8              //  java/lang/Object
  #3 = Utf8               foo
  #4 = Utf8               ()V
  #5 = Utf8               SourceFile
  #6 = Utf8               MyInterface.java
  #7 = Utf8               test/MyInterface
  #8 = Utf8               java/lang/Object
{
  public abstract void foo();
    Signature: ()V
    flags: ACC_PUBLIC, ACC_ABSTRACT
}

My question is: Why is there java.lang.Object in the constant pool, knowing that an interface does not inherit from the Object class?
Also if I change the interface definition to:
public interface MyInterface extends Comparable<MyInterface> {
    public void foo();
}

and run javap, I get the following:
  Compiled from "MyInterface.java"
public interface test.MyInterface extends java.lang.Comparable<test.MyInterface>
  Signature: #7             // Ljava/lang/Object;Ljava/lang/Comparable<Ltest/MyInterface;>;
  SourceFile: "MyInterface.java"
  minor version: 0
  major version: 51
  flags: ACC_PUBLIC, ACC_INTERFACE, ACC_ABSTRACT
  ...

What exactly is the purpose of including java.lang.Object in the signature Ljava/lang/Object;Ljava/lang/Comparable<Ltest/MyInterface;>; of the interface?
Also, if I try to view the bytecode using a tool (specifically JBE), it incorrectly shows that MyInterface has java.lang.Object as superclass with the class name java.lang.Object saved in the constant pool:

Note: Using jdk1.7.0_75

A: That Object class reference in the Constant Pool is the result of how the class file format has been defined in the Java VM Specification.
A class file consists of a single ClassFile structure:
ClassFile {
    u4             magic;  // The Famous 0xCAFEBABE
    u2             minor_version;
    u2             major_version;
    u2             constant_pool_count;
    cp_info        constant_pool[constant_pool_count-1];
    u2             access_flags;
    u2             this_class;
    u2             super_class;
    ...
}

Regarding that super_class, this section of the JVM Specification is relevant for your MyInterface interface:

super_class
For an interface, the value of the super_class item must always be a
  valid index into the constant_pool table. The constant_pool entry at
  that index must be a CONSTANT_Class_info structure representing the
  class Object.

So essentially, that java/lang/Object constant is needed only to fill the super_class item with a valid value.
All Java instances are always instance of the basic Object class but this time the real answer has more to do with how the JVM was built and with specific implementation choices rather than with the language itself.
Also, as noted by @Holger, this paragraph is also worth mentioning:

If the value of the super_class item is zero, then this class file
  must represent the class Object, the only class or interface without a
  direct superclass.

A: Actually all in Java is Object. In Java each construction is object.
Class IS Object
Interface IS Object
Enum IS Object.

So when you build program Object packed automatically. Because *.class may be used on another JVM.
@user43250937 correctly in this case too.
JVM Spec :

Compiled code to be executed by the Java Virtual Machine is represented using a hardware- and operating system-independent binary format, typically (but not necessarily) stored in a file, known as the class file format. The class file format precisely defines the representation of a class or interface, including details such as byte ordering that might be taken for granted in a platform-specific object file format

May be this link granted to your more informations.
Java-bytecode-fundamentals-using-objects-and-calling-methods
Look at
4:  invokeinterface #5,  1; //InterfaceMethod Job.execute:()Ljava/lang/Object;

JVM Specification


text:
Q: Перемещение маркеров по карте в Yandex.Mapkit API Можно ли переместить маркер с одного места на другое на карте в приложении под Android, и если можно, то как это реализовать?

A: Можно. Для этого нужно будет изменить координаты метки через PlacemarkMapObject.setGeometry()
Если речь о перемещении метки вручную (драгом) для этого она должна иметь соответствующую опцию: isDraggable = true
Наглядно вариант перетаскивания можно посмотреть в примере родственной МапКиту JS API Яндекса.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Разделить большой файл txt на python Значит есть задача, разделить один файл на несколько, что казалось бы легко, накидал я значит г**но код, все работает, но возникла проблема, при работе с файлами больше 10гб программа отказывается работать, запускается, повисает и закрывается. Может кто знает как разделить такие файлы? Все способы, что есть в интернете уже перепробовал.
import os
import threading
import time
import math

files = os.listdir()

s = 0
for x in files:
    if x == 'split':
        s = s + 1

if s != 1:
    os.mkdir('split')

def splitter(i, file_count, line_in_file_count, line_count):
    count = 0
    res = []
    res.append('')
    inp = open(i, 'r', encoding='ANSI')
    file_meter = 1
    line_meter = 1
    for file_meter in range(file_count):
        out_name = 'split/' + str(file_meter) + '.txt'
        out = open(out_name, 'w', encoding='ANSI').close()
        out = open(out_name, 'w', encoding='ANSI')
        for line_meter in range(line_in_file_count):
            if count <= line_count:
                for line in inp:
                    res[0] = line
                    count = count + 1
                    break
                if count <= line_count:
                    out.write(str(res[0]))
        out.close()

    inp.close()

for i in files:
    line_in_file_count = 0
    txt = i.endswith('.txt')
    if txt == True:

        line_count = sum(1 for line in open(i, 'r'))
        oper_id = int(input('В файле {} строк\nДля разбития на количество файлов введите 0, для разбития по количеству строк в файле введите 1: '.format(line_count)))
        start = time.time()
        if oper_id == 0:
            file_count = int(input('Введите количество файлов: '))
            line_in_file_count = math.ceil(line_count/int(file_count))
            print(line_in_file_count)
            splitter(i, file_count, line_in_file_count, line_count)

        if oper_id == 1:
            line_in_file_count = input('Введите количество строк в файле: ')
            file_count = line_in_file_count =math.ceil(line_count/int(line_in_file_count))
            print(file_count)
            splitter(i, file_count, line_in_file_count, line_count)

end = time.time()
print('DONE!\nWorking time:{}s\nThe program will automatically close after 5 seconds!'.format(round(end - start)))
time.sleep(5)


text:
Q: How to use R to plot a pie plot with different radius? For example,

pie(1:3)

But the radius is constant.
How to make the pie plot which the radius is 1,2,3 respectively?

A: Check radial.pie function in plotrix package
install.packages("plotrix")
library(plotrix)
radial.pie(c(1,2,3), labels=c("One", "Two", "Three"), radlab=TRUE)

would produce following figure


text:
Q: MySQL - Update table with min date from another table I have a table (table1) containing a user ID and transaction dates (stt_stid, stt_date) as well as some other non-relevant info.
I have another table (table2) with a couple hundred records that I need to get the min(stt_date) for based on table1.stt_stid = table2.stid.
table1 is 5M + rows and I'm having trouble writing an efficient join without getting an error.
I've tried something along the lines of:
UPDATE table2 JOIN (
    SELECT stt_stid,
           MIN(stt_date) AS mindate
      FROM table1
     WHERE stt_amt > 0
       AND stt_prid = 1
     GROUP BY stt_stid) temp
    ON table2.stid = table1.stt_stid
 SET table2.firstdate = temp.mindate

A: If that inline view query is supposed to be referencing table1, make sure you have an index defined
ON table1 (stt_stid, stt_date)

That will allow MySQL to make use of an index to satisfy the query. If MySQL can't use an index to satisfy the GROUP BY and get the minimum value, then that's going to require a "Using filesort" operation, on all the rows in table1, and that's expensive for large sets. (MySQL can make use of a suitable index to avoid that operation.)
The result from that inline view query is going to materialized as a "derived table", and then the outer query will run. Before MySQL 5.6, there won't be any index on the "derived table".
(I'm assuming that nearly every stid value in table1 also appears in table2, that is, that table2 doesn't contain a very small subset of stid values... if that's not the case, the moving a JOIN into the derived table may significantly reduce the size of the derived table.)


text:
Q: How to create files on host using Docker and a text editor for local development (permissions problem) I have run a docker container for local development (mysql container and prestashop container as described in docker hub). Also mounted volumes to both containers.
But when editing files in my computer with for example sublime text, I cannot create any file because in docker files owner is www-data:www-data.
Tried chown volume files to my user:group but of course, it breaks the site...
Also followed theses steps for linux and docker https://docs.docker.com/install/linux/linux-postinstall/ (to Manage Docker as a non-root user)
$ docker network create prestashop-net
$ docker run -ti --name mysql57 --network prestashop-net -e MYSQL_ROOT_PASSWORD=admin -p 3307:3306 -v /home/nicolas/docker/db-persist/mysql5.7:/var/lib/mysql --user $(id -u):$(id -g) -d mysql:5.7
$ docker run -ti --name ps1751 --network prestashop-net -e DB_SERVER=mysql57 -p 8080:80  -v /home/nicolas/Dropbox/proyectosWeb/docker/ps1751:/var/www/html --user $(id -u):$(id -g) -d prestashop/prestashop

What step am I missing here to be able to edit/create/delete files from sublime text (files that are inside container)?
I want to be able to add/delete/edit files from my host and sublime text editor without permission problems.
Thanks!

A: Ok finally after testing several docker images, this one worked ok https://aboullaite.me/dockerizing-your-lamp-enviroment/.
I think for some reason (sorry new to docker), the prestashop image is a minimal setup and it's not mapping UID nor GID from the host to the container... so it's impossible to modify any file from the host without sudo it.
This line in the Dockerfile did the trick "RUN usermod -u 1000 www-data" but of course, my user (in my computer) is GID = 1000 and group of the user that runs inside container is www-data (user is also www-data, because it is an apache server) and it works because of that. If my user had a different GID and group inside container was different, it would need some changes.
But for an apache enviroment that was what I was looking for, it works perfect, and now I can create/delete and modify files inside container from my computer in my sublime editor withour permission problems.


text:
Q: AKS- Unable to compile 16 bit integer for primality check I am trying to perform primality check on a 16 bit long number by using the AKS algorithm. I keep getting an error. Can someone please compile my codes and help me about where i am making a mistake. (number example which i want to compile: 1425412525412545.)
This is my AKSPrime class:
import java.math.BigInteger;

public class AKSPrime
{
public static void main(String[] args)
{
    AKSPrime p = new AKSPrime();

    TextReader k = new TextReader();

    System.out.print("Input number for primality testing: ");

    int i = k.readInt();

    System.out.println("Is " + i + " prime? " + p.isPrime(i));
}
public boolean isPrime(int numberToTest)
{
    boolean prime = true;
    boolean flag = true;
    boolean suitableQFound = false;
    boolean polynomialsCongruent = true;
    int b, q;
    int suitableQ;
    double power;

    for(int a = 2; a <= Math.sqrt(numberToTest); a++)
    {
        b = 2;
        power = Math.pow(a, b);

        while(!(power > numberToTest))
        {
            power = Math.pow(a, b);

            if(power == numberToTest)
            {
                prime = false;
                break;
            }

            b++;
        }
    }

    // Algorithm Line 2
    int r = 2;

    // Algorithm Line 3
    while( r < numberToTest && flag && !suitableQFound)
    {
        //Algorithm Line 4
        if(GCD(numberToTest, r) != 1)
        {
            return false;
        }

        //Algorithm Line 5
        if(nonAKSisPrime(r))
        {
            // Algorithm Line 6
            q = largestPrimeFactor(r - 1);
            double sqrtR = Math.sqrt(r);
            double logN = Math.log(numberToTest)/Math.log(2);

            // Algorithm Line 7
            if( q >= 4*Math.sqrt(r)*Math.log(numberToTest)/Math.log(2) )
            {
                // Algorithm Line 8
                suitableQ = q;
                suitableQFound = true;
            }
        }

        // Algorithm Line 9
        if(!suitableQFound)
            r++;
    }

    for(int a = 1; a <= 2 * Math.sqrt(r) * Math.log(numberToTest)/Math.log(2); a++)
    {

        PolynomialArray poly1 = new PolynomialArray();
        poly1.binomialExpansionViaSquaring(-1 * a, numberToTest);

        int [] coeffs2 = {1, numberToTest, -1 * a, 0};
        PolynomialArray poly2 = new PolynomialArray(coeffs2);

        poly1.subtract(poly2);

        polynomialsCongruent = poly1.specialMod(r, numberToTest);

        if(!polynomialsCongruent)
            prime = false;

    }

    return prime;
}

private boolean nonAKSisPrime(int x)
{
    int f = 2;
    boolean result = true;

    int s = (int)Math.sqrt(x);

    while(f <= s && result)
    {
        if(x % f == 0)
            result = false;
        f++;
    }

    return result;
}
private static int GCD(int u, int v)
{
    BigInteger bigU = new BigInteger (Integer.toString (u));
    BigInteger bigV = new BigInteger (Integer.toString (v));
    int gcd = bigU.gcd (bigV).intValue ();

    return gcd;
}

private static int largestPrimeFactor(int input)
{
    int f = 1;
    int r = 2;
    int x = input;

    while(x != 1 && r * r <= input)
    {
        while(x % r == 0)
        {
            x = x / r;
            f = r;
        }

        r++;
    }

    if(x == 1)
        return f;
    else
        return x;
}
}

This is my PolynomialArray class:
import java.math.BigInteger;

public class PolynomialArray
{
// instance variables
private BigInteger [] poly;
private int degree;
private int arraySize;
private static final int DEFAULT_SIZE = 1000000;

// constructor
public PolynomialArray()
{
    arraySize = DEFAULT_SIZE;
    poly = new BigInteger[arraySize];
    degree = 0;
}

// constructor that takes size as input
public PolynomialArray(int size)
{
    poly = new BigInteger[size];
    degree = 0;
    arraySize = size;
}

// constructor that takes data as input
public PolynomialArray(int[] data)
{
    poly = new BigInteger[DEFAULT_SIZE];

    for(int ctr = 1; ctr < data.length; ctr = ctr + 2)
    {
        if(data[ctr] > degree)
            degree = data[ctr];

        poly[data[ctr]] = new BigIntExtended(data[ctr - 1]);
    }
}

// constructor that takes size and data as inputs
public PolynomialArray(BigInteger[] data, int deg)
{
    poly = data;
    degree = deg;
}

// This method returns a String representation of the object.
public String toString()
{
    String outputString = "";

    if(degree != 0)
    {
        for(int i = 0; i <= degree; i++)
        {
            if(poly[i] != null && !poly[i].equals(BigInteger.ZERO))
            {
                outputString += "" + poly[i] + "*x^" + i + " + ";
            }
        }
    }
    else
        outputString += "0";
    return outputString;
}

// This method adds two PolynomialArrays
public void add(PolynomialArray p)
{
    if(p.getDegree() > degree)
    {
        degree = p.getDegree();
        BigInteger [] temp = new BigInteger [degree + 1];

        for(int d = 0; d <= degree; d++)
        {
            if(!this.getCoeffAtIndex(d).equals(BigIntExtended.ZERO))
            {
                if(temp[d] != null)
                    temp[d] = temp[d].add(this.getCoeffAtIndex(d));
                else
                    temp[d] = this.getCoeffAtIndex(d);
            }
        }

        for(int c = 0; c <= degree; c++)
        {
            if(!p.getCoeffAtIndex(c).equals(BigIntExtended.ZERO))
            {
                    temp[c] = p.getCoeffAtIndex(c);
            }
        }

        poly = temp;
    }

    for(int c = 0; c <= p.getDegree(); c++)
    {
        if(!p.getCoeffAtIndex(c).equals(BigIntExtended.ZERO))
        {
            this.addCoeffAtIndex(c, p.getCoeffAtIndex(c));
        }
    }

}

// This method subtracts p from this polynomial
public void subtract(PolynomialArray p)
{

    p.multiplyByConstant(-1);

    this.add(p);
}

// This method multiplies the coefficients of this polynomial
// by a constant c
public void multiplyByConstant(int c)
{
    for(int p = 0; p <= degree; p++)
    {
        if(poly[p] != null)
            poly[p] = poly[p].multiply(new BigIntExtended(c));
    }

}

// makes this Polynomial into a polynomial
// representing (x + a)^n, using an algorithm of
//  binomial expansion
public void binomialExpansion(int a, int n)
{
    poly = new BigInteger[n + 1];
    BigInteger temp = new BigIntExtended("0");
    BigInteger bigA = new BigIntExtended(a);

    for(int k = 0; k <= n; k++)
    {

        temp = factorial(n);
        temp = temp.divide(factorial(n-k).multiply(factorial(k)));

        bigA = new BigIntExtended(a);
        bigA = bigA.pow(k);

        poly[n - k] = temp.multiply( bigA);
    }

    degree = n;
}

// makes this Polynomial into a polynomial
// representing (x + a)^n, using an algorithm of
// successive squaring
public void binomialExpansionViaSquaring(int a, int n)
{
    poly = new BigInteger[n + 1];
    BigInteger[] tempPoly = new BigInteger[n + 1];
    tempPoly[0] = new BigIntExtended(a);
    tempPoly[1] = new BigIntExtended(1);
    int tempDegree = 1;

    BigInteger[] newPoly = new BigInteger[n + 1];
    newPoly[0] = new BigIntExtended(a);
    newPoly[1] = new BigIntExtended(1);
    int newDegree = 1;

    String binaryN = Integer.toBinaryString(n);

    char c;

    tempPoly = multiply(tempPoly, tempDegree, tempPoly, tempDegree);
    tempDegree *= 2;

    for(int index = 1; index < binaryN.length(); index++)
    {
        c = binaryN.charAt(index);
        if(c == '1')
        {
            tempPoly = multiply(tempPoly, tempDegree, newPoly, newDegree);
            tempDegree++;
        }

        if(index != binaryN.length() - 1)
        {
            tempPoly = multiply(tempPoly, tempDegree, tempPoly, tempDegree);
            tempDegree *= 2;
        }

    }

    poly = tempPoly;
    degree = tempDegree;
}

// This private helper method multiplies two polynomials
private BigInteger[] multiply(BigInteger[] bi1, int degree1, BigInteger[] bi2, int degree2)
{
    BigInteger [] polya = bi1;
    BigInteger [] polyb = bi2;
    int newDegree = degree1 + degree2;

    BigInteger [] polytemp = new BigInteger[newDegree + 1];

    for(int c = 0; c <= degree1; c++)
    {
        for(int d = 0; d <= degree2; d++)
        {
            if(polya[c] != null && polyb[d] != null)
            {
                BigInteger t = polya[c].multiply(polyb[d]);

                if(polytemp[c + d] != null)
                    polytemp[c + d] = polytemp[c + d].add(t);
                else
                {
                    polytemp[c + d] = new BigInteger("0");
                    polytemp[c + d] = polytemp[c + d].add(t);
                }
            }
        }
    }

    return polytemp;
}

// This method checks to see if this Polynomial
// is congruent to zero mod (x^r - 1, n)
public boolean specialMod(int r, int n)
{
    BigInteger total = new BigIntExtended("0");
    boolean mod = true;

    for(int start = 0; start < r; start++)
    {

        total = new BigIntExtended("0");

        for(int x = start; x < this.getDegree(); x = x + r)
        {
            BigInteger temp = poly[x];
            total = total.add(temp);
        }

        BigIntExtended bigN = new BigIntExtended(n);

        if(!total.mod(bigN).equals(BigIntExtended.ZERO))
            mod = false;
    }

    return mod;
}

// This method multiplies two polynomials together.
// Its runtime is O(n^2), because it has two nested
// loops that each run O(n) time.
public void multiply(PolynomialArray p)
{
    BigInteger [] poly2 = p.getPoly();
    int newDegree = this.getDegree() + p.getDegree();

    BigInteger [] polytemp = new BigInteger[newDegree + 1];

    for(int c = 0; c < poly.length; c++)
    {
        for(int d = 0; d < poly2.length; d++)
        {
            BigInteger t = poly[c].multiply(poly[d]);
            if(polytemp[c + d] != null)
                polytemp[c + d].add(t);
            else
            {
                polytemp[c + d] = new BigInteger("0");
                polytemp[c + d].add(t);
            }
        }
    }

    poly = polytemp;
    degree = newDegree;
}

// GETTERS AND SETTERS

// This method returns the array of coefficients
public BigInteger[] getPoly()
{
    return poly;
}

// This method returns the degree of the polynomial.
public int getDegree()
{
    return degree;
}

// This method returns the coefficient at the given
// power in the polynomial
public BigInteger getCoeffAtIndex(int index)
{
    if(poly[index] != null)
        return poly[index];
    else
        return BigInteger.ZERO;
}

// This method adds a to the coefficient at the given index
public void addCoeffAtIndex(int index, BigInteger a)
{
    if(poly[index] != null)
        poly[index] = poly[index].add(a);
    else
        poly[index] = a;
}

// This method computes the factorial of x, and
// returns it as a BigInteger, due to the tendency
// of factorial to exceed the capacity of ints
// extremely rapidly
public static BigInteger factorial(int x)
{
    if(x == 0)
        return new BigInteger("1");

    BigInteger result = new BigIntExtended("1");
    BigIntExtended c;

    for(int i = x; i >= 1; i--)
    {
        c = new BigIntExtended(i);
        result = result.multiply(c);
    }
    return result;
}
}

This is my BigIntExtended Class:
import java.math.BigInteger;

public class BigIntExtended extends BigInteger
{

// constructor that takes a primitive int,
// parses it to a String, and calls the
// superclass's constructor
public BigIntExtended(int n)
{
    super(new Integer(n).toString());
}

// constructor that takes a String
public BigIntExtended(String s)
{
    super(s);
}
}

My third class TextReader:
import java.io.*;
public class TextReader
{
  private PushbackReader in;   // the input stream
  private boolean rePrompting; // users should be prompted, but not files
  public TextReader(  )
  {
    in = new PushbackReader( new InputStreamReader( System.in ) );
   rePrompting = true;
  }
  public TextReader( String fileName )
  {
    try {
      in = new PushbackReader(new FileReader(fileName));
     rePrompting = false;
   }
    catch( Exception e ) {
      System.out.println("Can't open input file '" + fileName + "', program terminated");
      System.exit(1);
    }
  }
  private void error( String where )

  {
    System.out.println("\n***Failure in " + where + " message. Program terminated***" );
    System.exit( 1 );
  }
  public boolean readBoolean()
  {
    do
    {
      String torf = readWord( );
      if( torf.equalsIgnoreCase( "true" ) )
       return true;
      else if( torf.equalsIgnoreCase( "false" ) )
        return false;
      else
       System.out.println( torf + " is not 'true' or 'false'. Try again");
    } while( true );
  }
  public String readLine( )
  {
    String result = "";
    try {
      do
      {
        int next = in.read( );
        if( next == '\r' )
          continue;
        if( next == -1 || next == '\n' )
          break;
        result += (char)next;
      } while(true);
    }
    catch( Exception e ) {
      error ( "readLine" );
    }
    return result;

  }
  public char readChar()
  {
    return read( );
  }
  public char read( )

  {
    char result = ' ';

    try {
      result = (char)in.read();
      if (result == '\r')
       result = (char)in.read();
    }
    catch( Exception e ) {
      System.out.println( "Failure in call on read method, program terminated." );
      System.exit( 1 );
    }
  return result;
  }

  public void unread( char ch )
  {
    try {
      in.unread((byte)ch);
    }
    catch( Exception e )
    {
      error( "unread" );
    }
  }

  public char peek( )
  {
    int next = 0;
    try {
      next = in.read( );
    }
    catch( Exception e ) {
      error( "peek" );
   }

    if( next != -1 )

      unread( (char)next );

    return (char)next;

  }

  public String readWord()
  {
    String result = "";
    try {
      int next;
      do
      {
        next = in.read();
      } while( next != -1 && Character.isWhitespace( (char)next) );

      while (next != -1 && !Character.isWhitespace( (char)next ) )
      {
        result += (char)next;

        next = in.read();

      }
     while (next != -1 && next != '\n' && Character.isWhitespace((char)next))
      {
        next = in.read();
      }
  if (next != -1 && next != '\n')
        unread((char)next);
      } // end try
      catch (Exception e)
      {

       error( "readWord" );

      } // end catch
    return result;
  }
  public int readInt()
  {
    int result = 0;
    do // keep on trying until a valid double is entered
    {
      try
      {
        result = Integer.parseInt(readWord());
        break;  // result is good, jump out of loop down to return result;
      }
      catch (Exception e)
      {
        if(rePrompting)
          System.out.println("Invalid integer. Try again.");
        else
        {
          error( "readInt" );

          break;
        }
      }
    } while( true );

    return result;
  }
  public double readDouble()

  {    double result = 0.0;
    do  // keep on trying until a valid double is entered
    {
      try {
        result = new Double(readWord()).doubleValue();
        break;  // result is good, jump out of loop down to return result;
      }
      catch( Exception e )
      {
        if(rePrompting)
          System.out.println("Invalid floating-point number. Try again.");
        else
        {
          error("readDouble");
          break;
        }
      }
    } while( true );
    return result;
  }
  public boolean ready( )
  {
    boolean result = false;
    try {
      result = in.ready();
    }
    catch (IOException e) {
      error ( "ready" );
    }
    return result;
  }
  public static void main( String[] args )
  {
     System.out.print( "Enter password: " );
     String pass = "";
     TextReader k = new TextReader( );
     while( true )
     {
       char ch = k.peek();
       if(ch == '\n')
         break;
       pass += ""+ch;
//       k.unread( '*' );
     }
     System.out.println( pass );
  }
}

A: That implementation of the AKS primality test is limited to using 32 bit data types, which can store numbers up to 2,147,483,647. Your number is a lot bigger than that, so doesn't read it properly.
Sounds easy to fix, we should be able to just change all occurrences of int, to long since long data types can store very large numbers. Unfortunately, this won't work, because we are still limited by the maximum size for arrays in Java being 32-bit. So, it is quite impractical to do without delving into unsafe memory access.
If you want to check for primality on numbers that large, you can modify the code like this:
Replace main with this:
public static void main(String[] args)
{
    AKSPrime p = new AKSPrime();

    TextReader k = new TextReader();

    System.out.print("Input number for primality testing: ");

    long i = k.readLong();

    System.out.println("Is " + i + " prime? " + p.nonAKSisPrime(i));
}

Replace the nonAKSisPrime function with this one:
private boolean nonAKSisPrime(long x)
{
    long f = 2;
    boolean result = true;

    long s = (long)Math.sqrt(x);

    while(f <= s && result)
    {
        if(x % f == 0)
            result = false;
        f++;
    }

    return result;
}

And add this new function to TextReader, that reads long values:
  public long readLong()
{
    long result = 0;
    do // keep on trying until a valid long is entered
    {
      try
      {
        result = Long.parseLong(readWord());
        break;  // result is good, jump out of loop down to return result;
      }
      catch (Exception e)
      {
        if(rePrompting)
          System.out.println("Invalid long. Try again.");
        else
        {
          error( "readLong" );

          break;
        }
      }
    } while( true );

    return result;
  }

A: I am afraid you mean 16 byte integer, not bit. A java int is 4 byte, 32 bits, a long 8 bytes, 64 bits.
1425412525412545 might fit in a long, certainly not an int, and maybe you should use BigInteger on principle, to cover the full 16 bytes.
As that no longer is a primitive type, a bit more writing is required.


text:
Q: What happens to my saved game if I buy a new 3ds What happens to my saved game (Retail version not eShop) when I buy a new 3DS when my old one gets broken? I a case of total destruction of a 3DS system an you don't have the chance to make data transfer... Everybody says that saved games are being stored on the game cartridge but when I put my game in a new 3DS am I only able to play as a resident?

A: The save game on a physical copy of Animal Crossing: New Leaf is stored on the cartridge. If your system is destroyed but you still have the cartridge then you can resume playing on another system. I have a cartridge that I swap between two systems so I can confirm this.
Now what I can't confirm is if there is something strange going on with your New 3DS. This is something that you might want to contact Nintendo Customer Support about for further guidance.

A: Just go onto the Nintendo e-shop and download the Nintendo 3ds transfer app (it will look like a toaster). Then do the same on the new 3ds, and then all of the memory on your old one will be on your new one (not sure if that works for game cards though).


text:
Q: enp0s25 interface keeps reappearing in Ubuntu 20.04.03 LTS I've just started seeing something odd in my system (Ubuntu 20.04.03 LTS).  I've got a hardwired connection to my system, and noticed in the past few days that I see the interface enp0s25 as one of my pulldown options for a wired connection.  I saw that /etc/NetworkManager/system-connections has a list of all my wireless and wired connections, and saw a file 'enp0s25.nmconnection' there.  I moved it someplace else, and rebooted.
However, this connection still appears in my pulldown, and for some reason, even if I set my wired connection to 'Off'... this still reappears.   If I set things to 'Off', my system is connected to enp0s25.nmconnection, but there is no internet connectivity.  Here is how things appear when the system is connected normally; note the enp0s25 is there:

Looking at /etc/NetworkManager/system-connections, I don't see the enp0s25.nmconnection there.  How might this be repopulated?   Is there a way to find what process might be trying to reconnect this?
I do use Dropbox, so I'm wondering if this could be an issue.   The hardware (MAC) addresses of the 'Wired connection 1' and enp0s25 are the same, BTW.
Additionally, even when I remove the interface enp0s25, it can reappear, and, looking further, I see it has the 'Make available to other users' checkbox 'on'.
The output of 'ifconfig' shows the enp0s25 interface, when 'Wired connection 1' is connected.
As per @heynnma:
No entries for /etc/network/interfaces;
ls /etc/network returns:
if-down.d  if-post-down.d  if-pre-up.d  if-up.d

In /etc/netplan, there is only one file, 01-network-manager-all.yaml
# Let NetworkManager manage all devices on this system
network:
  version: 2
  renderer: NetworkManager

Trying sudo lshw -C network, gives the following (MAC address output obscured):
  *-network
       description: Ethernet interface
       product: Ethernet Connection I217-LM
       vendor: Intel Corporation
       physical id: 19
       bus info: pci@0000:00:19.0
       logical name: enp0s25
       version: 04
       serial: aa:bb:cc:dd:ee:ff
       size: 100Mbit/s
       capacity: 1Gbit/s
       width: 32 bits
       clock: 33MHz
       capabilities: pm msi bus_master cap_list ethernet physical tp 10bt 10bt-fd 100bt 100bt-fd 1000bt-fd autonegotiation
       configuration: autonegotiation=on broadcast=yes driver=e1000e driverversion=5.11.0-41-generic duplex=full firmware=0.13-3 ip=10.0.0.52 latency=0 link=yes multicast=yes port=twisted pair speed=100Mbit/s
       resources: irq:37 memory:f2600000-f261ffff memory:f263f000-f263ffff ioport:5080(size=32)
  *-network DISABLED
       description: Wireless interface
       product: Wireless 7260
       vendor: Intel Corporation
       physical id: 0
       bus info: pci@0000:04:00.0
       logical name: wlp4s0
       version: 83
       serial: a0:b0:c0:d0:e0:f0
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress bus_master cap_list ethernet physical wireless
       configuration: broadcast=yes driver=iwlwifi driverversion=5.11.0-41-generic firmware=17.3216344376.0 7260-17.ucode latency=0 link=no multicast=yes wireless=IEEE 802.11
       resources: irq:36 memory:f2400000-f2401fff

Here's the thing - I didn't have a wireless connection on my machine (always have been hardwired; this is a Desktop installation).   I did have a wireless adapter, and added the system to a local Wi-Fi connection to see if this would change things.  This did stop the appearance of the enp0s25, temporarily, however, the 'Turn Off' dropdown went away!  The only way to disconnect is to open the 'Wired settings' option, and disconnect via the slider.  However, when that happens... the enp0s25 reappears again as in the screen shot.


text:
Q: Hydra with Weblogic for testing credentials I'm looking for the good syntax with Hydra in order to validate the good credentials. My local weblogic server is running on 192.168.100.21, so far I've tried the following:
hydra -C userpass.txt -M my-local-IP.txt -o results.txt http-get -s 7001 -f -q -t 2 -m /console/j_security_check

hydra -C userpass.txt -M my-local-IP.txt -o results.txt http-head -s 7001 -f -q -t 2 -m /console/j_security_check

hydra -C userpass.txt -M my-local-IP.txt -o results.txt http-post-form "/console/j_security_check:user=^USER^&pass=^PASS^:F=failed" -s 7001 -f -q -t 2

So far none of them have been printing in the output 'results.txt' the valid credential.
Any help would be very appreciated.
Thanks

A: It looks like you are trying to test against the WebLogic admin console. Here's a working example for a WebLogic 11g/12c installation.
hydra 192.168.100.21 -s 7001 -l <username> -p <password> http-post-form -m "/console/j_security_check:j_username=^USER^&j_password=^PASS^:Authentication Denied"


text:
Q: What is wrong with this buffer overflow solution in c? I was just marked down on coursework for this incorrect solution to a buffer overflow in c but was not provided feedback on how it was wrong. Could somebody let me know what the problem is? Thank you.
The question stated to provide a solution in case a longer string than 16 was passed in to this function:
void function(char *str)
{
    char buffer[16];
    strcpy(buffer, str);
}

And here is my solution
void function(char *str)
{
    size_t str_length = strlen(str);

    char buffer[str_length];
    strcpy(buffer, str);
}

Thanks

A: You need to account for the null character terminating the string:
char buffer[str_length + 1];

Void_ptr points out that the above is not enough. So to be more robust:
void function(char *str)
{
    size_t str_length = strlen(str);
    char *buffer = malloc(str_length + 1);
    if (buffer == NULL)
        return;
    memcpy(buffer, str, str_length+1); // Thanks chux
    // Do something with with buffer...
    free(buffer);
}

Or maybe the professor was simply looking for this:
void function(char *str)
{
    char buffer[16];
    strncpy(buffer, str, sizeof(buffer));
    buffer[sizeof(buffer)-1] = '\0';
}

A: It depends on what you are allowed to use but I guess the safest way would be to use strdup and check if it has returned NULL.
void function(char *str)
{
    char *buffer;

    buffer = strdup(str);
    if (!buffer)
        exit(EXIT_FAILURE);
    free(buffer);
    /* free buffer or keep track of it or you'll end up with memory leaks */
}

In the case where you're not allowed to dynamically allocate memory, the use of strncpy is still a more secure alternative to strcpy.
void function(char *str)
{
    size_t str_length = strlen(str);
    char buffer[str_length + 1]; /* /!\ This is C99 */

    strncpy(buffer, str, str_length);
    buffer[str_length] = '\0';
}


text:
Q: Cannot get vue-google-charts to work in browser mode I'm starting to learn Vue.js and can use Google Charts standalone but cannot get the vue-google-charts component to work. I've included both vue.js and vue-google-charts.js as per instructions here https://github.com/devstark-com/vue-google-charts#browser but the chart does not render and get I the following error message
Unknown custom element: <gchart>

Example can be viewed here https://jsfiddle.net/ugLc0zrj/
What am I doing wrong?

A: In console you can see this error:
Cross-Origin Read Blocking (CORB) blocked cross-origin response https://raw.githubusercontent.com/devstark-com/vue-google-charts/master/dist/vue-google-charts.browser.js with MIME type text/plain. See https://www.chromestatus.com/feature/5629709824032768 for more details.

The script wasn't loaded. Other people had similar issues using raw.githubusercontent.com: Github issue- i couldn't use the component directly on browser
Use this CDN link suggested by authors instead: https://unpkg.com/vue-google-charts@0.3.3/dist/vue-google-charts.browser.js
Working fiddle


text:
Q: Ruby: sort an array exluding some symbols I have such an array: ["c", "-b", "a"]
["c", "-b", "a"].sort! returns ["-b", "a", "c"]
I want it to be sorted like ["a", "-b", "c"]
How do I exclude the minus sign from sorting?
What's the simplest way to get it?

A: ["c", "-b", "a"].sort_by{|e| e[/\w+/] }
# => ["a", "-b", "c"]

A: This ignores all non-alphanumeric symbols, and works for strings of any length:
["c", "-b", "a"].sort_by { |s| s.gsub(/\W/,'') }
# => ["a", "-b", "c"]

A: This also works, but sort_by is more direct:
["c", "-b", "a"].sort {|x,y| x[/\w+/] <=> y[/\w+/]} # => ["a", "-b", "c"]

Edit: Better, I think:
["c", "-b", "a"].sort {|x,y| x[/[^-]+/] <=> y[/[^-]+/]}


text:
Q: Double backslash on last line of matrix Is \\ necessary on the final line of environments like matrix, align, and gather? For example, with amsmath,
\[\begin{bmatrix}
    3 & 1\\
    2 & 4\\
\end{bmatrix}\]

and
\[\begin{bmatrix}
    3 & 1\\
    2 & 4
\end{bmatrix}\]

seem to produce the same output. But are they really the same? Is one preferable to the other, or is it a matter of taste? From my understanding, \\ in one of these environments is used to separate lines, and there's nothing else to separate the final line from, so it's not necessary.

A: There is no difference at all for bmatrix. There is for align.
Any array or tabular allows a trailing \\; it is obviously mandatory if \hline is needed at the bottom, but otherwise omitting it is safe.
Since Xmatrix (where X stands for noting, p, b, B, v or V) is array in disguise, the same applies. Also cases falls in this class.
It's very different with align, alignat, xalignat, flalign and gather (or *-forms thereof), where a trailing \\ would produce a new empty row (with the equation number in the case of no *), so it must be avoided.
As a habit, I tend to avoid the trailing \\ in Xmatrix, just for symmetry with the alignment environments mentioned above.


text:
Q: In Scala reflection, why reflection function on TypeTag still has type erasure? Considering the following scala program:
val arr: Seq[String] = Seq("abc", "def")
val cls = arr.head.getClass
println(cls)
val ttg: TypeTag[Seq[String]] = typeOf[Seq[String]]
val fns = ttg.tpe
  .members
val fn = fns
  .filter(_.name.toString == "head")
  .head                           // Unsafely access it for now, use Option and map under normal conditions
  .asMethod                       // Coerce to a method symbol

val fnTp = fn.returnType
println(fnTp)

val fnCls = ttg.mirror.runtimeClass(fnTp)
assert(fnTp == cls)

Since TypeTag has both Seq and String information, I would expect that fn.returnType give the correct result "String", but in this case I got the following program output:
cls = class java.lang.String
fnTp = A

And subsequently throw this exception:
A needed class was not found. This could be due to an error in your runpath. Missing class: no Java class corresponding to A found
java.lang.NoClassDefFoundError: no Java class corresponding to A found
    at scala.reflect.runtime.JavaMirrors$JavaMirror.typeToJavaClass(JavaMirrors.scala:1258)
    at scala.reflect.runtime.JavaMirrors$JavaMirror.runtimeClass(JavaMirrors.scala:202)
    at scala.reflect.runtime.JavaMirrors$JavaMirror.runtimeClass(JavaMirrors.scala:65)

Obviously type String was erased, leaving only a wildcard type 'A'
Why TypeTag is unable to yield the correct erased type as intended?

A: Seq.head is defined as def head: A. And fn is just a method symbol of the method head from a generic class Seq[A], it doesn't know anything about the concrete type. So its returnType is exactly that A just as defined in Seq.
If you want to know what that A would be in some concrete Type, you'd have to specify that explicitly. For instance, you can use infoIn on the method symbol:
scala> val fnTp = fn.infoIn(ttg.tpe)
fnTp: reflect.runtime.universe.Type = => String

scala> val fnRetTp = fnTp.resultType
fnRetTp: reflect.runtime.universe.Type = String


text:
Q: Need advice, Saving messages from JMS Queue to Hadoop Hbase a good solution? I'm new to the Hadoop world and I've been tasked to research solutions to ingest data from our current JMS Queues into our Hadoop cluster.
So far on my quest to becoming a data ingestion expert... I've scoured the web going through books and tutorials for a couple of weeks now. I've managed to write a simple Java Service which listens to one of our Queues and simply write the incoming messages to an HBase HTable.
After completing this proof of concept I have a couple of questions I would like ask the community/Hadoop/Hbase/data ingestion experts. Before I ask let me describe a little bit of my scenario/scope.

*

*We receive approximately 30,000 messages per day from our JMS Queue

*These messages are JSON objects which can range anywhere from 1 MB to 20 MB each

*Needs to be near real time

*We would like to continuously save these messages into Hadoop for future analytics and historical reference for years to come

*We don't need to parse the incoming messages, just store them. (Current line of thinking is to write another Service which will parse these messages and save them into proper schema later. Reason = No bottlenecking during message ingestion)

With my "proof of concept" Java Service, it works, but I don't know if this solution is the best for my case scenario especially in a Production environment.

*

*Is this a good approach/solution for my case scenario?

*If not, what other technologies would be a good fit for what I'm trying to do?

*Is using HBase for this overkill?

*Saving up to 20 MB in a single cell a good idea? Especially if we plan to continuously append messages to this table with no purging?

Appreciate any input, thanks!

A:
Is this a good approach/solution for my case scenario?
  If not, what other technologies would be a good fit for what I'm trying to do?

Flume can be another option. It provides jms source and HBase/Hive sinks.

Is using HBase for this overkill?

May not be, if the number of messages run into a large number over a period of time based on your daily input.
What is the purpose of storing messages in HBase if you plan to parse it out again into another store.
Depending on your needs, the another service (example, mapreduce) can consume jms messages, process it and output to what ever final destination you are thinking of instead of HBase. Unless you have a need to store original messages for a long term.


text:
Q: Facebook wall post link contains some extra Parameters I am using this code for writing to my facebook wall
$AccessToken       = $this->facebook->getAccessToken();
    $attachment = array(
    'access_token' => $AccessToken,
    'message' => "$Msg",
    'name' => 'some content',
    'link' => $link,
    'picture' => "$ShareImage",
    'description' => '',
    'caption'=>'',
    'properties' => array (
                              'Send one to a friend now:' => array  (
                                        'text' => 'Facebook App ',
                                        'href' => 'http://apps.facebook.com/appname/'
                                       ),
                              'Become a fan:' => array  (
                                        'text' => 'Page Name',
                                        'href' => 'http://www.Facebook.com/page/'
                                       )
);

It is working fine.But the problem is from the image the link is containing some extra parameter eg: www.mysite.com?id=12&ref=nf
But from the text the link showing the current link.Is their any way to remove the content ref=nf from the link that is pointing from the image

A: This is not possible to remove those extra parameters. ref is always added by Facebook to your links so you'll be able to track there from user visited it.
nf indicating user came from link he saw in News Feed


text:
Q: UNITY3D - Pink prefab because of BumpedDiffuse shader I'm trying to download assetBundle from server and unzip it. All is working fine with Standard Shader Material (u can see it on the video).
But if material in assetBundle is Mobile/BumpedDiffuse so prefab instantiated with pink color like no material attached to prefab. But if I click to prefab I can see that there is attached material on this prefab. And there are texture map on material. And the most interesting thing that if i changed shader to any other all is fine even if I changed from Mobile/BumpedDiffuse to Mobile/BumpedDiffuse
In general, watch my video.
Thank you.
Video with problem on YouTube
private IEnumerator DownloadPrefabContent(string url)
{
    var www = UnityWebRequestAssetBundle.GetAssetBundle(url);
    yield return www.SendWebRequest();

    AssetBundle assetBundle = DownloadHandlerAssetBundle.GetContent(www);

    var prefabRequest = assetBundle.LoadAssetAsync<GameObject>("prefab.prefab");
    yield return prefabRequest;

    GameObject prefab = null;
    prefab = prefabRequest.asset as GameObject;
    _sessionContext.AddPrefabToList(prefab);
    Instantiate(prefab, prefab.transform.position, Quaternion.identity);
}

A: The problem was in BuildTarget.Android. I change it to BuildTarget.StandaloneWindows64 and it is helped me.


text:
Q: Try-Catch not catching exception in method in C# I have a search box and button combo in a WPF desktop application.  On clicking the search button, it uses a Predicate in the Library.Find() method to search for the precise search term entered.  This is all inside of a try-catch block, so that if the search term isn't matched it won't crash the application.
The problem is that the exception isn't caught, rather it still crashes despite the try-catch block.  Through debugging, I know the type of the exception is a NullReferenceException.  I've also tried catching ArgumentNullException, as this is the type listed for the Library.Find() method, and I've even tried using just a generic Exception type, but nothing is ever caught.  Can someone please help explain this?  I'm sure it's something simple I'm overlooking, but none of the answers I looked at hada similar situation.
Note:  I don't have a try-catch block around the contents of the ShowRecord() method as this method is also used for record navigation buttons (i.e. Next Record, Prev Record, etc), and the ArgumentNull or NullReference don't make sense in that case.  I only have the try-catch around the code that could potentially throw the relevant error, as I was always taught.
searchButton Code:
private void searchButton_Click(object sender, RoutedEventArgs e)
{
    try
    {
        ShowRecord(gameLibrary.Find(x => x.GameName == searchBox.Text));
    }
    catch (ArgumentNullException ex)
    {
        string term = searchBox.Text;
        searchBox.Text = "'" + term + "' was not found in the library.  Please try another search term.";
    }
}

ShowRecord() Code:
public void ShowRecord(Game game)
{
    titleBlock.Text = game.GameName;
    systemBlock.Text = game.GameSystem;
    formatBlock.Text = game.GameFormat;
    completedBlock.Text = game.IsComplete.ToYesNo();
    totalledBlock.Text = game.IsTotaled.ToYesNo();
    gamepassBlock.Text = game.GamePassStatus;
    installedBlock.Text = game.IsInstalled.ToYesNo();

    recordNumber.Content = (gameLibrary.FindIndex(x => x == game) + 1).ToString();
    recordCount.Content = gameLibrary.Count;
}

EDIT
I was pasting the stack trace as requested in one of the comments, and may have figured out the issue in doing so.  As stated in the initial question, the ShowRecord() method is also used for record navigation; as such, there is a segment in it where the TextBoxes are assigned the values for the located record (i.e. TextBox.Text = gameLibrary.GameName).  It's at this point that the exception is occurring, so even though it's happening within the ShowRecord() call in the button click event, the issue is actually not related to the List.Find(Predicate) part that the exceptions were supposed to catch.  Does this make sense?  To add to this, @Tam Bui mentioned adding a second catch block with only Exception being caught, and adding a breakpoint inside this:  I did this, and it still didn't stop at the breakpoint, it stopped at the TextBox value assignment.
Assuming this is the cause, thanks to everyone for the help.  I saw the exception not being caught by the generic Exception, and the impossibility of that blocked out all other reasoning for me, hence the confusion and missing where the actual break occurred.


text:
Q: How to quote a string dynamically in Javascript? This kinda funny, i want to quote a string value for a function but javascript throws this error Uncaught SyntaxError: Unexpected token }
This my code
var val = "Testing String";
var table_row = "
Row1
";

function test( val ){
  alert( val );
}

The table row get created fine with the test function bound well with onClick event.
But when i click on the created link i get
`Uncaught SyntaxError: Unexpected token }

The Value within the test function should be a quoted string.
Note: If i remove the concatenation of the val string, and pass is as a string like this
table_row = "
Row1	";

... it works
Where am i goofing?
Gath.

A: Then in your original script also escape ":
var test = "\"test string\"";

A: i thing it ll help u sir,,,,

if row1 is variable
u can add by '+Row1+' seperator,
or else directly use bellow code;

var table_row = '
Row1	';
        //alert("++++++++++++"+table_row+"++++++++++++");

see ya ,,,

A: Given
var val = "Testing String";
var table_row = "
Row1
";

Should table_row not be
"
Row1
"

so the onclick attribute is only 'test(', because ' ends it?
Try:
var table_row = "
Row1
";

A: This what i did and now working fine;
var val = "Testing String";
table_row = "
Row1
";

function test( val ){
 alert( val)   // Displays "Testing String"
}

Thanks for your patience.


text:
Q: Chaining mongoose queries and return result in Schema I'm not sure if I'm having trouble because I don't understand JS or mongodb/mongoose.
Here's my current code:
/**
 * Fins all (biological) siblings of this person.
 * @returns {Array} Returns all the siblings as a list. If no siblings were found, returns an empty list.
 */
personSchema.methods.getSiblings = function () {
    const sibs = new Set();

    this.model('Person').findById(this.mother, function(err, mom) {
        mom.children.forEach((child) => { sibs.add(child); });
    });

    this.model('Person').findById(this.father, function(err, pa) {
        pa.children.forEach((child) => { sibs.add(child); });
    });

    console.log(sibs);
    return sibs;
}

I want this function to get all the children from this persons father and mother and return their ids as a list (effectively returning this persons biological siblings). Now the only thing that this function will ever return is an empty set. I think I understand why, and that is because the function does not wait for the queries to finish before returning. But how do I achieve this? I know I could use promises, but I want to add the fathers children even if the mother query returns an error...
Thanks for the help!
PS: Is there a nicer way to add all of the elements of a list to a set?
EDIT: I found a solution, but it's probably not optimal:
/**
* Finds all biological siblings of this person.
 * @param callback(sibs) the function to call when finished. Sets the sibs parameter of the callback function to a list
 * of sibling IDs or an empty list if no siblings were found.
 */
personSchema.methods.getSiblings = function (callback) {

const self = this;
const mId = this.mother;
const pId = this.father;
const sibs = [];

self.model('Person').findById(mId, "children", function (err, res) {
    if (!err)
        sibs.push(res.children);

    self.model('Person').findById(pId, "children", function (err, res) {
        if (!err)
            sibs.push(res.children);

        callback(_.uniqWith(sibs, _.isEqual));
    })
});

}


text:
Q: How to use mongodb from Lua 5.3 in OS X? I want to use mongodb from Lua 5.3 script in OS X. I found a project luamongo. Unfortunately I could not build it and I am not sure it is support Lua 5.3.
Is there any way to do that?


text:
Q: Multiply each integer in a flat array by 60 I have an array called $times. It is a list of small numbers (15,14,11,9,3,2). These will be user submitted and are supposed to be minutes. As PHP time works on seconds, I would like to multiply each element of my array by 60.
I've been playing around with array_walk and array_map but I can't get those working.

A: You may want to use foreach for simplicity in your case:
foreach( $times as &$val ){ $val *= 60; }

I assume that the values of your array are the ones you want to multiply, not the keys. As the above solution uses references, it will also alter your original array - but as you were aiming at array_map before, I think that you want that.
The solution above is probably easier to understand and most likely faster than using array_map which (obviously) has to call a function for each element.
I'd use array_map only for more complicated things such as advanced sorting algorithms and so on, but definitely not for something as trivial as this.

A: I'd personally second the suggestion from Gordon to just use a lambda (or created) function and either do:
array_map(function($el) { return $el * 60; }, $input_array);

(PHP >= 5.3) or
array_map(create_function('$el', 'return $el * 60;'), $input_array);

(PHP < 5.3)
Definitely I see no reasons for duplicating the array (can become cumbersome if lot of values are involved); also, pay attention that using foreach (which I second can be handy) can also be dangerous if you're not working with it carefully ...and then maintenance can become daunting anyways (because you have to remember to deal with it every time you work on that code). If you have no reasons for optimizing at this stage (IE your application has not problems of speed), don't do it now and don't worry about using array_map. You can think about ease of maintenance now and optimize later, in case you really need to.
In fact, if you go by reference and then you use foreach again, you might step into unexpected results (see example below...)
$a=array('1','2','3');

foreach ($a as &$v) {
        $v *= 60;
}
print_r($a);
foreach ($a as $v);
print_r($a);

Output is:
Array
(
    [0] => 60
    [1] => 120
    [2] => 180
)
Array
(
    [0] => 60
    [1] => 120
    [2] => 120
)
Probably not what you expect on the second cycle.
This is why I usually avoid the foreach & byref combo when I can.

A: array_walk($myArray, function(&$v) {$v *= 60;});

A: You can use array_map:

array_map() returns an array containing all the elements of arr1 after applying the callback function to each one. The number of parameters that the callback  function accepts should match the number of arrays passed to the array_map()

Examples with lambda functions for callbacks:
array_map(function($el) { return $el * 60; }, $input);

Same for PHP < 5.3
array_map(create_function('$el', 'return $el * 60;'), $input);

Or with bcmul for callback
array_map('bcmul', $input, array_fill(0, count($input), 60));

But there is nothing wrong with just using foreach for this as well.

A: Just iterate over the array with the foreach statement and multiply:
foreach ($times as $value) {

  $new_times[] = $value * 60;

}


text:
Q: overloaded method value async with alternatives: When I have the following code everything compiles fine.
 def create(name: String, age: Int) = Action.async {
    val json = Json.obj(
      "name" -> name,
      "age" -> age,
      "created" -> new java.util.Date().getTime())

    collection.insert(json).map(lastError =>
      Ok("Mongo LastError: %s".format(lastError)))
  }

But when extract the content to another method as follows
 def create(name: String, age: Int) = Action.async {
   createPerson(name,age)
 }

  def createPerson(name: String, age: Int) = Action.async {
    val json = Json.obj(
      "name" -> name,
      "age" -> age,
      "created" -> new java.util.Date().getTime())

    collection.insert(json).map(lastError =>
      Ok("Mongo LastError: %s".format(lastError)))
  }

it gives the error
[error] /media/pubudu/NTFSPartition/projects/catnet/data-collector-backend/app/controllers/Application.scala:50: overloaded method value async with alternatives:
[error]   [A](bodyParser: play.api.mvc.BodyParser[A])(block: play.api.mvc.Request[A] => scala.concurrent.Future[play.api.mvc.Result])play.api.mvc.Action[A] <and>
[error]   (block: play.api.mvc.Request[play.api.mvc.AnyContent] => scala.concurrent.Future[play.api.mvc.Result])play.api.mvc.Action[play.api.mvc.AnyContent] <and>
[error]   (block: => scala.concurrent.Future[play.api.mvc.Result])play.api.mvc.Action[play.api.mvc.AnyContent]
[error]  cannot be applied to (play.api.mvc.Action[play.api.mvc.AnyContent])
[error]   def create(name: String, age: Int) = Action.async {

Isn't the two code sections doing the same thing? If not, how can I extract the content of the method without getting the error? What I want to do is to call the extracted method from two different places.

A: The create method expects the return type to be Future[Result], but the calling of createPerson returns Action[AnyContent]. You can correct it by making following changes:
def create(name: String, age: Int) = Action.async {
   createPerson(name,age).map(lastError =>
      Ok("Mongo LastError: %s".format(lastError)))
 }

  def createPerson(name: String, age: Int):Future[String] = {
    val json = Json.obj(
      "name" -> name,
      "age" -> age,
      "created" -> new java.util.Date().getTime())

    collection.insert(json)
  }


text:
Q: How to avoid css selector applying style rules from another file I came across this problem while handling a large project and felt that i should seek an opinion from the community here.
I have specified a css class 'header' in style1.css, i.e.
.header { color: red;}

In another file, I inadvertently, named a class 'header' again with this rule :
.header { background-color: yellow; }

When i refreshed the browser i noticed the red font and after examining the style inspector found the problem. I tried to avoid the problem by applying specificity, i.e. #some-div .header, but that didnt stop it from applying the red font. Of course i could simply solve the problem by renaming header to something else, but i'm curious how developers who handle large projects handle this. Thanks for your time.

A: Well, from your code, you specified values for different properties in the two declarations of the header class. The first declaration specifies a color property and the second specifies a background-color property. From all indications you're not really "overriding" anything since you didn't give conflicting values for one property so, CSS is simply giving the values of the first declaration of the header class to the second one because there's no difference. If you wanted to override it for the second you'd have to probably add a different identifier to the second declaration of the header class to point to a unique element and specify a different value for the color property. Hope this satisfied your curiosity.

A: Don't use !important as another user suggested.  Avoid it all costs. It's the easy way out for the moment, but once you start going down that road, you're going to end up with a stylesheet that's terrible to manage.
Set your styles for a specific base and use classes and more specific selectors as overrides. Remember that stylesheets cascade.
For example, say you have a typical header font color that should be your .header.  If you have other one-off or unique headers that share same structure provide another class to that which makes sense to you.
So as an example:
Both headers have the .header styles but headers with the special class have blue text color which overrides red.

.header {
  color: red;
  width: 100%;
  display: block;
  background-color: #eee;
  padding: 10px;
  margin: 2px;
}
.header.special {
  color: blue;
}

Regular Header

Special Header

A: Just add a different class to one of the cases. For example:

.header {
  color: red;
}

.header.yellow-bg {
  color: initial;
  background-color: yellow;
}

Red header

Black/yellow header

The second declaration for color applies because it is more specific (2 classes > 1 class).


text:
Q: Inserting into DB from data in Hash and Arrays I have defined my hash and arrays like this:
POPULATION_SUMMARIES = {
    'ACO' => [   # year , member_count
        [2013, 523031],
        [2012, 492349],
        [2011, 432573]
    ]
}

So the table I want to insert into is PopulationSummary . And its row/fields are like this:
    ACO, 2013, 523031
    ACO, 2012, 492349
    ACO, 2011, 432573
Org_id, year, member_count

In DB, It's actually the ID of those "ACO" or other stuff, they are basically foreign keys of another table.(ie. Organization table).
So I am trying to loop through this and read the structure and write it in the table.
I went as far as something like this:
  POPULATION_SUMMARIES.each do |k, v|
    org_id = Organization.find_by_name(k).id  # so for example ID of ACO
    v.each do |o| # now read elements of each array
      # HERE :(  QUESTION
    end
  end

So the part I am having trouble with is how to say Ok the first number you read from the array, insert it for the year field, the second number you read from the table: insert it for member_count field....

A: This should get you close:
POPULATION_SUMMARIES.each do |org_name, summaries|
  org = Organization.find_or_create_by_name(org_name)

  summaries.each do |year, member_count|
    PopulationSummary.create({
      :organization => org,
      :year         => year,
      :member_count => member_count
    })
  end
end


text:
Q: What is static modularization? I've encountered the term static modularization in an interview with Niklaus Wirth in which he said

Nevertheless, I consider OOP as an aspect of programming in the large; that is, as an aspect that logically follows programming in the small and requires sound knowledge of procedural programming. Static modularization is the first step towards OOP. It is much easier to understand and master than full OOP, it's sufficient in most cases for writing good software, and is sadly  in most common languages (with the exception of Ada).
  In a way, OOP falls short of its promises.

I'm wondering what the term static modularization really means. It seems this term is not popularly used.
The full interview can be read here. http://www.eptacom.net/pubblicazioni/pub_eng/wirth.html


text:
Q: Swift: Import .csv as a string I am using Swift to import a .csv file stored in the project. However, I always get the error
fatal error: unexpectedly found nil while unwrapping an Optional value

I tried doing the same thing but converted it to a .txt file, and that failed also. However, if I just copy and paste the contents directly into a new .txt file, it works. I am just trying to turn this into a string so that I can work with it later.
let file = NSBundle.mainBundle().pathForResource("SL", ofType:"csv")
var text = String(contentsOfFile: file!, encoding: NSUTF8StringEncoding, error: nil)!
var rawStudents = text.componentsSeparatedByString("\n")

A: Make sure after dragging your csv file to your project to select the option copy to project if needed. You should always use if let to safely unwrap your optionals.
var error:NSError?
if let fileUrl = NSBundle.mainBundle().URLForResource("SL", withExtension:"csv") {
    if let text = String(contentsOfURL: fileUrl, encoding: NSUTF8StringEncoding, error: &error) {
        let rawStudents = text.componentsSeparatedByString(",")
    } else {
        println("error reading file")
        if let error = error {
            println(error.description)
        }

    }
}

A: After let file=NSBundle.mainBundle().pathForResource("SL", ofType:"csv") check if the file constant is nil or not, in the next line you are force unwrapping a potential nil which is a very bad idea.
The problem might be that the file is not located in the bundle.


text:
Q: Como controlar coordenadas de tela? eu preciso desenvolver um programa em Lua (aplicação desktop) que manipule coordenadas de tela, não precisa ser um ambiente gráfico (GUI), mas preciso ser capaz de, por exemplo, posicionar na coordenada (10, 10) - linha 10, coluna 10, e então exibir um texto, e posteriormente voltar a posicionar nessas coordenadas para exibir outro texto. O único jeito é utilizar um toolkit gráfico?
Obrigado.

A: Se você quer mover o cursor numa tela de terminal, você pode usar sequencias de escape para terminais, como em lua-term.
O seu exemplo seria:
term.cursor.goto(10, 10)
io.write("um texto")
...
term.cursor.goto(10, 10)
io.write("outro texto")

Você nem precisa usar uma biblioteca:  term.cursor.goto(10, 10) é equivalente a io.write("\027[10;10H"). Veja também essa mensagem.
Para uma lista das sequencias de escape mais comuns, veja por exemplo http://ascii-table.com/ansi-escape-sequences.php.


text:
Q: Nginx on Windows using WSGI now that i've decided to use Nginx as my favourite webserver to deploy Django, i got some "mist":

*

*i'm on Windows, that said, i got errors when i try to use Django as FastCGI, it seems that Flup dont load! it give me errors! and from the website, flup is not a good friend of Windows:
check out here

*all tutorials that i've found says that ngnix is good when it's used as reverse proxy, i already asked this question, and this is why it seems that now i can use 100% ngnix.

*i'll make my project on this, and i want to use something different than what is used in my university, they always use LAMP and i hate LAMP! i want something new! and something new and hot is Ngnix + Django ON WINDOWS!

so here is my question:
does really ngnix work on windows, alone, only ngnix to deploy a django project! i want please something for a total beginner coming from earth and speaking human language ^_^

*

*NB: please dont talk about IIS, i'll use a normal Windows XP pro to make my engineering project.

*NB2: what about this nginx bug , has been fixed?


text:
Q: Filter events by date using AngularJS I'd like to filter my events by date using AngularJS and jQuery Datepicker. But it seems not working using the input text...
My code below works with the title of the event...
Main issue : when I choose a date in the jQuery Datepicker, I get no events...

    $scope.onChange = function(){
      $scope.search.start = new Date(moment($scope.search.start, 'DD/MM/YYYY').format("YYYY-MM-DD 00:00:00"));
      $scope.search = _.reduce($scope.search, function(result, n, key) {
        if (n !== '') {
          result[key] = n;
        }
        return result;
      }, {});
      $scope.events = data.events;
      $scope.filteredEvents = $filter('filter')($scope.events, $scope.search);
    };
<input class="form-control datepicker" id="start" type="text" ng-model="search.start" ng-change="onChange()" autocomplete="off">
<input class="form-control" id="title" type="text" ng-model="search.title" ng-change="onChange()" autocomplete="off">

          {{event.title}}

{{event.start | date:"dd/MM/yyyy"}}

A: Out of the Box the JQueryUI datepicker will not work with angular because the angular model is not being updated when Jquery sets the input value.  You need to tell JQueryUI datepicker to update the model.
The best way to do that is create a directive that sets up the datepicker and adds an onSelect method that sets the view value model controllers view value ngModelCtrl.$setViewValue and applies it to the scope scope.$apply()
HTML:
<input type="text" ng-model="date" datepicker />

JS
app.directive('datepicker', function() {
    return {
        restrict: 'A',
        require : 'ngModel',
        link : function (scope, element, attrs, ngModelCtrl) {
            $(function(){
                element.datepicker({
                    dateFormat:'dd/mm/y',
                    onSelect:function (date) {
                        scope.$apply(function () {
                            ngModelCtrl.$setViewValue(date);
                        });
                    }
                });
            });
        }
    }
});

If you also want to use a date in a different format than available using the Date Picker you will need to format using the ng-change directive.
 <input class="form-control " datepicker type="text"
        ng-model="search.start" ng-change="onChange()"/>

   $scope.onChange = function(){
      $scope.search.start = moment($scope.search.start, 'DD/MM/YYYY')
                            .format("YYYY-MM-DDT00:00:00.000[Z]");
    };

Working Example


text:
Q: Codeigniter: passing data to another view Ok, so this question may be very simple and I'm just missing something basic but here goes. My website I'm currently building is developed in Codeigniter. It's a site for exercises.
Now one of my functions (biceps) calls a model (model_get) that grabs data from my database and then passes it into a view (content_biceps.php)
So to try and explain this best as possible here is my controller model and view for this.
Controller function:
    public function biceps(){

        if($this->session->userdata("is_logged_in")){

            $this->load->model("model_get");
            $data["results"] = $this->model_get->getExercises("1");

            $this->load->view("site_header");
            $this->load->view("site_nav");
            $this->load->view("site_sidebar");
            $this->load->view("content_biceps", $data);
            $this->load->view("site_footer");
        }   else {
            redirect ("site/restricted");
        }
    }

Model function get_data:
    function getData($page){
        $query = $this->db->get_where("pagedata", array("page" => $page));
        return $query->result();
    }

View content_biceps:
foreach($results as $row){

    echo '

'.$row->name.'

            image.'" alt="'.$row->name.'" />';

    $e_id = $row->e_id;
    echo $e_id;

    echo form_submit('exercise_submit', 'view');
    echo '
';
    echo form_close();
}

Now this view works great, it grabs the data i need such as the name, image and e_id for each exercise and displays them all.
If you notice the submit button  named 'view'. If you can imagine all of these exercises displayed on one page. They all have a unique e_id. I want it so that when i click the view button on a certain exercise, i am taken to a page view such as 'exercise_view' where i can use the e_id to grab the data for that particular exercise. At the moment I dont know how to take the e_id when i click view and use it in another page.
Any help would be great.

A: You can try to add an input with the e_id you want, for example

    <input type="hidden" name="e_id" value="{$e_id}" />
    <input type="submit" name="view" />

then in controller, you can get the e_id
$e_id = $this->input->post('e_id');


text:
Q: Azure Active Directory JWT for API authentication within Angular 4 I currently have 2 web apps(app services) setup on azure.  The first one is an angular 4 website the second one is a .net core 2.0 restful api.  I have CORs setup for the ui to talk to the api perfectly.  The only issue is there isn't any security around this API.
I am attempting to utilize the azure AD JWT token to be part of an authorize attribute within the API but the problem is the API can't validate the token since I don't have the secret key that azure is using to create the JWT token to begin with.  Also I am getting the token from /.auth/me.  Does anyone have any advice on how best to solve this problem?
Is there an api endpoint on azure that I can hit to get a valid JWT token for the current logged in user?  I noticed the /.auth/me one expires after an hour and the user is forced to visit /.auth/login/aad/callback in order to refresh the tokens.
I would love to know the best strategy to solve this, if it includes adal, msal, etc.  Also links to code would be very much appreciated.

A: I would recommend you use ADAL for Javascript in your angular 4 Web App to retrieve the id_token or access_token, then using the relevant token to access your .NET Core 2.0 restful API. For your angular app, you could still use the build-in authentication/authorization provided by Azure App Service without changing your code.
For your .NET Core 2.0 restful API, you could just leverage Authentication and authorization in Azure App Service (Easy Auth) provided by App Service or you could manually use Microsoft.AspNetCore.Authentication.JwtBearer package in your project for JWT authentication. Detailed code snippet, you could follow here.
Additionally, I would recommend you create each AAD app for your front-end web app and Api web app.


text:
Q: В график включаются лишние элементы Есть датасет, нужно вывести на графики каждую архитектуру из types по systems:
data = pd.read_csv('ap-northeast-1.csv', parse_dates=['2017-05-08 21:46:36+00:00'], dayfirst=False)
data.columns = ['Date', 'Architecture', 'OS', 'Office', 'price']
types= ['i2.2xlarge', 'i2.4xlarge', 'i2.8xlarge', 'i2.xlarge', 'i3.16xlarge', 'i3.2xlarge', 'i3.4xlarge', 'i3.8xlarge', 'i3.large', 'i3.xlarge']
systems = ['Windows', 'SUSE Linux', 'Linux/UNIX']

Сделал с костылем:
fig, axes = plt.subplots(5, 2, figsize=(20,60))
i = 0
j = 0
for i in range(10):
    d_grouped_by_i = data.groupby('Architecture').get_group(types[i])
    for row in range(5):
        for column in range(2):
            for j in range(3):
                date = d_grouped_by_i.groupby('OS').get_group(systems[j])['Date']
                price = d_grouped_by_i.groupby('OS').get_group(systems[j])['price']
                axes[row, column].plot(date, price, label=types[i]+' for '+systems[j])
                axes[row, column].set_title('Price of '+types[i])
                axes[row, column].set_ylabel('price per hour, $US')
                axes[row, column].grid()
                axes[row, column].legend(loc='upper left', title='Stock prices')
                plt.subplots_adjust(hspace=0.35)
                j+=1
            i += 1
plt.show()

В результате с первого по девятый графики выводятся 2 архитектуры для каждой OS - на графике 6 полос данных, а нужно 3. На десятом все в порядке. Прошу помощи у многоуважаемых специалистов! Ссылка на csv - ссылка


text:
Q: Excel find date difference between minimum and maximum date in month I'm trying to fix up a formula I have that's having some issues. It's supposed to track # days invoiced in a month, so the high-level idea is to take the maximum date in a month and subtract the minimum date in the month, and on error subtract the 1st day of the month. My current formula has issues adjust for invoices that may cross months, an example being 1/25 - 2/3 where if this were the only invoice, January should show 7 days invoiced and February would show 3. If there were another invoice from 2/15 - 2/28, I would want Feb to show the maxed invoice days, 14 in this example.
For reference here's what a table could look like:
 A              B           C                D                 E       F
 start month    end month   invoice begin    invoice end       Month   Max Days invoiced
 jan 1          feb 1       1/25/14          2/3/14            1/1     7
 feb 1          feb 1       2/15/14          2/28/14           2/1     14
                                                               3/1
                                                               etc.........

I tried the formula below but it was erroring out, plus I don't think it will account for gaps in invoices like in my example.:
=IF(B2:B100=X1,MAX(D2:D100),) - IF(A2:A100=X2,MIN(C2:C100),A2)
'where column X is a list of months, X1 = 1/1, X2 = 2/1, etc.

No luck with this formula either, keeps erroring out and giving 0 values:
{=DATEDIF(IF(A2:A100=E2,MIN(C2:C100),),IF(B2:B100=E2,MAX(D2:D100),),"d")}

I appreciate your help!

A: Not sure exactly what you are looking for but you could probably make use of the EOMONTH() function. Here's an example of it:
=EOMONTH(A2,0)-A2+1

by the way - here is how you would get the start of the month:
=EOMONTH(TODAY(),-1)+1

Try the following per your comment below:
"I think this could be useful but I'm not sure it would work if the invoice end was, say, 2/21 or anytime before the EOM"
=IF(B3>=EOMONTH(A3,0),EOMONTH(A3,0)-A3+1,B3-A3+1)


text:
Q: HC05 Bluetooth Module with Pi Pico Not Discoverable I have a HC05 Bluetooth module wired up to my Pi Pico with the following code.
//Example script of USB serial

#include "pico/stdlib.h"
#include <stdio.h>
#include "hardware/uart.h"

int main()
{

    const uint LED_PIN = PICO_DEFAULT_LED_PIN;
    gpio_init(LED_PIN);
    gpio_set_dir(LED_PIN, GPIO_OUT);

    // Initialise UART 0
    uart_init(uart0, 9600);

    // Set the GPIO pin mux to the UART - 0 is TX, 1 is RX
    gpio_set_function(0, GPIO_FUNC_UART);
    gpio_set_function(1, GPIO_FUNC_UART);

    while (true) {
        gpio_put(LED_PIN, 1);
        sleep_ms(250);
        gpio_put(LED_PIN, 0);
        sleep_ms(250);

        uart_puts(uart0, "Hello world!\n\r");
        sleep_ms(1000);

    }
}

The bluetooth module is blinking rapidly but I cant see it when searching for devices on my android phone or laptop.
Is there some configuration steps I am missing?
Am I able to set master/slave/Automatic modes with the PICO or do I need an Arduino?


text:
Q: Monitoring Java from within Java I want to write a simple visualization of a Java program by displaying the program's method calls as branches of a tree. This could be done quite simply by having the program itself tell the visualization what it is doing, but I want to be able to do this with any Java method/class and not just the ones I modify to do so.
What I need is the ability to watch the methods a program calls and what methods are called within that method and so on. Obviously, stack traces provide exactly this functionality:
 java.lang.NullPointerException
     at MyClass.mash(MyClass.java:9)
     at MyClass.crunch(MyClass.java:6)
     at MyClass.main(MyClass.java:3)

So I thought about having the program I want to monitor run in a thread and then just look at that thread's stack. However, the thread class does not really support this. It only supports printing the current stack.
Now I, of course, thought of simply changing the PrintStream of the System class so the thread would print its stack into my PrintStream, but this feels kind of wrong.
Is there a better way to do this? Are there any pre-existing classes/methods I can use?
Also, I'm currently downloading the Java source code, to check how exactly the thread class prints its stack so I could maybe subclass thread and imitate the dumpStack() method with my own getStack() method.

A: Look also at VisualVM, shipped with latest Java releases.

A: Oh shoot, looking through the source code I noticed the thread class has a method public StackTraceElement[] getStackTrace(), it just wasn't in the documentation I was reading. Now I feel dumb.
So yeah, that seems to be the solution.

A: One approach might be to use something like BCEL to preprocess the target bytecode to insert calls to your own code on every method entry and exit (probably best to do exit by wrapping the whole method in a try/finally block, to catch exception exits). From this, you can deduce the call tree exactly as it happens.

A: You could use AspectJ for that. Have a look at this description of exactly your use case.

A: Have a look at the ThreadMXBean class -- it my provide what you need. Essentially, you:

*

*call ManagementFactory.getThreadMXBean() to get an instance of ThreadMXBean;

*call getAllThreadIds() on the resulting ThreadMXBean to enumerate current threads;

*call getThreadInfo() to get the top n stack trace elements from a given list of threads.


text:
Q: Is there a word for "pretending to ask?" Is there a word for when you're asking someone something only to go through the motions and uphold social norms?
For instance, when you ask "Can I come in?" before just going in their house or whatever (in particular, you do not reasonably expect the answer to be "no," and they're also expected to go through the "routine" when they answer).

A: The term for this sort of nicety is phatic communication:

phatic a
Of or relating to communication used to perform a social function rather than to convey information or ideas.
TFD Online

It includes questions that don't expect a literal answer.

A: Acts like this fall under the category of politesse.  Basically, the adherence to social norms and decourousness.
In a roundabout way, the question can also be said to be rhetorical.  You are asking a question for which the answer is obvious or implied and you don't really expect an answer.

A: I would probably use the word "obligatory" for this purpose:

Obligatory: ...
(3) so commonplace as to be a convention, fashion, or cliché
[Merriam-Webster Dictionary]

For example, I've been working on a project recently and have a friend who is really knowledgeable on it. I'll regularly call him and ask for advice, and our conversations will start:

Me: Hey I have a quick question for you, but let me offer an obligatory "What's up?" first.
Him: Nothing, what's your question?

He and I both know I'm not really calling to talk about "What's up" in the middle of a work day, but it's a little abrupt to call someone out of the blue and begin grilling them with questions. That said, I know he usually only has a few minutes to talk during the day, so it lets him know that I'm not just trying to dawdle on the phone. Of course, it runs the risk of being considered rude based on the context it's used in, such as:

After John's brother died I sent him the obligatory bouquet of flowers.

This might be taken as a rather insensitive thing to say, as it could be interpreted as me saying that responding to the death of his brother is a mundane chore for me.


text:
Q: Fatal error when installing mongodb with NodeJS I am trying to install MongoDB with NodeJS. I am using latest versions for both.
When I am typing npm install I am receiving this error

C:\Users\Doodlemeat.node-gyp\0.12.2\Release\node.lib : fatal error LNK1107: in
  valid or corrupt file: cannot read at 0x23EBC [C:\Users\Doodlemeat\Desktop\Chat
  \node_modules\mongoose\node_modules\mongodb\node_modules\mongodb-core\node_modu
  les\kerberos\build\kerberos.vcxproj]


text:
Q: Passing arguments to objective function fmincon Matlab I am trying to minimize an objective function which consists of variables other than the constraint variable. Is there a way to pass arguments to such a function, for example:
data = xlsread('Returns.xlsx', 'Sheet2','A2:F324');

for i = 1:10
    returns = data(i:i+59,1:5);
    fund = data(i:i+59,6:6);
    lb = [0;0;0;0;0];
    ub = [1; 1; 1; 1; 1];
    [betas, fval] = fmincon(@obj_function, [0 .2 .2 .2 .2 .2], [], [], [], [], lb, ub, @constraints);
end

And the objective function is defined as:
function [ value ] = obj_function(betas)
    value = returns*betas(2:6) + betas(1);
    value = sum((value - fund)^2);
end

Since my objective function needs to extra variables returns and fund, what is the best way I can keep passing it from the main function? Below statement is invalid, what else can I do?
[betas, fval] = fmincon(@obj_function(returns, fund), [.2 .2 .2 .2 .2], [], [], [], [], lb, ub, @constraints);
EXTRA, function constraint is defined as follows:
function [ c, ceq ] = constraints( betas )
    c = [];
    ceq = betas(2)*1 + betas(3)*1 + betas(4)*1 + betas(5)*1 + betas(6)*1 - 1;
end

A: Use anonymous functions to create closures:
a = 1; b = 2;
[...] = fmincon(@(x) myObjFcn(x, a, b), ...)

Here is a documentation page explaining this in more details:

Passing Extra Parameters

A: An easy solution is to use global returns fund


text:
Q: Python dll call fails I am having a A.dll file consisting of one more B.dll in it.
This A.dll is loaded in Python using LoadLibrary call.
I am calling a function that is part of this A.dll file which is calling B.dll function in turn calling deviceiocontrol function of Windows.
If I comment the B.dll function call in A.dll file this scripts completed the function call otherwise it hangs.
Same dll function works with the C# application without any problem.


text:
Q: LogSuccessfulLogout Listener is not getting triggered when session idle timeout occurs (Laravel) In config/session.php there is key   'lifetime' => 1 for session idle timeout. After exceeding this time when the user gets log out the Listener app/Listeners/LogSuccessfulLogout.php should be triggered. But unfortunately it's not getting triggered. Otherwise if I try to logout manually it works fine.

A: Session expiration after lifetime does not invoke logout method of controller.
Servers keep session lifetime and the when a request with old session comes , create new session. So may a session expiration is 12:00.
User has not send request from 11:00.
Then at 14:00 send a request. So at 14:00
User logout. and before that time no operation is done.
I think to accomplish triggering logout listener , you can create scheduled or cron job when user login


text:
Q: Asp.net: PageMethods call results in error "Type 'System.String' is not supported for deserialization of an array." I'm try to use PageMethods to call a code behind static method, but it looks like it never gets to that method. It just fails with the error
"Type 'System.String' is not supported for deserialization of an array."

I have this working on another part of my program so I'm confused why it's broke here. I'm using a third party plugin jQuery called Chosen I wonder if that is the issue? Here is my code:
JavaScript file
$('.txtBusinessUnit').chosen().change(function ()
{
    var bu = $('.txtBusinessUnit').val();
    PageMethods.BUChanged(bu, onBUSuccess, onBUFailure);
});

function onBUSuccess(result) {
alert(result)
}

function onBUFailure(error) {
    alert(error); //errors message listed above
}

code behind
[WebMethod]
public static string BUChanged(string BU)
{
  return "it works";
}

Update: I used the Chrome debugger. It has the following error:
POST http://localhost:54234/Default.aspx/BUChanged 500 (Internal Server Error)

it errors on ScriptResource.axd with send(body) at this line
this._xmlHttpRequest.send(body);

With the following error
Failed to load resource: the server responded with a status of 500 (Internal Service Error)

Not sure what this means really..


text:
Q: If cell matches any others in range copy content to "results" sheet I want to check if the text in A3 matches the text in any other cells in range A5:A50.
If it does I want to copy the contents of the Y cell (with the same row number as the a cell that matched A3) into the next free cell in the A column in a sheet called results. It needs to also keep the cell colour when it copies the Y cell.
All I could get was putting this in the destination cell
= VLOOKUP(Sheet1!A3, Sheet1$A$5:$Y50, 25, TRUE)

That doesn't work as I need to run it over multiple sheets all with different names.

A: with activesheet
   for each c in .range("A5:A50").cells
      if c.value = .range("A3").value then
         c.offset(0,24).copy _
              worksheets("results").cells(rows.count,1).end(xlup).offset(1,0)
      end if
   next c
end with

A: You can employ a dynamic 3d-Vlookup technique by listing the sheetnames to search in a list somewhere, naming that range of cells MySheets and then use a construct like this:
=VLOOKUP(A3, INDIRECT("'" & INDEX(MySheets, MATCH(1, COUNTIF(INDIRECT("'" & MySheets &"'!A1:A50"), A3), 0)) & "'!A:B"), 2, 0)

There's a sample workbook on my site demonstrating this.


text:
Q: What is the Hadamard's Factorization of a function that has a finite number of zeros (2) The motivation to this question can be found in
What is the Hadamard's Factorization of a function that has a finite number of zeros
My question here is: I deduce that the function $h(s)$ has a finite number of roots in $(0,1)$. However how I can see that the corresponfing entire function $h(s)$ has also a finite number of roots in the whole complex plane.

A: Without knowing at least something more about $h$, you can't conclude that. The function $f(z) = \sin z$ has no zeros in $(0,1)$ but infinitely many zeros in the whole plane.


text:
Q: How to set the number of mappers in new Hadoop api? I've switched to the new Hadoop api (mapreduce) from the old one (mapred). I can't set the number of mappers in the new api. I can use job.setNumReduceTasks() to set the number of reducers but there isn't any method for number of mappers. I also tried conf.setInt("mapred.map.tasks", numMapper) and conf.setInt("mapreduce.map.tasks", numMapper) but it is not working either.

A: The number of mapper tasks is determined by the input split you have. Obviously, each part will be processed by 1 mapper. So essentially, your data determines the number of your mappers!
You can however use mapreduce.jobtracker.maxtasks.perjob to limit the parallelism (unfortunately, this affects both mappers and reducers!). But if you set this to 10, at most 10 mappers should run in parallel.
A more fine-grained control would be nice, but is an open ticket:

MAPREDUCE-5583: Ability to limit running map and reduce tasks

A: Starting from Hadoop 2.7, you can use mapreduce.job.running.map.limit and mapreduce.job.running.reduce.limit to control these at each job level.
Fixed by this JIRA ticket.

A: In YARN, one can set mapreduce.input.fileinputformat.split.minsize (its in megabytes) much higher than the blocksize of the files being read.  This will force more data through each mapper thereby reducing the number of mappers required.  However, some file formats may have their own minimum split size which takes priority over this setting.


text:
Q: Access HTML5 local storage from Angular2 I'm following this tutorial: https://medium.com/@blacksonic86/authentication-in-angular-2-958052c64492 about authentication in Angular2.
I've the issue with this part:
import localStorage from 'localStorage';
I've read somewhere else that I should use this library https://github.com/marcj/angular2-localstorage to access local storage in HTML5. Is it really the only option? Can I access HTML5 local storage from angular2 without using extra modules?

A: You can use localStorage directly in your service without import localStorage from 'localStorage';.

A: You should use directly localStorage, as mentioned by other here, it is a builtin browser features (supported browser).
Additionally I am adding below few examples on how to add an entry in it (they work both in the same way).
localStorage.colorSetting = '#a4509b';    // dot notation
localStorage['colorSetting'] = '#a4509b'; // bracket notation
localStorage.setItem('colorSetting', '#a4509b');

As a note, angular2-localstorage works on top of native localStorage and provide a "convenient" way to save and restore automatically a variable state in your directive.

A: I noticed that the local storage project is seeking someone to takeover and is not currently being maintained.  So I am not going to use it until then.  I was able to find the a fix in my tsconfig.json file.
In the property lib you can simply add dom
"lib": [
      "es2016",
      "dom"
    ]

This is supported in the compiler options https://www.typescriptlang.org/docs/handbook/compiler-options.html.
I had to restart visual studio code for this to remove the errors.


text:
Q: Error using tidyeval quo() with gather() I am trying to run gather() on data frames, and programmatically assign the .key column name using !!quo(). But I keep getting 'Error: Invalid column specification'. I even found a closed ticket where it shows that it should work (https://github.com/tidyverse/tidyr/issues/293).
I'm going to go back to using rename_() as a workaround, but it would be nice to use the more elegant NSE.
library('tidyverse')
data(mtcars)
my_var <- 'my_col_name'

The following works, but is a one-trick pony
> mtcars %>%
   as_tibble %>%
   rownames_to_column('car_make') %>%
   gather(my_col_name, values, -car_make)

# A tibble: 352 x 3
        car_make my_col_name values
           <chr>       <chr>  <dbl>
 1         Mazda RX4         mpg   21.0
 2     Mazda RX4 Wag         mpg   21.0
 3        Datsun 710         mpg   22.8
 4    Hornet 4 Drive         mpg   21.4
 5 Hornet Sportabout         mpg   18.7
 6           Valiant         mpg   18.1
 7        Duster 360         mpg   14.3
 8         Merc 240D         mpg   24.4
 9          Merc 230         mpg   22.8
10          Merc 280         mpg   19.2
# ... with 342 more rows

The following attempts to use tidyeval two give the same error:
> mtcars %>%
     as_tibble %>%
     rownames_to_column('car_make') %>%
     gather(!!quo(my_var), values, -car_make)

Error: Invalid column specification

> mtcars %>%
     as_tibble %>%
     rownames_to_column('car_make') %>%
     gather(!!enquo(my_var), values, -car_make)

Error: Invalid column specification

Library versions
tidyverse_1.1.1
dplyr_0.7.0
tidyr_0.6.3
rlang_0.1.1


text:
Q: How to ask Spring Cloud Config server to checkout configuration from specific branch? I have following Spring cloud config application.yml:
spring:
  application:
    name: configserver
  cloud:
    config:
      server:
        git:
          uri: https://xyz@bitbucket.org/xyz/microservices-configs.git
          username: xyz
          password: xyz
          basedir: target/configs
server:
  port: 8881

Following is my bootstrap.yml of user microservice:
spring:
  application:
    name: userservice
  cloud:
    config:
      uri: http://localhost:8881/

Scenario - 1
When I hit config server in browser like this:
http://localhost:8881/development/userservice-development.yml
It serves file properly. and when I look at basedir i.e. target/config, I see:
- userservice.yml
- gateway.yml

Exactly what I wanted, Since I added this two files only in development branch.
Scenario - 2
When I run my userservice microservice project using following command:
mvn clean spring-boot:run -Dspring.profiles.active=development
It fetches the right file from git, but it checkout from master branch ! but not from the development branch as I am expecting. am I expecting right ?  (FYI I have both development and production yml in master branch)
So the question is, how do we go for using config server ? Is there any configuration which we can set to fetch yml from that particular branch only ? I believe we need to set some label, because as per documentation, default label is master. Can anyone let me know how do we go for setting label in above scenario ?

A: According to the documentation, the configuration you want to set in your config client is:
spring.cloud.config.label=mybranch

Where mybranch is an existing branch in your git repo.

A: You can specify the default branch (more generally, Git label) that a config server uses if a client does not specify the label, via property spring.cloud.config.server.git.default-label, perhaps this is what you are after? Certainly solves the issue for me!

A: If only use the branch in a yml file just configure:
spring:
  cloud:
    config:
      server:
        git:
          uri: https://gitlab.com/somerepo.git
          username: someuser
          password: somepass
          default-label: branchname

A: Config server designed to use profile to separate environment.
Example:
/{application}/{profile}[/{label}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties

The branching make configuration inconsistency.
Concept of config server is based on 12-factor config  (http://12factor.net/config ) .
Check it out for detail reason.