text:
Q: Bootstrap cards underneath each other but the distance between them is way too big I'm building a quite simple webpage and it has 6 of those Bootstrap cards, 3 in a row and then it should have 3 below that. For some reason it puts an enormous gap between the first 2 cards, but not on the third one.
Here is how it looks right now (I've zoomed out so all cards are visible): https://imgur.com/FPBvYN2
and here is my code for the cards:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

Water zuivering

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis

Recyclen van restafval

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis

XXXXX XXXXX XXXXX

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis

XXXXX XXXXX 11111

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis

XXXXX XXXXX 22222

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis

XXXXX XXXXX 33333

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis

A: It might be because you're applying additional CSS. In Bootstrap you very rarely have to add any CSS when it comes to widths, paddings or margins. This can all be done in your HTML.
To start with, pretty much remove all CSS including width and height and see what it looks like. You might also find it handy to put your first 3 boxes inside a
 then a second Row for the next 3 boxes and so on.

A: Assuming you're wrapping all the code you pasted here inside a

you need to remove your inline styles. That includes both your width: 32rem and your height: auto (which you for some reason only have on some of your cards?
When you use the row/col logic from bootstrap you should not declare the width, as that is supposed to b 4/12 of your grid. Defining a width will break that.
I would furthermore advise you to place that type of code (height, width etc.) into a .css file, so you can change the values in one place instead of doing it on every card.

A: You commented out your closing
 tag here:

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis

This looks right after I removed the errant w-100 which conflicted with your width: 32rem inline style (I removed all of those). I also added the obligatory .container and .row divs which I assume you just didn't include in your question.
See the snippet below:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

Water zuivering

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu,
            pretium quis, sem. Nulla consequat massa quis

Recyclen van restafval

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu,
            pretium quis, sem. Nulla consequat massa quis

XXXXX XXXXX XXXXX

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu,
            pretium quis, sem. Nulla consequat massa quis

XXXXX XXXXX 11111

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu,
            pretium quis, sem. Nulla consequat massa quis

XXXXX XXXXX 22222

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu,
            pretium quis, sem. Nulla consequat massa quis


text:
Q: Unable to save image to database and folder using Slim Framework I am very new to PHP, I am using PHP Slim Framework. I have tried to research through Stack Overflow but didn't find an answer that answered my question.
I am trying add a car description on my school project, it captures all the fields well but the image is not being saved to the database and not being uploaded to the images folder, instead it saves the image in the database as a json as:
{
    "car_images":
    [
        {
            "file":"C:\\xampp\\tmp\\php8F2B.tmp"
        }
    ]
}

instead of a91cffe8c9b5082f.jpg.
when I try to view the image in a browser on my localhost it goes to this path:

http://localhost/carbac/public/category_image/%7B%22car_images%22:[%7B%22file%22:%22C://xampp//tmp//php8F2B.tmp%22%7D]%7D

What could I be doing wrong?
Below is my function for capturing the details:
public function add(Request $request, Response $response, $args){

    $car_category_id =  $request->getParam('car_category_id');
    $name =  $request->getParam('name');
    $description =  $request->getParam('description');
    $price = $request->getParam('price');
    $mileage =  $request->getParam('mileage');
    $fuel_type =  $request->getParam('fuel_type');
    $transmission =  $request->getParam('transmission');
    $fuel_economy =  $request->getParam('fuel_economy');
    $air_condition =  $request->getParam('air_condition');
    $hourly_price =  $request->getParam('hourly_price');
    $daily_price =  $request->getParam('daily_price');
    $year = $request->getParam('year');

    $directory = __DIR__ . '/../../../public/profile_image';

    $uploadedFiles = $request->getUploadedFiles()['category_image'];

    $avater = $request->getUploadedFiles();

    foreach($uploadedFiles as $uploadedFile) {
        if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
            $avater[] = \App\Helpers\FileUpload::moveUploadedFile($directory, $uploadedFile, ['png', 'jpeg', 'gif', 'jpg']);
        } else {

            $Flash = new Flash();
            $Flash->addMessage('message', "Sorry, something went wrong from our end, please notify site owner");
            $Flash->addMessage('status', "callout-danger");

            return $response->withRedirect($this->router->pathFor('car_description'));
        }

    }
    if( ! $avater ) {

        $Flash = new Flash();
        $Flash->addMessage('message', "Sorry, Please make image you are uploading is either a 'png', 'jpeg' or 'gif'");
        $Flash->addMessage('status', "callout-danger");

        return $response->withRedirect($this->router->pathFor('car_description'));
    }

    $car_description = CarDescription::create([
        'car_category_id' => $car_category_id,
        'name' => $name,
        'description' => $description,
        'year' => $year,
        'mileage' => $mileage,
        'price' => $price,
        'fuel_type' => $fuel_type,
        'transmission' => $transmission,
        'fuel_economy' => $fuel_economy,
        'air_condition' => $air_condition,
        'hourly_price' => $hourly_price,
        'daily_price' => $daily_price,
        'images' => json_encode($avater)
    ]);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can you overload type-casting operators in Swift? I'd like to implement automatic type conversions between known types in Swift. The C# way of doing it has been overloading type-casting operators. If I want my X type to be cross-assignable with, say, string, I would write:
public class X
{
     public static implicit operator string(X value)
     {
          return value.ToString();
     }

     public static implicit operator X(string value)
     {
          return new X(value);
     }
}

After that I could write stuff like:
string s = new X();
X myObj = s;

and they would be automatically converted. Is that possible in any way in Swift?

A: No, the language doesn't provide such functionality for custom types. There is bridging between Objective-C collections and Swift collections but that's baked in and not customizable.
// Swift array of `String` elements
let swiftArray: [String] = ["Bob", "John"]

// Obj-C array of `NSString` elements, but element type information
// is not known to the compiler, so it behaves like an opaque NSArray
let nsArray: NSArray = ["Kate", "Betty"]

// Obj-C array of an `NSString` and an `NSNumber`, element type
// information is not known to the compiler
let heterogeneousNSArray: NSArray = ["World", 3]

// Casting with `as` is enough since we're going from Swift array to NSArray
let castedNSArray: NSArray = swiftArray as NSArray

// Force casting with `as!` is required as element type information
// of Obj-C array can not be known at compile time
let castedSwiftArray: [String] = nsArray as! [String]

// Obj-C arrays can not contain primitive data types and can only
// contain objects, so we can cast with `as` without requiring a
// force-cast with `!` if we want to cast to [AnyObject]
let heterogeneousCastedNSArray: [AnyObject] = heterogeneousNSArray as [AnyObject]

Documentation for type casting is available here.
I think you can achieve what you want to do with initializers.
extension X {
    init(string: String) {
        self = X(string)
    }
}

extension String {
    init(x: X) {
        // toString is implemented elsewhere
        self = x.toString
    }
}

let x = X()
let string = "Bobby"

let xFromString: X = X(string: string)
let stringFromX: String = String(x: x)

Not directly related to your question but there is also a family of protocols that start with ExpressibleBy..., enabling you to do things like the following:
Let's say we want to initialize strings from integer literals. We can do that by conforming to and implementing ExpressibleByIntegerLiteral
// Strings can not be initialized directly from integer literals
let s1: String = 3 // Error: Can not convert value of type 'Int' to specified type 'String'

// Conform to `ExpressibleByIntegerLiteral` and implement it
extension String: ExpressibleByIntegerLiteral {
  public init(integerLiteral value: Int) {
    // String has an initializer that takes an Int, we can use that to
    // create a string
    self = String(value)
  }
}

// No error, s2 is the string "4"
let s2: String = 4

A nice use case for ExpressibleByStringLiteral can be found here.


text:
Q: How can we allocate a buffer that we are sure won't be paged? Maybe this one thing is related to buffer allocation in kernel. Suppose we want to write a music player, if paging happens, this may lead to choppy low quality music playing. Video Player, we want to write a real time software, or anything.
We want to assign one of the CPUs to a process, or we make a process very high priority, and then we want to make sure our buffer won't be paged to HDD. How is it done in C and Linux?

A: By calling:
int mlock(const void *addr, size_t len);//included in header #include <sys/mman.h>

with the start address of the area and its length, the system will garuntee that the memory specified will reside in RAM until you call
int munlock(const void *addr, size_t len);

You can also call the function mlockall(MCL_FUTURE); which will make all your following memory allocations be RAM residents but this poses the risk of allocating more than what's physically available and the result is implementation dependent.
EDIT:
For more details, check the following links:
http://pubs.opengroup.org/onlinepubs/007908799/xsh/mlock.html
http://pubs.opengroup.org/onlinepubs/007908799/xsh/mlockall.html
EDIT2: Zan Lynx's comment
Also note that using this to lock more than 64KB (on most Linux systems) will require root privileges. Best way in my opinion is to have a wrapper that launches as root, sets up relaxed real-time and memory lock requirements, switches user IDs and then runs the actual program.

P.S Normally when RT requirments arise, not only you lock your program in RAM but you also set the scheduler into real-time mode, for that you can check sched_setscheduler(..)


text:
Q: how to add zeros after decimal in Oracle I want to add zeroes after the number .
for eg  a=  6895
then a= 6895.00
datatype of a is number(12);
I am using the below code .
select to_char(6895,'0000.00')  from dual .

I m getting the desired result from above code but
'6895' can be any number.so due to that i need to add '0' in above code manually.
for eg.
select to_char(68955698,'00000000.00')  from dual .

Can any one suggest me the better method .

A: The number format models are the place to start when converting numbers to characters. 0 prepends 0s, which means you'd have to get rid of them somehow. However, 9 means:

Returns value with the specified number of digits with a leading space if positive or with a leading minus if negative. Leading zeros are blank, except for a zero value, which returns a zero for the integer part of the fixed-point number.

So, the following gets you almost there, save for the leading space:
SQL> select to_char(987, '9999.00') from dual;

TO_CHAR(
--------
  987.00

You then need to use a format model modifier, FM, which is described thusly:

FM Fill mode. Oracle uses trailing blank characters and leading zeroes
  to fill format elements to a constant width. The width is equal to the
  display width of the largest element for the relevant format model
...
The FM modifier suppresses the above padding in the return value of
  the TO_CHAR function.

This gives you a format model of fm9999.00, which'll work:
SQL> select to_char(987, 'fm9999.00') from dual;

TO_CHAR(
--------
987.00

If you want a lot of digits before the decimal then simply add a lot of 9s.

A:
datatype of a is number(12);

Then use 12 9s in the format model. And, keep the decimal to just 2. So, since the column datatype is NUMBER(12), you cannot have any number more than the given size.
SQL> WITH DATA AS(
  2  SELECT 12 num FROM dual union ALL
  3  SELECT 234 num FROM dual UNION ALL
  4  SELECT 9999 num FROM dual UNION ALL
  5  SELECT 123456789 num FROM dual)
  6  SELECT to_char(num,'999999999999D99') FROM DATA
  7  /

TO_CHAR(NUM,'999
----------------
           12.00
          234.00
         9999.00
    123456789.00

SQL>

Update Regarding leading spaces
SQL>  select ltrim(to_char(549,'999999999999.00')) from dual;

LTRIM(TO_CHAR(54
----------------
549.00

SQL>

A: With using CASE and SUBSTR it is very simple.
CASE WHEN SUBSTR(COLUMN_NAME,1,1) = '.' THEN '0'||COLUMN_NAME ELSE COLUMN_NAME END


text:
Q: Convert integer value to matching Java Enum I've an enum like this:
public enum PcapLinkType {
  DLT_NULL(0)
  DLT_EN10MB(1)
  DLT_EN3MB(2),
  DLT_AX25(3),
  /*snip, 200 more enums, not always consecutive.*/
  DLT_UNKNOWN(-1);
    private final int value;

    PcapLinkType(int value) {
        this.value= value;
    }
}

Now I get an int from external input and want the matching input - throwing an exception if a  value does not exist is ok, but preferably I'd have it be DLT_UNKNOWN  in that case.
int val = in.readInt();
PcapLinkType type = ???; /*convert val to a PcapLinkType */

A: I know this question is a few years old, but as Java 8 has, in the meantime, brought us Optional, I thought I'd offer up a solution using it (and Stream and Collectors):
public enum PcapLinkType {
  DLT_NULL(0),
  DLT_EN3MB(2),
  DLT_AX25(3),
  /*snip, 200 more enums, not always consecutive.*/
  // DLT_UNKNOWN(-1); // <--- NO LONGER NEEDED

  private final int value;
  private PcapLinkType(int value) { this.value = value; }

  private static final Map<Integer, PcapLinkType> map;
  static {
    map = Arrays.stream(values())
        .collect(Collectors.toMap(e -> e.value, e -> e));
  }

  public static Optional<PcapLinkType> fromInt(int value) {
    return Optional.ofNullable(map.get(value));
  }
}

Optional is like null: it represents a case when there is no (valid) value. But it is a more type-safe alternative to null or a default value such as DLT_UNKNOWN because you could forget to check for the null or DLT_UNKNOWN cases. They are both valid PcapLinkType values! In contrast, you cannot assign an Optional<PcapLinkType> value to a variable of type PcapLinkType. Optional makes you check for a valid value first.
Of course, if you want to retain DLT_UNKNOWN for backward compatibility or whatever other reason, you can still use Optional even in that case, using orElse() to specify it as the default value:
public enum PcapLinkType {
  DLT_NULL(0),
  DLT_EN3MB(2),
  DLT_AX25(3),
  /*snip, 200 more enums, not always consecutive.*/
  DLT_UNKNOWN(-1);

  private final int value;
  private PcapLinkType(int value) { this.value = value; }

  private static final Map<Integer, PcapLinkType> map;
  static {
    map = Arrays.stream(values())
        .collect(Collectors.toMap(e -> e.value, e -> e));
  }

  public static PcapLinkType fromInt(int value) {
    return Optional.ofNullable(map.get(value)).orElse(DLT_UNKNOWN);
  }
}

A: As @MeBigFatGuy says, except you can make your static {...} block use a loop over the values() collection:
static {
    for (PcapLinkType type : PcapLinkType.values()) {
        intToTypeMap.put(type.getValue(), type);
    }
}

A: There's a static method values() which is documented, but not where you'd expect it: http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
enum MyEnum {
    FIRST, SECOND, THIRD;
    private static MyEnum[] allValues = values();
    public static MyEnum fromOrdinal(int n) {return allValues[n];}
}

In principle, you can use just values()[i], but there are rumors that values() will create a copy of the array each time it is invoked.

A: You could add a static method in your enum that accepts an int as a parameter and returns a PcapLinkType.
public static PcapLinkType of(int linkType) {

    switch (linkType) {
        case -1: return DLT_UNKNOWN
        case 0: return DLT_NULL;

        //ETC....

        default: return null;

    }
}

A: This is what I use:
public enum Quality {ENOUGH,BETTER,BEST;
                     private static final int amount = EnumSet.allOf(Quality.class).size();
                     private static Quality[] val = new Quality[amount];
                     static{ for(Quality q:EnumSet.allOf(Quality.class)){ val[q.ordinal()]=q; } }
                     public static Quality fromInt(int i) { return val[i]; }
                     public Quality next() { return fromInt((ordinal()+1)%amount); }
                    }

A: You will have to make a new static method where you iterate PcapLinkType.values() and compare:
public static PcapLinkType forCode(int code) {
    for (PcapLinkType typе : PcapLinkType.values()) {
        if (type.getValue() == code) {
            return type;
        }
    }
    return null;
 }

That would be fine if it is called rarely. If it is called frequently, then look at the Map optimization suggested by others.

A: You would need to do this manually, by adding a a static map in the class that maps Integers to enums, such as
private static final Map<Integer, PcapLinkType> intToTypeMap = new HashMap<Integer, PcapLinkType>();
static {
    for (PcapLinkType type : PcapLinkType.values()) {
        intToTypeMap.put(type.value, type);
    }
}

public static PcapLinkType fromInt(int i) {
    PcapLinkType type = intToTypeMap.get(Integer.valueOf(i));
    if (type == null)
        return PcapLinkType.DLT_UNKNOWN;
    return type;
}

A: if you have enum like this
public enum PcapLinkType {
  DLT_NULL(0)
  DLT_EN10MB(1)
  DLT_EN3MB(2),
  DLT_AX25(3),
  DLT_UNKNOWN(-1);

    private final int value;

    PcapLinkType(int value) {
        this.value= value;
    }
}

then you can use it like
PcapLinkType type = PcapLinkType.values()[1]; /*convert val to a PcapLinkType */

A: You can do something like this to automatically register them all into a collection with which to then easily convert the integers to the corresponding enum. (BTW, adding them to the map in the enum constructor is not allowed. It's nice to learn new things even after many years of using Java. :)
public enum PcapLinkType {
    DLT_NULL(0),
    DLT_EN10MB(1),
    DLT_EN3MB(2),
    DLT_AX25(3),
    /*snip, 200 more enums, not always consecutive.*/
    DLT_UNKNOWN(-1);

    private static final Map<Integer, PcapLinkType> typesByValue = new HashMap<Integer, PcapLinkType>();

    static {
        for (PcapLinkType type : PcapLinkType.values()) {
            typesByValue.put(type.value, type);
        }
    }

    private final int value;

    private PcapLinkType(int value) {
        this.value = value;
    }

    public static PcapLinkType forValue(int value) {
        return typesByValue.get(value);
    }
}

A: static final PcapLinkType[] values  = { DLT_NULL, DLT_EN10MB, DLT_EN3MB, null ...}

...

public static PcapLinkType  getPcapLinkTypeForInt(int num){
    try{
       return values[int];
    }catch(ArrayIndexOutOfBoundsException e){
       return DLT_UKNOWN;
    }
}

A: This might not be a great solution, but its working for me:
public enum Type {
        WATER, FIRE, GRASS;

        public static Type getType(int value){
            if(value==WATER.ordinal()){
                return WATER;
            }else if(value==FIRE.ordinal()){
                return FIRE;
            }else if(value==GRASS.ordinal()){
                return GRASS;
            }else {
                return null;
            }
        }
    }

A: There is no way to elegantly handle integer-based enumerated types. You might think of using a string-based enumeration instead of your solution. Not a preferred way all the times, but it still exists.
public enum Port {
  /**
   * The default port for the push server.
   */
  DEFAULT("443"),

  /**
   * The alternative port that can be used to bypass firewall checks
   * made to the default <i>HTTPS</i> port.
   */
  ALTERNATIVE("2197");

  private final String portString;

  Port(final String portString) {
    this.portString = portString;
  }

  /**
   * Returns the port for given {@link Port} enumeration value.
   * @return The port of the push server host.
   */
  public Integer toInteger() {
    return Integer.parseInt(portString);
  }
}


text:
Q: Why does printf("%%") print only one percent (%) symbol? When I run this following code:
#include <stdio.h>
#include <conio.h>

void main(){
    clrscr();
    printf("%%");
    getch();
}

I get % as an output?
What might be the reason behind this logic?

A: That is what printf does: it is print formatted (f for formatted). It uses % as the formatting character. It is the only reserved character and needs to be escaped to represent it self, i.e. %%. See the manual for more information on formatting: printf.
P.S.: Never use a string that is not a part of the program as the first argument. To print a string message that was input by a user, do printf(%s, message);. Otherwise you will have a security hole in your code.

A: % comes into format specifiers.
Example
When we write printf("%d", 20);, it will print 20 rather than %d. because the compiler treats % as a format specifier. In the mind of the compiler, the meaning of % is somewhat special.
So if you want that "%" should be the output, then you must write printf("%%"). Here the first % sign will suppress the meaning of the % format specifier and will print % as an output.

A: From the standard ISO/IEC 9899:1999 (E)
7.19.6.1
Each conversion specification is introduced by the character %.
The conversion specifiers and their meanings are:
% - A % character is written. No argument is converted. The complete
 conversion specification shall be %%.

A: For C printf, % is a special character which typically indicates a parameter to substitute at that position: printf("Hello, %s\n", "World!"); results in "Hello, World!". There are lots of different things you can put after the % depending on the data you want to output. So that leaves the problem of "What if I want to print a percent symbol"?
The solution: Use %%.
The same is true of the special escape character \. "\n" means to print a new line.  If you want to actually print the forward slash, you have to put it twice \\
See Printf format string and MSDN.


text:
Q: Generics and inheritance with bounds In following code:
class BaseT {}

class Base<T extends BaseT> {}

class CLass1T extends BaseT {}

class Class1<T extends Class1T> extends Base<T> {}

I would like:
a) class Class1 should inherit class Base and parameter in bounds should be passed to class Base (It is done in this code)
b) Class1 should have parameter Class1T in their code, not T. Something like this:
class Class1<T> extends Base<Class1T> {}

c) Class1 should be opened to inheritance. Example:
class CLass2T extends CLass1T {}

class Class2 extends CLass1<Class2T> {}

How to do this? Is it possible?

A: This is your solution. If I understand correctly your requirement "open for inheritance".
class Class1<T extends Class1T> extends Base<T> {}


text:
Q: Test Facebook Graph API without Page Public Content Access permission Is there a way to test an app implemented Facebook Graph API required Page Public Content Access permission?
I was testing the {page_id}_{post_id} endpoint in Facebook Graph API Explorer to get a post, but got the error message:
This endpoint requires the 'pages_read_engagement' permission or the 'Page Public Content Access' feature. Refer to https://developers.facebook.com/docs/apps/review/login-permissions#manage-pages and https://developers.facebook.com/docs/apps/review/feature#reference-PAGES_ACCESS for details.

This error applies to both random pages and pages that I own. I couldn't use it at all. The app I've planned to do is mostly based on Facebook posts so I may say this is it's the main function, so I just can't have the app reviewed until I can test this endpoint successfully.
What can I do to make it work? Any help would be appreciated!

A: It turns out I chose the wrong type to create my facebook app. I chose to create a "Business Connected Experiences" app instead of a "Manage Business Integrations" one, so I couldn't fully access to the permissions I need to query on my own page. The former only doesn't provide me the pages_user_read_content and the likes, so it was unable for me to read comments from posts. Besides, I also use an user token instead of a page token (Thanks Lars for pointing this out for me).
So, I just create a new app with the right type and everything turns out well.
Hope this will help someone someday.


text:
Q: Python: RRuntimeError: Error in (function (data = NA, dim = length(data), dimnames = NULL) : 'dims' cannot be of length 0 I am trying to call R functions from python but for some reason which I do not know yet, I am getting an RRuntimeError when I am converting a numeral to R rather than a matrix (Dataframe) to R
For example, consider the following simple example
import rpy2.robjects as robjects, pandas as pd, numpy as np
from rpy2.robjects import r
from rpy2.robjects.numpy2ri import numpy2ri
from rpy2.robjects.packages import importr

df= pd.DataFrame(np.random.random((108, 2)), columns=['Number1','Number2'])
p = 3

resi1=np.array(df, dtype=float)
p1=np.array(p, dtype=float)

r_resi = numpy2ri(resi1)
r_p1= numpy2ri(p1)

Then the Output is
---------------------------------------------------------------------------
RRuntimeError                             Traceback (most recent call last)
<ipython-input-1-7970a0b7c100> in <module>()
     11
     12 r_resi = numpy2ri(resi1)
---> 13 r_p1= numpy2ri(p1)

D:\Anaconda3\lib\site-packages\rpy2\robjects\numpy2ri.py in numpy2ri(o)
     80         #FIXME: no dimnames ?
     81         #FIXME: optimize what is below needed/possible ? (other ways to create R arrays ?)
---> 82         res = rinterface.baseenv['array'](vec, dim=dim)
     83     # R does not support unsigned types:
     84     elif o.dtype.kind ==

 "u":

RRuntimeError: Error in (function (data = NA, dim = length(data), dimnames = NULL)  :
  'dims' cannot be of length 0

I am not sure what is going wrong here?

A: The converter numpy array -> R array needs needs the dimension of the array. There is none here:
>>> p1
array(3.0)
>>> p1.shape
()


text:
Q: $.AJAX Post not working in JS but works in Advanced Rest Client I'm having an issue with my JavaScript being able to contact the HttpPost service. I can access the same signature using the "Advance Rest Client Application" for chrome. However when I run my code in Console in Chrome I am unable to reach the service. Any thoughts? What am I missing from the signature on one vs the other? Please let me know if you need any more information.
JS AJAX Request (Stuck in Pending status)
    $.ajax({
        type: 'POST',
        url: 'http://local/r/GetSettings',
        data: '[{"SourceId":7,"DataType":0},{"SourceId":5,"DataType":1}]',
        dataType: "json",
        success: function(data){
            alert(data)
        },
        error : function (error) {
            alert("Error: " + error);
            console.log("ERROR. not working", error);
        }
    });

C# Service
    [HttpPost]
    public ActionResult GetSettings(List<Source> sources)
    {
        return new ContentResult
        {
            Content = "{}",
            ContentType = "application/json"
        };

     }

Advanced Rest Client Application (Success in returning {})
    http://local/r/GetSettings
    Content-Type: application/x-www-form-urlencoded
    Payload::: [{"SourceId":7,"DataType":0},{"SourceId":5,"DataType":1}]

A: Change your URL for ajax request
AppContextRootName: Your application context root
$.ajax({
     type : 'POST',
     url : '/AppContextRootName/GetSettings',
     dataType : 'json'
});

A: Thanks for the answers. I found out my issue why the Ajax call was not executing. I found out you can execute a AJAX statement while paused in the debugger!!! So don't try! It will execute and return and object but it will show pending in the network. Once you unpause the actual call is executed. You should just use Alert("Hello world") in the success and error and you will see it come back once you unpause.


text:
Q: How to enable Alert manager pick alert manager configs from a new kubernetes namespace? Alertmanager(kind: Alertmanager) is running in prometh namespace.
We have access to push alert rule definitions(kind: PrometheusRule) to prometh namespace, with additional labels in alert payload(sourceNamespace & destinationNamespace), as shown below:
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
  labels:
    prometheus: service-prometheus
    role: alert-rules
    app: kube-prometheus-stack
    release: monitoring-prom
  name: rule_a
  namespace: monitoring
spec:
  groups:
    - name: rule_a_alert
      rules:
        - alert: usage_exceed
          expr: salesforce_api_usage > 100000
          labels:
            severity: urgent
            sourceNamespace: app-dev
            destinationNamespace: prometh

Value of sourceNamespace indicate the namespace where application pods are running.
We have alert manager config(kind: AlertmanagerConfig) that match with rule definition(above) using below syntax:
route:
  routes:
  - match:
      severity: urgent

but we do not have access to push alert manager config into prometh namespace. we have access to push alert manager config only into app-dev

Is it possible to start alert manager, by enabling it to register new alertmanager configs from a new sourceNamespace in runtime? with alertmanager.alertmanagerSpec.alertmanagerConfigNamespaceSelector field
Related discussion: https://issueexplorer.com/issue/prometheus-operator/prometheus-operator/4263


text:
Q: Rails Server is not finishing inside terminal I am new to Rails  and working my way through RonR3 Tutorial. Everything has worked perfectly except by page 59
$ rails generate scaffold Micropost content: String user_id:integer.

When I try to run rails s or rails server my terminal application never seems to end. When I ctrl-c to shut down the server after 10+ hours the site can not be found on localHost. Any help would be much appreciated.
Everything seems to stall out around:
Started GET "/assets/users.js?body=1" for 127.0.0.1 at 2012-09-20 13:33:54 -0400
Served asset /users.js - 304 Not Modified (0ms)

Started GET "/assets/jquery_ujs.js?body=1" for 127.0.0.1 at 2012-09-20 13:33:54 -0400
Served asset /jquery_ujs.js - 304 Not Modified (0ms)

After this the terminal just sits there doing nothing...

A: With programs run from the terminal, they will run there unless they stop or have a daemon option. When you press ctrl-c, the rails webbrick server stops, so of course localhost won't show anything.
When the server is sitting there, it's waiting for a user to visit the site. It won't render views, for example, unless there's a request to render views.
If you want to run the webserver while still using the same terminal window, you need to run rails s as a daemon (background process). Instead, run the command as rails s -d which will "detach" the server process.
On a side-note, why not open multiple terminal windows, if your operating system has a GUI/Window Manager. I normally keep three terminal windows open to run the server, make git commits, check rake routes, etc.
Related Question: Running Webrick server in background?


text:
Q: iFrame alternative for getting cross-domain URL I'm creating a web-based game. As a part of it, the player must go to the home page of a website, and follow a series of link until he reaches to the "destination page" in the minor time possible. Think of it as a sort of link treasure hunt.
In order to control the game, I created a page with a javascript timer on the top, and an iFrame showing the website to surf (which is not mine and I have no control over it).
However this has a huge fault: it is not possible to detect the current cross-domain URL of the iFrame, so my page cannot know when the user has arrived to the destination page and stop the game.
Is there any alternative way I could achieve this?

A: You can wait upto the contentWindow of the iFrame is resolved and you have a reference to the iFrame's window, after you changed the source pragmatically.
once you have that, you can add a onload handler on iFrame's <body> and inject some postMessage call inside that handler, so once the body is loaded of the iFrame's window it wil call postMessage from the onload handler of body and it will notify your outer window, of-course you have to add message listener in outer window using window.addEventListener("message", callback)

A:
Is there any alternative way I could achieve this?

No, there is not.
The Same Origin Policy completely prevents you from accessing properties of any window object that displays content from another domain.
(If one was a subdomain of the other, then document.domain would help. But from your problem description it doesn't sound like that was the case.)

And besides the technical issue: Generating traffic and clicks (that will skew their statistics/analytics) on a site that you don't own, just for the purpose of being able to present your own game, would be rather unfair (aka a "dick move".)


text:
Q: Android OpenGL stuttering - vsync? I've a Problem with my Rendering Loop. During moving object's I see a Little stutter that Looks like eglSwapBuffers swap's same buffer twice. My FPS is constantly between 59 - 60 FPS. The movement takes deltaTime into account at calculate new Position.
What could that be ??? Could double buffering solve this Problem ???
Here is a small Video ( hopefully you'll see what I mean ).
http://youtu.be/bQYiqHUzPuI
Here is my Rendering Loop
BOOL CEngine::OnStep()
{
    BOOL    bResult = TRUE;
    UINT32  u32CurrFrameStartTime = GetTime();
    FLOAT32 f32DeltaTime;

    f32DeltaTime = ( u32CurrFrameStartTime - m_u32LastFrameStartTime ) / 1000000000.0f;
    m_u32LastFrameStartTime = u32CurrFrameStartTime;

    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
    GLERROR();

    if ( m_pScreenBase == NULL )
    {
        if ( eglSwapBuffers( m_pDisplay, m_pSurface ) == EGL_FALSE )
        {
            LogError( "eglSwapBuffers function failed." );
        }

        if ( ( m_pScreenBase = new CStartScreen() ) == NULL )
            LogError( "Can't allocate memory for CStartScreen." );

        m_pScreenBase->Initialize();
    }

    m_pScreenBase->Update( f32DeltaTime );
    m_pScreenBase->Render();

    if ( eglSwapBuffers( m_pDisplay, m_pSurface ) == EGL_FALSE )
    {
        LogError( "eglSwapBuffers function failed." );
    }

    m_i32FramesPerSecond += 1;

    if ( GetTime() - m_u32FPSResetTimer >= 1000000000 )
    {
        LogFPS( "%d", m_i32FramesPerSecond );
        m_i32FramesPerSecond = 0;
        m_u32FPSResetTimer = GetTime();
    }

    // return false when app should be exit
    return bResult;
}

Here is the update function
void CStartScreen::Update( FLOAT32  f32DeltaTime )
{
    for ( INT32 i = 0; i < MAX_SQUARES; i++ )
    {
        m_pSquare[ i ]->IncPosX( ( 400.0f * f32DeltaTime ) );

        if ( m_pSquare[ i ]->GetPosX() >= 800.0f )
        {
            m_pSquare[ i ]->IncPosX( -( 800.0f + m_pSquare[ i ]->GetWidth() ) );
        }
    }
}

If it's needed, I can post my EGL and OpenGL Setup too.
UPDATE 1 :
UINT32 is defined as
typedef unsigned int            UINT32;
inline UINT32 GetTime()
{
    timespec    sTime;
    UINT32      u32Return = 0;

    clock_gettime( CLOCK_MONOTONIC, &sTime );
    u32Return = ( sTime.tv_sec * 1000000000LL ) + sTime.tv_nsec;

    return u32Return;
}

And here is the delta time for 1 second
f32DeltaTime : 0.012029
f32DeltaTime : 0.016487
f32DeltaTime : 0.016548
f32DeltaTime : 0.023608
f32DeltaTime : 0.017631
f32DeltaTime : 0.023363
f32DeltaTime : 0.012963
f32DeltaTime : 0.026373
f32DeltaTime : 0.016470
f32DeltaTime : 0.012811
f32DeltaTime : 0.016439
f32DeltaTime : 0.016852
f32DeltaTime : 0.025931
f32DeltaTime : 0.012679
f32DeltaTime : 0.013243
f32DeltaTime : 0.014694
f32DeltaTime : 0.016561
f32DeltaTime : 0.016589
f32DeltaTime : 0.020299
f32DeltaTime : 0.014101
f32DeltaTime : 0.016626
f32DeltaTime : 0.016892
f32DeltaTime : 0.016347
f32DeltaTime : 0.018130
f32DeltaTime : 0.019623
f32DeltaTime : 0.012288
f32DeltaTime : 0.016677
f32DeltaTime : 0.016895
f32DeltaTime : 0.016405
f32DeltaTime : 0.018474
f32DeltaTime : 0.017564
f32DeltaTime : 0.014213
f32DeltaTime : 0.016659
f32DeltaTime : 0.016830
f32DeltaTime : 0.016486
f32DeltaTime : 0.018657
f32DeltaTime : 0.026178
**f32DeltaTime : 0.006349**
f32DeltaTime : 0.014091
f32DeltaTime : 0.016504
f32DeltaTime : 0.016617
f32DeltaTime : 0.024325
f32DeltaTime : 0.013866
f32DeltaTime : 0.015417
f32DeltaTime : 0.014500
f32DeltaTime : 0.016950
f32DeltaTime : 0.016418
f32DeltaTime : 0.018194
f32DeltaTime : 0.016803
f32DeltaTime : 0.017097
f32DeltaTime : 0.013594
f32DeltaTime : 0.016732
f32DeltaTime : 0.016599
f32DeltaTime : 0.017600
f32DeltaTime : 0.021286
f32DeltaTime : 0.012039
f32DeltaTime : 0.016735
f32DeltaTime : 0.017146
f32DeltaTime : 0.020083

Not sure but i think the line " f32DeltaTime : 0.006349 " could be the problem... But why f32DeltaTime is so small in some Frames ??? Does eglSwapBuffers does nothing at this Frame ??? But why ??? Question over question :)

A: It looks like your time base is in nanoseconds but held in a 32-bit integer.  If you're pulling values out of clock_gettime() in your GetTime() function, you'll need both seconds and nanoseconds, and should be holding it in a 64-bit integer.  Otherwise time will occasionally leap backward when you compute a delta.
For example, if you're only using tv_nsec:

*

*previous frame start time is 0s 900000ns

*current frame start time is 1s 100000ns

If you just subtract the nanoseconds, you'll get a backward leap of 800000ns, instead of a forward step of 200000ns.
You can check this by logging the f32DeltaTime values to see if they're consistent.


text:
Q: Error "Maximum Characters Exceeded in SQL Statement EDIT: Issue Displaying Table Thank you for helping. I am brand new to SQL programming (as in, this is my first assignment) and I completely don't understand why this is not working.
My goal is just to make this into a simple table. I was asked to use the SWL interpreter from sqlcourse.com, and when I put in the program I get the error "Maximum characters exceeded in SQL statement." Each time I check my statement I'm missing where the error is. Help please?
My Statement:
create table Marchetta1
(CustomerNum number(15), CustomerName char(15),
 Street varchar(15), City char(15),
 State char(2), Zip number(5), Balance number (8,2),
 CreditLimit number (8,2), RepNum varchar (5));

insert into Marchetta1
(CustomerNum, CustomerName, Street, City,
State, Zip, Balance, CreditLimit, RepNum)
values ('123', 'Bob Smith', '8215 Cherry St', 'Grove', 'FL', '33331', '500.23', '1000', 'FP123');

insert into Marchetta1 (CustomerNum, CustomerName, Street,
City, State, Zip, Balance, CreditLimit, RepNum)
values ('456', 'Lucy James', '4711 Ohio St', 'Chicago', 'IL', '60644',
'7000.44', '5000.80', 'FP123');

insert into Marchetta1 (CustomerNum, CustomerName, Street,
City, State, Zip, Balance, CreditLimit, RepNum)
values ('789', 'John Jones', '925 Main St', 'Grove', 'FL', '33385', '87.50', '2000.72', 'FP123');

EDIT: The fixes seemed to work and the commands are executed...but I have no way to check since my table is not displaying. How do I do that?
Thanks.

A:
"Maximum characters exceeded in SQL statement."

That's the problem.  Your SQL statement is too long.
What you have there are four different SQL statements.  You should be entering them one-by-one.

A: Just a note, while inserting 'number' values into the table, they're usually entered without inverted commas. For e.g. values (123, 'Bob Smith'....)


text:
Q: Aggregation function for Counting of Duplicates in a field based on duplicate items in another field I am using mongoengine as ORM with flask application. The model class is define like
class MyData(db.Document):
    task_id = db.StringField(max_length=50, required=True)
    url = db.URLField(max_length=500,required=True,unique=True)
    organization = db.StringField(max_length=250,required=True)
    val = db.StringField(max_length=50, required=True)

The field organization can be repeating and I want to get the count of duplicates with respect to values in another field. For example if the data in mongodb is like
[{"task_id":"as4d2rds5","url":"https:example1.com","organization":"Avengers","val":"null"},
 {"task_id":"rfre43fed","url":"https:example1.com","organization":"Avengers","val":"valid"},
 {"task_id":"uyje3dsxs","url":"https:example2.com","organization":"Metro","val":"valid"},
 {"task_id":"ghs563vt6","url":"https:example1.com","organization":"Avengers","val":"invalid"},
 {"task_id":"erf6egy64","url":"https:example2.com","organization":"Metro","val":"null"}]

Then I am querying all the objects using
data = MyData.objects()

I want a response like
[{"url":"https:example1.com","Avengers":{"valid":1,"null":1,"invalid":1}},{"url":"https:example2.com",Metro":{"valid":1,"null":1,"invalid":0}}]

I tried like
db.collection.aggregate([
  {
    "$group": {
      "_id": "$organization",
      "count": [
        {
          "null": {
            "$sum": 1
          },
          "valid": {
            "$sum": 1
          },
          "invalid": {
            "$sum": 1
          }
        }
      ]
    }
  }
])

but I am getting an error
The field 'count' must be an accumulator object

A: Maybe something like this:
db.collection.aggregate([
{
  "$group": {
  "_id": {
    k: "$organization",
    v: "$val"
   },
  "cnt": {
    $sum: 1
   }
  }
 },
 {
  $project: {
    _id: 0,
    k: "$_id.k",
    o: {
      k: "$_id.v",
      v: "$cnt"
    }
   }
  },
 {
   $group: {
    _id: "$k",
    v: {
      $push: "$o"
    }
  }
},
{
  $addFields: {
    v: {
      "$arrayToObject": "$v"
    }
  }
},
{
  $project: {
    _id: 0,
    new: [
      {
        k: "$_id",
        v: "$v"
      }
    ]
  }
},
{
  "$addFields": {
    "new": {
      "$arrayToObject": "$new"
    }
  }
},
{
 "$replaceRoot": {
   "newRoot": "$new"
 }
}
])

Explained:

*

*Group to count

*Project for arrayToObject

*Group to join the values

*arrayToObject one more time

*project additionally

*arrayToObject to form the final object

*project one more time

*replaceRoot to move the object to root.

P.S.
Please, note this solution is not showing the missing values  if they do not exist , if you need the missing values additional mapping / mergeObjects need to be added
playground1
Option with missing values ( if possible values are fixed to null,valid,invalid) :
just replace the second addFiedlds with:
   {
   $addFields: {
     v: {
    "$mergeObjects": [
      {
        "null": 0,
        valid: 0,
        invalid: 0
      },
      {
        "$arrayToObject": "$v"
      }
    ]
   }
  }
 }

playground2
++url:
playground3


text:
Q: Selenium hanging and timing out on basic page interactions on OWA. I'm using Selenium with a local FireFox browser to access live.com's spam box and read the email. For testing purposes, I've been using "binding.pry" to interact with my script and see where the problems are.
When I try to find the element representing an inbox message:
driver.find_element(:css,"#messageListContentContainer .ia_hc")

I get this error after 60 seconds:
Timeout::Error: execution expired
from /usr/lib/ruby/1.8/timeout.rb:64:in `rbuf_fill'

But, as I'm in Pry, I can quickly repeat the same command. After about 5 or 10 seconds, it finds the element.
Obviously I can get around the problem by putting a before, rescue, retry block around the call, but that means I'll have to wait 70-80 seconds to click a single email. Does anyone have any idea why find_element is taking so long that it times out, or why it doesn't time out the second time? Is it because the live.com (called "Outlook Mail" on the website) has a huge ammount of elements to search through? Is it something with the JavaScript they are using?
I've been able to duplicate this issue with both Firefox and PhantomJS
UPDATE:: I've found this is happening with all of the calls after any page refresh. I can call driver.page_source and I have the same problem. It seems selenium can't interact with the browser for a certain period of time after the page has refreshed. Could it be that selenium is having trouble reading everything off of the web page?

A: I have seen this happen in my own tests, but on an intermittent basis, and never completely reproducible. What seems to happen is that Selenium WebDriver just becomes blocked and unresponsive.
I know that I have just had to resort to rescuing the error, logging, and retrying in my code. After a few retrys, Selenium WebDriver seems to become responsive again and I'm able to continue on in my tests from there.
I have contacted the maintainer of the Ruby WebDriver gem, and he needs a reproducible test to be able to do some solid debugging. If you are able to provide a reproducible test case, please share it with us so that we can look into this issue. You can use this gist as a starting point to share with the community.

A: The problem just magically disappeared. It's not happening anymore and I can't duplicate it. Best of luck to the selenium crew finding it, it seems to come and go randomly.


text:
Q: AES Encyrption In MySQL odd table display hi I have some AES encrypted fields in my database encrypted like
AES_ENCRYPT(data, 'key')
but in the database they now look like they have lots of quesitons marks and such like in them
any ideas what I have done wrong?

A: You should store the data in a VARBINARY or BLOB column.  By using a text column, the client, and possibly the database at some times, is trying to convert the binary, non-text data to text.  The question marks are a result of that when the binary data doesn't match to a text character.


text:
Q: Parcelable is really usefull? I tried to send a parcel from the mainActivity to a fragment and i noticed a strange effect.
When you implement parcelable, android require to implement "writeToParcel" and "describeContents".
The strange effect is, if you write something inside "writeToParcel" or nothing, it doesn't matter. Android never call it.
Why these functions are required ?
Here is a working source code :
public class Movie implements Parcelable {
    private String title;
    private Float score;

    public Movie(String title, float score) {
        this.title = title;
        this.score = score;
    }

...... Getter and Setter......
    //Parcelable Methods

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        // Don't need to write anything in this area
        /*
        dest.writeString(title);
        dest.writeFloat(score);
        */
    }

    public static final Parcelable.Creator<Movie> CREATOR = new Parcelable.Creator<Movie>() {
//--------------> You can return null, it's never called and work perfectly!
        public Movie createFromParcel(Parcel in) {
            return null;//new Movie(in);
        }

        public Movie[] newArray(int size) {
            return null;//new Movie[size];
        }
    };
}

Any idear ?
Regards,


text:
Q: How to pass struct as argument from one contract to another contract I can pass array, uint, bool mappings from one contract to another contract. but I can not pass struct as argument,
//SPDX-License-Identifier: UNLICENSED

pragma solidity 0.8.11;

interface SampleInterface {
        struct Point {
                uint256 x;
                uint256 y;
        }
        function setPoint(Point memory) external;
        function getPoint() external view returns(Point memory);
}

contract Sample is SampleInterface {
    Point point;
    function setPoint(Point memory _point) external {
        point = _point;
    }

    function getPoint() external view returns(Point memory) {
        return point;
    }
}

This is my source contract. I have deployed the above contract and put the contract address into the following contract to call setPoint and getPoint,
//SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.11;

interface SampleInterface {
    struct Point {
        uint256 x;
        uint256 y;
    }
    function setPoint(Point memory point) external;
    function getPoint() external view returns(Point memory);
}
contract Operator {
    address sample;
    constructor(address _sample) {
        sample = _sample;
    }

    function setPoint(Point memory point) external {
        SampleInterface(sample).setPoint(point);
    }

    function getPoint() external view returns(Point memory) {
        return SampleInterface(sample).getPoint();
    }
}

But I am getting the following error,
Compiling your contracts...
===========================
> Compiling ./contracts/Operator.sol

DeclarationError: Identifier not found or not unique.
  --> project:/contracts/Operator.sol:18:20:
   |
18 |    function setPoint(Point memory point) external {
   |                      ^^^^^

Compilation failed. See above.
Truffle v5.5.9 (core: 5.5.9)
Node v12.14.0

Help me to fix this issue. How can I call setPoint and getPoint from Operator contract.

A: The Point structure doesn't exist in the scope of your contract, only in the interface that you've declared. To fix this issue, you need to use SampleInterface.Point instead of Point.
function setPoint(SampleInterface.Point memory point) external {
    SampleInterface(sample).setPoint(point);
}

function getPoint() external view returns(SampleInterface.Point memory) {
    return SampleInterface(sample).getPoint();
}


text:
Q: How to use Promise's reject? As the documentation says
resolve is

The Promise.resolve(value) method returns a Promise object that is
  resolved with the given value.

reject is

The Promise.reject(reason) method returns a Promise object that is
  rejected with the given reason.

I understand the uses of resolve but what will be the uses of reject and when to use it ?

A: Promise.reject is promise's way of throwing errors. Usually you would have a condition inside of your promise:
const user = {
    name: 'John',
    age: 17
}

const p = new Promise((resolve, reject) => {
    if (user.age > 18) {
        resolve('Welcome!');
    } else {
        reject(new Error('Too young!'));
    }
});

You can then chain then and catch methods to handle the results of resolve and reject respectively.
p.then(message => {
    console.log(message); // 'Welcome!', if promise resolves, won't work with age of 17
})
.catch(err => {
    console.error(err); // 'Too young!', because promise was rejected
});

A: Here are few examples this statement can be used for:
Function defined to return a Promise, however you perform some sync checks and would like to return an error:
function request(data) {
   if (!data) return Promise.reject("Empty data!");
   // other logic
}

Unit tests, for example you would like to test that default data is used if service returns error (rejected promise):
const mockService = mock(Service);
// mock request method to return rejected promise
when(mockService.performRequest()).thenReturn(Promise.reject("Failed!"));

// inject mock instance and check that default data used if service failed
const sut = new ClassUnderTest(mockService);
expect(sut.getData()).to.eq("Default data");


text:
Q: UIView transitionWithView: not working I'm making a layout editor for a comic book app. The page of the comic book is divided into rows and then each row has at least one column. When the user performs a vertical swipe over a column, it's supposed to divide into two separate columns. This part already works fine, but I wanted to add a simple curl-up transition for that using +transitionWithView:. Everything still works fine (the column divides nicely) but there's no animation. Here's the code:
- (void)divideColumnView:(CCLayoutColumnView *)columnView atPoint:(CGPoint)_divisionPoint {
// divides a single column into two smaller ones

// define frames for new columns
CGRect frameLeft = columnView.frame;
CGRect frameRight = frameLeft;
CGFloat width = _divisionPoint.x - frameLeft.origin.x;
frameLeft.size.width = width;
frameRight.size.width -= width;
frameRight.origin.x += width;

// set up the container for transition
UIView *rowView = [columnView superview];
UIView *containerView = [[UIView alloc] initWithFrame:columnView.frame];
[rowView addSubview:containerView];

// move the column to the container
columnView.frame = [containerView convertRect:columnView.frame fromView:rowView];
[containerView addSubview:columnView];

// set up columns that will be inserted to the container during transition
CCLayoutColumnView *leftColumnView = [[CCLayoutColumnView alloc] initWithFrame:[containerView convertRect:frameLeft fromView:rowView]];
CCLayoutColumnView *rightColumnView = [[CCLayoutColumnView alloc] initWithFrame:[containerView convertRect:frameRight fromView:rowView]];

[UIView transitionWithView:containerView
                  duration:0.5
                   options:UIViewAnimationOptionTransitionCurlUp
                animations:^{
                    [columnView removeFromSuperview];
                    [containerView addSubview:leftColumnView];
                    [containerView addSubview:rightColumnView];
                }
                completion:^(BOOL finished){
                    // add columns to their row
                    leftColumnView.frame = frameLeft;
                    rightColumnView.frame = frameRight;
                    [rowView addSubview:leftColumnView];
                    [rowView addSubview:rightColumnView];

                    // clean up
                    [containerView removeFromSuperview];
                    [containerView release];
                    [leftColumnView release];
                    [rightColumnView release];
                }];

}
I already checked the geometry of all views and it seems ok. Also, the completion block is executed properly.
What may be the problem?

A: I was also stuck at animating views with transitionWithView.
I don't know the hierarchy of your project, but if it is possible for you to create a separate class for the view you want to animate with this, it would be easy:
[UIView transitionWithView:self.view duration:1.0 options:UIViewAnimationOptionTransitionFlipFromLeft animations:^{} completion:^(BOOL f){}];
works..i.e. this function works properly with self.view.
I hope it helps.


text:
Q: What does $w(t) ∈ \mathcal{L}^1$ mean? I am reading a paper where it is mentioned the following:

The function $w(t) ∈ \mathcal{L}^1$, where $w(t) ≥ 0$

so what does $\mathcal{L}^1$ mean here?

A: In most contexts in math, the set $\mathcal{L}_1$ is the set of all such functions from a space $X$ to either $\mathbb{R}$ or $\mathbb{C}$ that are absolutely integrable:
$$ \mathcal{L}_1 = \left\{ f:X \to \mathbb{C} : \int_X |f| dx < \infty \right\} $$
In measure theory, the functions are measurable and the integral is $\int_X |f| d\mu$


text:
Q: how to get statuses from current_user.friends + limit to 10 statuses this is my code:
@current_user_statuses = current_user.statuses.limit(10)

@friends_statuses = current_user.friends.collect(&:statuses)

if current_user.friends.collect(&:doweets)[0].any?
  @friends_statuses = current_user.friends.collect(&:statuses)[0]
end

@statuses = (@current_user_statuses + @friends_statuses).sort_by{ |d| - d.created_at.to_i

i want to make it like this:
@current_user_statuses = current_user.statuses.limit(10)

@friends_statuses = current_user.friends.statuses.limit(10)

@statuses = (@current_user_statuses + @friends_statuses).sort_by{ |d| - d.created_at.to_i

but when i do it i get an error...
how can i do it?
my models:
Friendships model:
    belongs_to :user
belongs_to :friend, :class_name => "User", :foreign_key => "friend_id"

def self.are_friends(user, friend)
  return false if user == friend
  return true unless find_by_user_id_and_friend_id(user, friend).nil?
  return true unless find_by_user_id_and_friend_id(friend, user).nil?
  return false
end

def self.request(user, friend)
  return false if are_friends(user, friend)
  return false if user == friend
  f1 = new(:user => user, :friend => friend, :status => "pending")
  f2 = new(:user => friend, :friend => user, :status => "requested")
  transaction do
    f1.save
    f2.save
  end
end

def self.accept(user, friend)
  f1 = find_by_user_id_and_friend_id(user, friend)
  f2 = find_by_user_id_and_friend_id(friend, user)
  if f1.nil? or f2.nil?
    return false
  else
    transaction do
      f1.update_attributes(:status => "accepted")
      f2.update_attributes(:status => "accepted")
    end
  end
  return true
end

def self.reject(user, friend)
  f1 = find_by_user_id_and_friend_id(user, friend)
  f2 = find_by_user_id_and_friend_id(friend, user)
  if f1.nil? or f2.nil?
    return false
  else
    transaction do
      f1.destroy
      f2.destroy
      return true
    end
  end
end

user model:
      has_many :doweets
  has_many :friendships
  has_many :friends,
           :through => :friendships,
           :conditions => "status = 'accepted'"

  has_many :requested_friends,
           :through => :friendships,
           :source => :friend,
           :conditions => "status = 'requested'",
           :order => :created_at

  has_many :pending_friends,
           :through => :friendships,
           :source => :friend,
           :conditions => "status = 'pending'",
           :order => :created_at

thanks!!
edit:
my error:
NoMethodError: undefined method `doweets' for #

A: ids = [current_user.id, *current_user.friends.map(&:id)]
@statuses = Status.where(:user_id => ids).limit(10).order("created_at DESC")

that's it


text:
Q: Image upload to Firebase storage failed on storage My Angular app allows the user to upload an image to firebase CDN. This has worked up until the other day. After my last deployment which did not touch the image code, I get this error on the storage method:
firebase_app__WEBPACK_IMPORTED_MODULE_6__.storage is not a function

The code is here:
    import * as firebase from 'firebase/app';
    ...
    const storagePathname = `${storageLogos}${this.account.accountId}-${selectedImageFile.name}`;
    const logoStorageRef = firebase.storage().ref().child(storagePathname)
    await logoStorageRef.put(selectedImageFile).then(async snapshot => {
    ... do some other stuff ...
    }

Did something change on Firebase's side that I did not catch?

A: Stupid...
As I was typing "did not change the image code" in the question, that nagging voice in my head said that's the FIRST thing you'd check in someone else's code. And of course, it was. This
   import * as firebase from 'firebase';
was changed to this:
   import * as firebase from 'firebase/app';
And sure enough, that was the problem!


text:
Q: Message Event Handler Exist or not in window object I have a page in HTML that contains iframe. If message comes from iframe I have to handle it. But how to check if message event handler exist or not? My code is
$(window).on('message',function(e){
console.log(e.originalEvent.data);
});

When button is clicked this code set message event handler. But when again clicked - again message handler get added. Is there any method to know if in window object is message event handler present or not. Please guideline. I can't use global variable in my case. If it's possible to get event handler from window object then please explain the method.

A: Try
$(function () {
    $("body").text("click");
    // `message` `handler`
    window.msgHandler = function (e) {
        if (e.origin === "http://fiddle.jshell.net") {
            console.log(e, e.data);
        };
    };
    window.addEventListener('message', msgHandler, false);
    var iframe = $("", {
            "width": "150px",
            "height": "150px",
            "target": "_top"
    });
    $(iframe).one("load", function (e) {
        var _data = $(e.target)[0].nodeName + " loaded at " + e.timeStamp;
        window.postMessage(_data, "http://fiddle.jshell.net");

        $(e.target)
            .contents()
            .find("html")
            .html("
"
                  + _data
                  + "

");
        return false
    });
    var loadFrame = function (e) {
        // if in window object is message event handler present or not
        console.log("msgHandler" in window
                    ? [ window.msgHandler
                      , window.msgHandler.toString()
                      , typeof window.msgHandler ]
                    : false);
        $(e.target)
            .text("")
            .append($(iframe))
    };

    $(window).one("click", loadFrame);
});

jsfiddle http://jsfiddle.net/guest271314/9xC27/


text:
Q: JTabbedPane in Nimbus with different colors for each tab I want to create a JTabbedPane using the Nimbus Look and Feel that has different colors for each tab. I have found multiple ways to change the colors, but as far as I can tell, these technique apply globally to all tabs with a certain state (such as changing all tabs with TabbedPane:TabbedPaneTab[Enabled].backgroundPainter to be the same color)
Two useful SO links I have found (close but not quite the answer to my question):
Override Swing Nimbus L&F primary color per component instance
Set the Background Color for JTabbedPane
Below is a mockup image of what I'd like to achieve.

*edit - sorry forgot to include demo program source code. (This doesn't create the coloring but otherwise launches a new window with the appropriate tab pane.):
public class TabbedPaneExample extends JFrame {
    public static void main(String args[]) {
        try {
            for(javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.
                    getInstalledLookAndFeels()) {
                if("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        }
        catch(Exception ex) {
            ex.printStackTrace();
        }

        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TabbedPaneExample().setVisible(true);
            }
        });
    }

    public TabbedPaneExample(){
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        JTabbedPane pane = new JTabbedPane();
        pane.addTab("Blue", new JLabel("Blue tab"));
        pane.addTab("Red", new JLabel("Red tab"));
        pane.addTab("Yellow", new JLabel("Yellow tab"));

        this.add(pane);

        pack();
    }
}

*Edit - In regards to zilk's answer below - it does not appear to work.  Extending BasicTabbedPaneUI causes the Nimbus specific rendering to be lost. In order to keep the Nimbus rendering, SynthTabbedPaneUI needs to be extended. However, SynthTabbedPaneUI doesn't call paintTabBackground, instead it calls paintTabArea, which is both a protected method and an overloaded private helper method. It looks like all the logic occurs in the private helper method. I can't reproduce that private method in my own code because of private instance variables in SynthTabbedPaneUI and package private code in SynthContext which is used by paintTabArea.

A: You can set new UI that is extended BasicTabbedPaneUI for your tabbedpane. After that you should just override the paintTabBackground method. Try this codes
pane.setUI(new BasicTabbedPaneUI(){
        @Override
        protected void paintTabBackground(Graphics g, int tabPlacement,int tabIndex, int x, int y, int w, int h, boolean isSelected){
           //default backcolor
           Color bg = Color.LIGHT_GRAY;

           switch(tabIndex){
             case 0:
                   bg = Color.BLUE;
                   break;
              case 1:
                   bg = Color.YELLOW;
                   break;
              case 2:
                   bg = Color.RED;
                   break;
               }
            g.setColor(bg);

           switch (tabPlacement){
              case SwingConstants.TOP:
                   g.fillRect(x + 1, y + 1, w - 1, h - 1);
                   break;
              case SwingConstants.BOTTOM:
                   g.fillRect(x, y, w - 1, h - 1);
                   break;
              case SwingConstants.LEFT:
                   g.fillRect(x + 1, y + 1, w - 1, h - 2);
                   break;
              case SwingConstants.RIGHT:
                   g.fillRect(x, y + 1, w - 1, h - 2);
                   break;
               }
    }
 });

Edit:
Here is my codes result

P.S: Do not forget this
pane.setOpaque(true);


text:
Q: Ngram frequency ranking in Pyspark I would like to read a fairly large document and extract N-grams(Continous sequence of N words) from it. I would also like to sort it in ascending order of frequency. While I understand this is an extension of word count, I am not sure how to do this in Pyspark. Any help is appreciated.

A: One possible solution with toolz
from toolz.curried import sliding_window
from operator import add, itemgetter

rdd = sc.textFile("README.md")
tokens = rdd.map(str.split)

counts = (tokens
    .flatMap(sliding_window(3))
    .map(lambda x: (x, 1))
    .reduceByKey(add))

counts.top(3, key=itemgetter(1))

## [(('command,', 'which', 'should'), 2),
## (('on', 'how', 'to'), 2),
## (('Please', 'refer', 'to'), 2)]

Limitation of this approach is pretty much the same as usual - it operates on line by line basis so if documents spans over multiple lines you won't get n-grams which spanned over line boundaries.
It is possible to correct for that by keeping track of line number and position in line or using wholeTextFiles.


text:
Q: Weird IndexOUBException using buttons inside listview I am having a very strange issue in an activity using a listview that contains buttons.
The error seems to pop up kind of randomly (although we know that doesn't really exist), i mean to say I cant get a defined pattern to reproduce the error. It just happens every so often.
The big issue i'm having trying to figure this out is the logCat shows no error in my code, just in the code that (i believe) android uses to determine the view where the click is coming from. Take notice that no package that doesnt belong to android/java is mentioned in the error.
LogCat:
12-14 12:04:20.994: ERROR/AndroidRuntime(5619): FATAL EXCEPTION: main
12-14 12:04:20.994: ERROR/AndroidRuntime(5619): java.lang.IndexOutOfBoundsException
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at java.util.Arrays$ArrayList.get(Arrays.java:77)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at android.widget.ArrayAdapter.getItem(ArrayAdapter.java:298)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:351)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at android.widget.ArrayAdapter.getView(ArrayAdapter.java:323)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at android.widget.Spinner.makeAndAddView(Spinner.java:189)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at android.widget.Spinner.layout(Spinner.java:148)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at android.widget.Spinner.onLayout(Spinner.java:112)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at android.view.View.layout(View.java:7032)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1249)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1125)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at android.widget.LinearLayout.onLayout(LinearLayout.java:1042)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at android.view.View.layout(View.java:7032)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1249)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at android.widget.LinearLayout.layoutHorizontal(LinearLayout.java:1238)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at android.widget.LinearLayout.onLayout(LinearLayout.java:1044)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at android.view.View.layout(View.java:7032)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1249)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1125)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at android.widget.LinearLayout.onLayout(LinearLayout.java:1042)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at android.view.View.layout(View.java:7032)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at android.view.View.layout(View.java:7032)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1249)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1125)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at android.widget.LinearLayout.onLayout(LinearLayout.java:1042)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at android.view.View.layout(View.java:7032)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at android.view.View.layout(View.java:7032)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at android.view.ViewRoot.performTraversals(ViewRoot.java:1055)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1737)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at android.os.Looper.loop(Looper.java:123)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at android.app.ActivityThread.main(ActivityThread.java:4627)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at java.lang.reflect.Method.invokeNative(Native Method)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at java.lang.reflect.Method.invoke(Method.java:521)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
12-14 12:04:20.994: ERROR/AndroidRuntime(5619):     at dalvik.system.NativeStart.main(Native Method)

Here is my custom ArrayAdapter code, the error occurs when I click on various "boton_modificar" from the various rows repeatedly, mostly if I click them fastly.
private class CustomAdapter extends ArrayAdapter<DataType> {

  public CustomAdapter(Context context, int resource,List<DataType> objects) {
   super(context, resource, objects);
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
   View row = convertView;

   final int position2 = position;

   if (row == null) {
    LayoutInflater inflater = getLayoutInflater();
    row = inflater.inflate(R.layout.row_layout,parent,false);
   }

   //Some more code here

   ImageButton boton_modificar = (ImageButton) row.findViewById(R.id.modificar);
   boton_modificar.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
     DataT t = tr.get(position2);
     ((EditText) (findViewById(R.id.monto))).setText(Double.toString(t.m));
     ((Spinner) (findViewById(R.id.spinnerTipoB))).setSelection(t.posSTB);
     ((Spinner) (findViewById(R.id.spinnerB))).setSelection(t.posSB);
    }
   });
   return (row);
  }
 }

Does anybode have the slightest idea what this might be? Im tired of trying to figure this out and nothing. Most I found was a bug report of a similar issue, but I doubt its the same thing, in any case the report is here.
Thanks in advance, Stefano
Edit:
LogCat of just before the error pops, doubt it has anything to do with the position sets.
12-16 15:12:56.159: INFO/position2(21828): 7
12-16 15:12:56.159: INFO/Spinner A # elements:(21828): 3
12-16 15:12:56.159: INFO/Assigned position(21828): 1
12-16 15:12:56.159: INFO/Spinner B # elements:(21828): 20
12-16 15:12:56.159: INFO/Assigned position(21828): 5

Added code:
spinnerTipoB.setOnItemSelectedListener(new OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> arg0, View arg1,
                            int position, long arg3) {
                        int posId = tipoBIds[position];
                        if (posId == 0) {
                                spinnerB.setAdapter(arrayAdapterBP);
                        } else if (posId == 1) {
                            spinnerB.setAdapter(arrayAdapterBT);
                        } else if (posId == 2) {
                            spinnerB.setAdapter(arrayAdapterBO);
                        }
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> arg0) {
                        // Do Nothing
                    }
                });

spinnerB does nothing on position select.
All spinner array adapter are created like this:
arrayAdapterNAME = new ArrayAdapter<String>(this, R.layout.layoutspinner, DATA);

I would presume the error ocurrs because ((Spinner) (findViewById(R.id.spinnerB))).setSelection(t.posSB); is executed before spinnerB.setAdapter(arrayAdapterNAME)is done?

A: This problem has nothing to do with the ListView's adapter and everything to do with the Spinner adapter.
When you click one of your buttons you call setSelection() on both spinners. If you check the code in AbsSpinner.setSelection(int) you'll see that it caches the integer index of the newly selected item and calls requestLayout() to redraw itself (at some later point).
When the UI thread processes the layout messages, it lays out everything in the view tree but blows up when laying out a Spinner because the index it cached earlier is no longer valid. Something has altered the adapter's list... this must have happened in response to a UI event such (as a Button onClick()) and which got processed before the layout message being processed.
ADDED LATER FOLLOWING COMMENTS DISCUSSION AND CODE ADDED TO O.P.:
The wrong assumption was that Spinner.setSelection() would cause the onItemSelectedListener event to run before it returned. The fix for this specific problem was to set the spinner adapter from the button onClick() and then set selected indexes afterwards.


text:
Q: Two database-tables for one model I am working with an existing sqlserver-database.
In this database there are two tables containing "address-information".
One table has the information in French, the other in Dutch.
Both tables have the same layout.
[Key]
[Column("fu_VAT")]
public int VatNumber { get; set; }
[Column("fu_EindDatum")]
public int EindDatum { get; set; }
[Column("fu_vorm")]
public string Vorm { get; set; }
[Column("fu_NameOrigin")]
public int NameOrigin { get; set; }
[Column("fu_AdresOrigin")]
public int AdresOrigin { get; set; }
[Column("fu_Name")]
public string Name { get; set; }
[Column("fu_StraatNaam")]
public string StraatNaam { get; set; }

So I have created a class "Addresse" which contains the above definition.
And then I created 2 classes "Addresse_FR" and "Addresse_NL" which inherit "Addresse".
In my repository I created the following method :
public Addresse GetCompanyAddressByLanguageAndVatNumber(int VatNumber, int Language)
{
    switch (Language)
    {
        case 1: //Frans
            return xmlALaCarteContext.CWFirmaAddresseFr.Where(a => a.VatNumber == VatNumber).SingleOrDefault().ToAddresse();
        default:
            return xmlALaCarteContext.CWFirmaAddresseNl.Where(a => a.VatNumber == VatNumber).SingleOrDefault().ToAddresse();
    }
}

I was wondering if there was a better way of solving this.

A: Just so you don't create "Magic numbers", i.e 1 = French, etc.  Why not use CultureInfo.Name?  Of course you probably could stick to first two characters for language regardless of location.  I found 6 for French alone.  The values are ISO standards.
// Language contains CultureInfo.Name (iso name that aligns to country/language)
public Addresse GetCompanyAddressByLanguageAndVatNumber(int VatNumber, string Language)
{
    switch (Language)
    {
        case "fr-CA": //Canadian French
        case "fr-FR": //France French
            return xmlALaCarteContext.CWFirmaAddresseFr.Where(a => a.VatNumber == VatNumber).SingleOrDefault().ToAddresse();
        case "nl-NL": //Netherlands Dutch
            return xmlALaCarteContext.CWFirmaAddresseFr.Where(a => a.VatNumber == VatNumber).SingleOrDefault().ToAddresse();
        default:
            throw new NotImplementedException();
    }
}

You could also get tricky (love being bad) and have a Property Getter/Setter that uses virtual navigation properties to return the "right" address given the current culture and primary key (VAT is an FK I presume?)
public class myParent
{
    [Key]
    public int Id { get; set; }

    // navigation properties
    public int VatNumber { get; set; }
    private virtual Addresse FrenchAddress { get; set; }
    private virtual Addresse DutchAddress { get; set; }

    public Addresse CompanyAddress {
        get {
             switch (System.Globalization.CultureInfo.Name)
             {
                 case "fr-CA": //Canadian French
                 case "fr-FR": //France French
                     return FrenchAddress;
                 case "nl-NL": //Netherlands Dutch
                     return DutchAddress;
                 default:
                     throw new NotImplementedException();
            }
            set;
        }
    }
}

with corresponding Setter & fluent description.  I am not certain, but I think referencing CompanyAddress will cause the corresponding address to load.


text:
Q: How can I avoid Delimiters replacing Date values while printing in shell script? For the command:
cat <file_name>.asc | head -1

Output:

10/30/2006,19:41:58,1.4871,1,E

I wanted to append commas to this line to maintain field consistency.
So I tried various combinations like issuing,
Command : echo cat <file_name>.asc | head -1,,,
Output : ,,,30/2006,19:41:58,1.4871,1,E
Command : echo cat <file_name>.asc | head -1,
Output : ,0/30/2006,19:41:58,1.4871,1,E
Command : echo cat <file_name>.asc | head -1",,,"
Output : ,,,30/2006,19:41:58,1.4871,1,E
Command : chk=$(echo cat <file_name>.asc | head -1)
echo ${chk},,,
Output : ,,,30/2006,19:41:58,1.4871,1,E
But my expected output is very simple,

10/30/2006,19:41:58,1.4871,1,E,,,

Actually my logic is to open a file with CAT and do a while operation on each line to check the data and append comma wherever needed and write the output to another file.

A: If I understood correctly, you want do this conversion:
10/30/2006,19:41:58,1.4871,1,E --> 10/30/2006,19:41:58,1.4871,1,E,,,

If so, then you should use sed util:
cat <file_name>.asc | sed -e 's/$/,,,/' > output_file

A: echo `head -n 1 cat.asc`,,,

If you need this in a variable, it goes like this:
X=`head -n 1 cat.asc`,,,

This answers the question which you asked. However, you also mention that you want to process a whole file and do some adjustment for each line. In this case, I don't see how this approach will help....


text:
Q: UIGestureRecognizer and UIControlEventTouchUpInside work at the same time I am adding a UITapGestureRecognizer to my application to detect a double tap gesture.
UITapGestureRecognizer *tapgr = [[UITapGestureRecognizer alloc]
                                        initWithTarget:self action:@selector(handleTapGesture:)];
  tapgr.numberOfTaps = 2;
  tapgr.delegate = self;
  [_view addGestureRecognizer:tapgr];
  [tapgr release];

This is working fine unless I show a tooltip in my application. They are set up like this:
[_view.toolTipView addTarget:self action:@selector(handleTap:) forControlEvents:UIControlEventTouchUpInside];

Before the introduction of my gesture recognizer, these tooltips where clickable and reacted, now they aren't reacting anymore...
How can I make a gesture recognizer and a standard UIControlEventTouchUpInside-Setup work together?

A: I found a solution:
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
 if (gestureRecognizer == tapgr) {
   return ![touch.view isKindOfClass:[UIControl class]];
 }
 return YES;
}

This method prevents the GestureRecognizer from being fired when a UIControl (i.e. Button) is pressed.

A: if you want the _view can respond single tap and Double tap together, you can try this
   UITapGestureRecognizer * singleTap    = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
   UITapGestureRecognizer * doubleTap    = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];

   [doubleTap setNumberOfTapsRequired:2];

   //Add this code to disable double tap and only responds to single tap when user tap the _view just once time
   [singleTap requireGestureRecognizerToFail:doubleTap];

   [self addGestureRecognizer:doubleTap];
   [self addGestureRecognizer:singleTap];
   [singleTap release];
   [doubleTap release];

if you want to use TouchEvent try UIControlEventTouchDownRepeat
  [button addTarget:self actionselector(multipleTap:withEvent:) forControlEvents:UIControlEventTouchDownRepeat];

  //Try to check wheather is doulbe tap or single tap.

  -(IBAction)multipleTap:(id)sender withEvent:(UIEvent*)event {

     UITouch* touch = [[event allTouches] anyObject];

     if (touch.tapCount == 2) {

     // do action.

     }

  }

A: You can't do that. I think you should choose another way to implement that.


text:
Q: Call to undefined function wp_get_current_user() in capabilities.php I had a website which wasn't updated for a long time. Suddenly, few days ago, my website stopped working and found this error line in error_log file.
[18-Mar-2014 19:16:43 UTC] PHP Fatal error:  Call to undefined function wp_get_current_user() in /home8/****/public_html/wp-includes/capabilities.php on line 1289

I have tried everything I know and almost every claims found online. What could be the possible reason and solution for this outage?

A: Solution is include the pluggable file in your plguin file. After include this file easily resolve your problem.
require_once( ABSPATH . '/wp-includes/pluggable.php' );
$user_info = wp_get_current_user();

A: As seen at https://codex.wordpress.org/Function_Reference/wp_get_current_user

wp_get_current_user() is located in wp-includes/pluggable.php.

Do you have this file included?
(sorry if this is an stupid question, I don't know about wordpress)


text:
Q: Fast Python PDF metadata reader I'm looking for a very fast, lightweight Python library to read PDF metadata. I don't need any write capabilities. It would be better if only the metadata information is loaded, not the entire file.
I realise an interpreted language like Python isn't the best choice for speed, but as this solution needs to be cross platform and work with an existing Python application there doesn't seem to be much of a choice.
I checked out pyPdf and some other libraries, but am ideally looking for something lighter and faster, suitable for processing tens of thousands of files in one go.

A: pdfrw can read the metadata without reading parsing the entire file.  (Disclaimer:  I am the author of pdfrw.)  For example:
>>> from pdfrw import PdfReader
>>> PdfReader('pdf_reference_1-7.pdf').Info
{'/Title': '(PDF Reference, version 1.7)',
 '/CreationDate': '(D:20061017081020Z)',
 '/Producer': '(Acrobat Distiller 7.0.5 \\(Windows\\))',
 '/Creator': '(FrameMaker 7.2)',
 '/ModDate': "(D:20061118211043-02'30')",
 '/Author': '(Adobe Systems Incorporated)',
 '/Subject': '(Adobe Portable Document Format \\(PDF\\))'}

A: Here's something I just put together, built on top of the Python PDFMiner library. You can extract both "Info" and XMP type metadata with it.

A: Have you seen this answer to a similar question? It suggests using fopen and manually parsing the metadata. If the metadata is all you need, you can parse it yourself and make it as fast as you like.

A: It's a little Raw, but this should get you the meta data
f = open('file.pdf', 'r')
pdfdata=f.read()
metas=re.findall('<</Metadata(.*?)>>',pdfdata)


text:
Q: Javascript nodejs tedious mssql is there a way to get json? I'm using nodejs and tedious connector to get data from mssql server. In documentation, I only see this one way to retrieve data
var request = new Request("select Name, Value, Article_Id from [tableone] where Id = '1'", function (err, rowCount, rows) {

    if (err) {
        console.log(err);
    } else {
        console.log(rowCount + ' rows');
    }
});
request.on('row', function (rows) {

    ...
    bigArrat.push(JSON.stringify(rows));
});

But in my example I want all rows, not only one property but more. Currently, it return in separate row one cell eg. rows[0].value will return Name, rows[1].value Value ... for me it is rubbish.
I want to get all information in json array of object not all metadata or one property. There is a way to do this or there is a better connector for nodejs and sqlserver ?

A: Add this to your config.

rowCollectionOnRequestCompletion: true

var config = {
  userName: '', // update me
  password: '', // update me
  server: '', // update me
  options: {
    database: '', // update me
    encrypt: true,
    rowCollectionOnRequestCompletion: true
  }
}

Then on your query you can now get the data of rows.
var executeQuery = (res,query) => {
  request = new Request(query, (err, rowCount, rows) => {
    console.log("Rows: ", rows);
    res.send(rows);
  });
  connection.execSql(request);
}

I learned it from:
http://tediousjs.github.io/tedious/api-request.html
EDIT
Update not to have metadata:
var data = []
request = new Request(query, (err, rowCount, rows) => {
  if(err) {
    console.log(err)
    res.send({ status: 500, data: null, message: "internal server error."})
  } else {
    console.log(rowCount+' row(s) returned')
    res.send({ status: 200, data: data, message: "OK"})
  }
})
request.on('row', function(row){
  data.push({
    last_name: row[0].value,
    first_name: row[1].value
  })
})
connection.execSql(request)

A: If you are using express on server side I can recommend using express4-tedious (see https://www.npmjs.com/package/express4-tedious). It allows to easily write apis for SQL connections with small code and streams json result to response.
Connection:
var express = require('express');
var tediousExpress = require('express4-tedious');

var app = express();
app.use(function (req, res, next) {
    req.sql = tediousExpress(req, {connection object});
    next();
});

Example Api:
/* GET from tableone, streams json result into response */
router.get('/', function (req, res) {

    req.sql("select Name, Value, Article_Id from [tableone] where Id = '1' for json path")
        .into(res);

});

You can then call these apis e.g. from frontend.

A: The rows value sent to your initial callback is the array of rows being sent back:
var request = new Request("select Name, Value, Article_Id from [tableone] where Id = '1'", function (err, rowCount, rows) {

    if (err) {
        console.log(err);
    } else {
        console.log(rowCount + ' rows');
    }
    console.log(rows) // this is the full array of row objects
    // it just needs some manipulating

    jsonArray = []
    rows.forEach(function (columns) {
        var rowObject ={};
        columns.forEach(function(column) {
            rowObject[column.metadata.colName] = column.value;
        });
        jsonArray.push(rowObject)
    });
    return callback(null, rowCount, jsonArray);
});

A: In Sql Server 2016 you can format query results as JSON text using FOR JSON option, see https://msdn.microsoft.com/en-us/library/dn921882.aspx
You just need to read JSON fragments returned by query.

A: I tried that way but it did not work for me perhaps my knowledge of js and callbacks is not good enough. So, here is my solution. I had to add things to my config of connection to make rows of request work. You would also have to do this. Go to: at the end of new Request section, and to the rows.
here
Second thing, I did is pretty simple.
var jsonArray = [];
var rowObject= {};
var request = new Request("SELECT TOP 5 * FROM tableName",function(err,rowCounts,rows)
{
if (err)
{
console.log(err);
}
else
{
console.log(rowCounts + " rows returned");
}

//Now parse the data from each of the row and populate the array.
for(var i=0; i < rowCounts; i++)
{
var singleRowData = rows[i];
//console.log(singleRowData.length);
for(var j =0; j < singleRowData.length; j++)
{
  var tempColName = singleRowData[j].metadata.colName;
  var tempColData = singleRowData[j].value;
  rowObject[tempColName] = tempColData;
}
jsonArray.push(rowObject);
}
  //This line will print the array of JSON object.
  console.log(jsonArray);

and to show you how my connection.config looks like:
static config: any =
{

userName: 'username',
password: 'password',
server: 'something.some.some.com',
options: { encrypt: false, database: 'databaseName' ,
          rowCollectionOnRequestCompletion: true }
};//End: config

and this is how I am passing it to connection.
  static connection = new Connection(Server.config);

A: Complementing the answer from @Jovan MSFT:
var request = new Request('select person_id, name from person for json path', function(err) {
    if (err) {
        console.log(err);
    }

    connection.close();
});

And, finally, in the row event:
request.on('row', function(columns) {

    var obj = JSON.parse(columns[0].value);

    console.log(obj[0].name);
});

P.S.: the code above does not iterate over columns parameter because for json path returns a single array of objects in a single row and column.

A: Applying map-reduce function in returned rows:
rows.map(r=>{
      return r.reduce((a,k)=>{
        a[k.metadata.colName]=k.value
        return a
      }
      ,{})
    })

A: This is a combination of a few responses above. This uses FOR JSON AUTO in the SELECT statement and parses the "column" as JSON. The row/column nomenclature may be a bit misleading for folks unfamiliar with this API. In this case, the first "columns" value will be an array of the rows in your table:
var request = new Request("SELECT Name, Value, Article_Id FROM [tableone] WHERE Id = '1' FOR JSON AUTO", function (err, rowCount, rows) {
  if (err) {
    console.log(err);
  } else {
    console.log(rowCount + ' rows');
  }
});
request.on('row', (columns) => {
  const json = JSON.parse(columns[0].value);
});


text:
Q: translating a let as lambda From page 69 of R⁷RS I know what I can substitute a let with a lambda:
(let (a 10) something)
; is equivalent to
(lambda (a) something) 10

So I took this (from SICP):
(define new-withdraw
  (let ((balance 100))
    (lambda (amount)
      (if (>= balance amount)
          (begin (set! balance (- balance amount))
                 balance)
          "Insufficient funds"))))

and translated it to:
(define w-lam
  (lambda (balance)
    (lambda (amount)
      (if (>= balance amount)
          (begin (set! balance (- balance amount))
                 balance)
          "Insufficient funds")) 100))

but the behaviour in the REPL is different:
(new-withdraw 80)

;Value: 20

(w-lam 80)

;Value: 100

What am I missing?

A: Equivalent of
(let ((a 10)) something)
; With 2 pairs of parenthesis, but I take that is a typo

isn't
(lambda (a) something) 10

But
((lambda (a) something) 10)

(lambda (a) something) 10 isn't a valid construct anyway. It is 2, unrelated valid constructs (and, depending on the context, it may be legal or not to have two constructs one after the other). It is first a function, that does something in a context where a is a parameter. And then, a number, 10. You don't want a function that evaluate something. You want to actually evaluate something. So you need to call that function.
(lambda (a) something) 10 is like print; 10; in an imperative language. It means nothing. It is just a function (print) and then a number. Without connections. It happens to be legal, but void, in many languages. The function is not called. It is just a value (that happens to be a function). Which is ignored, since we do nothing with it.
((lambda (a) something) 10) on the other hand calls that function with parameter 10. Like print(10); in my analogy.
So, equivalent of
(let ((balance 100))
    (lambda (amount)
      (if (>= balance amount)
          (begin (set! balance (- balance amount))
                 balance)
          "Insufficient funds")))

is

((lambda (balance)
    (lambda (amount)
      (if (>= balance amount)
          (begin (set! balance (- balance amount))
                 balance)
          "Insufficient funds"))) 100)

tl-dr: here is the working code
Or, enclosed in your define w-lam
(define w-lam
  ((lambda (balance)
    (lambda (amount)
      (if (>= balance amount)
          (begin (set! balance (- balance amount))
                 balance)
          "Insufficient funds"))) 100))

Note that the equivalent let/lambda isn't just black magic. You don't need to find "formulas" in textbook for that. It is just logic.
(let ((a 10)) something)

Means that we create a new environment, in which symbol a is associated to value 10. And in this environment, something is evaluated
(lambda (a) something)

is a function that evaluate something, in a local environment in which a is the parameter passed to that function.
And, as you know
(f 10)

Calls function f with parameter 10.
So, just replace f by previous function (lambda (a) something).
And you get
((lambda (a) something) 10)

Which calls (lambda (a) something) with 1st parameter being 10.
And we know that calling this function means evaluating something in an environment where a is the 1st parameter passed, that is, here, 10.
If you are more familiar with more imperative languages, it just a replacing
{ // New block
    int a=10;
    printf("%d\n", a)
}

By
void f(int a){
    printf("%d\n", a);
}
f(10);

Or, in javascript (which has closer to scheme constructs)
{
    let a=10;
    console.log(a);
}

by
(function (a){
    console.log(a);
})(10);

Or
((a)=>console.log(a))(10)

Which is something people really do in javascript to create local environments.
So, it is just using parameters of a lambda (or anonymous functions in my analogies) as a local environment, and calling that function immediately with values we want to set in this local environment.


text:
Q: I can't understand how to use 'ANY' in Document Type Definition language Suppose we have this XML document
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE note [

<!ELEMENT note (to,from,heading,body, foo)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
<!ELEMENT foo ANY>

]>

<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
<foo><stuff>test</stuff></foo>
</note>

I'm using the ANY keyword for the element "foo" but I get an error saying
Line 20, Column 16: element "stuff" undefined

from this site http://validator.w3.org/check
why is this happening? isn't any supposed to accept any kind of parsable data in the foo element?

A: ANY means "Any element type defined in the DTD" not "Any element type the author cares to invent".
From the specification:

The declaration matches ANY, and the content (after replacing any entity references with their replacement text) consists of character data, CDATA sections, comments, PIs and child elements whose types have been declared.

(My emphasis)