text:
Q: AMPScript to create a contact in salesforce with validation rule We have a validation rule on creating contacts which forces the Account Name to be set.  When creating the Contact using AMPScript how do I set the Account to be the value I want?  (This can be a hard coded Account as we only use one).
I have tried setting the AccountId but this doesnt get past the validation rule.
CreateSalesforceObject("Contact",8,"FirstName",@firstName,"LastName",@lastName,"Email",@email,"Gender__c",@gender,"MobilePhone",@mobile,"Recieve_HTML_Emails__c",@emailTxtImage,"Receive_Text_Emails__c",@emailTxt,"Receive_SMS__c",@sms,"AccountId","TESTID")

Tried setting Account to TEST even though this is not a field on contact record.
CreateSalesforceObject("Contact",8,"FirstName",@firstName,"LastName",@lastName,"Email",@email,"Gender__c",@gender,"MobilePhone",@mobile,"Recieve_HTML_Emails__c",@emailTxtImage,"Receive_Text_Emails__c",@emailTxt,"Receive_SMS__c",@sms,"Account.Name","TEST")

Here is the validation Rule
Account.Name <> "TEST"

I have also tried changing the Validation Rule to be on the AccountId but this doesnt work when saving the contact through Salesforce.
Any help appreciated.
Cheers

A: School boy error, number of fields updated was 9 not 8, so the parameter in question was being missed. Changing it to 9 meant that using the AccountId worked.
Thanks


text:
Q: How does EF codefirst know which model class to create a table for? I was not able to find the answer to this online - please link me if I've overlooked any resources.
I understand how Entity Framework's codefirst works.  The question is: how does EF know which model class to create a table for and which model class to just treat as a class?
For example, in the sample MVC4 application that comes from creating a new MVC project with VS 2012 Express Developer, there are classes (LocalPasswordModel, LoginModel, RegisterModel, etc) in the Account Model that have no tables, and EF knows not to generate tables for these classes.
How does EF know this?

A: Entity Framework looks at your DbContext class, and creates a table for each DbSet<T> property that you define.
EF won't even see any class which is not referenced by the DbContext.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mapping nested classes via Entity Framework I have class with this definition :
public class WebSiteContent
    {
        public Guid Id { get; set; }
        public About About { get; set; }
        public Tips Tips { get; set; }
        public Images Images { get; set; }
    }

where my About and Tips and Images are look like this :
 public class About
    {
        public Guid Id { get; set; }
        public string Text { get; set; }
        public string Addres { get; set; }
        public int PhoneNumber { get; set; }
        public int Mobile { get; set; }
    }

and Tips :
 public class Tips
    {
        public Guid Guid { get; set; }
        public string Content { get; set; }
    }

and Images :
public class Images
    {
        public Guid Id { get; set; }
        public string Background { get; set; }
        public string Logo { get; set; }
        public About About { get; set; }

    }

here i just want to use about and Images and tips as a helper class to just create a property and don't want to have about,Images or tips table in database !
Entity framework needs Id to map all of above classes , how can I do that ?

A:
here i just want to use about and Images and tips as a helper class to
  just create a property and don't want to have about,Images or tips
  table in database

So you are looking for complex type. Mark your About, Tips and Images classes with [ComplexType] attribute.

Entity framework needs Id to map all of above classes , how can I do
  that ?

EF only needs Id for entities. If you map them as complex types you will not need to use any Id.
Btw. if you don't want to have those classes and their properties in database at all you can use [NotMapped] attribute instead.


text:
Q: Status bar sized incorrectly with a contained UINavigationController I make a UINavigationController a child of another view controller through containment. Everything works fine, except for a strange issue that occurs when launching the app with the in-call status bar turned ON and then switching it back OFF after the app UI is on the screen. There appears a strange black gap in place of the status bar.
Consider the self-contained example app below:
#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end

@implementation AppDelegate
- (BOOL)application:(UIApplication *)app didFinishLaunchingWithOptions:(NSDictionary *)opt
{
  // Content
  UILabel * aLbl = [[UILabel alloc] initWithFrame:CGRectMake(20, 100, 200, 40)];
  aLbl.text = @"In-call status bar issue";

  UIViewController * aContent = [[UIViewController alloc] init];
  aContent.title = @"Title";
  aContent.view.backgroundColor = UIColor.whiteColor;
  [aContent.view addSubview:aLbl];

  UINavigationController * aNav = [[UINavigationController alloc]
    initWithRootViewController:aContent];

  // Parentmost view controller containing the navigation view controller
  UIViewController * aParent = [[UIViewController alloc] init];
  [aParent.view addSubview:aNav.view];
  [aParent addChildViewController:aNav];
  [aNav didMoveToParentViewController:aParent];

  self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
  self.window.rootViewController = aParent;
  [self.window makeKeyAndVisible];

  return YES;
}
@end

int main(int argc, char ** argv)
  { @autoreleasepool { return UIApplicationMain(argc, argv, nil, @"AppDelegate"); } }

The easiest way to reproduce the problem is:

*

*Start the iOS Simulator.

*Press ⌘+Y to turn on the in-call status bar. The status bar will become wide and green.

*Launch the app manually and wait for the Navigation Controller to appear.

*Press ⌘+Y again to turn off the in-call status bar.

The UI should now look as follows:

Anyone know how to fix the problem?

A: You are adding a view (the navigation controller's view) as subview to another view (the parent view controller's view), without giving it a frame! This is something you should never do.
Just add these lines to your code:
aNav.view.frame = aParent.view.bounds;
aNav.view.autoresizingMask =
    UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;

Now the navigation controller's view has a frame, and maintains it in relation to its superview.


text:
Q: How to deal with mixed databases? Did you ever have the following situation: you need to store information, but a part of this information is well modeled with one type of database (in a very loose sense), and another part is well modeled with another type. Examples:

*

*a set of files and additional information about each of them stored in a relational SQL database.

*an OODB together with a triplestore.

*two previously completely unrelated key/value data storage which must be integrated, but kept separated.

What do you think it's the best way to deal with this kind of situation? keep the two types of data separated, and write a software layer that keep them synchronized ? use only one kind of database, adapting one kind of data into the other (e.g. storing the file into the relational db as a blob, or storing the relational part in a hacked up file-based database on the disk)?

A: I don't think "merging" the two worlds would be a good thing (performance, manteinance and so on).
First one is good for me, keep them separated and separate them from the business logic with a layer. Working with loosely coulped layer has many benefits. You could achieve this via design patters or by working with interfaces/abstract classes.

A: This kind of problem is known as federated database systems. I'd recommend reading the article on federated databases on wikipedia.
It's not an easy situation and the solutions to this problem depend a lot on how tight the data in your different "databases" is coupled/related and also on how similar the schema of the different "databases" is.

A: You describe a problem solved by Virtual Database Engines (also referred to as Federated DBMS Engines).
I suspect the ideal situation for you is a Conceptual Layer that sits atop disparate logical sources which could be any combination of: relational dbms engines (behind ERP, CRM, HR, Accounting systems), web services, XML, etc..
Virtuoso (my company's product) handles this by allowing you to attach exernal/remote data sources associated with a myriad data representation formats (as per list above). It then allows you to use an EAV/CR model (e.g. RDF Graph Model) as the basis for a Conceptual Layer that is both concrete and the focus of all subsequent data interaction. This conceptual layer endows each Data item with an HTTP scheme based Identifier; thus, you only need an HTTP aware user agent as you commence exploring the rich conceptual graph that now fronts your disparate logical data sources.
What I describe above is basically what's commonly known today as: HTTP based Linked Data.
Links:

*

*http://virtuoso.openlinksw.com
Kingsley


text:
Q: Applying different kernels to parts of a dataset and merging the output I am trying to create a classifier using SVM on a dataset that is composed of 6 sets of data for each of my observations. When I train the SVM (rbf kernel), I get a better performance of the classifier when I use only 2 out of 6 sets of features (reducing the number of features to about half): when I add features, my accuracy degrades by over 5%. I understand that "junk in, junk out", but we were surprised by the magnitude of this effect. Note that I scale the features to all have the same range and variance before training the SVM (using sklearn's MinMaxScaler()).
Our interpretation of this result is that we are not representing the feature space correctly - by calculating a single kernel on all 6 sets of features at the same time, I lose information from each single set of features. To make up for this, I want to calculate a kernel on each feature set independently (and so also find the optimal gamma separately) and then concatenate the results to train the classifier (a bit like what described here). Basically, I would like to do:
$$
k_{final} = k_1(X_1) + k_2(X_2) + k_3(X_3) + k_4(X_4) + k_5(X_5) + k_6(X_6)
$$

*

*Is this something that can be done and a sensible thing to do? And would it help with my problem?

*If so, can I implement this in sklearn? If so, how?

I have found a way to calculate kernels in sklearn (https://scikit-learn.org/stable/modules/gaussian_process.html#gp-kernels), and so I could calculate the kernel on each set separately. However, once I output the distance matrix, I am not sure how I would use it to train the SVM.
My understanding of kernels is only very intuitive, so I would appreciate an answer with limited maths!


text:
Q: How can I disable the HTTP TRACE method in Laravel Forge? I have an application that needs to pass a security review. I'm using Laravel Forge and the item in question is:

The application web server must be configured to disable the TRACE and
  other HTTP methods if not being used.

I tested it using
curl -v -X TRACE http://www.yourserver.com

via this guide:
https://security.stackexchange.com/questions/31659/testing-for-http-trace-method
And it didn't return an error message so I'm assuming that I still need to disable TRACE.
What's the best way to accomplish this using Laravel Forge?

A: You can edit your nginx configuration in Forge, so you just need to add a method filter in your conf:
if ($request_method !~ ^(GET|HEAD|POST)$ )
{
    return 444;
}


text:
Q: JOIN в Linq2Sql Здравствуйте, уважаемые знатоки. У меня возник вопрос по использованию Linq2Sql. Предположим, имеются таблицы следующего вида :

Кроме этого у меня есть класс примерно такого вида:
public class SomeModel
{
    public string DepartureCountryName { get; set; }

    public string DepartureCityName { get; set; }

    public string ArrivalCountryName { get; set; }

    public string ArrivalCityName { get; set; }
}

SomeModel - это модель, которая должна быть отображена на View. Она заполняется с помощью Linq2Sql запроса из таблицы SomeTable. Как мы видим в таблице SomeTable есть по два поля, ссылающихся на таблицы Countries и Cities. Для получения модели с помощью LinqToSql я делаю примерно следующее:
from some in dataContext.SomeTable
where какое_то_условие
select ConvertFromTableToModel(some)

//.......

public SomeModel ConvertFromTableToModel(SomeTable some)
{
    return new SomeModel
           {
               DepartureCountryName =  dataContext.Countries.
                                       First(x => x.Id == some.DepartureCountryId),
               DepartureCityName    =  dataContext.Cities.
                                       First(x => x.Id == some.DepartureCityId),
               ArrivalCountryName   =  dataContext.Countries.
                                       First(x => x.Id == some.ArrivalCountryId),
               ArrivalCityName      =  dataContext.Cities.
                                       First(x => x.Id == some.ArrivalCityId),
           }
}

то есть получается, что для получения каждой SomeModel мне приходится в методе ConvertFromTableToModel делать по 4 запроса к базе для получения DepartureCountryName,
DepartureCityName,  ArrivalCountryName и ArrivalCityName. Всего таких SomeModel может быть 500-1000 штук на одной view. То есть требуется создать 2000-4000 запросов к базе, что сильно сказывается на производительности (страница рендерится примерно за 10-15 секунд). Можно ли как-то  улучшить эту ситуацию? Насколько мне известно здесь можно воспользоваться join-ом, но появляется необходимость делать join сразу по нескольким полям к одной таблице (DepartureCountryId и ArrivalCountryId, DepartureCityId и ArrivalCityId), поэтому никак не могу сообразить как этот join сделать.
Перейти на EntityFramework или на ADO.NET к сожалению нельзя.
Заранее спасибо.

A: LinQ создает поля с ленивой инициализацией, если есть связи в БД. Поэтому в вашем случае лучше написать вот так:
var result = dataContext.SomeTable
    .Where(x => x.Id == id) //какое то условие писать тут
    .Select(x => new SomeModel
    {
        DepartureCountryName = x.Countrie.Name,
        DepartureCityName = x.Citie.Name,
        ArrivalCountryName = x.Countrie1.Name,
        ArrivalCityName = x.Citie1.Name,
    });

К сожалению, если вы создавали модель из Базы LinQ не подтягивает наименования связей. Из-за этого дублирующиеся связи между таблицами будут иметь такой вид Countrie, Countrie1 и т.д. Вам придется заглянуть внутрь сгенерированного файла dbml чтобы понять по какому именно ключу эта связь.
Их можно или переопределить в автоматически сгенерированном файле dbml, но это не желательно, поскольку если вы потом обновите модель эту часть придется восстанавливать руками.
Другой вариант расширить ваши таблицы, сделав читаемыми названия связанных таблиц поскольку все сгенерированные классы имеют модификатор partial.
Результатом такой конструкции будет SQL инструкция уже содержащие все необходимые JOIN и вам нет нужды писать их вручную.
Мало того, она будет выполнена только в тот момент, когда результаты вычисления реально понадобятся в программе благодаря ленивым вычислениям внутри LinQ. Если вы хотите принудительно выгрузить из базы все в данном месте в конце выражения необходимо написать .ToList().

A: Попробуйте так:
var result =
from s in dataContext.SomeTable
join c1 in dataContext.Countries on s.DepartureCountryId equals c1.Id
join ci1 in dataContext.Cities on s.DepartureCityId equals ci1.Id
join c2 in dataContext.Countries on s.ArrivalCountryId equals c2.Id
join ci2 in dataContext.Cities on s.ArrivalCityId equals ci2.Id
where какое_то_условие
select new SomeModel{
   DepartureCountryName = c1,
   DepartureCityName = ci1
   ArrivalCountryName = c2,
   ArrivalCityName = ci2
};


text:
Q: Как убрать виджет из макета У меня есть приложение, в котором есть 4 страницы и на 1-ой странице находится календарь и виджет с погодой, который после нажатия кнопки обрезается, так как находится в макете.
Я хочу убрать виджет с погодой из макета, однако не знаю как это правильно сделать.

До нажатия на кнопку:

После нажатия:

Как должно быть:

Вот сам код: (часть кода с погодой находится на 143 строке кода)
import sys
from PyQt5 import QtCore, QtGui, QtWidgets

from PyQt5.Qt import *
from ext import *
from main import App                              # +++
from part_1 import Main

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        #размер основного окн
        self.resize(845, 535)
        self.setFixedSize(QtCore.QSize(845,535))
#
        self.setStyleSheet("background-color: rgb(245, 45, 45);")
        #центральный виджет
        self.centralwidget = QtWidgets.QWidget()
        self.centralwidget.setObjectName("centralwidget")
        self.setCentralWidget(self.centralwidget)

# Content horizontalLayout_2
        self.Content = QtWidgets.QFrame(self.centralwidget)
        self.Content.setStyleSheet("background-color: rgb(255, 255, 255);")

        self.Content.setFrameShape(QtWidgets.QFrame.NoFrame)
        self.Content.setFrameShadow(QtWidgets.QFrame.Raised)
        self.Content.setObjectName("Content")
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.Content)
        self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout_2.setSpacing(0)
        #виджет слева
        self.frame_left_menu = QtWidgets.QFrame(self.Content)
        self.frame_left_menu.setMinimumSize(QtCore.QSize(45, 0))

        self.frame_left_menu.setStyleSheet("background-color: rgb(255, 255, 255); border: 0px solid; ")

        self.frame_left_menu.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame_left_menu.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame_left_menu.setObjectName("frame_left_menu")
        self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.frame_left_menu)
        self.verticalLayout_3.setContentsMargins(0, 0, 0, 0)

        self.frame_top_menus = QtWidgets.QFrame(self.frame_left_menu)
        self.frame_top_menus.setFrameShape(QtWidgets.QFrame.NoFrame)
        self.frame_top_menus.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame_top_menus.setObjectName("frame_top_menus")
        #указываем вертикальное выравнивание
        self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.frame_top_menus)
        self.verticalLayout_4.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_4.setSpacing(10)

        #домик
        self.btn_page_1 = QtWidgets.QPushButton("", self.frame_top_menus)
        self.btn_page_1.setIcon(QIcon('дом.png'))
        self.btn_page_1.setIconSize(QSize(45,45))
        self.btn_page_1.setMinimumSize(QtCore.QSize(0, 40))

        self.btn_page_1.setStyleSheet('border: 0px solid red;')

        self.btn_page_1.setObjectName("btn_page_1")
        self.verticalLayout_4.addWidget(self.btn_page_1)
        #Заметки
        self.btn_page_2 = QtWidgets.QPushButton("", self.frame_top_menus)
        self.btn_page_2.setIcon(QIcon('заметка1.png'))
        self.btn_page_2.setIconSize(QSize(45,45))
        self.btn_page_2.setMinimumSize(QtCore.QSize(0, 40))

        self.btn_page_2.setStyleSheet('border: 0px solid red;')
        self.btn_page_2.setObjectName("btn_page_2")

        self.verticalLayout_4.addWidget(self.btn_page_2)

        #погода
        self.btn_page_3 = QtWidgets.QPushButton("", self.frame_top_menus)
        self.btn_page_3.setIcon(QIcon('солнышко.png'))
        self.btn_page_3.setIconSize(QSize(45,45))
        self.btn_page_3.setMinimumSize(QtCore.QSize(0, 40))

        self.btn_page_4 = QtWidgets.QPushButton('', self.frame_top_menus)
        self.btn_page_4.setIcon(QIcon('папочка.png'))
        self.btn_page_4.setIconSize(QSize(45, 45))
        self.btn_page_4.setMinimumSize(QtCore.QSize(0, 40))

        timer = QTimer(self)
        timer.timeout.connect(self.showTime)
        timer.start(1000)

        font1 = QFont('Century Gothic', 13, QFont.Bold)
        self.timewidget = QtWidgets.QLabel()
        self.timewidget.setMinimumSize(QtCore.QSize(45,45))
        self.timewidget.setAlignment(Qt.AlignBottom)
        self.timewidget.setFont(font1)

        self.btn_page_3.setObjectName("btn_page_3")
        self.verticalLayout_4.addWidget(self.btn_page_3)

        self.verticalLayout_3.addWidget(self.frame_top_menus, 0, QtCore.Qt.AlignTop)
        self.horizontalLayout_2.addWidget(self.frame_left_menu)

        self.verticalLayout_4.addWidget(self.btn_page_4)

        self.frame_pages = QtWidgets.QFrame(self.Content)
        self.frame_pages.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame_pages.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame_pages.setObjectName("frame_pages")
        self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.frame_pages)
        self.verticalLayout_5.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_5.setObjectName("verticalLayout_5")

        self.stackedWidget = QtWidgets.QStackedWidget(self.frame_pages)
        self.stackedWidget.setMinimumSize(QtCore.QSize(800, 535))

        self.stackedWidget.setObjectName("stackedWidget")

#1 страница
        self.page_1 = QtWidgets.QWidget()
        self.page_1.setObjectName("page_1")
        self.verticalLayout_7 = QtWidgets.QVBoxLayout(self.page_1)
        self.verticalLayout_7.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_7.setObjectName("verticalLayout_7")
        #указываем что будет находится на 1 странице
        self.label_1 = QtWidgets.QLabel(self.page_1)
        font = QtGui.QFont()
        font.setPointSize(40)
        font.setFamily("Century Gothic")
        font.setPointSize(15)
        font.setKerning(True)
        self.label_1.setFont(font)

        self.label_1.setAlignment(QtCore.Qt.AlignCenter)
        self.label_1.setObjectName("label_1")
        self.verticalLayout_7.addWidget(self.label_1)

        self.main = App()

        self.main.setMinimumSize(QtCore.QSize(500, 154))
        self.main.w_root.setWindowFlag(Qt.FramelessWindowHint)

        self.verticalLayout_7.addWidget(self.main.w_root, alignment = QtCore.Qt.AlignRight)
        self.main.w_root.setWindowFlag(Qt.CustomizeWindowHint)
        self.stackedWidget.addWidget(self.page_1)

        #2 страница
        self.page_2 = QtWidgets.QWidget()
        self.page_2.setObjectName("page_2")
        self.verticalLayout_6 = QtWidgets.QVBoxLayout(self.page_2)
        self.verticalLayout_6.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_6.setObjectName("verticalLayout_6")
        #указываем что будет находиться в 2 странице
        self.label_2 = QtWidgets.QLabel("Страница2", self.page_2)
        font = QtGui.QFont()
        font.setPointSize(40)
        font.setFamily("Century Gothic")
        font.setPointSize(15)
        font.setKerning(True)
        self.label_2.setFont(font)
        self.label_2.setStyleSheet("color: #FFF; background-color: #1eae98;")
        self.label_2.setAlignment(QtCore.Qt.AlignCenter)
        self.label_2.setObjectName("label_2")
        self.verticalLayout_6.addWidget(self.label_2)
        self.stackedWidget.addWidget(self.page_2)
        #3 страница
        self.page_3 = QtWidgets.QWidget()
        self.page_3.setObjectName("page_3")
        self.verticalLayout_8 = QtWidgets.QVBoxLayout(self.page_3)
        self.verticalLayout_8.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_8.setObjectName("verticalLayout_8")
        #указываем что будет находиться на 3 странице
        self.label = QtWidgets.QLabel("Страница3", self.page_3)
        font = QtGui.QFont()

        font.setFamily("Century Gothic")
        font.setPointSize(15)
        font.setKerning(True)
        self.label.setFont(font)
        self.label.setStyleSheet("color: green; background-color: black;")
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setObjectName("label")
        self.verticalLayout_8.addWidget(self.label)
        self.stackedWidget.addWidget(self.page_3)

# page_4 verticalLayout_9
        self.page_4 = QtWidgets.QWidget()
        self.page_4.setObjectName('page_4')

        self.gg = Main()

        self.verticalLayout_9 = QtWidgets.QVBoxLayout(self.page_4)

        self.verticalLayout_9.addWidget(self.gg)

        self.verticalLayout_9.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_9.setSpacing(0)
        self.verticalLayout_9.setObjectName('verticalLayout_9')

        self.stackedWidget.addWidget(self.page_4)

        self.verticalLayout_5.addWidget(self.stackedWidget)
        self.horizontalLayout_2.addWidget(self.frame_pages)
        self.stackedWidget.setCurrentIndex(0)

# verticalLayout  centralwidget
        self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setSpacing(0)
# verticalLayout.addWidget(self.Content)
        self.verticalLayout.addWidget(self.Content)

        #Нажатие на дом
        self.btn_page_1.clicked.connect(
            lambda: self.stackedWidget.setCurrentWidget(self.page_1))
        #Нажатие на заметки
        self.btn_page_2.clicked.connect(
            lambda: self.stackedWidget.setCurrentWidget(self.page_2))
        #Нажатие на погоду
        self.btn_page_3.clicked.connect(
            lambda: self.stackedWidget.setCurrentWidget(self.page_3))

        self.btn_page_4.clicked.connect(
            lambda: self.stackedWidget.setCurrentWidget(self.page_4))

        self.frame_left_menu.installEventFilter(self)
        self.verticalLayout_3.addWidget(self.timewidget, 0, QtCore.Qt.AlignBottom)

# календарь
        self.calendarWidget = QtWidgets.QCalendarWidget(self.page_1)
        self.calendarWidget.setWindowFlag(Qt.FramelessWindowHint)
        self.calendarWidget.setEnabled(True)
        self.calendarWidget.setGeometry(QtCore.QRect(0, 154, 800, 381))
        self.calendarWidget.setFixedSize(QtCore.QSize(800, 381))
        self.calendarWidget.setWindowFlags(Qt.FramelessWindowHint)

        font = QtGui.QFont()
        font.setFamily("Century Gothic")
        font.setPointSize(15)
        font.setKerning(False)
        self.calendarWidget.setFont(font)
        self.calendarWidget.setAutoFillBackground(True)

        self.calendarWidget.setGridVisible(False)

        self.calendarWidget.setVerticalHeaderFormat(QtWidgets.QCalendarWidget.NoVerticalHeader)
        self.calendarWidget.setDateEditEnabled(False)
        self.calendarWidget.setDateEditAcceptDelay(0)
        self.calendarWidget.setObjectName("calendarWidget")

        self.calendarWidget.setStyleSheet(StyleSheet)

        self.verticalLayout_7.addWidget(self.calendarWidget)

    def showTime(self):
        current_time = QtCore.QTime.currentTime()
        label_time = current_time.toString('hh:mm')
        self.timewidget.setText(label_time)

StyleSheet = '''
/* Верхняя область навигации                            */
#qt_calendar_navigationbar {
    background-color: rgb(0, 188, 212);
    min-width: 800px;
    max-width: 800px;
    min-height: 35px;
    max-height: 35px;
}

/*  Кнопка последнего месяца и кнопка следующего месяца */
#qt_calendar_prevmonth, #qt_calendar_nextmonth {
    border: none;                     /* убрать границу */
    margin-top: 0px;
    color: white;
    min-width: 30px;
    max-width: 30px;
    min-height: 30px;
    max-height: 30px;
    border-radius: 10px;            /* выглядит как эллипс */
    font-weight: bold;              /* шрифт полужирный    */
    qproperty-icon: none;
    background-color: transparent; /* Цвет фона прозрачный */
}

#qt_calendar_prevmonth {
    qproperty-text: "<";         /* Изменить текст кнопки  */
}
#qt_calendar_nextmonth {
    qproperty-text: ">";
}
#qt_calendar_prevmonth:hover, #qt_calendar_nextmonth:hover {
    background-color: rgba(225, 225, 225, 100);
}
#qt_calendar_prevmonth:pressed, #qt_calendar_nextmonth:pressed {
    background-color: rgba(235, 235, 235, 100);
}

/*  год, месяц                                                */
#qt_calendar_yearbutton, #qt_calendar_monthbutton {
    color: white;
    margin: -1px;
    min-width: -1px;
    border-radius: 15px;
    background-color: rgba(0, 188, 212, 100)
}
#qt_calendar_yearbutton:hover, #qt_calendar_monthbutton:hover {
    background-color: rgba(225, 225, 225, 100);
}
#qt_calendar_yearbutton:pressed, #qt_calendar_monthbutton:pressed {
    background-color: rgba(235, 235, 235, 100);
}

/* Поле ввода года                                                        */
#qt_calendar_yearedit {
    min-width: 85px;
    color: white;
    background: transparent;         /* Сделать фон окна ввода прозрачным */
}
#qt_calendar_yearedit::up-button {   /* Кнопка вверх                      */
    width: 25px;
    subcontrol-position: right;
}
#qt_calendar_yearedit::down-button { /* Кнопка вниз     */
    width: 25px;
    subcontrol-position: left;
}

/* меню выбора месяца                                          */
CalendarWidget_QToolButton_QMenu {
     background-color: white;
}

CalendarWidget_QToolButton_QMenu_item {
    padding: 10px;
}
CalendarWidget_QToolButton_QMenu_item_selected_enabled {
    background-color: rgb(230, 230, 230);
    selection-color: rgb(45, 86, 100);
    selection-background-color: rgb(205, 217, 226);
}
CalendarWidget_QToolButton_menu-indicator {
    subcontrol-position: right center;
}

/* ниже календарной формы */
#qt_calendar_calendarview {
    outline: 0px;                                 /* Удалить выделенную пунктирную рамку */
    selection-background-color: rgb(0, 188, 212);
}
'''

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    app.setFont(QtGui.QFont("Century Gothic", 12,))
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

A: Предисловие:

*

*я убрал некоторые импорты, который неизвестны  и
не влияют на суть вопроса. Это виджет для четвертой страницы и еще что-то.

*я переместил виджет календарь, в то место, где он должен находится.

*я заменил виджет для загрузки на первую страницу своим,
так как ваш виджет не могу воспроизвести.

*поменяйте картинки на свои.
По сути заданного вопроса:

*

*как убрать виджет из макета - не надо его туда помещать.

*чтобы нарисовать один виджет поверх другого надо
для верхнего виджета установить родителя (нижний виджет)
    self.main = App()

    self.main.setParent(self.page_1)

*

*кнопка, о которой вы пишите, должна быть проверяемой
QPushButton.setCheckable(True)

*для этой же кнопки вы должны привязать сигнал clicked
к слоту (например self.button_clicked), в котором
будите менять размеры верхнего виджета, если он не сворачивается у вас.
self.designer_button.clicked.connect(self.button_clicked)

*в слоте button_clicked вы устанавливаете нужные вам размеры и
регулирует размер виджета, чтобы он соответствовал его содержимому.
    def button_clicked(self):
        #print(f'{self.designer_button.isChecked()}')
        if self.designer_button.isChecked():
            self.setMaximumSize(QtCore.QSize(345, 535))
            self.setMinimumSize(QtCore.QSize(345, 535))
            self.label_image.show()
        else:
            self.setMaximumSize(QtCore.QSize(345, 165))
            self.setMinimumSize(QtCore.QSize(345, 165))
            self.label_image.hide()
        self.adjustSize()                                # !!! ВАЖНО

q1302442.py
import sys
from PyQt5 import QtCore, QtGui, QtWidgets

from PyQt5.Qt import *
# ? from ext import *

#from main import App                                        # +++
from q1302442_second import App                              # ---

# ? from part_1 import Main

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        #размер основного окн
        self.resize(845, 535)
        self.setFixedSize(QtCore.QSize(845,535))
        self.setStyleSheet("background-color: rgb(245, 45, 45);")
        #центральный виджет
        self.centralwidget = QtWidgets.QWidget()
        self.centralwidget.setObjectName("centralwidget")
        self.setCentralWidget(self.centralwidget)

        # Content horizontalLayout_2
        self.Content = QtWidgets.QFrame(self.centralwidget)
        self.Content.setStyleSheet("background-color: rgb(255, 255, 255);")
        self.Content.setFrameShape(QtWidgets.QFrame.NoFrame)
        self.Content.setFrameShadow(QtWidgets.QFrame.Raised)
        self.Content.setObjectName("Content")
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.Content)
        self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout_2.setSpacing(0)

        #виджет слева
        self.frame_left_menu = QtWidgets.QFrame(self.Content)
        self.frame_left_menu.setMinimumSize(QtCore.QSize(45, 0))
        self.frame_left_menu.setStyleSheet("background-color: rgb(255, 255, 255); border: 0px solid; ")
        self.frame_left_menu.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame_left_menu.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame_left_menu.setObjectName("frame_left_menu")
        self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.frame_left_menu)
        self.verticalLayout_3.setContentsMargins(0, 0, 0, 0)

        self.frame_top_menus = QtWidgets.QFrame(self.frame_left_menu)
        self.frame_top_menus.setFrameShape(QtWidgets.QFrame.NoFrame)
        self.frame_top_menus.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame_top_menus.setObjectName("frame_top_menus")
        #указываем вертикальное выравнивание
        self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.frame_top_menus)
        self.verticalLayout_4.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_4.setSpacing(10)

        #домик
        self.btn_page_1 = QtWidgets.QPushButton("", self.frame_top_menus)
        self.btn_page_1.setIcon(QIcon('Ok.png'))
        self.btn_page_1.setIconSize(QSize(45,45))
        self.btn_page_1.setMinimumSize(QtCore.QSize(0, 40))
        self.btn_page_1.setStyleSheet('border: 0px solid red;')
        self.btn_page_1.setObjectName("btn_page_1")
        self.verticalLayout_4.addWidget(self.btn_page_1)
        #Заметки
        self.btn_page_2 = QtWidgets.QPushButton("", self.frame_top_menus)
        self.btn_page_2.setIcon(QIcon('im.png'))
        self.btn_page_2.setIconSize(QSize(45,45))
        self.btn_page_2.setMinimumSize(QtCore.QSize(0, 40))
        self.btn_page_2.setStyleSheet('border: 0px solid red;')
        self.btn_page_2.setObjectName("btn_page_2")
        self.verticalLayout_4.addWidget(self.btn_page_2)
        #погода
        self.btn_page_3 = QtWidgets.QPushButton("", self.frame_top_menus)
        self.btn_page_3.setIcon(QIcon('ball.png'))
        self.btn_page_3.setIconSize(QSize(45,45))
        self.btn_page_3.setMinimumSize(QtCore.QSize(0, 40))
        self.btn_page_4 = QtWidgets.QPushButton('', self.frame_top_menus)
        self.btn_page_4.setIcon(QIcon('lena-2.png'))
        self.btn_page_4.setIconSize(QSize(45, 45))
        self.btn_page_4.setMinimumSize(QtCore.QSize(0, 40))

        timer = QTimer(self)
        timer.timeout.connect(self.showTime)
        timer.start(1000)

        font1 = QFont('Century Gothic', 13, QFont.Bold)
        self.timewidget = QtWidgets.QLabel()
        self.timewidget.setMinimumSize(QtCore.QSize(45,45))
        self.timewidget.setAlignment(Qt.AlignBottom)
        self.timewidget.setFont(font1)

        self.btn_page_3.setObjectName("btn_page_3")
        self.verticalLayout_4.addWidget(self.btn_page_3)
        self.verticalLayout_3.addWidget(self.frame_top_menus, 0, QtCore.Qt.AlignTop)
        self.horizontalLayout_2.addWidget(self.frame_left_menu)
        self.verticalLayout_4.addWidget(self.btn_page_4)

        self.frame_pages = QtWidgets.QFrame(self.Content)
        self.frame_pages.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame_pages.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame_pages.setObjectName("frame_pages")
        self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.frame_pages)
        self.verticalLayout_5.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_5.setObjectName("verticalLayout_5")
        self.stackedWidget = QtWidgets.QStackedWidget(self.frame_pages)
        self.stackedWidget.setMinimumSize(QtCore.QSize(800, 535))
        self.stackedWidget.setObjectName("stackedWidget")

# 1 страница
        self.page_1 = QtWidgets.QWidget()
        self.page_1.setObjectName("page_1")
        self.verticalLayout_7 = QtWidgets.QVBoxLayout(self.page_1)
        self.verticalLayout_7.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_7.setObjectName("verticalLayout_7")
        #указываем что будет находится на 1 странице
        self.label_1 = QtWidgets.QLabel(self.page_1)
        font = QtGui.QFont()
        font.setPointSize(40)
        font.setFamily("Century Gothic")
        font.setPointSize(15)
        font.setKerning(True)
        self.label_1.setFont(font)
# +++
        self.label_1.setMinimumHeight(160)                              # +++
        self.label_1.setAlignment(QtCore.Qt.AlignCenter)
        self.label_1.setObjectName("label_1")
        self.verticalLayout_7.addWidget(self.label_1)

# +++ календарь должен быть здесь
# календарь
        self.calendarWidget = QtWidgets.QCalendarWidget(self.page_1)
        self.calendarWidget.setWindowFlag(Qt.FramelessWindowHint)
        self.calendarWidget.setEnabled(True)
        self.calendarWidget.setGeometry(QtCore.QRect(0, 154, 800, 381))
        self.calendarWidget.setFixedSize(QtCore.QSize(800, 381))
        self.calendarWidget.setWindowFlags(Qt.FramelessWindowHint)
        font = QtGui.QFont()
        font.setFamily("Century Gothic")
        font.setPointSize(15)
        font.setKerning(False)
        self.calendarWidget.setFont(font)
        self.calendarWidget.setAutoFillBackground(True)
        self.calendarWidget.setGridVisible(False)
        self.calendarWidget.setVerticalHeaderFormat(QtWidgets.QCalendarWidget.NoVerticalHeader)
        self.calendarWidget.setDateEditEnabled(False)
        self.calendarWidget.setDateEditAcceptDelay(0)
        self.calendarWidget.setObjectName("calendarWidget")
        self.calendarWidget.setStyleSheet(StyleSheet)
        self.verticalLayout_7.addWidget(self.calendarWidget)

# +++
        self.main = App()
# +++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
        self.main.setParent(self.page_1)  # Устанавливает родительский элемент виджета
        self.main.setMaximumSize(QtCore.QSize(345, 165))
        self.main.move(455, 0)            # Это соответствует перемещению (QPoint(x, y)).
# +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#        self.main.setMinimumSize(QtCore.QSize(500, 154))
#        self.main.w_root.setWindowFlag(Qt.FramelessWindowHint)
#        self.verticalLayout_7.addWidget(self.main.w_root, alignment = QtCore.Qt.AlignRight)
#        self.main.w_root.setWindowFlag(Qt.CustomizeWindowHint)
#        self.main.setMinimumSize(QtCore.QSize(500, 154))
#        self.verticalLayout_7.addWidget(self.main, alignment = QtCore.Qt.AlignRight)

        self.stackedWidget.addWidget(self.page_1)

        #2 страница
        self.page_2 = QtWidgets.QWidget()
        self.page_2.setObjectName("page_2")
        self.verticalLayout_6 = QtWidgets.QVBoxLayout(self.page_2)
        self.verticalLayout_6.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_6.setObjectName("verticalLayout_6")
        #указываем что будет находиться в 2 странице
        self.label_2 = QtWidgets.QLabel("Страница2", self.page_2)
        font = QtGui.QFont()
        font.setPointSize(40)
        font.setFamily("Century Gothic")
        font.setPointSize(15)
        font.setKerning(True)
        self.label_2.setFont(font)
        self.label_2.setStyleSheet("color: #FFF; background-color: #1eae98;")
        self.label_2.setAlignment(QtCore.Qt.AlignCenter)
        self.label_2.setObjectName("label_2")
        self.verticalLayout_6.addWidget(self.label_2)
        self.stackedWidget.addWidget(self.page_2)
        #3 страница
        self.page_3 = QtWidgets.QWidget()
        self.page_3.setObjectName("page_3")
        self.verticalLayout_8 = QtWidgets.QVBoxLayout(self.page_3)
        self.verticalLayout_8.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_8.setObjectName("verticalLayout_8")
        #указываем что будет находиться на 3 странице
        self.label = QtWidgets.QLabel("Страница3", self.page_3)
        font = QtGui.QFont()

        font.setFamily("Century Gothic")
        font.setPointSize(15)
        font.setKerning(True)
        self.label.setFont(font)
        self.label.setStyleSheet("color: green; background-color: black;")
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setObjectName("label")
        self.verticalLayout_8.addWidget(self.label)
        self.stackedWidget.addWidget(self.page_3)

# page_4 verticalLayout_9
        self.page_4 = QtWidgets.QWidget()
        self.page_4.setObjectName('page_4')

#        self.gg = Main()                                           # раскомментируйте
        self.verticalLayout_9 = QtWidgets.QVBoxLayout(self.page_4)
#        self.verticalLayout_9.addWidget(self.gg)                   # раскомментируйте
        self.verticalLayout_9.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_9.setSpacing(0)
        self.verticalLayout_9.setObjectName('verticalLayout_9')

        self.stackedWidget.addWidget(self.page_4)
        self.verticalLayout_5.addWidget(self.stackedWidget)
        self.horizontalLayout_2.addWidget(self.frame_pages)
        self.stackedWidget.setCurrentIndex(0)

        # verticalLayout  centralwidget
        self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setSpacing(0)
        # verticalLayout.addWidget(self.Content)
        self.verticalLayout.addWidget(self.Content)

        #Нажатие на дом
        self.btn_page_1.clicked.connect(
            lambda: self.stackedWidget.setCurrentWidget(self.page_1))
        #Нажатие на заметки
        self.btn_page_2.clicked.connect(
            lambda: self.stackedWidget.setCurrentWidget(self.page_2))
        #Нажатие на погоду
        self.btn_page_3.clicked.connect(
            lambda: self.stackedWidget.setCurrentWidget(self.page_3))

        self.btn_page_4.clicked.connect(
            lambda: self.stackedWidget.setCurrentWidget(self.page_4))

        self.frame_left_menu.installEventFilter(self)
        self.verticalLayout_3.addWidget(self.timewidget, 0, QtCore.Qt.AlignBottom)

    def showTime(self):
        current_time = QtCore.QTime.currentTime()
        label_time = current_time.toString('hh:mm')
        self.timewidget.setText(label_time)

StyleSheet = '''
/* Верхняя область навигации                            */
#qt_calendar_navigationbar {
    background-color: rgb(0, 188, 212);
    min-width: 800px;
    max-width: 800px;
    min-height: 35px;
    max-height: 35px;
}

/*  Кнопка последнего месяца и кнопка следующего месяца */
#qt_calendar_prevmonth, #qt_calendar_nextmonth {
    border: none;                     /* убрать границу */
    margin-top: 0px;
    color: white;
    min-width: 30px;
    max-width: 30px;
    min-height: 30px;
    max-height: 30px;
    border-radius: 10px;            /* выглядит как эллипс */
    font-weight: bold;              /* шрифт полужирный    */
    qproperty-icon: none;
    background-color: transparent; /* Цвет фона прозрачный */
}

#qt_calendar_prevmonth {
    qproperty-text: "<";         /* Изменить текст кнопки  */
}
#qt_calendar_nextmonth {
    qproperty-text: ">";
}
#qt_calendar_prevmonth:hover, #qt_calendar_nextmonth:hover {
    background-color: rgba(225, 225, 225, 100);
}
#qt_calendar_prevmonth:pressed, #qt_calendar_nextmonth:pressed {
    background-color: rgba(235, 235, 235, 100);
}

/*  год, месяц                                                */
#qt_calendar_yearbutton, #qt_calendar_monthbutton {
    color: white;
    margin: -1px;
    min-width: -1px;
    border-radius: 15px;
    background-color: rgba(0, 188, 212, 100)
}
#qt_calendar_yearbutton:hover, #qt_calendar_monthbutton:hover {
    background-color: rgba(225, 225, 225, 100);
}
#qt_calendar_yearbutton:pressed, #qt_calendar_monthbutton:pressed {
    background-color: rgba(235, 235, 235, 100);
}

/* Поле ввода года                                                        */
#qt_calendar_yearedit {
    min-width: 85px;
    color: white;
    background: transparent;         /* Сделать фон окна ввода прозрачным */
}
#qt_calendar_yearedit::up-button {   /* Кнопка вверх                      */
    width: 25px;
    subcontrol-position: right;
}
#qt_calendar_yearedit::down-button { /* Кнопка вниз     */
    width: 25px;
    subcontrol-position: left;
}

/* меню выбора месяца                                          */
CalendarWidget_QToolButton_QMenu {
     background-color: white;
}

CalendarWidget_QToolButton_QMenu_item {
    padding: 10px;
}
CalendarWidget_QToolButton_QMenu_item_selected_enabled {
    background-color: rgb(230, 230, 230);
    selection-color: rgb(45, 86, 100);
    selection-background-color: rgb(205, 217, 226);
}
CalendarWidget_QToolButton_menu-indicator {
    subcontrol-position: right center;
}

/* ниже календарной формы */
#qt_calendar_calendarview {
    outline: 0px;                                 /* Удалить выделенную пунктирную рамку */
    selection-background-color: rgb(0, 188, 212);
}
'''

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    app.setFont(QtGui.QFont("Century Gothic", 12,))
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

q1302442_second.py
import sys
from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5.QtCore import QPropertyAnimation, pyqtProperty
from PyQt5.QtWidgets import QGraphicsDropShadowEffect, QApplication, QMainWindow

class AnimationShadowEffect(QGraphicsDropShadowEffect):
    def __init__(self, color, *args, **kwargs):
        super(AnimationShadowEffect, self).__init__(*args, **kwargs)
        self.setColor(color)
        self.setOffset(0, 0)
        self.setBlurRadius(0)
        self._radius = 0
        self.animation = QPropertyAnimation(self)
        self.animation.setTargetObject(self)
        self.animation.setDuration(2000)
        self.animation.setLoopCount(-1)
        self.animation.setPropertyName(b'radius')
        self.animation.setKeyValueAt(0, 1)
        self.animation.setKeyValueAt(0.5, 30)
        self.animation.setKeyValueAt(1, 1)

    def start(self):
        self.animation.start()

    def stop(self, r=0):
        self.animation.stop()
        self.radius = r

    @pyqtProperty(int)
    def radius(self):
        return self._radius

    @radius.setter
    def radius(self, r):
        self._radius = r
        self.setBlurRadius(r)

class PushButton(QtWidgets.QPushButton):
    hover = QtCore.pyqtSignal(str)

    def __init__(self, parent=None):
        super(PushButton, self).__init__(parent)
        self.setText("Button")
        self.setFixedSize(200, 70)
        self.setCheckable(True)

    def enterEvent(self, event):
        self.hover.emit("enterEvent")

    def leaveEvent(self, event):
        self.hover.emit("leaveEvent")

class App(QMainWindow):
    def __init__(self):
        super(App, self).__init__()

        self.resize(357, 205)
        self.setStyleSheet("background-color: rgb(41, 41, 62);")
        self.centralwidget = QtWidgets.QWidget(self)
        self.setCentralWidget(self.centralwidget)

        self.label_image = QtWidgets.QLabel()
        self.pixmap = QtGui.QPixmap('Ok.png')
        self.label_image.setPixmap(self.pixmap)
        self.label_image.hide()

        self.designer_button = PushButton(self.centralwidget)
        self.designer_button.setStyleSheet("""
            QPushButton {
                background-color: rgb(28, 28, 42);
                border: 1px solid rgb(202, 202, 202);
                border-radius: 15px;
                color: rgb(202, 202, 202);
                font-family: Calibre, Helvetica Neue, Segoe UI, Helvetica, Arial, Lucida           Grande sans-serif;
                font-size: 16px;
                font-weight: 500;
            }
            QPushButton:hover {
                background-color: rgb(16, 16, 24);
                color: rgb(76, 76, 76);
            }
            QPushButton:pressed {
                background-color: rgb(6, 6, 8);
                color: rgb(41, 41, 62);
            }
        """)

        self.layout = QtWidgets.QGridLayout(self.centralwidget)
        self.layout.addWidget(
            self.label_image, 0, 1, alignment=QtCore.Qt.AlignCenter)
        self.layout.addWidget(
            self.designer_button, 1, 1,
                alignment=QtCore.Qt.AlignHCenter |QtCore.Qt.AlignBottom)

        self.aniButton = AnimationShadowEffect(QtCore.Qt.white, self.designer_button)

        self.designer_button.hover.connect(self.button_hover)
        self.designer_button.clicked.connect(self.button_clicked)
        self.designer_button.setGraphicsEffect(self.aniButton)

    def button_hover(self, hover):
        if hover == "enterEvent":
            self.aniButton.start()
        elif hover == "leaveEvent":
            self.aniButton.stop()

    def button_clicked(self):
        #print(f'{self.designer_button.isChecked()}')
        if self.designer_button.isChecked():
            self.setMaximumSize(QtCore.QSize(345, 535))
            self.setMinimumSize(QtCore.QSize(345, 535))
            self.label_image.show()
        else:
            self.setMaximumSize(QtCore.QSize(345, 165))
            self.setMinimumSize(QtCore.QSize(345, 165))
            self.label_image.hide()
        self.adjustSize()                                # !!! ВАЖНО

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    ex.show()
    sys.exit(app.exec_())


text:
Q: Common definitions in loose coupled design I'm trying to put together a very granulary loose coupled design.
But I can't decide how to handle common definitions.
Right now I seperate concerns by adding it as an external dll. Through injection and interfaces my domain can use my business logic without knowing the implementation.
The problem I'm having is that for all my components to be loosely coupled, they need to implement the same interfaces. My solution was a seperate project (dll) with just all the definitions.
This started out well, but seems to become bloathed and chains all code together on this one dll-dependency.
What's the most pragmatic way to go about ?
Thanks!

A: EDIT
Sorry I think I initially misunderstood your question. So you have one assembly which contains your interfaces and you have your implementations in other assemblies using DI to create your dependant objects. I tend to create a core assembly in my application which holds the main behaviours of the app (smart entities, enums and interfaces). This assembly depends on little but is heavy depended on by the rest of the application. Check out this project as an example - whocanhelpme.codeplex.com. You could call this core bloated but it, by definition, needs to be very rich.

You might find that many of your abstract units follow common design patterns. Here is a site that gives a good description of each one - you may be able to derive names from these (Observer, Factory, Adapter etc.):
http://www.dofactory.com/Patterns/Patterns.aspx

A: I would say, that the layer should only know about the next layer and its interfaces, so it is fine to place interfaces along with their implementations and then add references between layers (assemblies) in the chain.
You can configure DI using bootstrapper pattern and resolve through the locator. Regarding cross cutting concerns like logging, caching ect there should be separate assembly referenced to each layer. Here you can also employ contracts and in the future perhaps replace these cross cutting functionalities with another assembly implementing the same contracts.
Hope this helps at least a bit :)


text:
Q: Why mToolbar and Toolbar doesn't work in android studio I tried everything. But I can't It figure out.
Always tells me that they doesn't work--->mToolbar and Toolbar<---
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import android.widget.Toolbar;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.navigation.NavigationView;

public class MainActivity extends AppCompatActivity {

    private NavigationView navigationView;
    private DrawerLayout drawerLayout;
    private RecyclerView postList;
    private Toolbar mToolbar;
    private Toolbar supportActionBar;

mToolbar = (Toolbar) findViewById(R.id.main_page_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("home");

Also my Grandle. I don't know if it helps.
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'com.google.android.material:material:1.0.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.firebase:firebase-auth:16.0.5'
    implementation 'com.google.firebase:firebase-database:16.0.4'
    implementation 'com.google.firebase:firebase-storage:16.0.4'
    implementation 'de.hdodenhof:circleimageview:3.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}

I tried android.widget.support.v7.Toolbar; but It didn't help
The mistake was :
from --> import android.widget.Toolbar
To --> import androidx.appcompat.widget.Toolbar

A: By chance, in your layout, are you using the androidx version of the Toolbar? If you are, that's what is creating this error. In your Activity, you are referencing a different version of Toolbar.

A: I believe that the error may be in the import of the Toolbar class
in your exepmlo you are already using the androidrx standard but in the Toolbar object you are using the old import
import android.widget.Toolbar

But the new import is
import androidx.appcompat.widget.Toolbar

A: you are using androidX in your xml file, but in your java file you import the old library , try to remove
   import android.widget.Toolbar

and put the suitable one that you imported before in xml
  import androidx.appcompat.widget.Toolbar


text:
Q: mysql select nth column from table My DB Table is like this
   id | name | image
--------------------------------
   1  | aa   | a.jpg
--------------------------------
   2  | aa   | b.jpg
--------------------------------
   3  | bb   | c.jpg
--------------------------------
   4  | bb   | d.jpg
--------------------------------
   5  | aa   | e.jpg
--------------------------------
   6  | bb   | f.jpg
--------------------------------
   7  | aa   | g.jpg
--------------------------------
   8  | aa   | h.jpg
--------------------------------
   9  | aa   | i.jpg

And this is my html

First I need to Select * from the table where name="aa"
I know how to do this..
but I want to separate the columns to each div..
1st,4th,7th... ( 1 + (n-1)*3 ) images of name=aa GOES to div#first
2nd,5th,8th... ( 2 + (n-1)*3 ) images of name=aa GOES to div#second
3rd,6th,9th... ( 3 + (n-1)*3 ) images of name=aa GOES to div#third
Finally I need the result like this

  a.jpg
  g.jpg

  b.jpg
  h.jpg

  e.jpg
  i.jpg

Please let me know , how to do this with PHP , MYSQL
Sorry For My Bad English

A: The main point here seems to be the data selection. For this, one can use the modulo-operation. So, in the first div, insert all rows with
SELECT image FROM your_table WHERE name='aa' AND MOD(id,3)=1

In the second div insert  the result of
SELECT image FROM your_table WHERE name='aa' AND MOD(id,3)=2

And in the third this:
SELECT image FROM your_table WHERE name='aa' AND MOD(id,3)=0

EDIT: wait, it doesn't work directly like this (because the id is not increasing by 1 in the subset with name='aa'). Then you could additionally insert a ROW_NUMBER()-like step, see here. So here is a trial (untested):
SELECT images
FROM (SELECT t.*,
       @rownum := @rownum + 1 AS rownum
       FROM YOUR_TABLE t,
       (SELECT @rownum := 0) r
       WHERE t.name='aa')
WHERE MOD(rownum,3)=1

Try it similarly for the others.

A: The answer of this question is not working..
So I made another way with PHP..
$a = "";
while($row = mysql_fetch_array(mysql_query("Select * from table where name='aa' "))){
    $a . = $row['image'] . "";
}
$b = explode("",$a);
$c = count($B);
$_a = "";$_b  = "";$_c  = "";$_d = "";
for($i = 1;$i <= $c;$i++ ){
    $rem = $i % 3;
    if($rem == 1){
        $_a .= $b[$num - 1];
    }
    elseif($rem == 2){
        $_b .= $b[$num - 1];
    }
    elseif($rem == 0){
        $_c .= $d[$num - 1];
    }
}

AND MY HTML CODE IS

  <?=$_a?>

  <?=$_b?>

  <?=$_c?>


text:
Q: Angular 5 and Sass : in Bootstrap 's _reboot.scss file '@at-root' error : at-rule unknown I want to include Bootstrap's scss files in my project.
But when I open _reboot.scss file VS Code complains about :
    // IE10+ doesn't honor `<meta name="viewport">` in some cases.
    @at-root {
      @-ms-viewport {
        width: device-width;
      }
    }

'file:///[...]/node_modules/bootstrap/scss/_reboot.scss'
severity: 'Error'
message: 'at-rule unknown' at: '37,1'
source: 'scss'
code: 'css-unknownatrule'

I created the project with ng new  and opened it with VS Code. I don't know much about Lint (configuration, etc).
How can I get rid of this error ?


text:
Q: move files that match file names in another directory I have two directories:
dir_1 which has a.mp4, b.mp4, c.mp4, d.mp4 and dir_2 which has only a.txt, b.txt.
The script should move a.mp4 and b.mp4 to dir_3 because only these file names match the file names in dir_2.
I find it to hard follow the scripts when I need to do these type of particular operations.

A: Try,
for f in "dir_2"/*; do
    filename=${f##*/}
    mv -t "dir_3" "dir_1/${filename%.*}".*
done

*

*Loop files in dir_2 (use *.txt to only loop these files)

*${f##*/} gives you the file name without the path.

*${filename%.*} gives you the filename without extension.

*mv -t "dir_3" "dir_1/${filename%.*}".* moves all files with given filename (cleared from the extension) to dir_3. You can specify .mp4 instead of .* if you want.


text:
Q: How to identify the correct class for Beautifulsoup? I am trying to learn Scrapping , one problem I am facing is identifying correct class names , is there any particular rule/method to follow for identifying correct class names For Example in the code below I am trying to get Questions lists from stackoverflow page , for that I am clicking on inspect on the first question & i can see classname as question-hyperlink but when I try in the code below I get empty results , similarly if iI am trying with divname summary I get same empty results kindly guide on how can I fix this & avoid in future cases
import requests
from bs4 import BeautifulSoup

website = 'https://stackoverflow.com/'
r = requests.get(website)

if r.status_code == 200:
    print(f"Connected to {website}")
    soup = BeautifulSoup(r.content, 'html.parser')
    s = soup.find_all(class_name='question-hyperlink')
    print(s)
else:
    print(r)

print("Done")

A: You focused on the class name 'question-hyperlink'. Within beautiful soup you can simply write something like soup.find_all('div', class_='summary')
to get a specific class.
import requests
from bs4 import BeautifulSoup

url = 'https://stackoverflow.com/questions/tagged/python'

#A function that gets the H3 titles for the python tagged stackoverflow
#It saves and outputs a list with all the titles

def main():
    #get all elements from the entire page
    r = requests.get(url)
    soup = BeautifulSoup(r.text, 'html.parser')
    questions = soup.find_all('div', class_='summary')

    #only get me the H3 html tags
    question_text = []
    for question in questions:
        question_text.append(question.find('h3').text)
    print(question_text)

if __name__ == '__main__':
    main()

Output: ['How do I verify if certificate is ca trusted in python?',...]

A: The url you're using doesn't have any questions - https://stackoverflow.com shows only a starting page, unless you're logged in.
You need to change the url to https://stackoverflow.com/questions.
Also, you should be using class_=, not class_name= in find_all().
Then it works just fine.
import requests
from bs4 import BeautifulSoup

website = 'https://stackoverflow.com/questions/'

headers = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:95.0) Gecko/20100101 Firefox/95.0",
}
r = requests.get(website, headers=headers)

if r.status_code == 200:
    print(f"Connected to {website}")
    soup = BeautifulSoup(r.text, 'html.parser').find_all("a", class_="question-hyperlink")
    print(len(soup))

Output:
20


text:
Q: Serializing a RandomAccessSparseVector in Mahout I'm loading data into a RandomAccessSparseVector in Mahout 0.7, and I don't know how to serialize it. If I were using a VectorWritable I'd be able to use SequenceFile.Writer as so:
writer = new SequenceFile.Writer(
    fs, conf, new Path("filename"), LongWritable.class,
    VectorWritable.class);

There is no RandomAccessSparseVectorWritable, unfortunately.
One option is to forget sparse vectors altogether and load the data into a VectorWritable and serialize it. I'd like to avoid this because it is sloppy to manually enter a load of zeroes into a VectorWritable and then take up a bunch of room on disk when serializing. RandomAccessSparseVector also can't be cast to VectorWritable.
If it is of any use, I've set
Configuration conf = new Configuration();
conf.set("io.serializations",
    "org.apache.hadoop.io.serializer.WritableSerialization");

so that Hadoop knows how to serialize.

A: The solution is really simple. After a while of fruitless digging through the API docs, I happened upon a useful forum post. VectorWritable is not a vector type but a vector wrapper for serializing.  Before, I was trying to write a RandomAccessSparseVector generated like so
RandomAccessSparseVector vect = new RandomAccessSparseVector(columns);

by calling
key = new LongWritable(foo)
RandomAccessSparseVector vect = new RandomAccessSparseVector(columns);
writer.append(key, vect)

All I needed was to call
writer.append(key, new VectorWritable(vect))


text:
Q: JavaSript callback for month slider in bokeh map I am running into some issues with a bokeh map I am creating, I need to update the map with a javascript callback. I've searched stackoverflow far and wide, but nothing I try works. The callback needs to change the month I specified on the slider in the existing source. Can I just call the json_data(a) function with an updated value for a with the slider or do I tackle the problem some other way? Code is as follows:
shapefile = '/content/ne_110m_admin_0_countries.shp'
codes = '/content/country-codes_csv.csv'
gdf = gpd.read_file(shapefile)[['ADMIN', 'ADM0_A3', 'geometry']]
countries = pd.read_csv(codes)[['ISO3166-1-Alpha-3', 'ISO3166-1-Alpha-2']]
gdf.columns = ['country', 'country_code', 'geometry']
gdf.head()
sales_df['Month'] = sales_df['Transaction Date'].apply(lambda x: x.month)
sum_df = sales_df.groupby(['Month','Buyer Country']).sum().reset_index()

merged_gdf = gdf.merge(countries, left_on='country_code', right_on='ISO3166-1-Alpha-3', how = 'inner')

def json_data(a):
  month_df = sum_df[sum_df['Month'] == a]
  merged = merged_gdf.merge(month_df, left_on = 'ISO3166-1-Alpha-2', right_on = 'Buyer Country', how = 'left')
  merged.fillna('No data', inplace = True)
  merged_json = json.loads(merged.to_json())
  json_data = json.dumps(merged_json)
  return json_data

geosource = GeoJSONDataSource(geojson = json_data(7))
palette = brewer['YlGnBu'][8]
palette = palette[::-1]
color_mapper = LinearColorMapper(palette = palette, low = 0, high = 40, nan_color = '#d9d9d9')
tick_labels = {'0': '0%', '5': '5%', '10':'10%', '15':'15%', '20':'20%', '25':'25%', '30':'30%','35':'35%', '40': '>40%'}
color_bar = ColorBar(color_mapper=color_mapper, label_standoff=8,width = 500, height = 20,
                     border_line_color=None,location = (0,0), orientation = 'horizontal', major_label_overrides = tick_labels)

p = figure(title = 'Amount per country', plot_height = 600 , plot_width = 950, toolbar_location = None)
p.patches('xs','ys', source = geosource,fill_color = {'field' :'Amount', 'transform' : color_mapper},
          line_color = 'black', line_width = 0.25, fill_alpha = 1)
p.add_tools(HoverTool(tooltips=[('Country/region','@country'),('Amount bought', '@Amount')]))
p.xgrid.grid_line_color = None
p.ygrid.grid_line_color = None
p.add_layout(color_bar, 'below')

slider = Slider(title = 'Month',start = 6, end = 12, step = 1, value = 6)

callback = CustomJS(args=dict(slider = slider, source=geosource), code="""
    const a = slider.value;
    json_data(a);
    ??????????
    source.change.emit();
""")
slider.js_on_change('value', callback)

layout = column(p, widgetbox(slider))
show(layout)

Result of the code is not interactive with only month data I specified for the original geosource

A: *

*there is no need to code this all yourself.  Higher level API https://github.com/PatrikHlobil/Pandas-Bokeh

*code below shows this in action

*have assumed how your data frames look and geometry sourcing.  This code follows

solution
# bokeh generates a lot of shapely deprecation warnings
with warnings.catch_warnings():
    warnings.simplefilter("ignore")

    month_gdf.plot_bokeh(
        slider=[c for c in month_gdf.columns if c[0] == "m"],
        slider_name="month ",
        colorbar_tick_format="0.0",
        colormap="YlGnBu",
        hovertool_string="
@country

@Colormap{0.0}
",
    )

data sourcing, generation and preparation
from pathlib import Path
import requests
import geopandas as gpd
import pandas as pd
import numpy as np
import pandas_bokeh

pandas_bokeh.output_notebook()
import warnings

# get geometry from github
f = Path.cwd().joinpath("content")
if not f.is_dir():
    f.mkdir()
f = f.joinpath("ne_110m_admin_0_countries.shp")
if not f.is_file():
    for ext in [".cpg", ".dbf", ".prj", ".shp", ".shx"]:
        r = requests.get(
            f"https://github.com/nvkelso/natural-earth-vector/raw/master/110m_cultural/ne_110m_admin_0_countries{ext}",
            stream=True,
        )
        with open(f.parent.joinpath(f"{f.stem}{ext}"), "wb") as fd:
            for chunk in r.iter_content(chunk_size=128):
                fd.write(chunk)
shapefile = f
codes = "https://raw.githubusercontent.com/datasets/country-codes/master/data/country-codes.csv"

gdf = gpd.read_file(shapefile)[["ADMIN", "ADM0_A3", "SUBREGION", "geometry"]]
countries = pd.read_csv(codes)[["ISO3166-1-Alpha-3", "ISO3166-1-Alpha-2"]]
gdf.columns = ["country", "country_code", "subregion", "geometry"]

merged_gdf = gdf.merge(
    countries, left_on="country_code", right_on="ISO3166-1-Alpha-3", how="inner"
)

# synthesize sales dataframe
sales_df = pd.DataFrame(
    {
        "Transaction Date": np.repeat(
            pd.date_range("1-mar-2021", freq="W-MON", periods=100), 100
        ),
        "Buyer Country": np.random.choice(
            merged_gdf.loc[
                lambda d: d["subregion"].isin(
                    ["Northern Europe", "Western Europe", "Southern Europe"]
                ),
                "ISO3166-1-Alpha-2",
            ],
            10000,
        ),
        "Amount": np.random.uniform(20, 100, 10000),
    }
)

sales_df["Month"] = sales_df["Transaction Date"].apply(lambda x: x.month)
sum_df = sales_df.groupby(["Month", "Buyer Country"]).sum().reset_index()

# restructure so months are columns
sum_df = (
    sum_df.set_index(["Month", "Buyer Country"])
    .unstack("Month")
    .droplevel(0, 1)
    .reset_index()
)

month_gdf = merged_gdf.merge(
    sum_df, right_on="Buyer Country", left_on="ISO3166-1-Alpha-2"
)

# geojson and numeric column names don't work well together...
month_gdf = month_gdf.rename(
    columns={c: f"m{c}" for c in month_gdf.columns if isinstance(c, int)}
)


text:
Q: Presentation of $D_4$ When one writes $D_4=\langle r,s\mid r^4=s^2=1,rsrs=1\rangle$ they are describing a quotient group. Let $S=\{s,r\}$ and $R=\{r^4,s^2,rsrs\}$.
$$F_S=\langle r,s\rangle,\quad R^{F_S}=\{grg^{-1}\mid r\in R, g\in F_s\},\quad \langle R^{F_s}\rangle =N$$
and $D_4=F_S/N$. Is this correct?
Equivalently, they describe:
$$F_1\overset{\partial_1}\to F_0\overset{\epsilon}\twoheadrightarrow D_4,$$
where $\partial_1:F_1\to \text{ker}(\epsilon)$ is a surjection.
Where then, I take it that $F_0=F_S$ and $F_1=N$?

A: If $F_S$ is the free group generated by $r$ and $s$, then yes, $D_4=F/N$. Just writing $F=\langle r,s\rangle$ doesn't make sense, because the notation $\langle r,s\rangle$ assumes that we are already working within some group.

A: You might prefer the short exact sequence
$$1 \to N \overset{\partial_1} \hookrightarrow F_S\overset{\epsilon}\twoheadrightarrow D_4 \to 1$$
as this forces $\mathrm{im}\,\partial_1 = \ker \epsilon$, $\partial_1$ injective, and $\epsilon$ surjective.
The section on groups (same page) explains that this is equivalent to your first characterization; i.e., $D_4 \cong F_S/N$.


text:
Q: extern "C" Demangling Causing Strange Linker Errors I have the following header file
possion_surface_reconstructor.h
#ifndef POISSON_SURFACE_RECONSTRUCTOR_H
#define POISSON_SURFACE_RECONSTRUCTOR_H

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
#include <iostream>
#include <boost/format.hpp>

#include "../core/PreProcessor.h"
#include "../core/MyMiscellany.h"
#include "../core/CmdLineParser.h"
#include "../core/PPolynomial.h"
#include "../core/FEMTree.h"
#include "../core/Ply.h"
#include "../core/PointStreamData.h"
#include "../core/Image.h"

#include "callbacks.h"

namespace MeshingAdapter
{

    #undef USE_DOUBLE                               // If enabled, double-precesion is used
    #define DATA_DEGREE 0                           // The order of the B-Spline used to splat in data for color interpolation
    #define WEIGHT_DEGREE 2                         // The order of the B-Spline used to splat in the weights for density estimation
    #define NORMAL_DEGREE 2                         // The order of the B-Spline used to splat in the normals for constructing the Laplacian constraints
    #define DEFAULT_FEM_DEGREE 1                    // The default finite-element degree
    #define DEFAULT_FEM_BOUNDARY BOUNDARY_NEUMANN   // The default finite-element boundary type
    #define DIMENSION 3

    cmdLineParameter< char* >
        In("in"),
        Out("out"),
        TempDir("tempDir"),
        Grid("grid"),
        Tree("tree"),
        Transform("xForm");

    cmdLineReadable
        Performance("performance"),
        ShowResidual("showResidual"),
        NoComments("noComments"),
        PolygonMesh("polygonMesh"),
        NonManifold("nonManifold"),
        ASCII("ascii"),
        Density("density"),
        LinearFit("linearFit"),
        PrimalGrid("primalGrid"),
        ExactInterpolation("exact"),
        Normals("normals"),
        Colors("colors"),
        InCore("inCore"),
        Verbose("verbose");

    cmdLineParameter< int >
#ifndef FAST_COMPILE
        Degree("degree", DEFAULT_FEM_DEGREE),
#endif // !FAST_COMPILE
        Depth("depth", 8),
        KernelDepth("kernelDepth"),
        Iters("iters", 8),
        FullDepth("fullDepth", 5),
        BaseDepth("baseDepth", 0),
        BaseVCycles("baseVCycles", 1),
#ifndef FAST_COMPILE
        BType("bType", DEFAULT_FEM_BOUNDARY + 1),
#endif // !FAST_COMPILE
        MaxMemoryGB("maxMemory", 0),
#ifdef _OPENMP
        ParallelType("parallel", (int)ThreadPool::OPEN_MP),
#else // !_OPENMP
        ParallelType("parallel", (int)ThreadPool::THREAD_POOL),
#endif // _OPENMP
        ScheduleType("schedule", (int)ThreadPool::DefaultSchedule),
        ThreadChunkSize("chunkSize", (int)ThreadPool::DefaultChunkSize),
        Threads("threads", (int)std::thread::hardware_concurrency());

    cmdLineParameter< float >
        DataX("data", 32.f),
        SamplesPerNode("samplesPerNode", 1.5f),
        Scale("scale", 1.1f),
        Width("width", 0.f),
        Confidence("confidence", 0.f),
        ConfidenceBias("confidenceBias", 0.f),
        CGSolverAccuracy("cgAccuracy", 1e-3f),
        PointWeight("pointWeight");

    cmdLineReadable* params[] =
    {
    #ifndef FAST_COMPILE
        &Degree,
        &BType,
    #endif // !FAST_COMPILE
        &In,
        &Depth,
        &Out,
        &Transform,
        &Width,
        &Scale,
        &Verbose,
        &CGSolverAccuracy,
        &NoComments,
        &KernelDepth,
        &SamplesPerNode,
        &Confidence,
        &NonManifold,
        &PolygonMesh,
        &ASCII,
        &ShowResidual,
        &ConfidenceBias,
        &BaseDepth,
        &BaseVCycles,
        &PointWeight,
        &Grid,
        &Threads,
        &Tree,
        &Density,
        &FullDepth,
        &Iters,
        &DataX,
        &Colors,
        &Normals,
        &LinearFit,
        &PrimalGrid,
        &TempDir,
        &ExactInterpolation,
        &Performance,
        &MaxMemoryGB,
        &InCore,
        &ParallelType,
        &ScheduleType,
        &ThreadChunkSize,
        NULL
    };

    class PoissonSurfaceReconstructor
    {
    public:
        PoissonSurfaceReconstructor(
            ProgressCallback& progressCallback,
            WarningCallback& warningCallback,
            ErrorCallback& errorCallback);

        bool ExecuteSurfaceReconstruction(int argc, char* argv[]);

    private:
        template< unsigned int Dim, class Real >
        struct FEMTreeProfiler;

        template< unsigned int Dim, typename Real >
        struct ConstraintDual;

        template< unsigned int Dim, typename Real >
        struct SystemDual;

        template< unsigned int Dim >
        struct SystemDual< Dim, double >;

        template< class Real, typename ... SampleData, unsigned int ... FEMSigs >
        int Execute(int argc, char* argv[], UIntPack< FEMSigs ... >);

        template< unsigned int Dim, class Real, typename ... SampleData >
        int Execute(int argc, char* argv[]);

        template< typename Real, unsigned int Dim >
        int WriteGrid(ConstPointer(Real) values, int res, const char* fileName);

        template< typename Vertex, typename Real, typename SetVertexFunction, unsigned int ... FEMSigs, typename ... SampleData >
        int ExtractMesh(
            UIntPack< FEMSigs ... >,
            std::tuple< SampleData ... >,
            FEMTree< sizeof ... (FEMSigs), Real >& tree,
            const DenseNodeData< Real, UIntPack< FEMSigs ... > >& solution,
            Real isoValue,
            const std::vector< typename FEMTree< sizeof ... (FEMSigs),
            Real >::PointSample >* samples,
            std::vector< MultiPointStreamData< Real, PointStreamNormal< Real, DIMENSION >,
            MultiPointStreamData< Real, SampleData ... > > >* sampleData,
            const typename FEMTree< sizeof ... (FEMSigs), Real >::template DensityEstimator< WEIGHT_DEGREE >* density,
            const SetVertexFunction& SetVertex,
            std::vector< std::string >& comments,
            XForm< Real, sizeof...(FEMSigs) + 1 > iXForm);

        template< class Real, unsigned int Dim >
        XForm< Real, Dim + 1 > GetBoundingBoxXForm(Point< Real, Dim > min, Point< Real, Dim > max, Real scaleFactor);

        template< class Real, unsigned int Dim >
        XForm< Real, Dim + 1 > GetBoundingBoxXForm(
            Point< Real, Dim > min,
            Point< Real, Dim > max,
            Real width,
            Real scaleFactor,
            int& depth);

        template< class Real, unsigned int Dim >
        XForm< Real, Dim + 1 > GetPointXForm(InputPointStream< Real, Dim >& stream, Real width, Real scaleFactor, int& depth);

        template< class Real, unsigned int Dim >
        XForm< Real, Dim + 1 > GetPointXForm(InputPointStream< Real, Dim >& stream, Real scaleFactor);

        template<typename... Arguments>
        std::string FormatString(const std::string& fmt, const Arguments&... args);

        double Weight(double v, double start, double end);

        const float DefaultPointWeightMultiplier = 2.f;

        ProgressCallback _progressCallback;
        WarningCallback _warningCallback;
        ErrorCallback _errorCallback;
    };
}
#endif // POISSON_SURFACE_RECONSTRUCTOR_H

The .cpp file that back this class compiles fine. I can compile this code as an .exe and make some tweaks and it's what I want. However, I need this code to be called from C# so I create a wrapper class that is callable from C#
configuration.h
#ifndef MESHING_DLL_CONFIG_H
#define MESHING_DLL_CONFIG_H

#if defined(_MSC_VER)
#  define LIBRARY_EXPORT __declspec(dllexport)
#  define LIBRARY_IMPORT __declspec(dllimport)
#elif defined(__GNUC__) && __GNUC__ > 3
#  define LIBRARY_EXPORT __attribute__((visibility("default")))
#  define LIBRARY_IMPORT __attribute__((visibility("default")))
#else
#  define LIBRARY_EXPORT
#  define LIBRARY_IMPORT
#endif

#ifdef LIBRARY_API_EXPORTS
#  define LIBRARY_API LIBRARY_EXPORT
#elif LIBRARY_API_IMPORTS
#  define LIBRARY_API LIBRARY_IMPORT
#else
#  define LIBRARY_API
#endif
#endif /* MESHING_DLL_CONFIG_H */

wrappers.h
#ifndef MESHING_WRAPPERS_H
#define MESHING_WRAPPERS_H

#include <exception>
#include "configuration.h"
#include "callbacks.h"
#include "poisson_surface_reconstructor.h"

typedef intptr_t ArrayHandle;

extern "C"
{
    LIBRARY_EXPORT bool ExecutePoissonSurfaceReconstruction(
        int argc,
        char* argv[],
        ProgressCallback progressCallback,
        WarningCallback warningCallback,
        ErrorCallback errorCallback);

    LIBRARY_EXPORT bool Release(ArrayHandle arrayHandle);
}
#endif // MESHING_WRAPPERS_H

wrappers.cpp
#include "wrappers.h"

using namespace MeshingAdapter;

LIBRARY_EXPORT bool ExecutePoissonSurfaceReconstruction(
    int argc,
    char* argv[],
    ProgressCallback progressCallback,
    WarningCallback warningCallback,
    ErrorCallback errorCallback)
{
    try
    {
        PoissonSurfaceReconstructor* poissonSurfaceRecon =
            new PoissonSurfaceReconstructor(
                progressCallback,
                warningCallback,
                errorCallback);
        bool success = poissonSurfaceRecon->ExecuteSurfaceReconstruction(argc, argv);
        delete poissonSurfaceRecon;
        return success;
    }
    catch (const std::exception& ex)
    {
        errorCallback(ex.what());
        return false;
    }
}

LIBRARY_EXPORT bool Release(ArrayHandle arrayHandle)
{
    // #TODO can we do this smarter?
    return true;
}

However, the very inclusion of possion_surface_reconstructor.h causes 114 LNK2005 errors, mainly from classes I reference from different projects. An example being
2>wrappers.obj : error LNK2005: "private: static bool ThreadPool::_Close" (?_Close@ThreadPool@@0_NA) already defined in poisson_surface_reconstructor.obj
2>wrappers.obj : error LNK2005: "public: static unsigned __int64 ThreadPool::DefaultChunkSize" (?DefaultChunkSize@ThreadPool@@2_KA) already defined in poisson_surface_reconstructor.obj
2>wrappers.obj : error LNK2005: "private: static class std::vector<class std::thread,class std::allocator<class std::thread> > ThreadPool::_Threads" (?_Threads@ThreadPool@@0V?$vector@Vthread@std@@V?$allocator@Vthread@std@@@2@@std@@A) already defined in poisson_surface_reconstructor.obj
2>wrappers.obj : error LNK2005: "private: static class std::condition_variable ThreadPool::_DoneWithWork" (?_DoneWithWork@ThreadPool@@0Vcondition_variable@std@@A) already defined in poisson_surface_reconstructor.obj
2>wrappers.obj : error LNK2005: "public: static int const (* HyperCube::MarchingSquares::edges)[5]" (?edges@MarchingSquares@HyperCube@@2QAY04$$CBHA) already defined in poisson_surface_reconstructor.obj
2>wrappers.obj : error LNK2005: "char const * * type_names" (?type_names@@3PAPEBDA) already defined in poisson_surface_reconstructor.obj
2>wrappers.obj : error LNK2005: "char const * * BoundaryNames" (?BoundaryNames@@3PAPEBDA) already defined in poisson_surface_reconstructor.obj
2>wrappers.obj : error LNK2005: "char const * * ShowGlobalResidualNames" (?ShowGlobalResidualNames@@3PAPEBDA) already defined in poisson_surface_reconstructor.obj
2>wrappers.obj : error LNK2005: "private: static unsigned int volatile ThreadPool::_RemainingTasks" (?_RemainingTasks@ThreadPool@@0IC) already defined in poisson_surface_reconstructor.obj
2>wrappers.obj : error LNK2005: "public: static char const * const StackTracer::exec" (?exec@StackTracer@@2PEBDEB) already defined in poisson_surface_reconstructor.obj
2>wrappers.obj : error LNK2005: "public: static char const * const ImageWriterParams::DefaultTileExtension" (?DefaultTileExtension@ImageWriterParams@@2PEBDEB) already defined in poisson_surface_reconstructor.obj
2>wrappers.obj : error LNK2005: "public: static enum ThreadPool::ScheduleType ThreadPool::DefaultSchedule" (?DefaultSchedule@ThreadPool@@2W4ScheduleType@1@A) already defined in poisson_surface_reconstructor.obj

And more. Taking one example from the above list of errors ThreadPool::DefaultSchedule this is defined in one of the include files I reference and is part of my code base. This struct is defined as
struct ThreadPool
{
    enum ParallelType
    {
#ifdef _OPENMP
        OPEN_MP ,
#endif // _OPENMP
        THREAD_POOL ,
        ASYNC ,
        NONE
    };
    static const std::vector< std::string > ParallelNames;

    enum ScheduleType
    {
        STATIC ,
        DYNAMIC
    };
    static const std::vector< std::string > ScheduleNames;

    static size_t DefaultChunkSize;
    static ScheduleType DefaultSchedule;

    template< typename ... Functions >
    static void ParallelSections( const Functions & ... functions )
    {
        std::vector< std::future< void > > futures( sizeof...(Functions) );
        _ParallelSections( &futures[0] , functions ... );
        for( size_t t=0 ; t<futures.size() ; t++ ) futures[t].get();
    }

    static void Parallel_for( size_t begin , size_t end , const std::function< void ( unsigned int , size_t ) > &iterationFunction , ScheduleType schedule=DefaultSchedule , size_t chunkSize=DefaultChunkSize )
    {
        if( begin>=end ) return;
        size_t range = end - begin;
        size_t chunks = ( range + chunkSize - 1 ) / chunkSize;
        unsigned int threads = (unsigned int)NumThreads();
        std::atomic< size_t > index;
        index.store( 0 );

        if( range<chunkSize || _ParallelType==NONE || threads==1 )
        {
            for( size_t i=begin ; i<end ; i++ ) iterationFunction( 0 , i );
            return;
        }

        auto _ChunkFunction = [ &iterationFunction , begin , end , chunkSize ]( unsigned int thread , size_t chunk )
        {
            const size_t _begin = begin + chunkSize*chunk;
            const size_t _end = std::min< size_t >( end , _begin+chunkSize );
            for( size_t i=_begin ; i<_end ; i++ ) iterationFunction( thread , i );
        };
        auto _StaticThreadFunction = [ &_ChunkFunction , chunks , threads ]( unsigned int thread )
        {
            for( size_t chunk=thread ; chunk<chunks ; chunk+=threads ) _ChunkFunction( thread , chunk );
        };
        auto _DynamicThreadFunction = [ &_ChunkFunction , chunks , &index ]( unsigned int thread )
        {
            size_t chunk;
            while( ( chunk=index.fetch_add(1) )<chunks ) _ChunkFunction( thread , chunk );
        };

        if     ( schedule==STATIC  ) _ThreadFunction = _StaticThreadFunction;
        else if( schedule==DYNAMIC ) _ThreadFunction = _DynamicThreadFunction;

        if( false ){}
#ifdef _OPENMP
        else if( _ParallelType==OPEN_MP )
        {
            if( schedule==STATIC )
#pragma omp parallel for num_threads( threads ) schedule( static , 1 )
                for( int c=0 ; c<chunks ; c++ ) _ChunkFunction( omp_get_thread_num() , c );
            else if( schedule==DYNAMIC )
#pragma omp parallel for num_threads( threads ) schedule( dynamic , 1 )
                for( int c=0 ; c<chunks ; c++ ) _ChunkFunction( omp_get_thread_num() , c );
        }
#endif // _OPENMP
        else if( _ParallelType==ASYNC )
        {
            static std::vector< std::future< void > > futures;
            futures.resize( threads-1 );
            for( unsigned int t=1 ; t<threads ; t++ ) futures[t-1] = std::async( std::launch::async , _ThreadFunction , t );
            _ThreadFunction( 0 );
            for( unsigned int t=1 ; t<threads ; t++ ) futures[t-1].get();
        }
        else if( _ParallelType==THREAD_POOL )
        {
            unsigned int targetTasks = 0;
            if( !SetAtomic( &_RemainingTasks , threads-1 , targetTasks ) )
            {
                WARN( "nested for loop, reverting to serial" );
                for( size_t i=begin ; i<end ; i++ ) iterationFunction( 0 , i );
            }
            else
            {
                _WaitingForWorkOrClose.notify_all();
                {
                    std::unique_lock< std::mutex > lock( _Mutex );
                    _DoneWithWork.wait( lock , [&]( void ){ return _RemainingTasks==0; } );
                }
            }
        }
    }

    static unsigned int NumThreads( void ){ return (unsigned int)_Threads.size()+1; }

    static void Init( ParallelType parallelType , unsigned int numThreads=std::thread::hardware_concurrency() )
    {
        _ParallelType = parallelType;
        if( _Threads.size() && !_Close )
        {
            _Close = true;
            _WaitingForWorkOrClose.notify_all();
            for( unsigned int t=0 ; t<_Threads.size() ; t++ ) _Threads[t].join();
        }
        _Close = true;
        numThreads--;
        _Threads.resize( numThreads );
        if( _ParallelType==THREAD_POOL )
        {
            _RemainingTasks = 0;
            _Close = false;
            for( unsigned int t=0 ; t<numThreads ; t++ ) _Threads[t] = std::thread( _ThreadInitFunction , t );
        }
    }
    static void Terminate( void )
    {
        if( _Threads.size() && !_Close )
        {
            _Close = true;
            _WaitingForWorkOrClose.notify_all();
            for( unsigned int t=0 ; t<_Threads.size() ; t++ ) _Threads[t].join();
            _Threads.resize( 0 );
        }
    }
private:
    ThreadPool( const ThreadPool & ){}
    ThreadPool &operator = ( const ThreadPool & ){ return *this; }

    template< typename Function >
    static void _ParallelSections( std::future< void > *futures , const Function &function ){ *futures = std::async( std::launch::async , function ); }
    template< typename Function , typename ... Functions >
    static void _ParallelSections( std::future< void > *futures , const Function &function , const Functions& ... functions )
    {
        *futures = std::async( std::launch::async , function );
        _ParallelSections( futures+1 , functions ... );
    }
    static void _ThreadInitFunction( unsigned int thread )
    {
        // Wait for the first job to come in
        std::unique_lock< std::mutex > lock( _Mutex );
        _WaitingForWorkOrClose.wait( lock );
        while( !_Close )
        {
            lock.unlock();
            // do the job
            _ThreadFunction( thread );

            // Notify and wait for the next job
            lock.lock();
            _RemainingTasks--;
            if( !_RemainingTasks ) _DoneWithWork.notify_all();
            _WaitingForWorkOrClose.wait( lock );
        }
    }

    static bool _Close;
    static volatile unsigned int _RemainingTasks;
    static std::mutex _Mutex;
    static std::condition_variable _WaitingForWorkOrClose , _DoneWithWork;
    static std::vector< std::thread > _Threads;
    static std::function< void ( unsigned int ) > _ThreadFunction;
    static ParallelType _ParallelType;
};

Clearly static ScheduleType DefaultSchedule; being a static variable is causing a problem and the other errors are likely to be caused by the same issues (this is not my code originally and I need to wrap it to expose to C#).

*

*For the case of ThreadPool why is the value type struct ThreadPool that is a memeber of my PossionSurfaceReconstructor class causing this problem?

*What is the easiest way around this (not changing the struct to class for each instance of the error?

Thanks in advance.

A: The #include directive essentially performs text-level copy and paste of the contents of the specified file at the point where the #include appears. Your header MyMiscellany.h contains definitions for a bunch of static member variables:
size_t ThreadPool::DefaultChunkSize = 128;
ThreadPool::ScheduleType ThreadPool::DefaultSchedule = ThreadPool::DYNAMIC;
bool ThreadPool::_Close;
volatile unsigned int ThreadPool::_RemainingTasks;
std::mutex ThreadPool::_Mutex;
std::condition_variable ThreadPool::_WaitingForWorkOrClose;
std::condition_variable ThreadPool::_DoneWithWork;
std::vector< std::thread > ThreadPool::_Threads;
std::function< void ( unsigned int ) > ThreadPool::_ThreadFunction;
ThreadPool::ParallelType ThreadPool::_ParallelType;

The moment this header is included into more than one .cpp file, there will be more than one definition of these variables. There can be only one definition of a non-inline function or variable in a program [basic.def.odr]/4, which is exactly what the linker complains about:

2>wrappers.obj : error LNK2005: "private: static bool ThreadPool::_Close" (?_Close@ThreadPool@@0_NA) already defined in poisson_surface_reconstructor.obj
  […]

This error message just tells you that ThreadPool::_Close, etc., for which there appears a definition in wrappers.obj, already had a definition in poisson_surface_reconstructor.obj. Both, poisson_surface_reconstructor.cpp as well as wrappers.cpp (indirectly) included MyMiscellany.h, thus, each of the two object files resulting from compiling these two .cpp files contains definitions for all these variables. The definitions were pasted into each .cpp file when they included MyMiscellany.h.
To solve this problem, you can either make the variables in question inline (requires C++17), in which case you can also keep the definition inside the class rather than having to define the variable outside of the class
class ThreadPool
{
    …
    inline static bool Close = true;
    …
};

or move the definition to a separate .cpp file (see also this question for more on that).

Note: extern "C" has got nothing to do with demangling anything. All it does is declare that the entity in question shall have C language linkage, whatever that means on the target platform. On Windows, for example, even C linkage may still involve name mangling…
Furthermore, I would suggest to replace your volatile variable _RemainingTasks and custom SetAtomic implementation with std::atomic.
Finally, be aware that identifiers that contain a double underscore as well as identifiers that begin with an underscore followed by an uppercase letter such as, e.g., _Close, are reserved [lex.name]/3. You are actually not allowed to use identifiers like that in your code.


text:
Q: AngularJS How to add angular-breadcrumb dynamically for each page? I am using angular-breadcrumb to add breadcrumbs for my angularjs project.It works well when I add below code in module state of each page, when I click the menu it will redirect and display the correct breadcrumbs.
$stateProvider.state({
        name: 'index.cars',
        code: "cars",
        url: '/cars',
        templateUrl: 'partials/cars/index.html',
        controller: 'carsCtrl',
        ncyBreadcrumb: {
            label: 'CARS'
        },
   }

Now, I find that the project menus are configurable, that means all menus' name is configurable and I can get all of them from an api.
[
                {
                    "menuName": "CARS",
                    "operation":""#/index/cars"
                },
                {

                    "menuName": "PHONES",
                    "operation":""#/index/phones"
                },
             ]

Now, I am confused what the best solution to set my lable of breadcrumbs to the data returned by the interface globally?
I could filter the api data in each controller separately and assign the data like
 $stateProvider.state('index.cars', {
            url: '/cars',
            templateUrl: 'partials/cars/index.html',
            controller: function($scope) {
              //get menu name of car page from api
              $scope.foo='menuName';
            },
            ncyBreadcrumb: {
              label: 'State {{foo}}'
            }
          })

But I would like to find a better way and do not need to change each controller.

A: Exemple of an AngularJS breadcrumbs directive for use with ui-router
breacrumb.js
var breadcrumbs = function($state, $stateParams) {
    return {
        restrict: 'E',
        templateUrl: '/path/to/breadcrumbs.html',
        replace: true,
        compile: function(tElement, tAttrs) {
            return function($scope, $elem, $attr) {
                $scope.show = function(state){
                    if(!angular.isDefined(state.data)){
                        return false;
                    }
                    else if(!angular.isDefined(state.data.breadcrumbs)){
                        return false;
                    }
                    return true;
                };
            }
        }
    };
};

app.directive('breadcrumbs', ['$state', '$stateParams', breadcrumbs]);

breadcrumbs.html

        {{ state.data.title }}
        {{ state.data.title }}

example-state.js
var config = function ($stateProvider) {

$stateProvider
    // Ignored
    .state('index', {
        url: "/",
        abstract: true
        /***/
    })
    .state('index.overview', {
        url: '', // Inherit
        views: {
            /***/
        },
        data : {
            title : 'Overview',
            breadcrumbs : true
        }
    })
    .state('index.overview.children', {
        url: '/overview/:id',
        views: {
            /***/
        },
        data : {
            title : 'Children',
            breadcrumbs : true
        }
    });

};

angular.module('app', [/***/]).config(['$stateProvider', '$urlRouterProvider', config]);

index.html

            <breadcrumbs></breadcrumbs>

style.css
.breadcrumbs {
  border: 1px solid #e0e0e0;
  background-color: #FFFFFF;
  line-height: 1.5em;
  overflow: hidden;
}
.breadcrumbs > li {
  background-color: #f6f6f6;
  float: left;
  list-style: none outside none;
  padding: 0.35em 1.5em 0.35em 1em;
}
.breadcrumbs li:first-child > .breadcrumb:before,
.breadcrumbs li:first-child > .breadcrumb:after {
  display: none;
}
.breadcrumbs .breadcrumb {
  color: #a2a2a2;
  font-size: 0.75em;
  font-weight: bold;
  position: relative;
}
.breadcrumbs .breadcrumb:hover {
  color: #555555;
}
.breadcrumbs .breadcrumb:before,
.breadcrumbs .breadcrumb:after {
  border-color: transparent transparent transparent #e0e0e0;
  border-image: none;
  border-style: outset outset outset solid;
  border-width: 25px;
  content: "";
  height: 0;
  left: -40px;
  pointer-events: none;
  position: absolute;
  top: -1.5em;
  width: 0;
}
.breadcrumbs .breadcrumb:after {
  border-left-color: #f6f6f6;
}
.breadcrumbs .breadcrumb:before {
  left: -38px;
}
.breadcrumbs .current {
  background-color: #FFFFFF;
  margin-left: -15px;
}
.breadcrumbs .current .breadcrumb {
  color: #555555;
  left: 20px;
  overflow: hidden;
}


text:
Q: How to profile php on a shared server I have a PHP website which suddenly runs slow when you enter the site. It does not run slow every time, only on the first run. I did some modification to some plugins I have, maybe something there that is causing the delay, but I have disabled them, only to see the same lags.
Is there a good way to see what exactly takes so long to load. I am on a shared environment, and there are no debugging tools available such as xdebug and pear libraries.
Does anyone know what steps I can take in getting some details on what is running.

A: You can try the yslow add-on of firefox. This can show you why the site is slow from the client site. Take a look and also check your server side code too. If there is a query taking too much time.
You said it runs slow on very first time, it may be because of the client site load such as loading unwanted javascript code everytime. Load the javascript as they needed or you can minify the javascript.

A: If you running a MySQL setup then install phpMyAdmin.  Within phpMyAdmin you'll see a tab called 'Status', from there you can get stats about the queries that are hitting your DB and what you can do to improve performance.  If the problem is JS related, then definitely install ySlow like Singh suggested.


text:
Q: Accessing fields of particular layer I am trying to access the fields which I can see in this particular layer. I am able to see that it has fields but fetching the values in those fields is something that I am unable to do. Is there someway to do that?

A: Just use the REST interface 'Query', scroll to bottom of page that you gave, here is a query for OBJECTID > 0, shows 98 records.
Where field: OBJECTID > 0
Outfields: *
http://sampleserver6.arcgisonline.com/arcgis/rest/services/911CallsHotspot/MapServer/jobs/jef3fd04155ce410386cc7f64ebad694d/0/query?where=OBJECTID+%3E+0&text=&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&relationParam=&outFields=*&returnGeometry=true&maxAllowableOffset=&geometryPrecision=&outSR=&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&gdbVersion=&returnDistinctValues=false&f=html
In javascript, do something like this...
    var selectQuery = new esri.tasks.Query();
    selectQuery.where = "OBJECTID > 0";
    selectQuery.outFields = ["*"];
    var queryTask = new esri.tasks.QueryTask("http://sampleserver6.arcgisonline.com/arcgis/rest/services/911CallsHotspot/MapServer/jobs/jef3fd04155ce410386cc7f64ebad694d");
    queryTask.execute(selectQuery, function (features) {
        //do something with features returned
    });

A: Scoll to the bottom of the page you gave and click "Query". To return all features in the layer, enter "0=0" in the top text box (labeled "Where:"). "0=0" is a true condition for all features. Leave all the other text boxes blank and press the "Query (GET)" button at the bottom of the form.
I recommend the JavaScript answer from awesomo, but if you want to only get certain fields, replace the "*" in
    selectQuery.outFields = ["*"];

with the field headings you want to work with. If you only want to return CALL_TYPE, CITY, and Date, the JavaScript would be
    selectQuery.outFields = ["CALL_TYPE", "CITY", "Date"];

A: Did you try to get objects from this particular layer?
Your layer has /query endpoint, where you can query for objects on your layer Layer 0: Query
On this layer there is 98 objects. One sample object is OBJECTID:6