text:
Q: Python Tkinter Inherit DataFrame between classes I'm having an issues and I would kindly ask you to help me as I am not able to find a solution.
Basically I am trying to inherit the DataFrame loaded into a variable in one Class (Window1) and I'm trying to use the same DataFrame in another Class (Window1). Please find below my current simplified code (Thank you):
import tkinter as tk
from PIL import ImageTk, Image
from tkinter import filedialog, messagebox
import time, os, random, string
from datetime import datetime
from time import gmtime, strftime
import pandas as pd

class Page(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        container=tk.Frame(self)
        container.grid()
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames={}
        for F in (PageOne, PageTwo, PageThree):
            frame=F(container, self)
            self.frames[F]=frame
            frame.grid(row=0, column=0, sticky="nsew")
        self.show_frame(PageOne)

    def show_frame(self, cont):
        frame=self.frames[cont]
        frame.tkraise()

class PageOne(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        start_btn = tk.Button(self, text = "Start >>>", command=lambda:controller.show_frame(PageTwo), width = 10, activebackground = "#ffffff", relief="flat").grid()

        pass

class PageTwo(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        self.browse_btn = tk.Button(self, text="     Browse     ", command=self.select_file)
        self.browse_btn.grid(row=4, column=0, padx=290, pady=10, columnspan=3, sticky="w")

        self.browse_entry = tk.Entry(self, text="", width=30)
        self.browse_entry.grid(row=4, column=0, columnspan=3, padx=100, pady=10, sticky="w")

        self.continue_btn = tk.Button(self, text="Continue >>",  borderwidth=2, width=10, bg="#00c441", fg="#ffffff", command=lambda:[self.print_df(), controller.show_frame(PageThree)])
        self.continue_btn.grid(row=19, column=0, columnspan=3, padx=312, pady=5, sticky="w")
        self.continue_btn.config(state=tk.NORMAL)

    def select_file(self):

        self.path = filedialog.askopenfilename(defaultextension="*.csv", filetypes = (("csv files","*.csv"),("All Files", "*.*")))
        self.browse_entry.delete(0, tk.END)
        self.browse_entry.insert(0, self.path)
        ###following DataFrame I would like to use in in the PageThree class.
        self.df = pd.read_csv(self.path)

    def print_df(self):
        return self.df.head()

class PageThree(PageTwo):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        PageTwo.__init__(self, parent, controller)
        start_btn = tk.Button(self, text = "Data Frame", command=self.funct01, width = 10).grid()

    def funct01(self):
    ##this is where I would like to utilize the DataFrame (inside the function)
        instance=PageTwo(parent,controller)
        print(instance.select_file(self))

if __name__=="__main__":
    app=Page()
    app.geometry("400x400+100+100")
    app.mainloop()

A: You have to ask the Page instance (controller) to return the PageTwo instance, and you need to store the controller in the PageTwo "constructor".
I was not aware that you can hash a class definition (use it has the key of a dictionary).
import tkinter as tk
from PIL import ImageTk, Image
from tkinter import filedialog, messagebox
import time, os, random, string
from datetime import datetime
from time import gmtime, strftime
import pandas as pd

class Page(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        container=tk.Frame(self)
        container.grid()
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames={}
        for F in (PageOne, PageTwo, PageThree):
            frame=F(container, self)
            self.frames[F]=frame
            frame.grid(row=0, column=0, sticky="nsew")
        self.show_frame(PageOne)

    def show_frame(self, cont):
        frame=self.frames[cont]
        frame.tkraise()

    def getFrame(self, frame):
        return self.frames[frame]

class PageOne(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        start_btn = tk.Button(self, text = "Start >>>", command=lambda:controller.show_frame(PageTwo), width = 10, activebackground = "#ffffff", relief="flat").grid()

class PageTwo(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        self.browse_btn = tk.Button(self, text="     Browse     ", command=self.select_file)
        self.browse_btn.grid(row=4, column=0, padx=290, pady=10, columnspan=3, sticky="w")

        self.browse_entry = tk.Entry(self, text="", width=30)
        self.browse_entry.grid(row=4, column=0, columnspan=3, padx=100, pady=10, sticky="w")

        self.continue_btn = tk.Button(self, text="Continue >>",  borderwidth=2, width=10, bg="#00c441", fg="#ffffff", command=lambda:[self.print_df(), controller.show_frame(PageThree)])
        self.continue_btn.grid(row=19, column=0, columnspan=3, padx=312, pady=5, sticky="w")
        self.continue_btn.config(state=tk.NORMAL)

    def select_file(self):

        self.path = filedialog.askopenfilename(defaultextension="*.csv", filetypes = (("csv files","*.csv"),("All Files", "*.*")))
        self.browse_entry.delete(0, tk.END)
        self.browse_entry.insert(0, self.path)
        ###following DataFrame I would like to use in in the PageThree class.
        self.df = pd.read_csv(self.path)

    def print_df(self):
        return self.df.head()

class PageThree(PageTwo):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        PageTwo.__init__(self, parent, controller)
        start_btn = tk.Button(self, text = "Data Frame", command=self.funct01, width = 10).grid()

    def funct01(self):
        instance = self.controller.getFrame(PageTwo)
        dataFrame = instance.df
        print(dataFrame.head())

if __name__=="__main__":
    app=Page()
    app.geometry("400x400+100+100")
    app.mainloop()


text:
Q: Unable to connect to Azure Database from a web app deployed on Azure App Services account I deployed a web app on Azure App Services. When web app tries to connect to the Azure SQL Database connection failed.
I downloaded the event log from Kudu, I found the following error message:

Cannot open server 'servername' requested by the login. Client with IP
address '**************' is not allowed to access the server. To
enable access, use the Windows Azure Management Portal or run
sp_set_firewall_rule on the master database to create a firewall rule
for this IP address or address range.  It may take up to five minutes
for this change to take effect..

On Azure portal I found how to set server firewall by adding a range of client IP addresses (with lower bound and upper bound) according your client IP address. For instance, if client IP address is 00.000.000.09 the range of IP addresses is: low bound (00.000.000.0) and upper bound (00.000.000.255).
I set the server firewall for the IP address assigned to my Azure App Services account and also for my local machine to connect to Azure SQL Database from SQL Server Management Studio. After setting firewall, I can connect to Azure SQL Database with SQL Server Management Studio. Unfortunately unable to connect from web app. When I download event log from Kudu I find the same message error.
Someone could help to solve that issue.
Thanks.

A: *

*Go to your SQL Server in Azure Portal.

*Go to "Firewall and Virtual Network".

*Turn on "Allow Azure Service and resources to access this server".

A: Allowing Azure Service and resources to access this server may not be the correct approach. This may be a security issue in many cases. We have to create managed identity and assign to webapp or sql server where required.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why do you have to enqueue a stylesheet in wordpress? Why do you have to enqueue the parent theme stylesheet in a WordPress child theme? I've created style.css in the child theme and when I add a change to it, it works without the functions.php file that enqueues the parent stylesheet, such as changing the background color of an element. I've searched for and answer but can find nothing that tells my why. Everything just says that you have to.

A: When it comes to loading the styles in WordPress themes there are many ways to skin a cat.
Parent enqueues child style.css -
In some themes the parent style.css is enqueued with wp_enqueue_style() within the parent theme php code.
The 2015 default theme is an example of this method. In functions.php line 233 there is the line wp_enqueue_style( 'twentyfifteen-style', get_stylesheet_uri() );. When the theme is standalone get_stylesheet_uri() returns the theme's own style.css. When a child theme is present get_stylesheet_uri() returns the child theme style.css.
The above is the likely case for your parent theme.
Child enqueues parent style.css -
From the child theme you can load the parent styles by by one of two methods.

*

*enqueue_style() with parameters pointing to the parent theme. Some php similar to: wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );. This is the method you are talking about.

*@import from within the child theme style.css file. A typical line of code for this would read: @import url( '../parent-theme-folder/style.css' );. This is not ideal as @import slows down your page load time.

Better Method - Don't use root style.css
It's not strictly necessary to use style.css in the root folder at all. The only thing WordPress strictly needs this file for is to read the theme information in the top comments. This very requirement means that the style.css can't be minimised, or at least is a pain to minimise. Minimising is the process of removing all the spaces in a file of code to reduce the file size. This reduces page load speed.
So now a lot of modern themes are enqueuing their main style from a different minimised css file in a theme subfolder. The main style.css simply consists of the informational comment section read by the core php code but not loaded on the front end.


text:
Q: Avoid Conversion from single element vector to primitive type I have a problem with constant single element std::vector when pass through a function. C++ compiler automatically call wrong function when the std::vector variable contain a single element. This is though the policy of C++ design. However is there any explicit method to specify in such a case. Here are the examples of the problems
assume i have two overload functions both have the same name "foo"

void foo(const std::vector<int> A)
{
         // do vector operator
     printf("vector thing");
}

void foo(int a)
{
     // do integer operator
     printf("integer thing")
}

In general case both of these functions are called correctly
foo({1,2,3});    // print do vector thing
foo( 3 );        // print do integer thing

however from c++ rule. when call
foo({5});        // print do integer thing ( I want it to call as vector )

one of the methods is to create a variable
std::vector<int> B = { 5 };

in order to solve this problem.
I feel this method is a bit clumsy. Is there any method that can void the compiler to treat {5} as 5 and call foo(int a).
note:
here is the reference that explain what the problem is
c++11 single element vector initialization in a function call

A: You need another overload, taking std::initializer_list as a parameter:
void foo(std::initializer_list<int> A)
{
    foo(std::vector<int>(A.begin(), A.end()));
}

If you always call this function by creating vectors directly with {...}, rather than using std::vector variables, then you can remove std::vector overload completely and operate directly on std::initializer_list.

A: No, because as of C++17 the rules explained on the linked answer still hold.
You can create a temporary instead of a variable, though.
foo(std::vector{5});      // C++17 with class type deduction
foo(std::vector<int>{5}); // older versions

A: One way to disambiguate the function call is to make the integer overload a function template:
template <class Int> void foo(Int a)
{
   std::printf("generalized (maybe integer) thing\n");
}

This way, the invocation
foo({3});

will consider the non-templated function a better match while foo(3) instantiates and calls the function template. This because {3} is an std::initializer_list<int> with one element in the context of type deduction. You can also redirect to the original foo(int a) function like this:
void fooImpl(int a)
{
   std::printf("integer thing\n");
}

template <class Int> void foo(Int&& a)
{
   fooImpl(std::forward<Int>(a));
}

This refuses to compile when e.g. calling foo with an argument not convertible to an integer, which might be a desirable usage restriction. Also, it should be very unlikely that you encounter a performance overhead due to the forwarding intermediate function.


text:
Q: 503 error with Symfony 4 and Debug enabled I have an issue with my Symfony 4.1 project. My server is on PHP FPM 7.2 and Apache 2.4.
When i enable the Debug component in a dev environment, i cannot access my application and i have a 503 error.
On the apache server, i can see this error:
AH01067: Failed to read FastCGI header

no error in the fpm container.
At first i thought about a memory_limit issue, but the error disappear when i activate XDebug on the fpm container. And XDebug eats quite a lot of memory, so i don't know where is the problem.
If anybody has any idea, it will be really appreciated.
Thx,
JM


text:
Q: Assigning random numbers in an array in java (non repeating) I am trying to set up a game of Deal or No Deal. I need to assign one of the money values to each case. I was wondering if this would be possible and if so, how. I would set up 2 arrays, case for the case number (1-26) and money for the different values (specific numbers between 1 and 1,000,000 that I would set at the beginning). I then would like to take a random value out of array money and assign it a value in array case but also check to make sure it isn't already stored in another case variable.
int cases[]=new int[26];
int money = {1,2,,5,10,25,50,75,100,200,300,400,...};

Every value stored in money will be used once and only once.
Every case will get assigned one and only one value.

A: Use an ArrayList instead.
ArrayList<Integer> money = ....;

for (int i = 0; i < 26; i++){
    int pick = (int)(Math.random() * money.size());
    cases[i] = money.remove(pick);
}

However, if you're going to use an ArrayList, you may as well take advantage of the wealth of methods found in Collections, such as Collections#shuffle. Per the docs,

Randomly permutes the specified list using a default source of randomness. All permutations occur with approximately equal likelihood.

You could then use the method like so:
ArrayList<Integer> money = ....;
Collections.shuffle(money);
//money is now functionally what `cases` used to be

A: You should have at least 26 values in money[] array
    int cases[]=new int[26];
    int[] money = {1,2,5,10,25,50,75,100,200,300,400....};
    Random random = new Random();
    int index = 0;
    firstLoop:
    while(cases[25]==0){
        int randomChosenIndex = random.nextInt(money.length);
        int randomChosenValueFromMoney = money[randomChosenIndex];
        for (int i = 0; i < index; i++) {
            if (cases[i]==randomChosenValueFromMoney) {
                continue firstLoop;
            }
        }
        cases[index++] = randomChosenValueFromMoney;
    }


text:
Q: Select drop-down value by text array where %like% jQuery I try to use jQuery if title input into my control panel have %like% some words
like
I love to eat apple

and I need to find love, apple
if found let jQuery select from dropdown menu value id 5
$("#HowYouKnow option").each(function() {
  if($(this).text() == theText) {
    $(this).attr('selected', 'selected');
  }
});

I found this code that when found text = text
I need it %like% text with array to use many text ('text1','text2')

A: If you want to select dropdown item based on input use this code:
if($("#input").val().match(/love|apple/)) {
    $("#select").val(5);
}


text:
Q: How do I configure the Column names in a Scala Table? I am writing a Scala program to manage a database, and have drawn all of the data into a 2-dimensional ArrayBuffer where row 0 is the column names, and the subsequent rows contain the info for each entry in the table.
When trying to put this into a Table, ho=w do I go about assigning the Column headers?
Syntax suggestions would be greatly appreciated.
Pseudocode:
Data=ArrayBuffer()
Data(0)={"Name","Birthday","ID"}
Data(1)={"Bob", "07/19/1986", "2354"}
Data(2)={"Sue", "05/07/1980", "2355"}
Data(3)={"Joe", "08/12/1992", "2356"}
Data(4)={"Jim", "11/20/1983", "2357"}

I want to put this into a Table where Data(0) describes the column headers, and the subsequent rows describe rows in the table, but I can't figure out how to set the row headers.

A: The easiest way to put data in a Table is to use its constructor:
new Table (rowData: Array[Array[Any]], columnNames: Seq[_])

The slightly tricky thing here is that arrays are not covariant (see Why doesn't the example compile, aka how does (co-, contra-, and in-) variance work?), which means that an Array[String] is not a subtype of Array[Any]. So you need some way of turning one into the other: a map does the job.
Also, for the column names to show, you need to put the table in a ScrollPane.
import swing._
import collection.mutable.ArrayBuffer

object Demo extends SimpleSwingApplication {

  val data = ArrayBuffer(
    Array("Name","Birthday","ID"),
    Array("Bob", "07/19/1986", "2354"),
    Array("Sue", "05/07/1980", "2355")
  )

  def top = new MainFrame {
    contents = new ScrollPane {
      contents = new Table(
        data.tail.toArray map (_.toArray[Any]),
        data.head
      )
    }
  }
}

Will give you a table:

Edit: you can also use a cast: data.tail.toArray.asInstanceOf[Array[Array[Any]]], which is more efficient than mapping.

A: assuming you are talking of swing, if you put your table inside a scrollpane and create your table model based on the array buffer shown, the first row will be taken as column names by default.


text:
Q: Query doesn't insert into table I using a register form and i would like to see if i have missing columns/tables. I'm using var_dump $stmt; and echo $e->getMessage();
Every time I get successfully message but the code doesn't insert anything into the database .
If I'm using echo $e->getMessage(); I get this:

object(PDOStatement)#11 (1) { ["queryString"]=> string(153) "INSERT INTO bg_user(user_id, passwd, email, account_status) VALUES(:login, :password, :email, :status)" }
Notice: Undefined variable: e in include\classes\user.php on line 89
Fatal error: Uncaught Error: Call to a member function getMessage() on null in include\classes\user.php:89 Stack trace:
#0 include\functions\register.php(57): USER->register('test123', 'a3876fafbc8b9b9...', 'test@tex.com', NULL)
#1 pages\register.php(11): include('D:\Working Stat...')
#2 index.php(199): include('D:\Working Stat...')
#3 {main} thrown in include\classes\user.php on line 89

This is my code:
public function register($username,$password,$email,$ref)
{
    global $safebox_size;

    try
    {
        $password = md5($password);
        $social_id = rand(1000000, 9999999);
        $status = "OK";

        $stmt = $this->account->prepare("INSERT INTO bg_user(user_id, passwd, email, account_status)
                                                   VALUES(:login, :password, :email, :status)");

        $stmt->bindparam(":login", $username);
        $stmt->bindparam(":password", $password);
        $stmt->bindparam(":email", $email);
        $stmt->bindparam(":status", $status);

        $stmt->execute();

        $lastId = $this->account->lastInsertId();
        $safebox_password = "000000";

        $stmt = $this->player->prepare("INSERT INTO safebox(account_id, size, password)
                                                   VALUES(:account_id, :size, :password)");

        $stmt->bindparam(":account_id", $lastId);
        $stmt->bindparam(":size", $safebox_size);
        $stmt->bindparam(":password", $safebox_password);

        $stmt->execute();

        if($ref && count(getAccountInfo($ref)))
            addReferral($lastId, $ref);

        return $stmt;
    }
    catch(PDOException $e)
    {
        //echo $e->getMessage();
        print 'ERROR';
    }
}

My question is: what command do I have to use for var_dump, echo, print etc. to report errors (missing columns or tables)?


text:
Q: How to represent one special related record I have two tables, project and photo. photo has ID,projectID,path : each project has multiple photos.
Now one of these photos is the one that has to be displayed. The question is how to represent this in the database.
Earlier, I used descending order of ID numbers and chose the latest one, but that failed and caused problems. Now I am not sure which way to go :

*

*Create a new table projectPhotoDisplayed that holds project.ID and photo.ID(those that are to be displayed only) numbers.
The bad : too much work, as well as replicating the information that photo table already has (photos associated with projects ).

*Create a new binary field in the photo table. If true, then display, else not.
The bad : Structurally does not prevent multiple photos being marked to display. I want radio button behavior

*Create a new field in the project table that stores the photoID of the photo to be displayed.
The bad : Does not ensure that the particular photoID is actually linked to this project. Also does this information belong here?

*Any approach with foreign keys so that referential integrity is maintained..?

Using PHP and MySQL InnoDB database, though I'm sure it won't matter.
Which is the best way to store this info?

A: All the three ways are viable solutions, but I would avoid the first one and the third one because of redundant information which could get "out of sync". There could be a photoID stored as foreign key of a photo which belongs - or is moved to - a different project.

Create a new binary field in the photo table.

You surely meant a boolean field, not a binary field. This would be my favorite option. To make sure there will be at maximum one photo to be displayed, you may add "before update" and "before insert" triggers to your DB, counting the numbers of rows where your "display" column has the value "true" and throwing an error if there would be more than one. Here you find an example how to use "before insert" triggers for verifying constraints.


text:
Q: How to randomly replace a string in a list based on another list of strings I have the following problem, where I have a list of strings and I want to replace certain words randomly based on another list.
my original list looks like this:
original_list = [['Bananas' 'are' 'boring' 'and' 'too' 'sweet'],
['Why','can', 'we','get','apples','but','no','blueberries'],
['this','is','not','good','for','eat','some','grapes'],
['have','you','ever','tried','to','buy','all','the','different','apples']]

this is the list of words I would like to randomly replace in original_list:
orginal_words = ['Bananas','apples','grape']

and this is the list of words I would like to randomly select instead for the original_words:
replacement_words = ['popcorn','juice','chocolate','chips','cake','sweets']

I figured out a way to do this for an individual word, but I'm not sure how to make it more efficient based on lists:
from random import shuffle
shuffle(replacement_words)
for el in replacement_words:
    for test_str in original_list:
        test_str = test_str.replace('Bananas', el)
        print("String after random replacement : " + str(test_str))

A: You can pick randomly replacement_words list by index, using:
ind = random.randint(0, len(replacement_words))

Also, it doesn't guarantee the uniqueness of elements. You can generate list well in advance and make:
for new_word, old_word in zip(original_list, replacement_words_indices):
  # Do replacement here

The algo will be linear, not quadratic.


text:
Q: Nginx redirect traffic to ilo I have a hp proliant server with ilo and a nginx server.
To reach ilo from outside the router I use port 81 and 444 because 80 and 443 are already taken by nginx.
But is there a way that I can somehow redirect the trafic(of a certain domain e.g. ilo.example.com) via nginx to my ilo IP?

A: This isn't the right way to handle ILO access.
(Do you NEED a public DNS entry for your ILO?)
It should be behind a VPN, if possible. Maybe static NAT if you have the capability and IP space...
However, on the ILO side, the port settings are fully configurable.

A: HP iLO is an out-of-band server control interface which is used to control the server even when the OS that is installed on it is offline, or completely damages/uninstalled. For this to implement, it has a separate IP address, and, if installed properly, a separate LAN port (shared mode, when it's connected through the OS interfaces is available, but it's a source of many problems). This also means that it has it's own network controller and it's own IP address, so saying 80 and 443 are already taken by nginx you cannot be more wrong, because either your iLO is misconfigured and thus not working, either iLO and your OS have completely different IP addresses and probably VLANs.


text:
Q: How to implement observer pattern without having to bind to a specific class? I want to observe an object being deleted at the function level.  In other words, I would say inside of a function, observe that object and allow me to interrogate something to know if it has gotten deleted.  When the function is done, don't observe it anymore.
This is my current API:
template <typename T>
class DeleteReporter
{
    std::pair<T*, bool>* obj_deleted_pair;
public:
    DeleteReporter(T* pObject);
    operator bool();
    ~DeleteReporter();
};

template <typename T>
DeleteReporter<T> make_DeleteReporter(T* pObject);

template <typename T>
void MarkDeleted(T* pObject);

And here is the implementation:
template <typename T>
std::vector<std::pair<T*, bool>>& obj_deleted_pairs()
{
    static std::vector<std::pair<T*, bool>> obj_deleted_pairs;
    return obj_deleted_pairs;
}

template <typename T>
DeleteReporter<T> make_DeleteReporter(T* pObject)
{
    return DeleteReporter<T>(pObject);
}

template <typename T>
void MarkDeleted(T* pObject)
{
    auto it = std::find_if(obj_deleted_pairs<T>().begin(), obj_deleted_pairs<T>().end()
        , [pObject](std::pair<T*, bool>& obj_deleted_pair)
        {
            return obj_deleted_pair.first == pObject;
        });
    if (it != obj_deleted_pairs<T>().end())
    {
        it->second = true;
    }
}

template <typename T>
DeleteReporter::DeleteReporter(T* pObject)
{
    obj_deleted_pairs<T>().emplace_back(pObject, false);
    obj_deleted_pair = &*obj_deleted_pairs<T>().rbegin();
}

template <typename T>
DeleteReporter::operator bool()
{
    return obj_deleted_pair->second;
}

template <typename T>
DeleteReporter::~DeleteReporter()
{
    obj_deleted_pairs<T>().erase(obj_deleted_pairs<T>().begin()
        + std::distance(&*obj_deleted_pairs<T>().begin(), obj_deleted_pair));
}

To use, there would be a call in the destructor to MarkDeleted() with this passed to it.  Then in the function, it would instantiate DeleteReporter using make_DeleteReporter() passing the object to observe.  Later, the DeleteReporter object would be queried to ensure that the object didn't get deleted sometime after the instantiation before trying to talk to it.
Originally, I didn't have this as a template, but instead the functions had taken void*.  I then realised that, if the object was multiply inherited, it is possible that the pointer may not properly match.
Implementing using a template as I've done will also cause this to happen as the pointer may be in the wrong vector.  I could specifically state the type, but I would rather have the compiler determine this.  So my question is, is there some way to traverse the inheritance tree to find the object?  Or maybe there is some other way this can be done?
I also would rather not have to add additional functions and members to the  classes to observe.  I have thought of that, but would like it if I could have a cleaner separation.

A: I didn't get a chance to see the comments that @Igor gave till now, but last night I was thinking about this and I deemed that it wasn't possible to determine the correct list, so I'm not bothering and stating that the user must know what type to watch for.
I also thought of the same errors as @Igor stated and then some.  Here is the final implementation that I am using:
#pragma once
#include <memory>
#include <vector>
#include <algorithm>

#define _AFXDLL  // required if using the MFC DLL and not a static implementation
#include <afx.h> // used for the ASSERT() macro
// DeleteReporter
//
// DESCRIPTION
//   This class is to warn a function that at somepoint in its execution, the
//   object of interest has been deleted.
//
// USAGE
//   To use, add the function call MarkDeleted(this); to the end of the
//   destructor of the type you wish to test for.
//
//   In the function that you want to check for the destruction, create a
//   DeleteReporter<T> variable, where T is the type where you added the
//   MarkDeleted(this) to.
//
//   You can now query the object you created to determine if the object of
//   interest has been deleted.
//
//   Example:
//
//   C::~C()
//   {
//     ...
//
//     MarkDeleted(this);
//   }
//
//   void C::fn()
//   {
//      ...
//
//      DeleteReporter<C> C_Deleted(this);
//
//      ... do stuff ...
//
//      if (!C_Deleted)
//      {
//        ... call member functions ...
//      }
//
//      ...
//   }
//
//                                            By: Adrian Hawryluk January 2017
template <typename T>
void MarkDeleted(T* pObject);

template <typename T>
class DeleteReporter
{
    friend void MarkDeleted<T>(T* pObject);
    using        pair_t = std::pair<T*, bool>;
    using shared_pair_t = std::shared_ptr<pair_t>;
    struct vector_t;

    static vector_t obj_deleted_pairs;

    shared_pair_t obj_deleted_pair;
public:
    DeleteReporter(T* pObject);
    DeleteReporter(DeleteReporter const &)  = delete;
    DeleteReporter(DeleteReporter       &&) = delete;
    operator bool();
    ~DeleteReporter();
};

//////////////////////////////////////////////////////////////////////////////
// Implementation

template <typename T>
void MarkDeleted(T* pObject)
{
    using      vector_t = typename DeleteReporter<T>::vector_t;
    using shared_pair_t = typename DeleteReporter<T>::shared_pair_t;
    vector_t& obj_deleted_pairs = DeleteReporter<T>::obj_deleted_pairs;
    for (shared_pair_t& obj_deleted_pair : obj_deleted_pairs)
    {
        if (obj_deleted_pair->first == pObject)
        {
            obj_deleted_pair->second = true;
        }
    }
}

template <typename T>
struct DeleteReporter<T>::vector_t : std::vector<shared_pair_t>
{
    ~vector_t()
    {
        // When deleting the storage vector, it should be empty, or there's an error
        ASSERT(size() == 0);
    }
};

template <typename T>
typename DeleteReporter<T>::vector_t DeleteReporter<T>::obj_deleted_pairs;

template <typename T>
DeleteReporter<T>::DeleteReporter(T* pObject)
{
    obj_deleted_pair = std::make_shared<pair_t>(pObject, false);
    obj_deleted_pairs.emplace_back(obj_deleted_pair);
}

template <typename T>
DeleteReporter<T>::operator bool()
{
    return obj_deleted_pair->second;
}

template <typename T>
DeleteReporter<T>::~DeleteReporter()
{
    auto& it = std::find(obj_deleted_pairs.begin(), obj_deleted_pairs.end(), obj_deleted_pair);
    obj_deleted_pairs.erase(it);
}


text:
Q: Spring Boot HTTP security configuration anonymous filter and a custom filter on a different path I have experienced a strange problem while trying to configure HTTP security by using WebSecurityConfigurerAdapter. Here is the full configuration class I tried so far:
@Slf4j
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
@ConditionalOnProperty(name = "module.client.security.enabled")
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Value("${management.endpoints.web.base-path}")
  private String managementEndpoint;

  @Autowired
  private List<ModuleProperties> moduleProperties;

  @Override
  public void configure(WebSecurity web) {
    web.ignoring()
        .antMatchers(this.managementEndpoint + "/**");
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.httpBasic().disable();
    http.formLogin().disable();
    // FIXME also doesn't work because of the later http.requestMatchers().antMatchers() calls
    http.authorizeRequests()
        .antMatchers("/**").anonymous();

    http.requestMatchers()
        .antMatchers("/app/**")
        .and()
        .addFilterBefore(new ClientResolveFilter(), FilterSecurityInterceptor.class);

  }

What I would like to do is actually enabling anonymous authentication for all endpoints — to prevent NullPointerExceptions when operating on SecurityContextHolder — Plus, enabling/adding a custom filter to only a subset or different endpoint path which is /app/** in this case.
I expected the above code would work but what exactly happens is the AnonymousAuthenticationFilter disabled for all and both filters only work for the path /app/** only.
If I remove the http.requestMatchers().antMatchers("/app/**") part, then AnonymousAuthenticationFilter works for all paths as normal. I suspect that the second .antMatchers("/app/**") call kinda replaces the former one or substitutes it implicitly which doesn't make sense to me, but I could be wrong.
I tried diving into the source but still confused and cannot find a clean solution to make it work as my expectation. Any ideas and help will be appreciated.
Cheers!
EDIT: I'm using Spring Boot 2.5.2 and the Spring Security version is 5.5.1

A: The addFilterBefore (and other addFilter*) method will add the filter to the filter chain which apply to all request. If you want the filter to apply to certain requests only, then you have to check inside the filter (eg. using HttpServletRequest.getgetRequestURI() to check the url).

A: After @Dickson's advice, I found a special bean called FilterRegistrationBean provided by spring boot.
Thus, I configured it as a bean which applies a specific servlet filter to only configured paths:
@Bean
public FilterRegistrationBean<ClientResolveFilter> clientResolveFilter(){
  final FilterRegistrationBean<ClientResolveFilter> frb = new FilterRegistrationBean<>();
  frb.setFilter(new ClientResolveFilter());
  frb.addUrlPatterns("/app/*");
  return frb;
}

This solution worked perfectly for my requirement.
Pay attention to that the path string is not an ant matcher now — must be written with single /app/* instead of double /app/** — it's actually the pattern when we manually configured web.xml file like in the old days :)


text:
Q: Django 1.5 "The _imagingft C module is not installed" I'm presenting an error with the PIL module from Django
This is the traceback:
ImportError at /captcha/image/693b44b881c73846dce71a6e81460b642f76de9d/
The _imagingft C module is not installed
Request Method: GET
Request URL:http://127.0.0.1:9001/captcha/image/693b44b881c73846dce71a6e81460b642f76de9d/
Django Version: 1.5.7
Exception Type: ImportError
Exception Value:
The _imagingft C module is not installed
Exception Location: F:\autanacenditel\django1.5\lib\site-packages\PIL\ImageFont.py in __getattr__, line 34
Python Executable:  F:\autanacenditel\django1.5\Scripts\python.exe
Python Version: 2.7.5
Python Path:
['C:\\Users\\kristian\\autana\\recaudacion',
'C:\\Windows\\system32\\python27.zip',
'F:\\autanacenditel\\django1.5\\DLLs',
'F:\\autanacenditel\\django1.5\\lib',
'F:\\autanacenditel\\django1.5\\lib\\plat-win',
'F:\\autanacenditel\\django1.5\\lib\\lib-tk',
'F:\\autanacenditel\\django1.5\\Scripts',
'C:\\Python27\\Lib',
'C:\\Python27\\DLLs',
'C:\\Python27\\Lib\\lib-tk',
'F:\\autanacenditel\\django1.5',
'F:\\autanacenditel\\django1.5\\lib\\site-packages',
'F:\\autanacenditel\\django1.5\\lib\\site-packages\\PIL']

My pip freeze
(django1.5) C:\Users\kristian\autana\comun>pip freeze
Django==1.5.7
Geraldo==0.4.17
PIL==1.1.7
South==0.8.4
amqp==1.4.5
anyjson==0.3.3
argparse==1.2.1
billiard==3.3.0.17
celery==3.1.11
django-braces==1.4.0
django-celery==3.0.11
django-debug-toolbar==1.1
django-extensions==1.3.7
django-floppyforms==1.1.1
django-simple-captcha==0.3.0
django-storages==1.1.6
djangorestframework==2.1.16
html5lib==0.95
kombu==3.0.15
pisa==3.0.33
psycopg2==2.5.2
python-dateutil==2.2
pytz==2014.2
reportlab==2.7
requests==1.1.0
simplejson==3.4.0
six==1.6.1
sqlparse==0.1.11
wsgiref==0.1.2

I don't know why is this happening, I've looked for some solution here on SO, but with no luck, any ideas?
Thanks in advance!
UPDATE
Solved! I just needed to use easy_install PIL instead of pip install PIL, easy_install automatically finds the binary with all libraries in it, which is where pip fails, at least on windows.


text:
Q: How to use OpenGL ES shader to convert rgbaToYuv and then render onto ImageReader's surface I want to fill the ImageReader by openGl.
and my shader can convert rgbaToyuv.
So here is my code:
ImageReader.newInstance(vConfig.width, vConfig.height, ImageFormat.YUV_420_888, 2, /*1 << 17*/);

eglSurface= eglCreateWindowSurface(xxx, imageReader.getSurface, xxx);
glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, textureOfCameraFrame);
eglSwapBuffers(eglDisplay, mEGLSurface);

But i got below error:
The producer output buffer format 0x1(RGBA) doesn't match the ImageReader's configured buffer format 0x23(YUV_420_888)

from
https://cs.android.com/android/platform/superproject/+/master:frameworks/base/media/jni/android_media_ImageReader.cpp;l=590
it says that imgReaderFmt != bufferFormat.
But what can i do to make it work with YUV_420_888 format.

A: If you want the GPU to render YUV you'll need to use the EXT_YUV_target extension functionality to set up a YUV render pass.
https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_YUV_target.txt


text:
Q: Angular ngRoute causes infinity loop and stack overflow I might be a bit thick here, but I was trying to get ng-view and ngRoute working, and thought I got it all working, but it seems like the whole thing is just looping.
To explain, it's a node server, using express, jade, angular.
It is set up so that the call should only go to layout, which then opens the routes in ngroute and renders based on that.
So this is my layout.jade
doctype html
html(ng-app="goMinute")
  head
    title= title
    base(href="/")
    link(rel='stylesheet', href='/stylesheets/style.css')
  banner
    .banner GoMinut
        p.banner-hit The place for simple meeting minutes

  body(ng-controller='BodyController as app')
      div.content
          ng-view

    script(src='/bower_components/angular/angular.js')
    script(src='/bower_components/angular-route/angular-route.js')
    script(src='/bower_components/angular-route/angular-route.js')
    script(src='/bower_components/angular-resource/angular-resource.js')
    script(src='/bower_components/jquery/dist/jquery.js')
    script(src='/bower_components/bootstrap/dist/js/bootstrap.min.js')
    script(src='/javascripts/goMinute.js')

So far so god, had to set base to something, and / seems to make it happy (not certain if this call this infinity loop
This then calls goMinute.js which contains the routes, and it SEEMS like they are called
(function() {
    var goMinute = angular.module('goMinute', ["ngResource", "ngRoute"]).
        config(['$routeProvider', '$locationProvider',
            function ($routeProvider, $locationProvider) {
                $locationProvider.html5Mode(true);
                $routeProvider
                    .when('/index', {
                        templateUrl: 'partials/index',
                        controller: 'IndexController'
                    })
                    .when('/login', {
                        templateUrl: '/partials/login',
                        controller: 'loginController'
                    })

                    .otherwise({redirectTo: "/login"});
            }
        ]
    );
    goMinute.controller('BodyController', function ($scope, $http) {
        console.log("I am body")
    })

    goMinute.controller('IndexController', function ($scope, $http) {
        console.log("This will be Index")
    })

    goMinute.controller('loginController', function ($scope, $http) {
        console.log("This will be login")
    });
})();

However, whenever I call the webpage (and idenpendent if I call /index, /login or other. It will go past "I am body" once, thenhit the IndexController about 500 times before throwing a stack overflow.
Any thoughts?
Oh, and at the time, it generates the layout, but does not seem to output the information in index partial.

A: After much muching about I think I found the issue (and I was looking in the wrong place).
The problem was not in the router, or at least I don't think so. The problem was with the express router.
I had originally set it up as follows:
app.use('/', routes);
app.use('*', routes);
app.use('/users', users);
app.use('/partials', partials);

Which worked on another site. But I started thinking, what if the loop is caused server side, so removed the * line
app.use('/', routes);
app.use('/users', users);
app.use('/partials', partials);

Which seems to have done the trick. Problem is that I added the * line because some example told me to, so there is of course the chance that I broke it now, and it just seems like it is working.


text:
Q: When scraping a Google page, the 1st page is duplicated in output. What should I do? Google searches for "Smart Factory" and scraping a large number of pages.
Google's source is starting (0-90) instead of the start page (1-10), but the first page does not read the contents of each page and duplicates the output.
My code:
library(rvest)
library(KoNLP)

title <- lapply(paste0('https://www.google.co.kr/search?q=smart+factory&ei=MNEnWZfgJoPw0AS7-aYY&sa=N&biw=1011&bih=677&bav=on.2,or.r_cp.#safe=active&q=smartfactory&start=', 0:90),
          function(url){

            url %>% read_html() %>%
              html_nodes(".r") %>%
              html_text()

          })

title

Also, when outputting in Korean, the language is broken and output.

Why is this happening?


text:
Q: pushing values in to drop down after Navigation in BB 10 cascades I have a Tabbed pane in bb 10  cascades and one of my Tab is like...in this link
http://pastebin.com/LRzyNdHZ (paste this link  in address bar, if it doesn't open)
and As you observe ,in "Add/Delete Symbols" Action Item, I try  to "AddOrDelete.qml" where I have a Drop down. you can find that  "AddOrDelete.qml" in this link
http://pastebin.com/mw1nE7yj
now i have a method in "DatabaseOperations.cpp" like...
QList<QString>   DatabaseOperations::readRecords(QString tableName){

QList<QString> sym_ID_List;
  // 1. Get the local DB connection. Note, called database()
  //    Will automatically open a connection to the database
     QSqlDatabase database = QSqlDatabase::database(); // opens the default database.

  // 2. Create a query to search for the records
     QSqlQuery query(database);
     const QString sqlQuery = "SELECT * FROM "+tableName;

     if (query.exec(sqlQuery)) {

         // Get the field indexes. We know the order of the fields, and could skip this step.
         // However this will still work if the fi changeldse order in the query string.
         const int customerIDField = query.record().indexOf("SymbolId");

         // 3. Start navigating through the records by calling the 'next' function.
        //     When there are no longer any records it will return false.
         int recordsRead = 0;
         while (query.next()) {
             // 4. Access the data (stored in the query) via the field indexes
             //    and add the data to the model.
            if(!query.value(1).toString().contains("skipRecord")){
                //alert("recordsRead"+query.value(1).toString());
                sym_ID_List.insert(recordsRead,query.value(1).toString());
            }

             recordsRead++;
         }
         qDebug() << "Read " << recordsRead << " records succeeded";
         if (recordsRead == 0) {
            // alert(tr("The customer table is empty."));
         }
     } else {
        // alert(tr("Read records failed: %1").arg(query.lastError().text()));
     }

     // 6. Optionally close the database connection if we no longer plan to use it
     database.close();
     return sym_ID_List;

}
now i would like to push these values in to drop down which is defined in "AddOrDelete.qml.
currently I am in Home Screen(i.e Tabbed pane with four Tabs... one of the tab is given in First link).I navigate to "AddOrDelete.qml" file From Action Item with Id : "Add/Delete Symbols".I have only one app.cpp file where I have Lode HomeScreen, like this...
ApplicationUI::ApplicationUI(bb::cascades::Application *app) : QObject(app){

qmlRegisterType < Timer > ("CustomTimer", 1, 0, "Timer");
QmlDocument *qml = QmlDocument::create("asset:///Template.qml").parent(this);
qml->setContextProperty("_app", this);
TabbedPane *root = qml->createRootObject<TabbedPane>();
app->setScene(root);

}
For your Information, I did the navigation from Qml Itself. To push the Vaues from the DatabaseOpartion(), Do i need to Create a seperate .CPP for "AddOrDelete.qml". If so How Can i link "App.cpp" file and "second.cpp" file. how can i navigate to and from Home screen(Tabbed pane). I have been faceing this problem since last week, I think i get a solution here,
Thanks!!!


text:
Q: Node Express on Heroku, service time spiking I've got a Node application running on Heroku serving out web content and acting as an REST API endpoint, both using node-express. The issue I'm seeing is that occasionally service times are spiking dramatically. (Sometimes to 20000+ms, up from, say, 50ms.) This seems to be happening both on occasional static file loads, as well as a very simple API call that provides a heartbeat connection to active pages. These spikes are happening on a very small percentage of overall page-loads (<1%), so I'm having trouble duplicating them myself.
For example:
heroku router - - at=info method=GET path="/static/js/thirdparty/jquery.min.js" host=somehost request_id=c1a88972-ba1b-4861-80c3-d8949fc1aa24 fwd="XXX.XXX.XXX.XXX" dyno=web.1 connect=64ms service=9560ms status=200 bytes=96677

Or, in the case of the API call:
2014-10-25T01:33:39.360282+00:00 heroku router - - at=info method=POST path="/heartbeat/" host=somehost request_id=4b35cac3-b726-460d-a7fe-6cfc622b8b1c fwd="XXX.XXX.XXX.XXX" dyno=web.1 connect=0ms service=6962ms status=200 bytes=167
I'm at a loss for how to properly diagnose this. I'm running a single dyno currently, so my best guess is something is locking up the dyno. I'm not yet in production, and even then expect my level of traffic to be quite low – nothing that broadly justifies having multiple simultaneous dynos running at any given time. When I've tried to step through my code and add logs on the server-side, I've never seen anything running slowly on my side. I appreciate that there could be a number of variables in my code that cause this – some occasional hiccup in my heartbeat that delays the response. But that doesn't explain why I'm also seeing it in the files served statically.

A: You're mentioning here that you're using node + express -- since node applications are only running in a single thread, the likely culprit here is that your application is doing something which is locking up the CPU.
The reason I know this is that your connect time is only 64ms here (this is the amount of time it took for the user's request to get from the load balancer to your dyno) -- but the service time itself is 9560ms -- this means almost all the processing time was taking place in your application code.


text:
Q: How to read large request from tcp socket using recv or read function in C++? I'm developing a server which will be receiving http requests. All works fine, but when the request is large, for example 30 mb, a part of this request is missing. In other words, server is not able to read all data when large request is received.
Here is a code of my tcp server:
TcpServer.h:
#include <cstring>
#include <string>
#include <vector>
#include <thread>
#include <functional>
#include <fcntl.h>
#include <chrono>
#include <thread>
#include <iostream>
#include <poll.h>

#if defined(_WIN32) || defined(_WIN64)

#include <winsock2.h>
#include <ws2tcpip.h>

typedef SOCKET socket_t;
typedef int msg_size_t;

#define WSA_LAST_ERR WSAGetLastError()
#define SOCKET_SEND SD_SEND
#define SOCKET_RECEIVE SD_RECEIVE

#pragma comment (lib, "Ws2_32.lib")

#elif defined(__unix__) || defined(__linux__)

#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>

typedef int socket_t;
typedef ssize_t msg_size_t;

#define INVALID_SOCKET (socket_t)(-1)
#define SOCKET_ERROR (-1)
#define SOCKET_SEND SHUT_RDWR
#define SOCKET_RECEIVE SHUT_RDWR
#define WSA_LAST_ERR errno

#else
#error Library is not supported on this platform

#endif

#define DEFAULT_HOST "127.0.0.1"
#define DEFAULT_PORT 8000

#define MAX_BUFF_SIZE 8192 * 8 - 1

typedef std::function<void(const std::string&, const socket_t&)> tcpHandler;

class TcpServer
{
private:
    uint16_t _port;
    const char* _host;
    tcpHandler _handler;
    socket_t _socket;
    sockaddr_in _socketAddr{};
    void startListener();
    void serveConnection(const socket_t& client);
    static int closeSocket(const socket_t& socket);
    static void wsaCleanUp();
    void cleanUp(const socket_t& connection);
    std::string recvAll(const socket_t& connection);
    int init();

    enum ReadResult
    {
        Continue, None
    };

    ReadResult _handleError(char* buffer, int& status);

public:
    struct Context
    {
        const char* host = nullptr;
        uint16_t port = 0;
        tcpHandler handler = nullptr;
    };

    explicit TcpServer(TcpServer::Context ctx);
    void listenAndServe();
    static void send(const char* data, const socket_t& connection);
    static void write(const char* data, size_t bytesToWrite, const socket_t& connection);
    ~TcpServer();
};

TcpServer.cpp:
#include "tcp_server.h"

bool set_socket_blocking(int fd, bool blocking)
{
    if (fd < 0)
    {
        return false;
    }

#if defined(_WIN32) || defined(_WIN64)
    unsigned long mode = blocking ? 0 : 1;
    return ioctlsocket(fd, FIONBIO, &mode) == 0;
#else
    int flags = fcntl(fd, F_GETFL, 0);
    if (flags == -1)
    {
        return false;
    }

    flags = blocking ? (flags & ~O_NONBLOCK) : (flags | O_NONBLOCK);
    return fcntl(fd, F_SETFL, flags) == 0;
#endif
}

TcpServer::TcpServer(TcpServer::Context ctx)
{
    if (ctx.host == nullptr)
    {
        ctx.host = DEFAULT_HOST;
    }

    if (ctx.port == 0)
    {
        ctx.port = DEFAULT_PORT;
    }

    this->_host = ctx.host;
    this->_port = ctx.port;

    if (ctx.handler == nullptr)
    {
        throw std::invalid_argument("Context::handler can not be null");
    }

    this->_handler = ctx.handler;

    if (ctx.logger == nullptr)
    {
        ctx.logger = Logger::getInstance();
    }

    this->_socketAddr = {};
    this->_socket = {};
}

TcpServer::~TcpServer()
{
    TcpServer::cleanUp(this->_socket);
}

int TcpServer::init()
{
    this->_socketAddr.sin_family = AF_INET;
    this->_socketAddr.sin_port = htons(this->_port);
    this->_socketAddr.sin_addr.s_addr = inet_addr(this->_host);

    memset(this->_socketAddr.sin_zero, '\0', sizeof this->_socketAddr.sin_zero);

    this->_socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);

    if (this->_socket == INVALID_SOCKET)
    {
        std::cout << "Failed to initialize server at port " + std::to_string(this->_port) << '\n';
        TcpServer::wsaCleanUp();
        return INVALID_SOCKET;
    }

    if (bind(this->_socket, (sockaddr*)&this->_socketAddr, sizeof(this->_socketAddr)) == SOCKET_ERROR)
    {
        std::cout << "Failed to bind socket to port " + std::to_string(this->_port) << '\n';
        TcpServer::cleanUp(this->_socket);
        return SOCKET_ERROR;
    }

    if (listen(this->_socket, SOMAXCONN) == SOCKET_ERROR)
    {
        std::cout << "Failed to listen at port " + std::to_string(this->_port) << '\n';
        return SOCKET_ERROR;
    }

    return 0;
}

TcpServer::ReadResult TcpServer::_handleError(
    char* buffer, int& status, int line, const char *function, const char *file
)
{
    switch (errno)
    {
        case EBADF:
        case EFAULT:
        case EINVAL:
        case ENXIO:
            // Fatal error.
            free(buffer);
            throw "Critical error";
        case EIO:
        case ENOBUFS:
        case ENOMEM:
            // Resource acquisition failure or device error.
            free(buffer);
            throw "Resource failure";
        case EINTR:
            // TODO: Check for user interrupt flags.
        case ETIMEDOUT:
        case EAGAIN:
            // Temporary error.
            return ReadResult::Continue;
        case ECONNRESET:
        case ENOTCONN:
            // Connection broken.
            // Return the data we have available and exit
            // as if the connection was closed correctly.
            status = 0;
            break;
        default:
            free(buffer);
            throw "Returned -1";
    }
    return ReadResult::None;
}

void TcpServer::listenAndServe()
{
    if (this->init() != 0)
    {
        return;
    }

#if defined(_WIN32) || defined(_WIN64)
    int status;
    WSADATA wsaData;
    status = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (status != 0)
    {
        std::cout << "WSAStartup() failed with error #" + std::to_string(status) << '\n';
        return;
    }
#endif

    this->startListener();
    TcpServer::wsaCleanUp();
}

void TcpServer::startListener()
{
    bool listening = true;
    while (listening)
    {
        try
        {
            socklen_t connectionLen = sizeof(this->_socketAddr);
            socket_t connection = accept(this->_socket, (sockaddr*)&this->_socketAddr, &connectionLen);

            if (connection != INVALID_SOCKET)
            {
                    set_socket_blocking(connection, false);

                std::thread newThread(&TcpServer::serveConnection, this, connection);
                newThread.detach();
            }
            else
            {
                std::cout << "Invalid socket connection" << '\n';
            }
        }
        catch (const std::exception& exc)
        {
            std::cout << exc.what() << '\n';
            listening = false;
        }
        catch (const char* exc)
        {
            std::cout << exc << '\n';
            listening = false;
        }
        catch (...)
        {
            std::cout << "Error occurred while listening for socket connection" << '\n';
            listening = false;
        }
    }
}

void TcpServer::serveConnection(const socket_t& connection)
{
    try
    {
        std::string data = TcpServer::recvAll(connection);

        if (!data.empty())
        {
            this->_handler(data, connection);
        }
    }
    catch (const BaseException& exc)
    {
        std::cout << exc.what() << '\n';
    }
    catch (const std::exception& exc)
    {
        std::cout << exc.what() << '\n';
    }
    TcpServer::cleanUp(connection);
}

std::string TcpServer::recvAll(const socket_t& connection)
{
    msg_size_t ret = 0;
    int status = 0;
    unsigned long size = 0;
    std::string data;

    // Poll descriptor structure
    struct pollfd descriptor{};

    // Input stream
    descriptor.fd = connection;
    descriptor.events = POLLIN;

    char* buffer = (char*) calloc(MAX_BUFF_SIZE, sizeof(char));
    do
    {
        // Wait 20 ms
        status = poll(&descriptor, 1, SO_RCVTIMEO);
        if (status == -1)
        {
            this->_handleError(buffer, status, _ERROR_DETAILS_);
        }
        else if (status == 0)
        {
            // Timeout, skip
        }
        else
        {
            // Reset the descriptor.revents to reuse the structure
            if (descriptor.revents == POLLIN)
            {
                descriptor.revents = 0;
            }

            ret = read(connection, buffer, MAX_BUFF_SIZE);
            if (ret > 0)
            {
                data.append(buffer, ret);
                size += ret;
            }
            else if (ret == -1)
            {
                this->_handleError(buffer, status);
            }
        }
    }
    while (status > 0);

    free(buffer);

    if (data.size() != size)
    {
        throw "Invalid request data total size";
    }
    return data;
}

void TcpServer::send(const char* data, const socket_t& connection)
{
    if (::send(connection, data, std::strlen(data), 0) == SOCKET_ERROR)
    {
        throw "Failed to send bytes to socket connection";
    }
}

void TcpServer::write(const char* data, size_t bytesToWrite, const socket_t& connection)
{
    if (::write(connection, data, bytesToWrite) == -1)
    {
        throw "Failed to send bytes to socket connection";
    }
}

int TcpServer::closeSocket(const socket_t& socket)
{
#if defined(_WIN32) || defined(_WIN64)
    return ::closesocket(socket);
#elif defined(__unix__) || defined(__linux__)
    return ::close(socket);
#endif
}

void TcpServer::wsaCleanUp()
{
#if defined(_WIN32) || defined(_WIN64)
    WSACleanup();
#endif
}

void TcpServer::cleanUp(const socket_t& socket)
{
    if (TcpServer::closeSocket(socket) == SOCKET_ERROR)
    {
        std::cout << "Failed to close socket connection" << '\n';
    }
    TcpServer::wsaCleanUp();
}

I think, the problem is in recvAll function. I've tried to set poll's timeout to more than 20 ms in line 19 (SO_RCVTIMEO equals 20), and the server became reading larger requests. But increasing timeout is not a solution, bacause I don't know what timeout value is required for 1 gb or greater request. Here is a code of recvAll function:
std::string TcpServer::recvAll(const socket_t& connection)
{
    msg_size_t ret = 0;
    int status = 0;
    unsigned long size = 0;
    std::string data;

    // Poll descriptor structure
    struct pollfd descriptor{};

    // Input stream
    descriptor.fd = connection;
    descriptor.events = POLLIN;

    char* buffer = (char*) calloc(MAX_BUFF_SIZE, sizeof(char));
    do
    {
        // Wait 20 ms
        status = poll(&descriptor, 1, SO_RCVTIMEO);
        if (status == -1)
        {
            this->_handleError(buffer, status, _ERROR_DETAILS_);
        }
        else if (status == 0)
        {
            // Timeout, skip
        }
        else
        {
            // Reset the descriptor.revents to reuse the structure
            if (descriptor.revents == POLLIN)
            {
                descriptor.revents = 0;
            }

            ret = read(connection, buffer, MAX_BUFF_SIZE);
            if (ret > 0)
            {
                data.append(buffer, ret);
                size += ret;
            }
            else if (ret == -1)
            {
                this->_handleError(buffer, status);
            }
        }
    }
    while (status > 0);

    free(buffer);

    if (data.size() != size)
    {
        throw "Invalid request data total size";
    }
    return data;
}

How can I fix this function, or maybe the server to make it read large requests fully?

A: You need to keep calling recv until the request is finished. TCP can't tell you when the request is finished - that's just not something it does (well, it can tell you when the connection is closed, but that would close the connection). So you need another way to know when to stop reading.
At the moment, you stop reading whenever there isn't any data for 20ms. That's not very reliable. A network disruption could cause a 20ms delay and then you'd stop too early.
In HTTP, the client tells you how long the request body is by using the Content-Length header. The request consists of the request headers and the request body, so the server needs to read the headers (which stop after a blank line), then look at the headers to see how long the request body is, then read the body (which stops after that number of bytes).


text:
Q: Multilanguage site performance I'm currently working on a site (ASP MVC) that support Multilanguage where every web content is stored in Database, for example I have english version, spanish version, etc. But I'm worried about the performance when it goes to production because everytime a user hit my page, there are at least 20 database calls to get the content.
Is there anything I can do to make this more efficient?
What I can't do is :

*

*Merge all database call into 1 call on every page load (this takes
too much effort).

*Make a separate html page for every language (I need the end user to be able to add new language without me changing the code hence the
database design).
I was thinking about caching everything in user's browser and compare it everytime they hit my page and it will only call the database if it doesn't match but I'm not sure how to approach this.
Any help will be appreciated and sorry for bad english.

A: I would suggest to go with static dictionary in this case, as @Vsevolod-Goloviznin suggested in the comments.
Let me elaborate my approach

*

*You probably have a localized resource in your database identified with some named key and language key as well:
var homePageTitle = Database.GetResource("homeTitle", "es");

*You should build up a static dictionary that will be used as cache and will have all the resources in the database in memory, for easy and convenient access:
public static MultiLanguageManager {
    private static Dictionary<string, Dictionary<string, string>> ContentCache;

    ...
    public static GetResource(string key, string language) {
        return (ContentCache[language])[key];
    }
}

*Then in your front-end you will have something like this:
...
<title>@MultiLanguageManager.GetResource("aboutTitle", "en")</title>
...

*Whenever user changes the localized content in the database, you should rebuild the ContentCache dictionary manually:
// update localized content
...
MultiLanguageManager.RebuildContentCache();
...

By using this approach you can reduce the number of database calls to minimum (retrieve only logic units, and not static resources), and control the consistency of your localization data.
One possible drawback might be the size of the static dictionary that you will build, but with Today's abundance of resources, this should not be a problem in 99% of the cases.


text:
Q: Is it bad/dangerous/inappropriate to put arbitrary backups in /var/backups? There's a system-created /var/backups directory on Debian-based systems. I need a place to store backups of several git repositories (the primaries are on bitbucket). If I store them in /var/backup/git will that break apt-get, or will they get automatically deleted at inopportune times? Is there any reason I shouldn't use /var/backup? If there is, what is a reasonable alternative?

A: Nowadays, it seems the FHS suggests you can freely create whatever subdirectory under /srv, e.g. /srv/archives/bitbucket.
What I don't find really clear with the FHS definition is that backups aren't files "served by the system". Anyway, /srv is a free namespace.

A: /var/backups is specific to Debian. It is not specified in the FHS, and its use is not documented in Debian policy (See Debian Bug report logs - #122038). The behavior is described in http://ubuntuforums.org/showthread.php?t=1232703.
While I agree with @fpmurphy that there is little danger of Debian ever removing your backup files in /var/backup, I think that it is not good policy to use a directory that is so Debian-specific. For one, Debian might change its policy and break things. For another, the user community already has specific expectations about what the directory is for. And finally, because it is not "portable" in the sense that it is not clear where this directory would be in a non-Debian distribution.
If my understanding of the FHS is correct, it would be appropriate to put clones of Git repositories in /opt/<project_name>/.git or in /usr/local/src/<project_name/.git. My personal inclination would be to use the former because it leaves the door open to backup project resources that are not source files and therefore not in Git.
If you really want to emphasis the backup nature of these repositories, you could put them in /backups, or even /home/backups, two directory names that are often used as mount points for external storage.

A: The best way to backup git repositories is to have a (bare) clone of the repository. git is quite frugal in its space usage, there will be almost no gain in compressing anything there. And a clone can easily be kept up to date (unless upstream does stupid pranks like wholesale history rewriting, nothing can be lost).


text:
Q: I want to increase the size of my boot partition (Ubuntu 14.04 version) I read in another post that kernels are distributed as new releases rather than upgrades. I didn't know this when I was allocating space to my partitions during my initial install of Ubuntu. As a result I ran out of space on my boot partition. Can I increase the size of it using GParted and how do I do this without doing damage to my system?
1      1049kB  512MB   511MB  fat32              boot
 2      512MB   768MB   256MB  ext2
 3      768MB   1000GB  999GB                     lvm
Model: Linux device-mapper (linear) (dm)
Disk /dev/mapper/ubuntu--vg-swap_1: 3712MB
Sector size (logical/physical): 512B/4096B
Partition Table: loop
Number  Start  End     Size    File system     Flags
 1      0.00B  3712MB  3712MB  linux-swap(v1)
Model: Linux device-mapper (linear) (dm)
Disk /dev/mapper/ubuntu--vg-root: 996GB
Sector size (logical/physical): 512B/4096B
Partition Table: loop
Number  Start  End    Size   File system  Flags
 1      0.00B  996GB  996GB  ext4
Sorry, don't know how to capture and post the terminal output screen.


text:
Q: Ionic+ angular : Impossible to remove outline on   or  I'm creating my application with a login page and I have my "Forgotten password ?".
But I have already tried   and  with .class, :focus {outline: none} but there is still a yellow square around my item…
I don't have this problem with my browser, only with my android application…
Mot de passe oublié ?

Someone has a solution about this issue ?
Thank you
enter image description here

A: My solution :
:focus{
    outline: -webkit-focus-ring-color auto 0px;
 }


text:
Q: Node.js Canvas image overlapping issue / canvas is creating image on top of previous image I'm having an issue with Canvas when trying to create a generated collection of .png images.
I can create the .png files fine but the first image or the image before is not being cleared.
index.js
const fs = require("fs");
const { createCanvas, loadImage } = require("canvas");
const canvas = createCanvas(1000,1000);
const ctx = canvas.getContext("2d");
const edition = 10;
const {layers,width,height} = require("./input/config.js");

const saveLayer = (_canvas, _edition) => {
    fs.writeFileSync(`./output/${_edition}.png`, _canvas.toBuffer("image/png"));
};

const drawLayer = async (_layer, _edition) => {
    let element = _layer.elements[Math.floor(Math.random() * _layer.elements.length)];
    const image = await loadImage(`${_layer.location}${element.fileName}`);
    ctx.drawImage(
        image,
        _layer.position.x,
         _layer.position.y,
         _layer.size.width,
         _layer.size.height
         );
    console.log(`I created the ${_layer.name} layer, and chose element ${element.name}`);
    saveLayer(canvas, _edition);
};

for(let i = 0; i <= edition; i++){

    layers.forEach(layer => {
        drawLayer(layer, i);
    });
  console.log("Creating edition " + i);
};

config.js
const fs = require("fs");
const width  = 1000;
const height = 1000;

const dir = __dirname;

const rarity = [
    {key: "", val: "original" },
    {key: "_r", val: "rare" },
    {key: "_sr", val: "super rare" },
];

const addRarity = (_str) => {
    let itemRarity;
    rarity.forEach((r) => {
        if (_str.includes(r.key)){
            itemRarity = r.val;
        }
    });
    return itemRarity;
};

const cleanName = (_str) => {
    let name = _str.slice(0, -4);

    return name;
};
const getElements = (path) => {
    return fs
    .readdirSync(path)
    //.filter((item) => !/(^|\/)\.|^\/\.|/g.test(item))
    .map((i,index) => {
        return {
            id: index,
            name: cleanName(i),
            fileName: i,
            rarity: addRarity(i),
        };
    });
};

const layers = [
    {
    id: 1,
    name: "0",
    location: `${dir}/0/`,
    elements: getElements(`${dir}/0/`),
    position: {x:0, y:0},
    size: {width: width, height: height},
},
{
    id: 2,
    name: "1",
    location: `${dir}/1/`,
    elements: getElements(`${dir}/1/`),
    position: {x:0, y:0},
    size: {width: width, height: height},
},
{
    id: 3,
    name: "2",
    location: `${dir}/2/`,
    elements: getElements(`${dir}/2/`),
    position: {x:0, y:0},
    size: {width: width, height: height},
},
{
    id: 4,
    name: "3",
    location: `${dir}/3/`,
    elements: getElements(`${dir}/3/`),
    position: {x:0, y:0},
    size: {width: width, height: height},
},
{
    id: 5,
    name: "4",
    location: `${dir}/4/`,
    elements: getElements(`${dir}/4/`),
    position: {x:0, y:0},
    size: {width: width, height: height},
},
];

//console.log(layers);
module.exports = {layers,width,height};

The code is working fine and I'm able to create 10 .png files.

From the images above you can see the blue hat from Image 1 is still showing in Image 2.
Edit: What I've tried -
   ctx.beginPath();
   context.clearRect(0, 0, canvas.width, canvas.height);

const createNFTs = async() =>{

    for(let i = 1; i <= edition; i++){

        for (const layer of layers) await drawLayer(layer, i);
        console.log("Creating edition " + i);

    };
};

Final Code:
 for(let i = 1; i <= edition; i++){
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        for (const layer of layers) await drawLayer(layer, i);
        console.log("Creating edition " + i);

    };

A: You have a forEach calling an async function.
forEach and async do not go together: the forEach is drawing the next image before the previous one is finished
Replace
layers.forEach(layer => {
    drawLayer(layer, i);
});

with
for (const layer of layers) {
    await drawLayer(layer, i);
    ctx.clearRect(0, 0, canvas.width, canvas.height);
}

(adding clear)
and put it in an async function


text:
Q: sfDoctrineGenerator Delete does not work Lately, I have been exploring the sfDoctrineGenerator of Symfony for my backend interface.  The problem is this:
I am using sfDoctrineGuardPlugin for user management.  The sfGuardUser module uses sfDoctrineGenerator.  All of the functions needed (delete, edit, add) are working. So far so good.
I then created a new module using this link as reference.  The add and edit functions now work but I can not make delete (both batch and single delete) work.  I tried to explicitly add it under the batch actions, but it still does not work. It says that it has already deleted showing a flash message success, but no element was deleted.  Can someone point me to the right direction where the problem could have originated?
Here is a copy of my generator.yml
generator:
  class: sfDoctrineGenerator
  param:
    model_class:           News
    theme:                 admin
    non_verbose_templates: true
    with_show:             false
    singular:              ~
    plural:                ~
    route_prefix:          news
    with_doctrine_route:   true
    actions_base_class:    sfActions

    config:
      actions: ~

      fields:
        news: {label: Announcement}
        created_at: {label: Date Published}
        updated_at: {label: Date Updated}
        user_id: {label: Author}
        user_name: {label: Author}

      list:
        title:          Announcements List
        display:        [=title, created_at, updated_at, user_name]
        sort:           [created_at, desc]
        max_per_page:   10
        batch_actions:
          _delete:    ~

      filter:
        display:  [title, user_id]

      form:
        class:    NewsForm

      edit:
        title:    Editing Announcement "%%title%%"

      new:
        title:    New Announcement

If you need something else from me, please do not hesitate to comment.  Any help will be much appreciated.  Thanks in advance.
UPDATE:
Here is the request header as viewed in Chrome:
Request URL:http://localhost:8080/inventory_dev.php/news
Request Method:GET
Status Code:200 OK
Request Headersview source
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Cookie:ja_purity_tpl=ja_purity; fontSize=100; __atuvc=312|19; JSESSIONID=9DDD204812F0C53A8B3D33B89BF7A7C8; matciis=ha6l8ci8h3i2bp696e4h33vig2; symfony=ld2qept3j5cddjsb16qie098u3
Host:localhost:8080
Referer:http://localhost:8080/inventory_dev.php/news
User-Agent:Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.52 Safari/536.5
Response Headersview source
Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection:Keep-Alive
Content-Type:text/html; charset=utf-8
Date:Wed, 30 May 2012 08:30:02 GMT
Expires:Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive:timeout=5, max=99
Pragma:no-cache
Server:Apache/2.2.21 (Win32) PHP/5.3.8
Transfer-Encoding:chunked
X-Powered-By:PHP/5.3.8

A: This is one of the D'OH moments in life.
The problem was that in my schema.yml, I specified:
actAs: { Timestampable: ~ , SoftDelete: ~ }

This means that when I delete the element, it only adds the timestamp to it instead of physically deleting it.  I removed the SoftDelete from the configuration and the problem was fixed.
Maybe there should be a functionality in sfDoctrineGenerator to support SoftDelete?


text:
Q: Maps Android Studio no se muestra cuando la app es descargada de play store Estoy teniendo un problema al mostrar google maps en mi app, antes se mostraba correctamente el mapa, el marcador con el acercamiento solicitado, cuando emulo mi proyecto en el emulador o lo hago en mi celular a través de cable, el mapa se muestra correctamente, pero ahora que subí mi app a play store, el mapa no se muestra en los dispositivos que la descargan desde allí.
tengo configurada la credencial en GoogleApi desde hace varios meses, ahora he generado una nueva clave y la agregué al proyecto pero aun no me muestra el mapa.
Cuando solicité la primer clave en GooleAPIs mi proyecto tenía un nombre de paquete distinto al que ahora tengo y no estoy seguro si esta sea la razón, he buscado en GoogleAPIs la configuración del proyecto para cambiar el nombre de proyecto pero no me lo encuentro, tambien quisiera saber si creando un nuevo proyecto en GoogleAPIs esto se podría arreglar.
A continuación les muestro el archivo java, el xml y unas capturas de GoogleAPIs, agradezco su ayuda.
JAVA
public class Fragment_Rutas extends Fragment implements OnMapReadyCallback {

public Fragment_Rutas() {
    // Required empty public constructor
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_rutas, container, false);

    SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    return v;
    //AIzaSyBfIvrguKAhUaW8CA0dvgyEXEFADleNCtc
}

@Override//acercamiento
public void onMapReady(GoogleMap googleMap) {

    LatLng bogota = new LatLng(4.653421, -74.145150);
    googleMap.addMarker(new MarkerOptions().position(bogota)
            .title("Uniagustiniana"));
    googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(bogota, 16.1f));
}
}

XML
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="300dp"
    android:background="#94dea7">

    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.SupportMapFragment" />

</LinearLayout>

Imagen de la actividad

Imagen GoogleAPIs, credenciales.

A:
cuando emulo mi proyecto en el emulador o lo hago en mi celular a
  través de cable, el mapa se muestra correctamente

Recuerda que la Keystore que usas para debug no es la misma que se usa para firmar una aplicación para producción.
Obten el SHA-1 del Keystore con el cual firmaste tu aplicación para la Playstore y habilita la API en la consola para el paquete de tu aplicación, con esto debe funcionar.

El API Key para debug no es el mismo que el que se define para una aplicación destinada a la Play Store.


text:
Q: MVC4 Razor drop down list binding with foreign key So as I wanted to have a deeper understanding.  I added a little bit more functionality to the MSFT tutorial on MVC4 that you can find here (http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/intro-to-aspnet-mvc-4)
The model is very simple. You have movies and directors. Every movie has 1 director max.
I want the user to be able to assign a director to a movie from a drop down list and save it but somehow the movie gets saved with a null Director_ID field in the database.
Here are my simple models:
public class Movie
{
    public int ID { get; set; }
    [Required]
    public string Title { get; set; }
    public DateTime ReleaseDate { get; set; }
    [Required]
    public string Genre { get; set; }
    public decimal Price { get; set; }
    public string Ranking { get; set; }
    public Director Director { get; set; }
}

public class Director
{
    public int ID { get; set; }
    public string Name { get; set; }
}

When the movie table gets generated it comes with a Director_ID field. Sweet!
I would like the user to select a director while editing a movie form a drop down list so
in the movie edit view I managed to bind a drop down list to a list of all directors obtained form the database

        @Html.DropDownListFor(model => model.Director.ID, ViewBag.Directors as List<SelectListItem>, "All")

Controller:
    //GET
    public ActionResult Edit(int id = 0)
    {
        var DirectorsList = new List<SelectListItem>();

        var DirQuery = from d in db.Directors select d;
        foreach (var d in DirQuery)
        {
            DirectorsList.Add(new SelectListItem { Value = d.ID.ToString(), Text = d.Name });
        }
        ViewBag.Directors = DirectorsList;

        Movie movie = db.Movies.Find(id);
        if (movie == null)
        {
            return HttpNotFound();
        }
        return View(movie);
    }

I get my list of all directors in my drop down. All right!
Now when I save the movie :
    [HttpPost]
    public ActionResult Edit(Movie movie)
    {
        if (ModelState.IsValid)
        {
            movie.Director = db.Directors.Find(movie.Director.ID);
            db.Entry(movie).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(movie);
    }

The argument movie that the Edit method receives comes with a Director property (as I specified in the model), when I browse into it I see the two properties form director:
"ID": which comes with the proper value that the user selected form the drop down and "Name": set to null.
As you can see in the code I pick the whole director object form the database matching the drop down value and save it
The problem is that when saving the movie, the foreign key on Movies table (Director_ID) never gets updated.
What am I doing wrong? Is there any better approach for doing this?

A: Make Id of the Director part of your model, like
public class Movie
{
    public int ID { get; set; }
    [Required]
    public string Title { get; set; }
    public DateTime ReleaseDate { get; set; }
    ...
    public int DirectorId { get; set; }

    public virtual Director Director { get; set; }
 }

Then in your controller:
//GET
public ActionResult Edit(int id = 0)
{
    Movie movie = db.Movies.Find(id);
    if (movie == null)
    {
        return HttpNotFound();
    }

    ViewBag.DirectorId = new SelectList(db.Directors, "DirectorId", "Name", movie.DirectorId);
    ...
}

And in your view:

Edit

@using (Html.BeginForm()) {
   @Html.ValidationSummary(true)

<fieldset>
    <legend>Movie</legend>
    ...

        @Html.LabelFor(model => model.DirectorId, "Director")

        @Html.DropDownList("DirectorId", String.Empty)
        @Html.ValidationMessageFor(model => model.DirectorId)

    ...


text:
Q: Haskell type mismatch with csv parsing I'm trying to parse a csv file where I want to ignore the first line and the last line, as in:
Someheader
foo, 1000,
bah, 2000,
somefooter

I wrote some Haskell using the cassava library:
{-# LANGUAGE OverloadedStrings #-}

import Control.Applicative
import qualified Data.ByteString.Lazy as BL
import Data.Csv
import qualified Data.Vector as V
import Control.Monad (mzero)

data Demand = Demand
    { name     :: !String
    , amount   :: !Int
    } deriving Show

instance FromRecord Demand where
    parseRecord r
         | length == 2 = Demand <$> r .! 0
                                <*> r .! 1
         | otherwise = mzero

main :: IO ()
main = do
    csvData <- BL.readFile "demand.csv"
    case decode HasHeader csvData of
        Left err -> putStrLn err
        Right (_, v) -> V.forM_ v $ \ p ->
            putStrLn $ (name p) ++ " amount " ++ show (amount p)

When I run this get a type mismatch, that I can't figure out:
parser.hs:34:15: error:
    • Couldn't match expected type 'V.Vector a2'
                  with actual type '(a1, V.Vector Demand)'
    • In the pattern: (_, v)
      In the pattern: Right (_, v)

My guess is that I haven't unpacked the Vector in the record correctly? Any help, gratefully received.

A: decode has the type FromRecord a => HasHeader -> ByteString-> Either String (Vector a) based on the documentation for cassava.
So the correct pattern would be Right v instead of Right (_, v).
Another problem in the code, is that length is a function, and you didn't apply it to anything, in the guard | length == 2 = .... I believe the correct code should instead be | length r == 2 = ...
Here's the complete code after those changes:
{-# LANGUAGE OverloadedStrings #-}

import Control.Applicative
import qualified Data.ByteString.Lazy as BL
import Data.Csv
import qualified Data.Vector as V
import Control.Monad (mzero)

data Demand = Demand
    { name     :: !String
    , amount   :: !Int
    } deriving Show

instance FromRecord Demand where
    parseRecord r
         | length r == 2 = Demand <$> r .! 0
                                <*> r .! 1
         | otherwise = mzero

main :: IO ()
main = do
    csvData <- BL.readFile "demand.csv"
    case decode HasHeader csvData of
        Left err -> putStrLn err
        Right v -> V.forM_ v $ \ p ->
            putStrLn $ (name p) ++ " amount " ++ show (amount p)


text:
Q: How to solve simultaneous equations with modulo arithmetic I have a system of two simultaneous equations:
$$a + 2b  = x \pmod 3$$
$$a + b = n$$
where $a, b \geq 0$  are integers.  The integer $x > 0$  is known modulo $3$ and the variable $n$ is an integer which is known. Both $a$ and $b$ are unknown.

Is it possible to compute $b \pmod 2$ from these two equations?

A: From the second equation, $a=n-b$, so
$$
b\equiv x-n\pmod{3}
$$
There will be both even and odd solutions. If $x-n$ is odd, then
$b_1=x-n+3$ and $b_2=x-n+6$ will be solutions. Similarly if $x-n$ is even.


text:
Q: Tableview won't scroll to top, hidden by scope bar when returning from view controller I have a tableview with a searchbar with a scope.
The user searches, and search results appear perfectly in the tableview. When the user clicks on a cell in the tableview, they are taken to another view controller. But when I go back to the tableview from the view controller, I get issues.
The cell that I had previously selected becomes fairly centered on the screen, but it means that the tableview got positioned higher than it was before. The issue with this is that I can no longer scroll to the cells that were higher than the selected cell. Scrolling down works fine until the bottom. The top of tableview also gets hidden by my scope bar. Whats weird though, is that if I go to another tab and then return, the tableview fixes its position.
Here is what I do for my searchbar, incase the issues lies there.
override func viewDidAppear(_ animated: Bool) {
    searchController.isActive = true
}
override func viewDidLoad() {
    searchController.searchResultsUpdater = self
    searchController.dimsBackgroundDuringPresentation = false
    searchController.searchBar.isUserInteractionEnabled = false
    searchController.searchBar.delegate = self
    searchController.searchBar.barStyle = .black
    searchController.searchBar.scopeButtonTitles = ["Title1", "Title2", "Title3"]
    searchController.searchBar.sizeToFit()
    definesPresentationContext = true
    searchController.hidesNavigationBarDuringPresentation = false

    navigationItem.searchController = searchController
    navigationItem.hidesSearchBarWhenScrolling = false

    ...
}

So obviously, how can I avoid the tableview not letting me scroll up and the scope bar not covering the top of the tableview when I am returning from another view?


text:
Q: Auto select when selected in database I have the following code in my Rails app:

Budget (optional)

  <select id="trip_currency" name="trip[currency]">
    <option value="" disabled="disabled">Please select</option>
    <option value="EUR">Euro - EUR</option>
    <option value="USD">United States Dollars - USD</option>
    <option value="GBP">United Kingdom Pounds - GBP</option>
    <option value="CAD">Canada Dollars - CAD</option>
  </select>

When a user selects USD, it is stored in my database. Then when he edits the page, it always go back to the first option value EUR.
How do I write in Rails to have USD selected according to database? I have previous code for country selects using:
<%= country_select("user", "location", [], :include_blank => true, :option_value => "#{params[:location]} selected") %>

I'm not sure how to re-implement the above on my budget because the options in budget are expanded to individual option.
Please advise. Thank you.

A: I suggest you use the following methodology in general:
1) In your view:
<%= your_form_variable.select(:civility,  Your_model::CURRENCIES, {:include_blank => 'SPlease select'}) %>

2) in your model:
CURRENCIES = [["EUR", "Euro - EUR"], [...]]


text:
Q: rndc Zone transfer completed but where is the hosts file? Good day
When I run the following command from slave
 rndc retransfer example.com

(or  rndc addzone example.com '{ type slave; masters { masterip; }; };') before it was created
the log returns:
 received control channel command 'retransfer example.com'
 zone example.com/IN: Transfer started.
 transfer of 'example.com/IN' from masterip#53: connected using myslaveip #55162
 zone example.com/IN: transferred serial 2023021400: TSIG 'rndc-key'
 transfer of 'example.com/IN' from masterip#53: Transfer completed: 1 messages, 7 records, 303 bytes, 0.114 secs (2657 bytes/sec)
 zone example.com/IN: sending notifies (serial 2023021400)`

however example.com.hosts is not created /var/named/slaves nor is the zone entry created in /etc/named.conf
if i delete all files in /var/named/slaves and restart named server it does download all the files from the master. but only if they are specified in /etc/named.conf
I did read
Bind, force zone update on slave
same problem here but no anwer
https://github.com/webmin/webmin/issues/640
thank you in advance


text:
Q: Total sum is less than sum of sums by tags in InfluxDB measurement? Or I am doing something wrong. I have a service that counts requests it receives. Requests have platform, version of client application that does them, and other tags. When service is restarted (which happens rarely on updates, metrics are reset).
So, I want to count percentage of queries from each platform in recent time range, and do:
SELECT SUM("received")  as "received"
FROM (
  SELECT NON_NEGATIVE_DIFFERENCE(MAX("received")) as "received"
  FROM  "http_metrics"
  WHERE time >= now() - 4h GROUP BY time(1s)
) GROUP BY "platform";

Which returns:
...
tags: platform=ios
time                 received
----                 --------
1970-01-01T00:00:00Z 581

tags: platform=unknown
time                 received
----                 --------
1970-01-01T00:00:00Z 12310

tags: platform=web
time                 received
----                 --------
1970-01-01T00:00:00Z 6196

And do the same without grouping:
SELECT SUM("received")  as "received"
FROM (
  SELECT NON_NEGATIVE_DIFFERENCE(MAX("received")) as "received"
  FROM  "http_metrics"
  WHERE time >= now() - 4h GROUP BY time(1s)
);

Which returns:
time                 received
----                 --------
1970-01-01T00:00:00Z 8274

Which is obviously incorrect, because "unknown" platform could not receive more requests than all of them. But I even don't know which is incorrect, total or by-platform or both?
How to count total and by-platform sum of requests properly?

A: Ok, so the problem was that as my measurement had other tags, like server and app version, and separate counter for each of that, then they all become interleaved, which could be seen on a graph, which should be smooth and cumulative, but is very spiky:

But when we add GROUP BY *
SELECT "received" FROM  "http_metrics"  WHERE $timeFilter GROUP BY *;

It splits into lot's of separate smooth series:

Now, that is differentiable, and from that we could create subquery to aggregate from.
Total:
SELECT SUM("received") as "received" FROM (
    SELECT NON_NEGATIVE_DIFFERENCE(MAX("received")) as "received"
    FROM "http_metrics"
    WHERE time >= now() - 6h
    GROUP BY time(1s), *
) WHERE  time >= now() - 6h;

time                           received
----                           --------
2018-07-17T01:07:46.184292033Z 1367

Grouped:
SELECT SUM("received") as "received" FROM (
    SELECT NON_NEGATIVE_DIFFERENCE(MAX("received")) as "received"
    FROM "http_metrics"
    WHERE time >= now() - 6h
    GROUP BY time(1s), *
) WHERE  time >= now() - 6h
GROUP BY "platform";

... I'm not going to bore you with response, but sum matches total sum.

So, I guess moral the story should be: every time you want to differentiate counters which have some tags, you need to GROUP BY *


text:
Q: New Installation working but no page formatting I have installed version 2.3.5 p1 on my windows server 2016 PC and have the site running so you can log in at admin and also view the site.
In all cases the pages are shown with no template or images.
I know I am also braking the rules as the site is on IIS which i have to use due to exchange sever web requirements.
I hope its a simple fix.

A: Please Go to Magento Root Directory in shell or terminal and run this command
php bin/magento setup:static-content:deploy -f

A: Thnankyou for the advice. I have ran this command previously and tried again. It seams to run OK but does not resolve the problem.
As below.

A: As you can see, the css files are not loaded and if you right click the homepage and go to "View page source" you will find out that by clicking the css file link, it gives 500 internal error. Try remove the .htaccess file from pub/ and then run php bin/magento setup:static-content:deploy -f.

A: got a little closer. it seems to be a web.config issue with the css. I have added this code from web. in web.config file.
Issue now resolved

    <system.webServer>
        <rewrite>
            <rules>
                <clear />
                <!-- HTTP_AUTHORIZATION variable removed-->
                <rule name="TRACE and TRACK HTTP methods 2" stopProcessing="true">
                    <match url=".*" ignoreCase="false" />
                    <conditions>
                        <!-- TRACE and TRACK HTTP methods disabled to prevent XSS attacks-->
                        <add input="{REQUEST_METHOD}" pattern="^TRAC[EK]" ignoreCase="false" />
                    </conditions>
                    <action type="Redirect" redirectType="Temporary" url="{R:0}" />
                </rule>
                <rule name="Route requests to index.php 2" stopProcessing="true">
                    <match url=".*" ignoreCase="false" />
                    <conditions>
                        <add input="{URL}" pattern="^/(media|skin|js)/" ignoreCase="false" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="pub/index.php" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</location>
<!--Custom configuration for the pub/static directory-->
<location path="pub/static">
    <system.webServer>
        <rewrite>
            <rules>
                <clear/>
                <rule name="Imported Rule 1-1 - pub" stopProcessing="false">
                    <match url="^pub/static/version.+?/(.+)$" ignoreCase="false" />
                    <action type="Rewrite" url="pub/static/{R:1}" />
                </rule>
                <rule name="Imported Rule 2" stopProcessing="false">
                    <match url="^pub/static/(.+)$" ignoreCase="false" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="pub/static.php?resource={R:1}" appendQueryString="false" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</location>


text:
Q: Questions about proving $\lnot \lnot a = a$ This is all in the context of a Hilbert system with modus ponens $A, A\to B \vdash B$ and axioms:
Axiom $1$: $A \to (B \to A)$
Axiom $2$: $(A \to (B \to C)) \to ((A \to B) \to (A \to C))$
Axiom $3$: $(\lnot B \to \lnot A) \to (A \to B)$
So I tried to prove double-negation elimination by doing the following:
\begin{array}{ccc}
1 & \{ \lnot \lnot a \} \vdash \lnot \lnot a & \text{Premise}\\
2 & \{ \lnot \lnot a \} \vdash \lnot \lnot a \to (\lnot \lnot \lnot \lnot a \to \lnot \lnot a)  & \text{ Axiom } 1\\
3 & \{ \lnot \lnot a \} \vdash \lnot \lnot \lnot \lnot a \to \lnot \lnot a  & \text{ Modus Ponens } 1, 2\\
4 & \{ \lnot \lnot a \} \vdash (\lnot \lnot \lnot \lnot a \to \lnot \lnot a) \to (\lnot a \to \lnot \lnot \lnot a)  & \text{ Axiom } 3\\
5 & \{ \lnot \lnot a \} \vdash \lnot a \to \lnot \lnot \lnot a  & \text{ Modus Ponens } 3, 4\\
6 & \{ \lnot \lnot a \} \vdash (\lnot a \to \lnot \lnot \lnot a) \to (\lnot \lnot a \to  a)  & \text{ Axiom } 3\\
7 & \{ \lnot \lnot a \} \vdash \lnot \lnot a \to  a  & \text{ Modus Ponens } 5, 6\\
8 & \{ \lnot \lnot a \} \vdash a  & \text{ Modus Ponens } 1, 7\\
9 & \vdash \lnot \lnot a \to a  & \text{ Deduction Theorem } \\
\end{array}
And then I continued on, to prove double negation introduction:
\begin{array}{ccc}
10 & \vdash \lnot \lnot \lnot a \to \lnot a & \text{Double Negation Elimination}\\
11 & \vdash (\lnot\lnot \lnot a \to \lnot a) \to (a \to \lnot \lnot a) & \text{ Axiom } 3\\
12 & \vdash a \to \lnot \lnot a & \text{ Modus Ponens } 10, 11\\
\end{array}
My questions:

*

*Am I allowed to invoke the deduction theorem in the middle of a proof like this (step $9$)? Is this considered a context change? Is context-changing allowed?

*Are the proofs even right/correct?

*Assuming it's all correct: Are we able to combine them to say that $a \to \lnot \lnot a$ and $\lnot \lnot a \to a$, therefore $a \iff \lnot \lnot a$ or is this symbol not allowed?

*What ultimately let us say $\lnot \lnot a = a$, the use of the equal sign here?

A: *

*The sequence 1-8 is a derivation (in the Hilbert system for implicative propositional classical logic) of $\lnot \lnot a \vdash a$. Step 9 does not correspond to an inference rule in such Hilbert system, thus the sequence 1-9 is not a derivation of $\vdash \lnot \lnot a \to a$ in such Hilbert system. The deduction theorem says that, since there is a derivation of $\lnot \lnot a \vdash a$, then there exists another derivation (which you didn't construct, but there exists) of $\vdash \lnot \lnot a \to a$. So, if the question is "Show a derivation of $\vdash \lnot \lnot a \to a$ in  such Hilbert system", you didn't answer it; but if the question is "Show that $\vdash \lnot \lnot a \to a$ is derivable in  such Hilbert system", your answer is fine (except that step 9 is not allowed as an inference rule in the Hilbert system, i.e. you should consider the sequence 1-8 and then apply the deduction theorem to conclude). See also here.

*Concerning the proof of $\vdash \lnot \lnot a \to a$, see point 1. Your derivation for $\vdash a \to \lnot \lnot a$ (which is completely independent and separated from the derivation 1-8) is correct, on the proviso that you have already proved that $\vdash \lnot \lnot \lnot a \to \lnot a$ is derivable in the Hilbert system.

*If  you want to consider $\leftrightarrow$ as a connective in the formal language, then you need to add some axioms concerning it in the Hilbert system. Without these axioms, the formula $a \leftrightarrow \lnot \lnot a$ makes no sense in the Hilbert system and hence it is not allowed.
The list of axioms that you
have to add to the Hilbert system for the connective $\leftrightarrow$ is here.

*The notation $a = \lnot \lnot a$ (I prefer to write $a\equiv \lnot \lnot a$ or $a\dashv\vdash \lnot \lnot a$) means that both $\vdash \lnot \lnot a \to a$ and $\vdash a \to \lnot \lnot a$ are derivable in the Hilbert system, which is essentially what you have proved (or want to prove). Note that  $a = \lnot \lnot a$ and $a\equiv \lnot \lnot a$ and $a\dashv\vdash \lnot \lnot a$ are not formulas in the language, they are just notations in  the meta-language. See also point 3.