text:
Q: Simplficando comparações encadeadas Segundo o pycharm (que está com as configurações padrões para pep8) diz que é possivél simplificar está linha.
        elif student['averange'] >= 5 and student['averange'] < 7:
            student['situation'] = 'Recuperação'

A: Porque Python tem uma feature muito legal de comparações que permitem que mais de uma comparação com o mesmo elemento sejam escritas na mesma notação que usamos em matemática. Então, se queremos saber se um número está entre "5" e "7", em vez de escrever "se x > 5 e x < 7", como pensamos ao programar, dá pra escrever "se 5 < x < 7", como fazemos em matemática. Internamente, o Python transforma isso em
"5 < x and x < 7".
Sua linha então ficaria assim:
elif 5 <= student['averange'] < 7:


text:
Q: Angular Material Table - assign width to specific column in dynamic table I have a dynamic angular material table component, that works like this:
<table mat-table [dataSource]="dataSource" class="table"
       matSort>

  <ng-container *ngFor="let column of columns" [matColumnDef]="column.key">
    <mat-header-cell *matHeaderCellDef mat-sort-header>
      {{column.name}}
    </mat-header-cell>
    <mat-cell *matCellDef="let row"
              [@getIn]>
            {{row[column.key] || 'N/A'}}
    </mat-cell>
  </ng-container>

  <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
  <mat-row *matRowDef="let row; columns: displayedColumns;"
           matRipple
           [matRippleDisabled]="!allowSelect"
           [class.selectableRow]="allowSelect"></mat-row>
</table>

The component accepts a list of columns, for example:
[{
   key: "date",
   name: "Date",
}, {
   key: "title",
   name: "Book Name",
}]

It works, but I'm trying to enhance it and send width attribute to one of the columns (it can be any). For example:
[{
       key: "date",
       name: "Date",
       width: 110
    }, {
       key: "title",
       name: "Book Name",
    }]

How I can adjust the columns width based on thie attributes? I do not want to hardcode the class name based on this column title in the CSS (as it won't be dynamic anymore). Please note that the width is applied only to specific columns.
I tried to update the mat-cell flex style attribute as follows:
<mat-cell *matCellDef="let row"
              [@getIn]
              [style.flex]="column.width ? '0 0 ' + column.width + 'px' : null">

but it messes up the width of the rest of the columns (I guess it overwrites the current flex attribute, and I have no idea what the default is)
Any idea?

A: I am working in Angular CLI ver. 9, and following is tested!
Simply use @Input() property of MatTable [width]="column.width"
e.g.
<ng-container matColumnDef="Column">
        <th mat-header-cell *matHeaderCellDef> Column Name </th>
        <td [width]="element.width" mat-cell *matCellDef="let element"> {{element.manuscriptNumber}} </td>
</ng-container>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Merge Profiles option of Contact Form validation rejects https:// urls in profile fields Steps to reproduce:

*

*Go to the "Contact Us" page at https://stackoverflow.com/contact

*Select "I need to merge user profiles"

*The autofilled profile URL may be https://, in which case it will be throw a validation error on submission, like:

Error: "your profile link should be of the form http://stackoverflow.com/users/<id>/<display-name>"

Obviously this also occurs if you manually paste a https link, which is overwhelmingly likely if you're security conscious or using the HTTPS Everywhere plugin.
I would hope it's just an overly aggressive validation pattern, since there's no functional difference I can tell between the 2 profile pages.

A: Fixed in build rev 2014.3.31.2103 on meta and 2014.3.31.1502 on sites.


text:
Q: C++ program hanging BETWEEN functions? I have a lengthy program that basically manages a hash table; adds, deletes, etc. I'm hitting an extremely bizarre bug in my program, though.
Basically I have a delete function that hashes a values, checks a linked list stored in an array given by a hash value for the appropriate object, and, if found, deletes it and exits the function. It looks essentially like this:
template<typename T>
void HashTable<T>::remove(T* t){
    LinkedList<T> list= data[(hash(t))];
    Node<T>* prev = NULL;
    Node<T>* cur = list.head;
    bool running = cur != NULL;
    while(running){
      T key = cur->getKey();
      if(t == key){
          if(prev == NULL){
              cur = cur->getNext();
              running = false;
          }else{
              prev->setNext(cur->getNext());
              cout << &key << '\n';
              cur = NULL;
              running = false;
          }
      }
      prev = cur;
      cur = cur->getNext();
    }
    cout << "Are we getting here?"; //yes
}

I'm calling this function in this way:
Type* b = buildType(); //produces a Type* from CL arguments
hash.remove(b);
cout << "Are we getting to THIS SPOT?"; //no

Basically, the above program outputs "Are we getting here?" but not "Are we getting to THIS SPOT?"
I have no clue what could be the problem in this case, and it took me quite a while to even realize that there could possibly be a problem here. Does anyone know what the issue could possibly be?

A: In this line
LinkedList<T> list= data[(hash(t))]

you are creating a copy of the LinkedList you are obtaining from data.  I bet you do not mean to be making a copy, but mean to be using a reference.  Furthermore, I'd guess it is using the default copy constructor rather than one you intentionally created.  Then when the destructor for that copy of the LinkedList is called, it is deleting heap entries that are still held by the original LinkedList, resulting in heap corruption and eventually a hang.


text:
Q: EJB/JPA: Foreign Key Constraint violation when trying to persist entity in many-many relationship I have an EJB many-to-many (bi-directional) relation between classes (entity-classes) Person and Hobby. There are corresponding tables in the database, called PERSON and HOBBY, as well as a table PERSON_HOBBY for the many-to-many relationship.
As I will detail below,  the problem is that whenever I try to persist a person with hobbies, I run into a Foreign Key constraint violation. This is because the entityManager tries to save new rows into PERSON_HOBBY that contain references to a person-entity with ID=0, which doesn't exist in the PERSON table. I'll come back to that later, but first I'll show the relevant parts of the entity classes.
First, here is entity class Person:
@Entity
public class Person {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private String email;

    @ManyToMany(cascade = {CascadeType.MERGE}, fetch = FetchType.EAGER)
    /* Note: I used to have CascadeType.PERSIST in the above line as well, but
      it caused "Detached object passed to persist" exceptions whenever I tried to
      persist a person with hobbies. So I suppose I was right in deleting
      CascadeType.PERSIST...? */
    @JoinTable(name = "PERSON_HOBBY",
    joinColumns = @JoinColumn(name="personId", referencedColumnName="id"),
    inverseJoinColumns = @JoinColumn(name="hobbyId", referencedColumnName="id"))
    private List<Hobby> hobbies = new ArrayList<Hobby>();

    public List<Hobby> getHobbies () {
        return hobbies;
    }

    public void setHobbies (List<Hobby> hobbies) {
        this.hobbies = hobbies;
        for(Hobby h:hobbies) {  // this is to maintain bi-directionality
            h.addPerson(this);
        }
    }
    // other getters and setters omitted here.

Then entity class Hobby:
@Entity
public class Hobby {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column(nullable = false)
    private String description;

    @ManyToMany(mappedBy = "hobbies", fetch = FetchType.EAGER)
    private List<Person> persons;

    public Hobby() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    // getter and setter for Description omitted here.

    public List<Person> getPersons () {
        return persons;
    }

    public void setPersons (List<Person> persons) {
        this.persons = persons;
    }

    public void addPerson (Person p) {
        this.persons.add(p);
    }
}

I also have a stateless session bean, that's shown here as far as relevant to the issue:
        @Stateless
        @Default
        public class PersonRepositoryImpl implements PersonRepository {

            @PersistenceContext
            private EntityManager entityManager;

            @Override
            public Person create(Person p) {
               entityManager.persist(p);
               entityManager.flush();
               return p;
            }

            @Override
            public Person createPersonWithHobbies(Person p, List<Hobby>hobbyLijst) {
            p = create(p); // I've also tried simply: create(p);
            System.out.println("The newly assigned ID for the persisted
            person is: " + p.getId());
            // That last line **always** prints the person-ID as being 0 !!!!
            p.setHobbies(hobbyLijst);
            entityManager.merge(p); // This should save/persist the person's hobby's!
            entityManager.flush();
            return p;
        }
    }

Now from my servlet, I've been trying in two different ways. First, I tried calling method create(p) on the above session bean. That is, after creating a new Person instance p, setting all its non-relational fields, AND calling setHobbies on it (with a non-zero list of Hobby objects taken from the database), I called:
personRepo.create(p);

But this resulted in the Foreign Key (FK) exception:

INSERT on table 'PERSON_HOBBY' caused a violation of foreign key
  constraint 'FK_EQAEPVYK583YDWLXC63YB3CXK' for key (0).  The statement
  has been rolled back."

The FK-constraint mentioned here is the one in PERSON_HOBBY referring to PERSON.
The second way I tried was to make the following call from the servlet:
personRepo.createPersonWithHobbies(p, hobbyLijst);

where, just like before, p is the new person object; and hobbyLijst is that person's list of hobbies. And this resulted in the exact same FK-exception as the earlier call to personRepo.create(p).
Importantly, the println statement within method createPersonWithHobbies, calling getId() on the newly persisted person-object, ALWAYS gives that object's ID as being 0. Which I suppose does explain the FK-exception, since there's no person entity/row in the PERSON table with an ID of 0, nor is there supposed to be one. But of course the getId() call should not output 0. Instead, it should output the newly generated ID of the newly persisted person entity. (And yes, it IS persisted correctly in the PERSON tabel, with a correctly generated ID>0. So the correct ID is there in the PERSON-table - it just seems to be invisible to the entityManager and/or the container.)
Thanks.


text:
Q: Invalid body indentation level (expecting an indentation level of at least 4) I just upgraded to PHP 7.3 and I'm getting this error:
Invalid body indentation level (expecting an indentation level of at least 4)

Here is the code:
    $html = <<<HTML
<html>
<body>
    HTML test
</body>
</html>
HTML;

A: This is caused by the new flexible Heredoc syntaxes in PHP 7.3.
In previous versions of PHP, the closing marker was not allowed to have indentation:
    $string = <<<EOF
Hello
EOF;

As of PHP 7.3, the closing marker can be indented.
In this example, EOF is indented by 4 spaces. The body of the string will also have 4 spaces stripped from the beginning of each line.
    $string = <<<EOF
    Hello
    EOF;

If the closing marker is indented further than any lines of the body, it will throw a Parse error:
    $string = <<<EOF
  Hello
    EOF;

The reason for the error message is two-fold:

*

*The closing marker is indented further than 1 or more lines within the body

But perhaps more likely, for those upgrading to PHP 7.3:

*

*I've chosen a marker HTML which is also present within the string. Because of the flexible spacing now allowed, PHP was incorrectly detecting that the string had closed before I intended.

A: Had similar issue the indentation of the closing "output;" was an issue. Leave no space on the left.
    $html = <<<HTML
      <html>
       <body>
         HTML test
       </body>
      </html>
    OUTPUT;        // leave no space on the left before the code
    echo $html;
    }


text:
Q: Using jcarousel.js - saving the images and position exactly, after navigation I am using jcarousel.js plugin to order
 list of images in my jQuery Mobile app with carousel affect. Each time I initialize my page the images are different (comes from WS) so after I set them into
 I call it like this:
 $('#imagesPageDiv').live('pagebeforeshow', function (e, data) {
                   jQuery('#carouselDiv').jcarousel({ visible: 4, scroll: 2});
              });

It works fine.
Each image have URL to that same big image.The problem occurs when coming back to that same page.
I dont want to set the images from start, want to come back exactly to the same images and the place (image position) before I clicked on it.
I set flag, so basically I know when I'm coming back and when I starting it from start.
So I tried to save all the page before navigating to the next page, and after coming back append it again to the page:
  globalDivContent = $('#imagesPage #box');

After coming back to that page I appending it:
 $("#imagesPage").empty();
   $("#imagesPage").append(globalDivContent );

Realy getting the same courosel with the real images and posstion exepct one problem: it    doesnt scroll's.
   The arrows are clickable but aren't doing nothing
I compared the codes when starting the page and coming back to page and it similar. Any ideas how can i implement my idea?
      <!DOCTYPE html>

                <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" />
                <link rel="stylesheet" href="http://sorgalla.com/projects/jcarousel/skins/tango/skin.css" />

Index page

A: I would advise saving only the information you need, rather than copying the entire div in one go. This would allow you to cherry-pick the data your really need and safely persist it across page loads.
The best solution for this would be to use local storage. This allows you to save string-to-string values persistently across a site as far back as IE8 (see more information here: http://www.html5rocks.com/en/features/storage).
For example, you could save your data like this:
localStorage["carouselSource"] = JSON.stringify(
    $('#carouselDiv li img').map(function(i,e){
        return $(this).attr('src');
    }).get();
);

and retrieve it like this (before the jCarousel call):
var items = jQuery.parseJSON(localStorage["carouselSource"]);

jQuery.each(items, function(i,e){
    $('#carouselDiv').append('

');
});

This would ensure that the same set of images are displayed when the user returns to the page. You could use a similar technique to save things like the position of the slider and any other variable data you want to save.


text:
Q: Automate the laravel homestead to reload my Homestead.yaml configurations After installing the homestead and adding the box, and configured the Homestead.yaml that contains the url homestead.app
After doing an up and ssh, going to /etc/nginx/sites-enabled the homestead.app was there.
So I changed the homestead.app into site.daison.app in my Homestead.yaml from my hosts and doing a homestead halt and homestead up again and ssh just to reload my configurations as I thought.
Going back to the /etc/nginx/sites-enabled the homestead.app still remain.
So what I did is to destroy my homestead using the command homestead destroy and doing the up and ssh again going back to /etc/nginx/sites-enabled the config site.daison.app is now there.
Question:
Is there a way to do this and reload my homestead configurations instead of destroying it and doing things again and again?

A: Go to the directory where you homestead is created. Type in the terminal
vagrant provision

Homestead is just a predefined vagrant-box.
Documentation:
http://laravel.com/docs/4.2/homestead#daily-usage


text:
Q: Consistant and Smooth Movement Via Joystick So this is the code I have placed in the touchesMoved function and all of works. I also have ways of stopping each animation and movement in other functions that are not posted here.
The problem I am having, and it was fairly obvious to me before I finished coding it is that the movement will stutter/jitter and it isn't the smoothness I was looking for. I also wanted to ask how I could limit the speed at which the sprite moves as right now you can see that it moves by variable "v" which is based on how far you move from the joystick.
My joystick works in a way where your initial touch is the "base" and where you move too is the new direction.
TLDR: How do I limit movement speed where the speed is currently based on variable "v" and make the movement more smooth?
    for touch in touches {
        let location = touch.location(in: self)

        let v = CGVector(dx: location.x - joystickMove.x, dy: location.y - joystickMove.y)
        let angle = atan2(v.dy, v.dx)
        deg = angle * CGFloat(180/M_PI)
        readyToMove = true

        switch(deg){

        case -44...45:
            player.walkRight()
            let action = SKAction.moveBy(x: v.dx, y: v.dy, duration: 0.5)
            let repeatAction = SKAction.repeatForever(action)
            player.run(repeatAction, withKey: "move")
            break;
        case 46...135:
            player.walkUp()
            let action = SKAction.moveBy(x: v.dx, y: v.dy, duration: 0.5)
            let repeatAction = SKAction.repeatForever(action)
            player.run(repeatAction, withKey: "move")
            break;
        case 136...180, (-180)...(-135):
            player.walkLeft()
            let action = SKAction.moveBy(x: v.dx, y: v.dy, duration: 0.5)
            let repeatAction = SKAction.repeatForever(action)
            player.run(repeatAction, withKey: "move")
            break;
        case (-134)...(-45):
          player.walkDown()
            let action = SKAction.moveBy(x: v.dx, y: v.dy, duration: 0.5)
            let repeatAction = SKAction.repeatForever(action)
            player.run(repeatAction, withKey: "move")
            break;
        default:

            break;
        }
}

A: The jittering is caused by the SKActions each runs 0.5 seconds. In the meanwhile multiple other touch events can happen which can trigger multiple other movements.
You are also adding everytime new actions to the sprite which repeats forever.
I would move the animation to the update method:
var lastUpdateTime = TimeInterval()
var yourSpriteSpeed: CGFloat = 100.0
override func update(_ currentTime: TimeInterval) {

    let dt = CGFloat(currentTime - lastUpdateTime)
    lastUpdateTime = currentTime

    player.position = CGPoint(x: player.position.x + dx * yourSpriteSpeed * dt, y: player.position.x + dy * yourSpriteSpeed * dt)

}

A: To limit a vector v to a specific magnitude, you need to check if its magnitude exceeds the threshold and then normalise it.
Pseudocode:
func mag(v) -> Double {
    return sqrt(v.x * v.x + v.y * v.y)
}

func mult(v, amount) -> Vector {
    return Vector(v.x * amount, v.y * amount)
}

func div(v, amount) -> Vector {
    return Vector(v.x / amount, v.y / amount)
}

func unit(v) -> Vector {
    return  v.div(mag(v))
}

So now you do:
// ... compute v as before

if mag(v) > MAX_SPEED {
    v = unit(v).mult(MAX_SPEED)
}

// use v.x, v.y as before

While this approach will limit your joystick speed, I doubt it will completely rid you of your jitter issues (it just scales it back to the amount at MAX_SPEED).
PS: To get completely smooth motion, you need to maintain position and velocity as separate variables, and have a notion of a target velocity controlled by your joystick. At every frame, you update position based on current velocity and lerp current velocity to target velocity.
Abrupt changes in velocity is what causes jitters; lerping is one way to smoothen it out.


text:
Q: Is there a way to continue within a futures for_each stream? I am doing a for_each loop over a stream of futures received via a mspc::Receiver
rx.for_each(move |trade| {
    if something_true {
        continue;
    }

    // down here I have computation logic which returns a future
});

I would like to do something like the logic above.
Of course, I could just do an if/else statement but both branches have to return the same type of future, which is hard for me to do as the future I generate in my computation logic is a long chain of messy futures. Which got me thinking if there is actually a simple way of approaching this, like a continue or some sort?

A: Let's solve the two issues separately. First, the easiest: if your chain of futures inside for_each() is not homogeneous (they rarely will be), consider returning a boxed future (i.e. Box<dyn Future<Item = _, Error = _>>). You may need to typecast the closure return to that, as the compiler will sometimes not get what you are trying to do.
Now, for the "continue if condition" - this typically means you're filtering out certain elements of the stream, which indicates that the better function to call may include filter() or an intermediate state - i.e. returning a future whose item type is Option<_>, and then filtering based on that in the next member of the chain.

A: No, you cannot. continue is syntax that is only accepted by the core Rust language and crates cannot make use of it.
You could instead return early:
rx.for_each(move |trade| {
    if true {
        return future::ok(());
    }

    future::ok(())
});

both branches have to return the same type of future

Use Either or a boxed trait object
rx.for_each(move |trade| {
    if true {
        return Either::A(future::ok(()));
    }

    Either::B(future::lazy(|| future::ok(())))
});

See also:

*

*How do I conditionally return different types of futures?
I'd probably move the condition to the stream such that the for_each never sees it:
rx.filter(|trade| true)
    .for_each(move |trade| future::ok(()));


text:
Q: "Enabling ... during" or "enabling ... through"? I want to say that:

I worked on enabling Marketing and Engineering teams during several
  product launches.

Is "during" the right word to use here? Should it be "through"? How do I know which is the right preposition to use?

A: First, I think you probably mean to say "I worked to enable" not "I worked on enabling", or even simpler "I enabled".  The problem with "worked on enabling" is it has the connotation of something that took a long time to complete, like:

*

*I worked on the Hoover Dam.

*I'm working on my anger issues; I've worked on them and seen improvement.

*I worked on the staff of a newspaper for my first job.

You don't want to convey the idea that it took you a long time to enable the teams so that's why the alternatives I suggest are preferable.
Now examining:

*

*I enabled Marketing and Engineering teams during several product launches, versus

*I enabled Marketing and Engineering teams through several product launches

The first version, using "during", connotes that this work was periodic, that there would be a product launch, and you would need to shift gears and move into enabling mode, and then the launch would end, and you would switch to a different type of work for a period.  The second version, using "through", connotes that this work was continuous, that another product would probably start being launched even before the first was done launching, and therefore year-round you were focused on enabling these teams participating in the product launches. I don't think either word has a better connotation to it or would be more helpful on a resume than the other, so you probably just want to use whichever word is more accurate.


text:
Q: Lepton 3.5 thermal camera image quality issue [running on Jetson Nano] I am using Lepton 3.5 with Pure-thermal 2. Compiled C + V4l2 code on Jetson Nano from Groupgets git page: https://github.com/groupgets/purethermal1-uvc-capture.
Initially got this error message Libv4l didn't accept RGB24 format. Can't proceed. Then changed image resolution from 80x60 to 160x120 and pixel format YUYV to UYVY then the code works but not generating good images. The image contains multiple strips having different colors as shown below:

Changing pixel format to GREY and resolution 640*480, generated the image shown below:

Please anyone suggest how to get the perfect images in GREY, UYVY and other supported formats.
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <fcntl.h>
    #include <errno.h>
    #include <sys/ioctl.h>
    #include <sys/types.h>
    #include <sys/time.h>
    #include <sys/mman.h>
    #include <linux/videodev2.h>
    #include <libv4l2.h>

    #define CLEAR(x) memset(&(x), 0, sizeof(x))

    struct buffer {
            void   *start;
            size_t length;
    };

    static void xioctl(int fh, int request, void *arg)
    {
            int r;

            do {
                    r = v4l2_ioctl(fh, request, arg);
            } while (r == -1 && ((errno == EINTR) || (errno == EAGAIN)));

            if (r == -1) {
                    fprintf(stderr, "error %d, %s\n", errno, strerror(errno));
                    exit(EXIT_FAILURE);
            }
    }

    int main(int argc, char **argv)
    {
            struct v4l2_format              fmt;
            struct v4l2_buffer              buf;
            struct v4l2_requestbuffers      req;
            enum v4l2_buf_type              type;
            fd_set                          fds;
            struct timeval                  tv;
            int                             r, fd = -1;
            unsigned int                    i, n_buffers;
            char                            *dev_name = "/dev/video0";
            char                            out_name[256];
            FILE                            *fout;
            struct buffer                   *buffers;

            fd = v4l2_open(dev_name, O_RDWR | O_NONBLOCK, 0);
            if (fd < 0) {
                    perror("Cannot open device");
                    exit(EXIT_FAILURE);
    }

            CLEAR(fmt);
            fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
            fmt.fmt.pix.width       = 640;
            fmt.fmt.pix.height      = 480;
            fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_GREY;
            fmt.fmt.pix.field       = V4L2_FIELD_NONE;
            xioctl(fd, VIDIOC_S_FMT, &fmt);
            if (fmt.fmt.pix.pixelformat != V4L2_PIX_FMT_GREY) {
                    printf("Libv4l didn't accept RGB24 format. Can't proceed.\n");
                    exit(EXIT_FAILURE);
            }
            if ((fmt.fmt.pix.width != 80) || (fmt.fmt.pix.height != 60))
                    printf("Warning: driver is sending image at %dx%d\n",
                            fmt.fmt.pix.width, fmt.fmt.pix.height);

            CLEAR(req);
            req.count = 2;
            req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
            req.memory = V4L2_MEMORY_MMAP;
            xioctl(fd, VIDIOC_REQBUFS, &req);

            buffers = calloc(req.count, sizeof(*buffers));
            for (n_buffers = 0; n_buffers < req.count; ++n_buffers) {
                    CLEAR(buf);

                    buf.type        = V4L2_BUF_TYPE_VIDEO_CAPTURE;
                    buf.memory      = V4L2_MEMORY_MMAP;
                    buf.index       = n_buffers;

                    xioctl(fd, VIDIOC_QUERYBUF, &buf);

                    buffers[n_buffers].length = buf.length;
                    buffers[n_buffers].start = v4l2_mmap(NULL, buf.length,
                                  PROT_READ | PROT_WRITE, MAP_SHARED,
                                  fd, buf.m.offset);

                    if (MAP_FAILED == buffers[n_buffers].start) {
                            perror("mmap");
                            exit(EXIT_FAILURE);
                    }
            }

            for (i = 0; i < n_buffers; ++i) {
                    CLEAR(buf);
                    buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
                    buf.memory = V4L2_MEMORY_MMAP;
                    buf.index = i;
                    xioctl(fd, VIDIOC_QBUF, &buf);
            }
            type = V4L2_BUF_TYPE_VIDEO_CAPTURE;

            xioctl(fd, VIDIOC_STREAMON, &type);
            for (i = 0; i < 20; i++) {
                    do {
                            FD_ZERO(&fds);
                            FD_SET(fd, &fds);

                            /* Timeout. */
                            tv.tv_sec = 2;
                            tv.tv_usec = 0;

                            r = select(fd + 1, &fds, NULL, NULL, &tv);
                    } while ((r == -1 && (errno = EINTR)));
                    if (r == -1) {
                            perror("select");
                            return errno;
                    }

                    CLEAR(buf);
                    buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
                    buf.memory = V4L2_MEMORY_MMAP;
                    xioctl(fd, VIDIOC_DQBUF, &buf);

                    sprintf(out_name, "out%03d.ppm", i);
                    fout = fopen(out_name, "w");
                    if (!fout) {
                            perror("Cannot open image");
                            exit(EXIT_FAILURE);
                    }
                    fprintf(fout, "P6\n%d %d 255\n",
                            fmt.fmt.pix.width, fmt.fmt.pix.height);
                    fwrite(buffers[buf.index].start, buf.bytesused, 1, fout);
                    fclose(fout);

                    xioctl(fd, VIDIOC_QBUF, &buf);
            }

            type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
            xioctl(fd, VIDIOC_STREAMOFF, &type);
            for (i = 0; i < n_buffers; ++i)
                    v4l2_munmap(buffers[i].start, buffers[i].length);
            v4l2_close(fd);

            return 0;
    }

A: have you checked the usb descriptor?
the purethermal firmware creates an uvc device and with lsusb you can get a list of the supported formats and frames in the usb descriptor.


text:
Q: Reprojection function fails in R My aim is to reproject two R objects to a common CRs, but I keep running into this error
Error
Error in (function (classes, fdef, mtable)  :
  unable to find an inherited method for function 'proj4string<-' for signature '"data.frame", "CRS"'

This is my code
setwd("H:/R")
library("rgdal")
library("sp")#Shiet. I just loaded more than one library in one sentence. It didn't work though
library("rgeos")
library("ggplot2")
library("raster")
Census.Data <-read.csv("practicaldata.csv")
Polygon.Data <- readOGR(dsn = "H:/R", layer = "Camden_oa11")
House.Data <-  readOGR("Camden_house_sales")
Polygons.Census <- merge(Census.data, Polygon.Data, by.x ="OA", by.y ="OA11CD")
proj4string(Polygons.Census) <- CRS("+init=EPSG:27700")
proj4string(House.Data) <- CRS("+init=EPSG:27700")

What could be causing the error?

A: I've constructed some simple sample data (something you should always do in questions here so we can reproduce your problem) and I can get your error on this line (you don't tell us which line is your problem but let's see if its this):
> proj4string(Polygons.Census) <- CRS("+init=EPSG:27700")
Error in (function (classes, fdef, mtable)  :
  unable to find an inherited method for function 'proj4string<-' for signature '"data.frame", "CRS"'

Reading the error message tells us its trying to find a function for setting proj4string where the first argument is a data.frame and the second is a CRS. So Polygons.Census at this point is a data frame, and not a spatial data frame. How is this happening?
Polygons.Census is created like this:
Polygons.Census <- merge(Census.Data, Polygon.Data, by.x ="OA", by.y ="OA11CD")

(note you have Census.data and Census.Data and these are two different objects, but you'd get a different error if one doesn't exist so I'll assume you've got two copies of the same data because you've been inconsistent with .data and .Data).
Here Census.Data is a plain data frame read in from a CSV file. You've merged the spatial data, and with merge like this the returned object is the same type as the first argument, Census.Data. Its a plain data frame. This has dropped the spatial nature of the object, so you can't set a CRS for it because its not spatial, and R gives the error saying this.
If you do the merge the other way round you get a spatial object:
> class(merge(Polygon.Data, Census.Data, by.x="OA11CD",by.y="OA"))
[1] "SpatialPointsDataFrame"
attr(,"package")
[1] "sp"

Compared with this way round, plain data frame:
> class(merge(Census.Data, Polygon.Data, by.y="OA11CD",by.x="OA"))
[1] "data.frame"

Depending on the nature of the merge, this may be what you meant to do, to create a new spatial object with attributes taken from matching OAs in the census data.
Once you've done this this way round you can assign a coordinate system if the data has a wrong system already, or use spTransform to convert the coordinates. You've not shown which coordinates the data is in so I'm not going to show you this, maybe ask a new question about transforming spatial data if you can't get this to work. But I should have given you enough information to do the merge.
Also STRONG recommendation to install and use the sf package for spatial data since sp and friends are going away soon.


text:
Q: Excel vba how to copy sheet with all formatting & page setup I've seen quite a few examples for making a full copy of a worksheet but none of them are working for me. In my case the sheet has to go into a new workbook. In my actual code wb is defined global and the workbook is created in another sub that called this one.
  Dim wb As Workbook
  Set wb = Workbooks.Add()
  Dim newtab as Worksheet

  With ActiveWorkbook
   .Sheets("Sample Attendance").Copy After:=wb.Sheets(.Sheets.Count)
   Set newtab = wb.Sheets(wb.Sheets.Count - 1)
  End With

didn't work.
Likewise
  ActiveWorkbook.Sheets("Sample Attendance").Copy After:=wb.Sheets(1)
  Set newtab = wb.Sheets("Sample Attendance")
  newtab.Name = tabname

both methods return after the Copy statement.
I've been moderately successful with this:
  Set newtab = wb.Worksheets.Add
  newtab.Name = tabname
  Set Attendance = ThisWorkbook.Sheets("Sample Attendance")
  Attendance.Range("A:BB").Copy Destination:=newtab.Cells(1, 1)

which works. But then I have to copy all of the PageSetup across which is giving me fits and takes forever.

A: I see two problems with your 1st piece of code...

*

*You are using Activeworkbook. When you add a new workbook, the new workbook becomes your active workbook :)

*The second problem is the DOT before .Sheets.Count in wb.Sheets(.Sheets.Count). why pick the count from the workbook you are copying?
Try this
Sub Sample()
    Dim thiswb As Workbook, wb As Workbook
    Dim newtab As Worksheet

    Set thiswb = ThisWorkbook
    Set wb = Workbooks.Add()

    With thiswb
        .Sheets("Sample Attendance").Copy After:=wb.Sheets(wb.Sheets.Count)
        Set newtab = wb.Sheets(wb.Sheets.Count - 1)
    End With
End Sub

A: Give this a shot:
Sub SheetCopier()
    Dim OriginalWB As Workbook
    Dim NewWB As Workbook
    Set OriginalWB = ActiveWorkbook
    Workbooks.Add
    Set NewWB = ActiveWorkbook
    OriginalWB.Sheets("qwerty").Copy Before:=NewWB.Sheets(1)
End Sub


text:
Q: Two static IPs from Comcast to two devices. How to connect? I have a car wash that has equipment running that must have a static IP.  I also want to view my cameras from home.  I have a comcast connection and they have given me two static IP's.  What is the best way to do this.  Can I put in two routers off a switch connected to my comcast box?

A: Do not waste two static IPs on this. Just use one router, to the WAN side of which you will assign one of the two static IPs (keeping the other for future needs), and connect your equipment to the LAN side of the router if the number of cables is smaller than the number of gates available on the router, or buy a cheap switch (not a hub, careful) as per the number of cables, then draw one cable from the switch to one of the LAN-side gates of the router.
In order to view the cameras from remote you will have to do some port forwarding, the internet is replete with instructions on how to do it.


text:
Q: Why is this rangev3 implementation of vectors summation slower than the STD equivalent? I am considering using rangev3 in a library of mine. I like rangev3's syntax, but the priority is performance. The library runs lots of vector multiplications and additions, mostly 128 samples long. I used Google benchmark to assess for instance addition of two vectors. The ranges version is much slower than the STD version (almost 10x slower for short vector lengths). This is somewhat surprising, as rangev3 (and the future std::ranges in C++20) is often claimed to have good performance.
Is there an issue with how I am using rangev3 here? Or is it something to do with the compiler not being able to unroll rangev3 code well? Or does rangev3 performance gains show up only for many daisy-chained operations?
Notes: the output = rng1; assignment should not allocate memory as the vector length is the same (I tried to use ranges::copy, but it becomes 100 times slower). I tried to pre-initialise and randomise the vectors A and B, but saw no difference. I did notice that if I had more operations in a pipeline, the gap between STL and ragesv3 narrowed, but only for long vectors (above 32000 for 5 consecutive operations).
Below is a self-contained example with performance metrics. I am running C++17 LLVM libc++ on a 4-core i7 MacBook Pro with -O3 flag.
#include <range/v3/all.hpp>
#include <benchmark/benchmark.h>

static void AddBenchmark(benchmark::State& state) {
  const size_t length = state.range(0);

  std::vector<double> B(length);
  std::vector<double> A(length);
  std::vector<double> output(length);

  while (state.KeepRunning()) {
    std::transform(A.begin( ), A.end( ), B.begin( ), output.begin(), std::plus<>( ));
    benchmark::ClobberMemory(); // Force output to be written to memory.
  }
}
BENCHMARK(AddBenchmark)->RangeMultiplier(8)->Range(1<<7, 1<<20);

static void AddRangesBenchmark(benchmark::State& state) {
  const size_t length = state.range(0);

  std::vector<double> B(length);
  std::vector<double> A(length);
  std::vector<double> output(length);

  while (state.KeepRunning()) {
    auto rng1 = ranges::view::transform(A, B, std::plus<>( ));
    output = ranges::to<std::vector<double>>(rng1);
    benchmark::ClobberMemory(); // Force output to be written to memory.
  }
}
BENCHMARK(AddRangesBenchmark)->RangeMultiplier(8)->Range(1<<7, 1<<20);

BENCHMARK_MAIN();

which outputs
AddBenchmark/128                 30.3 ns         30.2 ns     23194091
AddBenchmark/512                  121 ns          121 ns      5758094
AddBenchmark/4096                1917 ns         1906 ns       417300
AddBenchmark/32768              25054 ns        24795 ns        28182
AddBenchmark/262144            385913 ns       382803 ns         1718
AddBenchmark/1048576          2100095 ns      2096442 ns          328
AddRangesBenchmark/128            218 ns          218 ns      3131249
AddRangesBenchmark/512            579 ns          579 ns      1169688
AddRangesBenchmark/4096          5071 ns         5069 ns       123231
AddRangesBenchmark/32768        50702 ns        50649 ns        14382
AddRangesBenchmark/262144      482216 ns       481333 ns         1288
AddRangesBenchmark/1048576    3349331 ns      3347475 ns          200

A: (Too long for a comment)
When I try to compile this code, I get:
<source>:1468:14: error: no match for 'operator=' (operand types are 'std::vector<double>' and 'ranges::transform2_view<ranges::ref_view<std::vector<double> >, ranges::ref_view<std::vector<double> >, std::plus<void> >')
 1468 |     output = rng1;

and that's a legit error, I think. So, perhaps you mis-copy-pasted? Or do you want to be using ::to<std::vector<double>>() there?


text:
Q: Help with a (subjective) conditional probability problem I'm having trouble working out the conditional probabilities in this problem.
I tell you that I'm about to toss a coin, which is either fair, or will land heads every time.
You are told there is a 0.5 chance I pick either coin. Given this information, your subjective probability of the toss landing heads should be 0.75.
If I toss the coin 3 times for you, and it lands heads each time, how should you adjust your subjective probability, and to what value?
Thanks!

A: Let $X$ be the event that the coin being flipped is fair.
Let $Y$ be the event that you have $3$ starting flips all landing on heads.
We can calculate $P(X|Y)$, the probability that the coin being flipped is the fair coin given you have $3$ flips all landing with heads. $$P(X|Y)=\dfrac{P(X\cap Y)}{P(Y)}$$
$P(X\cap Y)=\dfrac{1}{2^3}\bigg(\dfrac{1}{2}\bigg)=\dfrac{1}{16}$. This is the probability that the coin is fair and you flipped heads thrice.
$P(Y)=\bigg(\dfrac{1}{2}\bigg)1+\bigg(\dfrac{1}{2}\bigg)\dfrac{1}{8}=\dfrac{9}{16}$. This is the total probability that we got heads thrice (either from the all-heads coin or the fair coin).
Hence $P(X|Y)=\dfrac{1}{9}$.
Since there is a $\dfrac{1}{9}$ chance that the coin is fair, and a $\dfrac{8}{9}$chance that the coins is all-heads, the probability of the next flip also being heads is $\bigg(\dfrac{1}{2}\bigg)\dfrac{1}{9}+\dfrac{8}{9}=\dfrac{17}{18}$.

A: Let us call $R$ the result event (3 times head), $H$ the event "the coin falls always on heads" and $F$ the event "the coin is fair".
The probability that we get 3 heads is
$$ P(R)=P(R|H)P(H)+P(R|F)P(F)=1\times\frac12+\frac18\times\frac12=\frac9{16}.$$
So the probability that we have a fair coin is, after Bayes formula,
$$P(F|R)=\frac{P(R|F)P(F)}{P(R)}=\frac{\frac18\times\frac12}{\frac9{16}}=\frac19.$$
We should therefore adjust our subjective probabilities to $P_{\rm new}(F)=\frac19$ and $P_{\rm new}(H)=\frac89$.


text:
Q: Correct way to pass object reference into .NET Core Web API I'm just starting out with .NET Web API programming, and I have a question for seasoned .NET developers - what is the "correct" way to pass an object reference into a Create endpoint?
I have the following models:
public class Task
{
    public int ID { get; set; }
    public string Title { get; set; }
    public virtual User User { get; set; }
}

public class User
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

And my Controller - endpoint to create a Task:
[HttpPost]
public async Task<IActionResult> PostTask([FromBody] Models.Task task)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    _context.Task.Add(task);
    await _context.SaveChangesAsync();

    return CreatedAtAction("GetTask", new { id = task.ID }, task);
}

By default, this has some interesting behavior. It expects an entire User model to be passed into the POST request (see below), and will actually create the user when passed:
{
  "id": 0,
  "title": "string",
  "user": {
    "id": 0,
    "firstName": "string",
    "lastName": "string"
  }
}

I understand technically why it would do this, but this is definitely not acceptable behavior in a real app - so my question is - what is the "correct/appropriate" way to pass a UserID and do validation on the model in .NET? Should I forego the use of "ModelState.IsValid" and do manual validation?
As a secondary question - I am using NSwag to generate Swagger docs from my API, and it's showing "id" as a parameter that needs to be passed into the POST method. Obviously, ID cannot be passed as it's generated in code, but is there a way to get Swagger to not show ID as being a passable property?

A: Then create a  data transfer model that exposes only the data you want sent over the wire.
public class NewTaskDto {
    [Required]
    public string Title { get; set; }
    [Required]
    public int UserId { get; set; }
}

and map the data to your models on the server, along with what ever validation is required. For example checking that the UserId exists and is valid.
[HttpPost]
public async Task<IActionResult> PostTask([FromBody] NewTaskDto data) {

    if(data != null) {
        validateUserId(data.UserId, ModelState);
    }

    if (!ModelState.IsValid) {
        return BadRequest(ModelState);
    }

    Models.Task task = MapDataToTask(data); //create Task and copy members

    await saveTask(task);

    return CreatedAtAction("GetTask", new { id = task.ID }, task);
}

That way the doc will only see the and report on the exposed members.

A: The attribute [Required] is mandatory and then you can check parameter.


text:
Q: Avoid clicking twice to begin editing boolean (checkbox) cell in Backgrid We are using Backgrid and have discovered that to begin editing a "boolean" (checkbox) cell in Backgrid, you must click twice: the first click is ignored and does not toggle the state of the checkbox.  Ideally we would get to the root of what is causing this behavior (e.g. is preventDefault being called) and solve it there, but I at first I tried a different approach with the following extension of BooleanCell's enterEditMode method which seemed like a logical place since it was upon entering edit mode that the checkbox click was being ignored.
Problem is my attempt also toggles the state of the previously edited checkbox.  Here is the code.
var BooleanCell = Backgrid.BooleanCell.extend({
    /*
    * see https://github.com/wyuenho/backgrid/issues/557
    */
    enterEditMode: function () {
        Backgrid.BooleanCell.prototype.enterEditMode.apply(this, arguments);
        var checkbox = this.$('input');
        checkbox.prop('checked', !checkbox.prop('checked'));
    }
});

A: The following seems to work:
var BooleanCell = Backgrid.BooleanCell.extend({
    editor: Backgrid.BooleanCellEditor.extend({
        render: function () {
            var model = this.model;
            var columnName = this.column.get("name");
            var val = this.formatter.fromRaw(model.get(columnName), model);

            /*
             * Toggle checked property since a click is what triggered enterEditMode
            */
            this.$el.prop("checked", !val);
            model.set(columnName, !val);

            return this;
        }
    })
});

This is because the render method gets called by Backgrid.BooleanCell's enterEditMode method on click, and said method destroys and re-creates the checkbox as follows but in so doing loses the checked state (after the click) of the original "non-edit-mode" checkbox
  this.$el.empty();
  this.$el.append(this.currentEditor.$el);
  this.currentEditor.render();

A: A simpler approach:
var OneClickBooleanCell = Backgrid.BooleanCell.extend({
  events: {
    'change input': function(e) {
      this.model.set(this.column.get('name'), e.target.checked);
    },
  },
});

This bypasses the CellEditor mechanism entirely and just reacts to the input event on the checkbox by updating the model.


text:
Q: React v15.0.0: Since that renderToString is deprecated, how to go about server-side rendering? There is a new release candidate of React, v 15.0.0. Since the renderToString method now is deprecated in the library, and apparently is going to be discontinued in future versions, what is the way to support server-side rendering with React in the new version?
On the docs page, no replacement for the renderToString or other explanation has been provided except that this particular method is no longer supported.
Thank you

A: As described in the comments, the correct (and only) way to render to a string with recent versions of React is to use ReactDOMServer's renderToString. Lots of existing answers and documentation refer to the removed React.renderToString, though. It has been deprecated for a while, but apparently only removed recently.
A quick and dirty example of what this might look like (running with node-babel):
const Express = require('express')
const React = require('react')
const ReactDomServer = require('react-dom/server')

const Label = React.createClass({
  render: function () {
    return <p> Foo! </p>
  }
})

const server = Express()

server.use(function(req, res) {
  const appHtml = ReactDomServer.renderToString(<Label />)
  res.send(appHtml)
})

server.listen(3000)


text:
Q: Does the Divisor Function $\sigma(n)$ have analogues for other Fuchsian groups? I have been reading about the divisor function $\sigma = 1 \ast 1$ and proved an elementary identity:
$$ \Big[\sum_{d|n} \sigma_0(d)\Big]^2  = \sum_{d|n} \sigma_0(d)^3$$
Here $\sigma_0 = \sum_{d|n} 1$ counts the divisors of $n$.  Could be the first of many such kind of identity?  I wouldn't even be sure where to look for identities for $\sigma_k$.

Perhaps you could prove such a result with Eisenstein series:
$$ G_k(z) = - \frac{B_k}{k} + \sum_{n=1}^\infty \sigma_{k-1}(n)q^n = \frac{(2\pi i)^k}{(k-1)!} \times \frac{1}{2}\sum \frac{1}{(m \tau + n)^k}$$
However $G_0$ is not a meaningful Eisenstein series.

Could the divisor function have analogues for other Fuchsian groups?  The Ramanujan sum
$$ \sum_{(a,q)=1} e^{2\pi i \frac{a}{q}} = \mu(q)$$
related to the Mobius function.  This certainly has analogues for other Fuchsian groups.

A: Looks similar to the elementary formula $(\sum_{k=1}^n k)^2=\sum_{k=1}^n k^3$. Here's why. The function $\sigma_0$ is multiplicative, so
$$
  \begin{aligned}
  \sum_{d\mid n} \sigma_0(d)
  &= \prod_{p^{e_p}\|n} (1+\sigma_0(p)+\sigma_0(p^2)+\cdots+\sigma_0(p^{e_p}))\\
   &= \prod_{p^{e_p}\|n} (1+2+\cdots+(e_p+1))\\
   &= \prod_{p^{e_p}\|n} \frac{(e_p+1)(e_p+2)}{2}.\\
  \end{aligned}
$$
Similarly, since $\sigma_0^3$ is multiplicative,
$$
  \begin{aligned}
  \sum_{d\mid n} \sigma_0(d)^3
  &= \prod_{p^{e_p}\|n} (1+\sigma_0(p)^3+\sigma_0(p^2)^3+\cdots+\sigma_0(p^{e_p})^3)\\
   &= \prod_{p^{e_p}\|n} (1^3+2^3+\cdots+(e_p+1)^3)\\
   &= \prod_{p^{e_p}\|n} \left(\frac{(e_p+1)(e_p+2)}{2}\right)^2.\\
  \end{aligned}
$$
Voila, no need for Eisenstein series! And similar results are easily proven.

A: If you are looking for identities involving $\sigma_k$, you could try looking at Duke's article "When is the product of two Hecke eigenforms an eigenform?". For instance, the fact that $E_8=E_4^2$ immediately implies that $$\sigma_7(n)=\sigma_3(n)+120\sum_{m=1}^{n-1}\sigma_3(m)\sigma_3(n-m)$$ by simply computing Fourier coefficients. This work has been extended by a number of authors. (Duke only considered eigenforms for $\mathrm{SL}_2(\mathbb Z)$.) For instance, Emmons and Lanphier (in "Products of an arbitrary number of Hecke eigenforms") considered products of an arbitrary number of eigenforms and Johnson (in "Hecke eigenforms as products of eigenforms") considered eigenforms of higher level (e.g. eigenforms for the Fuchsian group $\Gamma_1(N)$).
In essence, the idea is that whenever you have a relation involving Hecke eigenforms, you get an elementary number theoretic identity by considering the Fourier coefficients.


text:
Q: Absolutely continuous measure which is not equivalent Does there exist a simple example of a probability measure on $[0,1]$ such that ${\rm spt}\,\mu = [0,1]$ and $\mu \ll \mathcal{L}$ but $\mathcal{L} \not\ll \mu$? Here $\mathcal{L}$ denotes the Lebesgue measure.

A: Let $C$ be  a fat  Cantor set and $\mu (E)=\mathcal L (E\setminus C)$. Then $\mu$ has full support (since $C$ has no interior) and it is absolutely continuous w.r.t. Lebesgue measure but $\mu (C)=0$ whereas Lebesgue measure of $C$ is  $>0$.


text:
Q: How can I draw a curved line segment using QuadCurve2D.Double? Here is the line of code where I declare the curve:
QuadCurve2D.Double curve = new QuadCurve2D.Double(50,100,100,170,150,100);

Now what code can I use to draw this curve? I tried something like:
g.draw(curve);

but obviously that didn't work. Any suggestions?

A: I've made a minimum test case of what I think your describing here.
This program works but I can't really help you unless I can see the code you are working with.
import java.awt.geom.*;
import java.awt.*;
import javax.swing.*;

public class CurveDraw extends JFrame {
        public static void main(String[] args) {
                CurveDraw frame = new CurveDraw();
                frame.setVisible(true);
        }
        public CurveDraw() {
                setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                setSize(400,400);
        }
        public void paint(Graphics g) {
                QuadCurve2D.Double curve = new QuadCurve2D.Double(50,100,100,170,150,100);
                ((Graphics2D)g).draw(curve);
        }
}

A: Works fine for me...

public class PaintQuad {

    public static void main(String[] args) {
        new PaintQuad();
    }

    public PaintQuad() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new PaintMyQuad());
                frame.setSize(200, 200);
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class PaintMyQuad extends JPanel {

        @Override
        protected void paintComponent(Graphics g) {

            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();

            QuadCurve2D.Double curve = new QuadCurve2D.Double(50,100,100,170,150,100);

            g2d.setColor(Color.RED);
            g2d.draw(curve);

        }

    }

}

Two things come to mind.

*

*Make sure you've set the color of the graphics, the default is the back ground color of the pane

*Make sure that the size of your container is large enough (and is layout correctly) to show the graphics.


text: Q: How to connect database to Report or Report Wizard in Visual Basic 2012? My database is Vertrigo(MySql) and i don't know how to connect my database to report or report wizard in Visual Basic 2012. I need the report or report wizard in order to  print all the data that i have in my database. Can you help me? Please?


text:
Q: Исправление html, следуя w3.validator Прогоняю страницы сайта через validator.w3.org. Подозреваю, что другие HTML-валидаторы будут также ругаться...
Вылезает ошибка та же по сути, но на разных элементах.
Вариант 1

Error: Attribute secondaryImage not allowed on element img at this
  point.

Ошибка указывает на вот этот тэг (сокращен для простоты):

Вторая картинка показывается при наведении мышкой на src.
Суть: secondaryImage мне необходим для корректной работы сайта.
Вариант 2

Error: Attributes fieldtype and optional are not allowed on element input at this point.

Ошибка указывает на вот этот тэг (сокращен для простоты):
<input type="TEXT" name="searchStr" FIELDTYPE="TEXT" OPTIONAL="YES">

Перед отправкой формы запускается библиотека, которая проверяет заполнение полей, используя эти дополнительные аттрибуты.
Суть: аттрибуты необходимы для корректной работы библиотеки валидации.
.
Я знаю как решить все эти проблемы. Просто это на данном этапе развития сайта это большой объем работы.
.
Итак, основной вопрос:
насколько серьезна эта ошибка валидатора?
Связывался ли кто-то с такой проблемой, что seo-шники потом требовали устранять это под страхом смерти?

A: Опасность кастомных атрибутов не в том, что они что-то ломают сейчас, а в том, что они потенциально могут что-нибудь сломать в будущем. Вот выйдет новая версия браузера, которая особым образом обрабатывает атрибут OPTIONAL - и во что сайты превратятся?)
А для data-атрибутов гарантируется, что браузер никогда не будет их как-то обрабатывать, кроме занесения в dataset.

A: *

*С точки зрения валидатора:
Кастомные атрибуты надо начинать с префикса data и писать маленькими буквами.

*С точки зрения браузеров:
Съедят все.

*С точки зрения SEO:
Понятия не имею. Влияние кажется мне маловероятным.

<input type="text" name="searchStr" data-field-type="TEXT" data-optional="YES">


text:
Q: Best way to insert high trafic into CosmosDb with Entity Framework Core we have ASP.NET Core 6.0 website and want to write logging data into CosmosdDB.
Therefor i have a static CosmosDB Manager, which has the CosmosDBContext as static property, and the add method uses this context to AddLog() and SaveContext().
I had to put the Context in a lock, as multiple calls to the AddLog() method caused an error.
Is this the right way to have (concurrent) Writes to the CosmosDB?
I had previously separate Context for each request, but this opened to many threads...
Any thoughts on this Implementation?
public static class LogManager {

    private static CosmosDBContext Context { get; set; }

    public static void AddLog(string data) {

        var item = new LogItem {
            Data = data
        };

        if (Context == null) Context = new();

        lock (Context) {
            Context.Add(item);
            Context.SaveChanges();
        }

    }

}

public class LogItem {
    public string Data { get; set; }
}


text: Q: Pivot4j does not install on my pentaho 9.3.0.0 server I hope you are doing well. I am using the Pentaho BI server version 9.3.0.0 on my Windows 10 x64 bit. I want to use Pivot4j to browse my OLAP cube that I created with workbench. When I click in the UI menu bar on File->New, Pivot4j does not exist in the list as you see in screenshot1 above enter image description here. Then I proceeded to download it but I can't install it on my server. Here is the screenshot2 enter image description here  of the error that is showing. Please help me to install it because I am newbie with this tool, and really I need it. Thank you in advance.


text:
Q: Meaning of a convergence warning in glmer I am using the glmer function from the lme4 package in R, and I'm using the bobyqa optimizer (i.e. the default in my case).  I am getting a warning, and I'm curious what it means.
Warning message:
In optwrap(optimizer, devfun, start, rho$lower, control = control,  :
  convergence code 3 from bobyqa: bobyqa -- a trust region step failed to reduce q

I searched "a trust region step failed to reduce q."  Found some information in the minqa package, which said "Consult Powell for explanation."  I did (you can too, if you want! see the references and links to them below), but I fail to understand.  In fact, I failed to find anything about reducing q.
M. J. D. Powell (2007) "Developments of NEWUOA for unconstrained minimization without
derivatives", Cambridge University, Department of Applied Mathematics and Theoretical Physics,
Numerical Analysis Group, Report NA2007/05, http://www.damtp.cam.ac.uk/user/na/NA_papers/NA2007_05.pdf.
M. J. D. Powell (2009), "The BOBYQA algorithm for bound constrained optimization without
derivatives", Report No. DAMTP 2009/NA06, Centre for Mathematical Sciences, University of
Cambridge, UK. http://www.damtp.cam.ac.uk/user/na/NA_papers/NA2009_06.pdf.
P.s. I know I can change the optimizer, and I will to see if I can get output without warnings or errors.  I will also check the gradient and Hessian if I can, as per a comment/answer by Ben Bolker.  I'm using glmer within dredge from MuMIn and I'm not sure if Ben's answer will work without some additional tinkering, but I'll work on it once my computer finishes what it's doing, anyway, I digress.
Update
As per Dr. Bolker's comment below, I began looking through the FORTRAN code (Here is the code for anyone interested in looking but not downloading it).  "430" appears in the bobyqb.f portion of the code.  Simply search for "430" or "reduce Q" to find the relevant code.
This is my first encounter with FORTRAN code, but I think the code says that if the following conditions are met, produce the warning: NTRITS > 0, VQUAD >= 0, IPRINT > 0.  "The integer NTRITS is set to the number "trust region" iterations that have occurred since the last "alternative" iteration." VQUAD appears several times, and I'm not yet clear on it's significance as its value seems to be dependent on a variety of other variables, the values of which sometimes depend on other variables.From bobyqa.f: "The value of IPRINT should be set to 0, 1, 2 or 3, which controls the amount of printing. Specifically, there is no output if IPRINT=0 and there is output only at the return if IPRINT=1.".
So, it seems the task is to figure out the significance of VQUAD being >= 0 and, perhaps, understanding how / when IPRINT became > 0.  I'll have to go back to the paper to have a look, but the math, or at least its symbolic expression, is a bit of a barrier for me.  Unless, someone knows about the algorithm or has the desire to learn about it, I think I'll have to iteratively increase my understanding of the warning by going back and forth between the papers, the code, and the internet until I understand what it means.

A: Before going in to the code, allow me to give you a quick primer on trust region methods.  Let $f(x)$ be your objective function and $x_k$ be your current iterate.  Iteration $k$ of a generic trust region method looks something like this:

*

*Pick a maximum step size, $\Delta_k$

*Build an model of $f(x)$ at $x = x_k$; call it $Q(x)$.

*Find the step, $s_k$, that minimizes $Q_k(x_k + s_k)$ subject to the constraint $||s_k|| \leq \Delta_k$

*If $s_k$ is "good enough", let $x_{k+1} = x_k + s_k$

*Otherwise, refine your model and try again

One of the the ways you determine if $s_k$ is "good enough" is by comparing the decrease predicted by the model to the actual decrease in the objective function.  This is what the portion of the code after 430 does.  However, before that, there's a quick sanity check to see if the model predicts a decrease AT ALL.  And that's what's happening at 430.
To understand the value of VQUAD, we first have to understand a few other variables.  Fortunately, there are good comments right below the declaration of SUBROUTINE BOBYQB.  The salient variables are:

*

*GOPT, the gradient of the model

*HQ, the Hessian of the model

*D, the trial step (I called this $s_k$ above)

Beginning a few lines above 410, you'll see DO 410 J=1,N.  This begins a for-loop (and a nested for-loop) that evaluates the change predicted by the model using trial step D.  It accumulates the predicted change in VQUAD.  The first part of the for-loop evaluates the first-order terms and the nested for-loop evaluates the second-order terms.  It would probably be easier to read if the loops were indented, like this:
    DO 410 J=1,N
        VQUAD=VQUAD+D(J)*GOPT(J)
        DO 410 I=1,J
            IH=IH+1
            TEMP=D(I)*D(J)
            IF (I .EQ. J) TEMP=HALF*TEMP
410         VQUAD=VQUAD+HQ(IH)*TEMP

There's another for-loop after this to incorporate other parameters in to the model.  I have to admit, I don't fully understand this - my best guess is that it's particular to how they build the model.
At the end of all this, VQUAD holds the change in objective function predicted by the model.  So if VQUAD is non-negative, that's bad.  Now this particular solver can use an alternative step computation (probably a line search), which is where NTRITS comes in to play.  So the logic at 430 is saying, "If the last iteration used the alternative step computation AND the model does not predict a decrease AND IPRINT > 0, print the warning message."  Note that the solver is going to terminate regardless of the value of IPRINT.
Speaking of IPRINT, that value is passed to BOBYQA by the calling function.  In this case, your R routine is the calling function.  There's a verbose parameter to glmer - I would be dimes to dollars that same value is passed to BOBYQA.  Try setting verbose to 0 and you probably won't see the warning.  But it won't change what's going on under the hood, of course.


text:
Q: Android App crashes when restoring from background after a long time im new in programming and i have strange problem.I try to restore app from background afrer long time in the background and have  crashe with NullPointerException.
this is the error from logcat
05-06 14:19:28.278: W/~~~~~~~~~~~~~~~~MainActivity(12129): onSaveInstanceState() com.main.MainActivity@43087bb0 fragment: PrivateCabinetFragment{430d2ae0 #0 id=0x7f09005e PrivateCabinetFragment}
05-06 14:19:35.168: E/BaseFragment(13342): onCreate
05-06 14:19:35.168: D/AndroidRuntime(13342): Shutting down VM
05-06 14:19:35.168: W/dalvikvm(13342): threadid=1: thread exiting with uncaught exception (group=0x4158cba8)
05-06 14:19:35.168: E/AndroidRuntime(13342): FATAL EXCEPTION: main
05-06 14:19:35.168: E/AndroidRuntime(13342): Process: com, PID: 13342
05-06 14:19:35.168: E/AndroidRuntime(13342): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.main.MainActivity}: java.lang.NullPointerException
05-06 14:19:35.168: E/AndroidRuntime(13342):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at android.app.ActivityThread.access$800(ActivityThread.java:135)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at android.os.Handler.dispatchMessage(Handler.java:102)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at android.os.Looper.loop(Looper.java:136)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at android.app.ActivityThread.main(ActivityThread.java:5017)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at java.lang.reflect.Method.invokeNative(Native Method)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at java.lang.reflect.Method.invoke(Method.java:515)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at dalvik.system.NativeStart.main(Native Method)
05-06 14:19:35.168: E/AndroidRuntime(13342): Caused by: java.lang.NullPointerException
05-06 14:19:35.168: E/AndroidRuntime(13342):    at com.main.MainActivity.setUnreadedMessages(MainActivity.java:151)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at com.main.PrivateCabinetFragment.onCreate(PrivateCabinetFragment.java:104)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at android.support.v4.app.Fragment.performCreate(Fragment.java:1437)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:877)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1070)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at android.support.v4.app.FragmentManagerImpl.dispatchCreate(FragmentManager.java:1856)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:210)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at com.main.BaseActivity.onCreate(BaseActivity.java:55)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at com.main.MainActivity.onCreate(MainActivity.java:65)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at android.app.Activity.performCreate(Activity.java:5231)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
05-06 14:19:35.168: E/AndroidRuntime(13342):    ... 11 more

and this is my code
package com.main;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

   import com.R;
    import com.connection.ActionGetData;
    import com.data.Constants;

public class MainActivity extends BaseActivity implements OnClickListener, DialogInterface.OnCancelListener {
    private final static String CLASS_TAG = MainActivity.class.getSimpleName();
    private Fragment mContent;
    private PrivateCabinetFragment privateCabinetFrag;
    private SettingsFragment settingsFragment;
    private NewOrderMainFragment stayOrderFragment;
    private PopularQuestionListFragment questionsFragment;
    private PaymentsMenu paymentsMenu;
    private MessageMain messageMain;
    private MyRequestOrdersListFragment requestList;
    private ImageView service;
    private ImageView helpAndSupport;
    private ImageView payments;
    private ImageView settings;
    private RelativeLayout btnService;
    private RelativeLayout btnHelpAndSupport;
    private RelativeLayout btnPayments;
    private RelativeLayout btnSettings;
    private RelativeLayout btnMessages;
    private ImageView btnSupportStayOrder;
    private TextView btnSupportRequestOrders;
    private TextView btnSupportPopularQuestion;
    private ImageView messages;
    private TextView tvNewMessages;
    private RelativeLayout dashBoard;
    private LinearLayout toggleButton;
    private Bundle extras;
    private String fragment_tag = "";
    private FragmentManager frag_manager;
    private int onBackpress = 0;
    public static boolean sDisableFragmentAnimations = false;

    protected Animation animUp;
    protected Animation animDown;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        Log.e(CLASS_TAG,"savedInstanceState"+ savedInstanceState);
        if (savedInstanceState != null) {
            Log.e(CLASS_TAG, "savedInstanceState" + savedInstanceState.isEmpty());

            Log.i(CLASS_TAG, "savedInstance != null");
            Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            finish();

        } else {

            setContentView(R.layout.main_activity);
            overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
            extras = getIntent().getExtras();
            tvNewMessages = (TextView) findViewById(R.id.tv_new_messages);
            service = (ImageView) findViewById(R.id.iv_services_main_board);

            btnService = (RelativeLayout) findViewById(R.id.rl_services_main_board);
            btnService.setOnClickListener(this);

            helpAndSupport = (ImageView) findViewById(R.id.iv_support_main_board);
            btnHelpAndSupport = (RelativeLayout) findViewById(R.id.rl_support_main_board);
            btnHelpAndSupport.setOnClickListener(this);

            payments = (ImageView) findViewById(R.id.iv_payments_main_board);
            btnPayments = (RelativeLayout) findViewById(R.id.rl_payments_main_board);
            btnPayments.setOnClickListener(this);

            messages = (ImageView) findViewById(R.id.iv_message_main_board);
            btnMessages = (RelativeLayout) findViewById(R.id.rl_message_main_board);
            btnMessages.setOnClickListener(this);

            settings = (ImageView) findViewById(R.id.iv_settings_main_board);
            btnSettings = (RelativeLayout) findViewById(R.id.rl_settings_main_board);
            btnSettings.setOnClickListener(this);

            toggleButton = (LinearLayout) findViewById(R.id.ll_toggle_container);
            toggleButton.setBackgroundDrawable((getResources().getDrawable(R.drawable.top_panel_background)));

            dashBoard = (RelativeLayout) findViewById(R.id.dash_board);

            btnSupportStayOrder = (ImageView) findViewById(R.id.iv_new_order);
            btnSupportStayOrder.setOnClickListener(this);

            btnSupportPopularQuestion = (TextView) findViewById(R.id.tv_popular_questions);
            btnSupportPopularQuestion.setOnClickListener(this);

            btnSupportRequestOrders = (TextView) findViewById(R.id.tv_my_orders);
            btnSupportRequestOrders.setOnClickListener(this);

            questionsFragment = new PopularQuestionListFragment();
            privateCabinetFrag = new PrivateCabinetFragment();
            settingsFragment = new SettingsFragment();
            stayOrderFragment = new NewOrderMainFragment();
            paymentsMenu = new PaymentsMenu();
            messageMain = new MessageMain();
            requestList = new MyRequestOrdersListFragment();
            animUp = AnimationUtils.loadAnimation(this, R.anim.anim_up);
            animDown = AnimationUtils.loadAnimation(this, R.anim.anim_down);
            frag_manager = getSupportFragmentManager();
            service.setBackgroundResource(R.drawable.services_main_board_pressed);
            if (extras != null) {
                boolean payments = extras.getBoolean(Constants.EXTRAS_MAIN_ACTIVITY_PAY_FRAGMENT);
                if (payments) {
                    fragment_tag = PaymentsMenu.class.getSimpleName();
                    pushFragmentsWithoutAnimation(paymentsMenu, fragment_tag);

                }
            } else {
                fragment_tag = PrivateCabinetFragment.class.getSimpleName();
                pushFragmentsWithoutAnimation(privateCabinetFrag, fragment_tag);
            }
        }

    }

public void setUnreadedMessages(int count) {
    if (count > 0) {
        tvNewMessages.setVisibility(View.VISIBLE);

        tvNewMessages.setText(Integer.toString(count));
    } else {
        tvNewMessages.setVisibility(View.INVISIBLE);
    }

}

@Override
protected void onSaveInstanceState(Bundle outState) {

    Log.w("~~~~~~~~~~~~~~~~" + CLASS_TAG, "onSaveInstanceState() " + toString() + " fragment: " + mContent);

    try {
        frag_manager.putFragment(outState, "mContent", mContent);
    } catch (Exception e) {
        Log.e(CLASS_TAG, "!!!!!!!!");
        e.printStackTrace();
    }
    super.onSaveInstanceState(outState);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    Log.w("~~~~~~~~~~~~~~~~" + CLASS_TAG, "onRestoreInstanceState() " + toString() + " fragment: " + mContent.getClass().getSimpleName());
    mContent = frag_manager.getFragment(savedInstanceState, "mContent");
    Log.i(CLASS_TAG, "savedInstance != null");

    super.onRestoreInstanceState(savedInstanceState);

}

public void pushFragments(Fragment fragment, String tag) {
    onBackpress = 0;
    String old_tag = "";
    try {
        old_tag = mContent.getClass().getSimpleName();

    } catch (Exception e) {
        e.printStackTrace();
        old_tag = "new";
    }
    mContent = fragment;
    if (old_tag.equals(tag)) {

    } else {
        clearFragments();
        // frag_manager.popBackStack(null,
        // FragmentManager.POP_BACK_STACK_INCLUSIVE);
        FragmentTransaction ft = frag_manager.beginTransaction();

        ft.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_left).replace(R.id.frame_container, fragment, tag);
        ft.commit();
        if (getCurrentFocus() != null) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
    }

}

public void clearFragments() {
    sDisableFragmentAnimations = true;
    frag_manager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);

}

public void pushFragmentsWithoutAnimation(Fragment fragment, String tag) {
    onBackpress = 0;
    String old_tag = "";
    try {
        old_tag = mContent.getClass().getSimpleName();

    } catch (Exception e) {
        e.printStackTrace();
        old_tag = "new";
    }
    mContent = fragment;
    if (old_tag.equals(tag)) {

    } else {
        clearFragments();
        FragmentTransaction ft = frag_manager.beginTransaction();

        ft.replace(R.id.frame_container, fragment, tag);
        ft.commit();
        if (getCurrentFocus() != null) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
    }
}

public void navigateTo(Fragment fragment) {
    onBackpress = 0;
    mContent = fragment;

    frag_manager.beginTransaction().setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_left, R.anim.slide_in_right, R.anim.slide_out_right)
            .replace(R.id.frame_container, fragment).addToBackStack(Integer.toString(frag_manager.getBackStackEntryCount() + 1)).commit();

    if (getCurrentFocus() != null) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
    }

}

public void navigateBack() {
    Log.v(CLASS_TAG, "navigateBack()");
    onBackpress = 0;

    final int cnt = frag_manager.getBackStackEntryCount();

    Log.v(CLASS_TAG, "stack depth: " + cnt);

    if (cnt >= 1) {

        frag_manager.popBackStack();

        if (getCurrentFocus() != null) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
    } else {
        onBackPressed();
        Log.v(CLASS_TAG, "Can't navigate");
    }
}

@Override
public void onBackPressed() {
    if (clients_Data.getClientAcc().size() < 2) {
        if (onBackpress >= 1) {
            hideProgressDialog();
            if (clients_Data.isLogedIn()) {
                ActionGetData.doLogOut();
                finish();
            }
            super.onBackPressed();
        } else if (onBackpress < 1) {
            Toast.makeText(this, getString(R.string.push_for_exit), Toast.LENGTH_SHORT).show();
        }
        onBackpress++;
    } else {
        super.onBackPressed();
        MainActivity.this.overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_right);
    }
}

public void isPayments() {
    hideTopPanel();
    payments.setBackgroundResource(R.drawable.payments_main_board_pressed);
    helpAndSupport.setBackgroundResource(R.drawable.support_main_bord_unpressed);
    messages.setBackgroundResource(R.drawable.message_main_board_unpressed);
    service.setBackgroundResource(R.drawable.services_main_board_unpressed);
    settings.setBackgroundResource(R.drawable.settings_main_board_unpressed);
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.rl_support_main_board:

        helpAndSupport.setBackgroundResource(R.drawable.support_main_bord_pressed);

        btnSupportPopularQuestion.setTextColor(getResources().getColor(R.color.top_panel_text_color_selected));
        btnSupportPopularQuestion.setBackgroundColor(getResources().getColor(R.color.top_panel_background_selected));

        btnSupportRequestOrders.setTextColor(getResources().getColor(R.color.top_panel_text_color_unselected));
        btnSupportRequestOrders.setBackgroundColor(getResources().getColor(R.color.top_panel_background_unselected));

        btnSupportStayOrder.setImageResource(R.drawable.stay_order_unselected);

        fragment_tag = PopularQuestionListFragment.class.getSimpleName();

        pushFragments(questionsFragment, fragment_tag);
        messages.setBackgroundResource(R.drawable.message_main_board_unpressed);
        service.setBackgroundResource(R.drawable.services_main_board_unpressed);
        settings.setBackgroundResource(R.drawable.settings_main_board_unpressed);
        payments.setBackgroundResource(R.drawable.payments_main_board_unpressed);

        break;
    case R.id.tv_popular_questions:

        btnSupportPopularQuestion.setTextColor(getResources().getColor(R.color.top_panel_text_color_selected));
        btnSupportPopularQuestion.setBackgroundColor(getResources().getColor(R.color.top_panel_background_selected));

        btnSupportRequestOrders.setBackgroundColor(getResources().getColor(R.color.top_panel_background_unselected));
        btnSupportRequestOrders.setTextColor(getResources().getColor(R.color.top_panel_text_color_unselected));

        btnSupportStayOrder.setImageResource(R.drawable.stay_order_unselected);
        fragment_tag = PopularQuestionListFragment.class.getSimpleName();
        pushFragments(questionsFragment, fragment_tag);
        break;
    case R.id.tv_my_orders:

        btnSupportRequestOrders.setBackgroundColor(getResources().getColor(R.color.top_panel_background_selected));
        btnSupportRequestOrders.setTextColor(getResources().getColor(R.color.top_panel_text_color_selected));

        btnSupportPopularQuestion.setTextColor(getResources().getColor(R.color.top_panel_text_color_unselected));
        btnSupportPopularQuestion.setBackgroundColor(getResources().getColor(R.color.top_panel_background_unselected));

        btnSupportStayOrder.setImageResource(R.drawable.stay_order_unselected);
        fragment_tag = MyRequestOrdersListFragment.class.getSimpleName();
        pushFragments(requestList, fragment_tag);
        break;
    case R.id.iv_new_order:

        btnSupportStayOrder.setImageResource(R.drawable.stay_order_selected);

        btnSupportPopularQuestion.setTextColor(getResources().getColor(R.color.top_panel_text_color_unselected));
        btnSupportPopularQuestion.setBackgroundColor(getResources().getColor(R.color.top_panel_background_unselected));

        btnSupportRequestOrders.setBackgroundColor(getResources().getColor(R.color.top_panel_background_unselected));
        btnSupportRequestOrders.setTextColor(getResources().getColor(R.color.top_panel_text_color_unselected));
        fragment_tag = NewOrderMainFragment.class.getSimpleName();
        pushFragments(stayOrderFragment, fragment_tag);
        break;
    case R.id.rl_payments_main_board:

        hideTopPanel();
        payments.setBackgroundResource(R.drawable.payments_main_board_pressed);
        fragment_tag = PaymentsMenu.class.getSimpleName();
        pushFragments(paymentsMenu, fragment_tag);
        helpAndSupport.setBackgroundResource(R.drawable.support_main_bord_unpressed);
        messages.setBackgroundResource(R.drawable.message_main_board_unpressed);
        service.setBackgroundResource(R.drawable.services_main_board_unpressed);
        settings.setBackgroundResource(R.drawable.settings_main_board_unpressed);

        break;
    case R.id.rl_services_main_board:

        hideTopPanel();
        service.setBackgroundResource(R.drawable.services_main_board_pressed);
        privateCabinetFrag = new PrivateCabinetFragment();
        fragment_tag = PrivateCabinetFragment.class.getSimpleName();
        pushFragments(privateCabinetFrag, fragment_tag);
        helpAndSupport.setBackgroundResource(R.drawable.support_main_bord_unpressed);
        messages.setBackgroundResource(R.drawable.message_main_board_unpressed);
        settings.setBackgroundResource(R.drawable.settings_main_board_unpressed);
        payments.setBackgroundResource(R.drawable.payments_main_board_unpressed);

        break;
    case R.id.rl_settings_main_board:

        hideTopPanel();
        settings.setBackgroundResource(R.drawable.settings_main_board_pressed);
        fragment_tag = SettingsFragment.class.getSimpleName();
        pushFragments(settingsFragment, fragment_tag);
        messages.setBackgroundResource(R.drawable.message_main_board_unpressed);
        service.setBackgroundResource(R.drawable.services_main_board_unpressed);
        payments.setBackgroundResource(R.drawable.payments_main_board_unpressed);
        helpAndSupport.setBackgroundResource(R.drawable.support_main_bord_unpressed);

        break;

    case R.id.rl_message_main_board:

        hideTopPanel();
        messages.setBackgroundResource(R.drawable.message_main_board_pressed);
        service.setBackgroundResource(R.drawable.services_main_board_unpressed);
        payments.setBackgroundResource(R.drawable.payments_main_board_unpressed);
        helpAndSupport.setBackgroundResource(R.drawable.support_main_bord_unpressed);
        settings.setBackgroundResource(R.drawable.settings_main_board_unpressed);
        fragment_tag = MessageMain.class.getSimpleName();
        pushFragments(messageMain, fragment_tag);

        break;

    }

}

public void hideTopPanel() {
    if (dashBoard.isShown()) {
        // dashBoard.startAnimation(animUp);
        dashBoard.setVisibility(View.GONE);
    }
}

public void showTopPanel() {
    if (!dashBoard.isShown()) {
        dashBoard.setVisibility(View.VISIBLE);
        dashBoard.startAnimation(animDown);
    }
}

@Override
protected void onPause() {
    Log.e(CLASS_TAG,"ON onPause");
    // TODO Auto-generated method stub
    super.onPause();
    onBackpress = 0;
}

@Override
protected void onResume() {
    Log.e(CLASS_TAG,"ON onResume");
    // TODO Auto-generated method stub
    super.onResume();
    onBackpress = 0;
}

@Override
protected void onStart() {
    Log.e(CLASS_TAG,"ON Start");
    super.onStart();
}

}

A: The stacktrace says you're still in the superclass onCreate() which recreates the fragments and calls back to MainActivity setUnreadedMessages(). At that point member variables such as tvNewMessages are not initialized.
Generally, fragments should not have such dependencies to the hosting activities. Consider reworking the design there.


text:
Q: How to emit explicit interface implementation using reflection.emit? Observe the following simple source code:
using System;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;

namespace A
{
  public static class Program
  {
    private const MethodAttributes ExplicitImplementation =
      MethodAttributes.Private | MethodAttributes.Virtual | MethodAttributes.Final |
      MethodAttributes.HideBySig | MethodAttributes.NewSlot;
    private const MethodAttributes ImplicitImplementation =
      MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig;

    private static Type EmitMyIntfType(ModuleBuilder moduleBuilder)
    {
      var typeBuilder = moduleBuilder.DefineType("IMyInterface",
        TypeAttributes.NotPublic | TypeAttributes.Interface | TypeAttributes.Abstract);
      typeBuilder.DefineMethod("MyMethod", MethodAttributes.Assembly | MethodAttributes.Abstract |
        MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.NewSlot,
        typeof(void), new[] { typeof(int) });

      return typeBuilder.CreateType();
    }

    public static void Main()
    {
      var assemblyName = new AssemblyName("DynamicTypesAssembly");
      var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
      var moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name, assemblyName.Name + ".dll", true);
      var myIntfType = EmitMyIntfType(moduleBuilder);

      var typeBuilder = moduleBuilder.DefineType("MyType",
        TypeAttributes.Public | TypeAttributes.BeforeFieldInit | TypeAttributes.Serializable |
        TypeAttributes.Sealed, typeof(object), new[] { myIntfType });

      //var myMethodImpl = typeBuilder.DefineMethod("IMyInterface.MyMethod", ExplicitImplementation,
      //  null, new[] { typeof(int) });
      var myMethodImpl = typeBuilder.DefineMethod("MyMethod", ImplicitImplementation,
        null, new[] { typeof(int) });
      var ilGenerator = myMethodImpl.GetILGenerator();
      ilGenerator.Emit(OpCodes.Ret);

      var type = typeBuilder.CreateType();
      assemblyBuilder.Save("A.dll");
    }
  }
}

Below is the equivalent C# code obtained by decompiling the A.dll assembly using the Reflector:
internal interface IMyInterface
{
    void MyMethod(int);
}
[Serializable]
public sealed class MyType : IMyInterface
{
    public override void MyMethod(int)
    {
    }
}

Now what if I wish the MyType type implement the IMyInterface interface explicitly?
So I take these lines:
//var myMethodImpl = typeBuilder.DefineMethod("IMyInterface.MyMethod", ExplicitImplementation,
//  null, new[] { typeof(int) });
var myMethodImpl = typeBuilder.DefineMethod("MyMethod", ImplicitImplementation,
  null, new[] { typeof(int) });

and switch the comments to yield this code:
var myMethodImpl = typeBuilder.DefineMethod("IMyInterface.MyMethod", ExplicitImplementation,
  null, new[] { typeof(int) });
// var myMethodImpl = typeBuilder.DefineMethod("MyMethod", ImplicitImplementation,
//  null, new[] { typeof(int) });

But now, the application fails to create the dynamic type. This line:
var type = typeBuilder.CreateType();

throws the following exception:
System.TypeLoadException was unhandled
  Message="Method 'MyMethod' in type 'MyType' from assembly 'DynamicTypesAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation."
  Source="mscorlib"
  TypeName="MyType"
  StackTrace:
       at System.Reflection.Emit.TypeBuilder._TermCreateClass(Int32 handle, Module module)
       at System.Reflection.Emit.TypeBuilder.TermCreateClass(Int32 handle, Module module)
       at System.Reflection.Emit.TypeBuilder.CreateTypeNoLock()
       at System.Reflection.Emit.TypeBuilder.CreateType()
       at A.Program.Main() in C:\Home\work\A\Program.cs:line 45
  InnerException:

Can anyone show me what is wrong with my code?
Thanks.

A: That seems duplicate to this question...
Which points to MSDN:

However, to provide a separate
  implementation of I.M(), you must
  define a method body and then use the
  DefineMethodOverride method to
  associate that method body with a
  MethodInfo representing I.M(). The
  name of the method body does not
  matter.

        // Build the method body for the explicit interface
        // implementation. The name used for the method body
        // can be anything. Here, it is the name of the method,
        // qualified by the interface name.
        //
        MethodBuilder mbIM = tb.DefineMethod("I.M",
            MethodAttributes.Private | MethodAttributes.HideBySig |
                MethodAttributes.NewSlot | MethodAttributes.Virtual |
                MethodAttributes.Final,
            null,
            Type.EmptyTypes);
        ILGenerator il = mbIM.GetILGenerator();
        il.Emit(OpCodes.Ldstr, "The I.M implementation of C");
        il.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine",
            new Type[] { typeof(string) }));
        il.Emit(OpCodes.Ret);

        // DefineMethodOverride is used to associate the method
        // body with the interface method that is being implemented.
        //
        tb.DefineMethodOverride(mbIM, typeof(I).GetMethod("M"));


text:
Q: Bluemix cloudant: Sudden errors being thrown by service We are using Node.js module nano to interact with Cloudant instance on Bluemix. Suddenly today we have started getting the below errors while getting data from a view in a Cloudant instance. Any clue what might be wrong?
 [{couch_os_process,prompt,3,[{file,"src/couch_os_process.erl"},{line,65}]},
  {couch_query_servers,'-map_docs/2-fun-1-',2,
                       [{file,"src/couch_query_servers.erl"},{line,243}]},
  {lists,map,2,[{file,"lists.erl"},{line,1237}]},
  {couch_query_servers,map_docs,2,
                       [{file,"src/couch_query_servers.erl"},{line,239}]},
  {couch_view_updater,view_compute,2,
                      [{file,"src/couch_view_updater.erl"},{line,256}]},
  {couch_view_updater,do_map,2,
                      [{file,"src/couch_view_updater.erl"},{line,161}]},
  {lists,foldl,3,[{file,"lists.erl"},{line,1261}]},
  {couch_view_updater,do_maps,4,
                      [{file,"src/couch_view_updater.erl"},{line,153}]}]}

A: It appears that the indexer is crashing trying to index a particular document. Probably you made a change to your documents, likely the ingestion of a larger document. One indication that it is a 'recent' change to a document causing the crash is to query the view with stale=ok. This will request a response from the last built version of the index (with the last correct version of the document). If this returns correctly it means that the issue is caused by a recent change attempting to be indexed.

A: This may be an intermittent issue due to a login and application management issue in the US-South region. You can track Platform and Service issues at the Bluemix Status page. If the system status is okay and you still get these errors, open a Bluemix Support  ticket.

A: It's probably a problem with one of the Map Reduce views you have defined on the design document that contains the view you are accessing.


text:
Q: electron setWindowOpenHandler is not a function I created an Electron-App for my web-app, which uses SAML. I want to allow the saml window to show up.
So I used the BrowserWindow.WebContents.setWindowOpenHandler function.
I first tried it, where the window object is being instanciated with a new BrowserWindow. That didn't work. I found on GitHub a new method, using the event "web-contents-created"
//Erlaube SAML Authentifizierung, andere Seiten werden blockiert
app.on("web-contents-created", (createEvent, contents) => {
  contents.setWindowOpenHandler(({url}) => {
    if(url.startsWith("https://login.microsoftonline.com/")) {
      return {action: 'allow'};
    }
    else return {action: 'deny'};
  });
});

That didn't word either, I always get the same error messages:

I'm using TypeScript and it's valid code.
I'm using Electron 17.1.2
Anyone knows why and how?


text:
Q: Drupal. Get path alias from current url without the installation's folder arguments I'd like to retrieve the current page path alias without the installation's folder arguments.
I'm using:
drupal_get_path_alias(request_uri())

But this returns installation/whatever/actual/path and I want to retrieve the actual/path only no matter what installation/whatever is.
Thanks in advance :)

A: Found it. It was actually a mix of both suggestions:
$current_path = drupal_get_path_alias($_GET["q"]);

Thanks though.

Update: the previous solution doesn't always work
Someone suggested using an alternative method:
str_replace(base_path(), '', drupal_get_path_alias(request_uri(), 1));

But, is there any way of doing the same without using the slightly expensive str_replace?
Thanks

A: The path of the node you are on?
http://api.drupal.org/api/function/drupal_get_path_alias/6
if ($node || (arg(0) == 'node' && arg(2) != 'edit')) {
   $system_path = 'node/'.arg(1);
   $current_path = drupal_get_path_alias($system_path);
}

That code will fire on node pages and tell you the page alias.
For more information, you can dump out $_GET and look at the 'q' query string value.

A: Maybe you can use base_path() and str_replace like this :
str_replace (base_path(), '', drupal_get_path_alias(request_uri()), 1);

The base_path is saved in the database.

A: $current_page_url = drupal_get_path_alias( implode( '/', arg() ) );

also works

A: Have you tried $_GET['q']?

A: I tend to plump for the full url instead to avoid any problems that arise when base_path() isn't just '/'.
$url = (($_SERVER['HTTPS'])?"https://":"http://")  .  $_SERVER['HTTP_HOST'] . url($_GET['q']);

or even more simply:
$url = url($_GET['q'], array('absolute'=>true));

A: Fastest solution.
substr(drupal_get_path_alias(request_uri(), 1), strlen(base_path()));
To pass it into an argument
$arg = explode('/', substr(drupal_get_path_alias(request_uri(), 1), strlen(base_path())));


text:
Q: Can you turn a button into an image when its clicked in c#? Trying to either change the background image of a button when it's clicked or change the button into an image when clicked.
 var brush = new ImageBrush
            {
                ImageSource = new BitmapImage(new Uri("image1.jpg", UriKind.Relative))
            };
            Button1.Background = brush;

A: If you are using UWP or WPF, you can do it in this way (which is exactly what you already have):
ImageBrush brush1 = new ImageBrush();
brush1.ImageSource = new BitmapImage(new Uri("uri to image"));
btn.Background = brush1;

or as described here: example