text:
Q: Initializing an empty array in C++ I am writing a program in C++ and I need to initialize an array of a struct object I have created. It looks something like this:
typedef struct {
float x;
float y;
} vec2;

And then I initialize an array like this:
vec2 hotSpot[1000];

I thought when I initialized such an array, it would be completely empty, but when I print the value of sizeof(hotSpot), it says 8000!
Am I going wrong somewhere, or have I misunderstood some concept? How do I make this array empty?

A: Your array is not, and can never be "empty". It has, and will always have, 1000 elements. Thus is the nature of C++ arrays.
The problem is that those elements are not in any deterministic state, and indeed accessing any element that has not been initialized is undefined behaviour.
More generally, objects in C++ can never be "empty". They always exist. If an object didn't exist, there wouldn't be an object. Some objects always exist in a definite state, while other objects (such as primitive types, or a named object after having been std::moved) can exist in an uninitialized or indeterminate state -- they still exist, but the only thing you're allowed to do with them is assign a value to them.

A: Your hotSpot can not be empty as you initialized it as an array of 1000. There for, there are 1000 elements.
When vec2 hotSpot[1000]; happens, it places all 1000 values as an uninitialized variable.
The elements in hotSpot are not valid as they have not been initialized. If you are looking to set them all to zero, you could use memset to initialize them all to zero.
For more information on arrays, please take a look at this reference.

A: I am guessing that you want to initialize your 'empty' array this way:
vec2 hotSpot[]; // Defines an array of undefined length

But if you want to initialize it as 'empty', i.e. fill its entire content with zeros:
vec2 hotSpot[1000]; // Defines an array of 1000 items in length
memset(hotSpot, 0, sizeof(hotSpot)); // Fill the array with zeros

A: they are empty data-wise, but memory allocated to be able to hold 1000 * 2 float * 4 bytes

A: A float is just 4 bytes in your machine.When initialized,the hotSpot takes up 8000 totally.


text:
Q: Implications on the formulation of Surv - time and time2 I have a question on the formulation used in the function coxph, in particular on the of the different ways of entering time of the observations in the Surv function.
My results are different if I enter the time when each observation started and stopped:
a. Surv (time =start_ind, time2 = stop_ind, event = death)

As opposed to only adding information of the interval during which the observation took place:
b. Surv (time =stop_ind - start_ind , event = death)

An example of the output for a is (11.215,26.167+] and for b 14.952.
I initially thought that both approaches should give me the same outcome as I expected the interval to be used  in a. However, as the results differ I understand that in a the model may also use the information on how the different events (deaths) are distributed along the study period. For instance, let's say that in the first two years of the study I have a lot of death related to on given risk factor but after that this was not so important. I understand that the effect of such a risk factor will be less strong in a as it is constrained to one particular period.
In my analysis, I know that there is a lot of temporal variation in the risk factors because the origin of the data varies over time as well as some external factors. In this case I believe it is an important information to add both, time and time2.
Is my interpretation correct? If not, what is the difference between a and b?

A: A survival model requires a choice about the starting time, time = 0, from which all subsequent survival estimates are made. Your 2 models make substantially different choices.
In the Surv(time1, time2, event) syntax of model a, the time interval is relative to an earlier 0 time. With (time1, time2) of (11.215,26.167), all calculations using that data row are evaluating survival since time = 0. This provides information between time = 11.215 and time = 26.167, for this case and all others still at risk during that time interval. As @Rootless17b says, this is the syntax used when covariate values change over time.
Model b, using the time difference of 14.952 as a single time point in the Surv(time, event) syntax, resets  a time of 11.215 in the original time scale as time =  0 for that case. It will provide information about events that happen between time = 0 and time = 14.952, for this case and all other cases at risk during that time interval. With this formulation each case will have its own choice of time = 0.
In clinical studies time = 0 is usually the time of entry of each participant into the study, say the date of diagnosis of a cancer. If you defined the original time scale in terms of actual calendar dates, this is equivalent to what you have written for model b.
So you have to think carefully about the reference time = 0 after which you want to estimate survival.

A: Approach a is generally used for time-varying covariates. These are covariates that change their value throughout the time of observation. Also you should have multiple rows per subject in your dataset that specifiy each time period (with tstart and tstop) whenever a value changes. You also have to specify the id argument for this approach to work properly. id should be a unique identifier for each subject in the dataset. There is a great vignettes on CRAN how to create such datasets how to calculate a Cox model with time-varying covariates: https://cran.r-project.org/web/packages/survival/vignettes/timedep.pdf
Approach b gives you survival estimates for one time interval (e.g. diagnosis date to date of death in days). Importantly the variables you put into the survfit function or the coxph funtion, should be all known at the start of this interval (e.g. diagnosis date / time point 0). From a cox model based on Survival function b you would then be able to get a Hazard ratios for these variables throughout the time of observation.
In the example you gave, the output for b is correct. It gives you a survival time (= observation time) of 14.952 based on your start and stop dates. In the output for a the model would assume that the time interval between timepoints 11.215 and 26.167 would be one part of the whole survival period. Since you haven´t specified the id argument, I don´t know what the exact behavior would be but I´d assume that it would handle all non-overlapping intervals as one individual.

redpajama_set_name: RedPajamaStackExchange


text:
Q: One-way partial table synchronization for desktop application I'm a programmer, but I'm not experienced with databases, and this is my first post, if my post is not respecting any rules please point them out so I can improve them, thank you.
I have desktop application (.Net WPF application) using a local database (MS SQL).
I have also a central server containing a MS SQL server database
And a mobile app that needs access (read-only) to the data located in the central server.
Each client has the desktop application installed on their computer (from which all data is inserted/modified/deleted), and they also have the mobile app that should give them access (read-only) to the data located in the central server.
All clients share the same central database, and the same tables, but each client can only access specific rows that belong to them.
I'm trying to figure out how to synchronize the inserted/modified/deleted rows in the desktop database to the central database (only one-way synchronization).
I have done some research, and I found that there are several technologies that can be used, like Replication, CDC, software (Symmertricds...) or even programming it from ground up, but I'm still confused which one is the right one for this case.
Any help would be appreciated, thank you.


text:
Q: Periodic DNS Fault I have a reseller account. but sometimes, somthings goes wrong on my websites. I think server is hacked or DNS server is hacked. I searched similar content on google, then I found same HTML codes on hacker websites.
Explaining the problem: mydomain.com is active everytime but sometime, floowing code is appeared. Please note that I have not this page or similar materials on account. Whether my domain contents is empty and only images folder is exist.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<title>Welcome thisdomain.com</title>
<link rel="stylesheet" href="/nobrand.css" type="text/css" />
<meta name="description" content="Web Hosting. Professional Web hosting services with free domain name, unlimited web hosting space and unlimited bandwidth." />
<meta name="keywords" content="web hosting, hosting, web host, host, website hosting, webhosting, web hosting provider, web hosting service, web hosting supplier, cheap web hosting, web space, web site hosting, web space hosting, best web hosting, cpanel hosting" />

This Domain is
PARKED.

©2012. All rights reserved.

What is the problem?

A: Check your A records on your registar's DNS configuration page and make sure they are pointing to the right place.


text:
Q: Constructing a method to search a binary tree I have constructed a binary search tree that will sort people based on their name, the code for this is:
code for the class Person:
package Tree;

public class Person {
private int age;
private String name;
private String gender;

public Person( String name, String gender,int age) {
    this.age = age;
    this.name = name;
    this.gender = gender;
}

public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getGender() {
    return gender;
}

public void setGender(String gender) {
    this.gender = gender;
}

@Override
public String toString() {
    return "Person [age=" + age + ", name=" + name + ", gender="
            + gender + "]";
}
}

the search tree code is:
package Tree;

public class BinarySearchPerson {

private boolean empty;
private Person person;
private BinarySearchPerson left;
private BinarySearchPerson right;

public BinarySearchPerson(Person person, BinarySearchPerson left,
        BinarySearchPerson right) {
    this.empty = false;
    this.person = person;
    this.left = left;
    this.right = right;
}

public BinarySearchPerson() {
    this.empty = true;
}

public boolean isEmpty() {
    return empty;
}

public Person getPerson() {
    if (isEmpty()) {
        throw new IllegalStateException(
                "Trying to access root of an empty tree");
    }
    return person;
}

public void setPerson(Person person) {
    this.person = person;
}

public BinarySearchPerson getLeft() {
    if (isEmpty()) {
        throw new IllegalStateException(
                                        "Trying to access subtree of an empty tree");
    }
    return left;
}

public void setLeft(BinarySearchPerson left) {
    this.left = left;
}

/**
 * gets the right subtree of this node
 */
public BinarySearchPerson getRight() {
    if (isEmpty()) {
        throw new IllegalStateException(
                                        "Trying to access subtree of an empty tree");
    }
    return right;
}

public void setRight(BinarySearchPerson right) {
    this.right = right;
}

public static BinarySearchPerson insert(Person person, BinarySearchPerson bt){
    int n = person.getName().compareTo(bt.getPerson().getName());

    if (n<0){
        if(bt.getLeft().isEmpty() == true){
             BinarySearchPerson newLeft = new BinarySearchPerson(person,new BinarySearchPerson(),new BinarySearchPerson());
             bt.setLeft(newLeft);
             return bt;
        }
        else{
            insert(person, bt.getLeft());
            return bt;

        }
    }

    if (n>0){
        if(bt.getRight().isEmpty() == true){
             BinarySearchPerson newRight = new BinarySearchPerson(person,new BinarySearchPerson(),new BinarySearchPerson());
             bt.setRight(newRight);
             return bt;
        }
        else{
            insert(person, bt.getRight());
            return bt;
        }
    }
    else return bt;

}

public static int lookupAge(String name) {
    Person person =
    if (name.compareTo(person.getName())==0){
        return person.getAge();
    }
    else return -1;

}

}

and the code i have been using to test it with:
package Tree;

public class TreeTest {

public static void main(String[] args) {
    Person p = new Person("John", "M",32);
    Person p1 = new Person("Alex", "M",15);
    Person p2 = new Person("Tom", "M",24);
    Person p3 = new Person("Bill", "M",23);
    Person p4 = new Person ("Jackson", "F", 50);

    BinarySearchPerson bt = new BinarySearchPerson(p,new BinarySearchPerson(),new BinarySearchPerson());
    BinarySearchPerson bt1 = BinarySearchPerson.insert(p1, bt);
    BinarySearchPerson bt2 = BinarySearchPerson.insert(p2, bt1);
    BinarySearchPerson bt3 = BinarySearchPerson.insert(p3, bt2);
    BinarySearchPerson bt4 = BinarySearchPerson.insert(p4, bt3);
    System.out.println("alex".compareTo("john"));

    System.out.println(bt4.getLeft().getRight().getRight().getPerson().getName());

}

}

The method works and sorts the names out well. What I am trying to do now is create a new method
lookupAge(String name);
that can be used to search the tree for a person's name. I have a rough idea of how to do this but i am struggling with the syntax for creating this method. The method must be able to be called like:
bt.lookupAge("Tom");

and that should return 24, which is Tom's age.
I need to look through the tree to find tom but the method only has parameter name so i don't know how to refer to the tree bt. I have never made a method this way before, only by including all the parameters that i need to use. I would be ok making it if it was
lookupAge(String Name, BinarySearchPerson bt);

but i can't include the tree as a parameter.
any help would be great, thank you.

A: Write your method in the BinarySearchPerson class  so that it looks something like
public int lookupAge(String name) {...

Once written, if someone calls the method like in your example, bt.lookupAge("Tom"), the 'this' parameter will refer to bt.  You'll then compare this.person.getName() to name and either return this.person.getAge(), or return something like this.lookupAge(getRight().getPerson().getName())


text:
Q: League of Legends amateur league? Well I was wondering if there are any amateur leagues for league of legends. Tournaments and such for people who are not in the pro scene.

A: Every sunday, the ESL organises GO4LOL. If you live in Europe that might be helpful. You could also join the ESL ladders (1v1, 2v2, 5v5).
Look it up: http://www.esl.eu/

A: If you want to play for fun,
I can suggest looking at pages like Battlefy
or Razer arena (which was launched just recently).
There you can often find some amateur tournaments for various regions,
plus it is really easy for admins to host a tournament.
I don't know in which division you are in, but sometimes there are restricted tournaments as well (e.g. only bronze to platinum allowed), mostly it is up to diamond 1 though.
AFAIK there are some leagues, where you can play in different divisons, according to your skill-level. It is called HouseParty5v5 (and has its own Subreddit btw)

A: Short answer: Not official by RIOT.
You can find tons of small tournaments in local areas. Usually made by PC bang or special groups.
Here the Challenger Circuit by RIOT

A: If you're a university student, then there are two leagues that run tournaments for college teams.
Collegiate Starleague: League of Legends

*

*More organized because they are using the CSL: Starcraft framework

*Larger prize pool

*Only one team per school

IvyLoL

*

*More casual tournament

*Can have more than one team per school

A: If your from the UK there is a open tourny called UKlol,
They used to run each sunday,
here is a few of there Videos.


text:
Q: Crystal report: Unable to connect: incorrect log on parameters This is the code of Crystal Report:
    ReportDocument reportDocument = new ReportDocument();
    reportDocument.Load(Server.MapPath(ReportName + ".rpt"));
    reportDocument.SetParameterValue("@userid", Convert.ToInt64(5));
    reportDocument.SetParameterValue("@Reportname", ReportName);
    reportDocument.SetParameterValue("@SessionId", Session.SessionID.ToString());
    CrystalReportViewer1.ReportSource = reportDocument;
    reportDocument.SetDatabaseLogon("sa", "Password1", "192.168.0.245", "databaseName", true);

It is saying "Unable to connect: incorrect log on parameters." although the login information is correct.
If I set the value to  "reportDocument.SetDatabaseLogon("sa", "Password1", "192.168.0.240", "databaseName", true);" it is working fine which is the login information was given during the designing the Crystal Report.

A: Can try this and see if it helps?
       ConnectionInfo connectionInfo = new ConnectionInfo
                                            {
                                                UserID = user,
                                                Password = pwd,
                                                ServerName = server,
                                                DatabaseName = db
                                            };
        TableLogOnInfo tableLogOnInfo = new TableLogOnInfo
                                            {
                                                ConnectionInfo = connectionInfo
                                            };
        foreach (Table table in reportDocument.Database.Tables)
        {
            table.ApplyLogOnInfo(tableLogOnInfo);
        }

A: I have same problem but has solved.
The problem is in odbc connection. Just install SQL native client to add connection in odbc.
Download link
https://support.fotoware.com/hc/en-us/articles/208664385-Microsoft-SQL-Native-Client-fails-to-download-during-FotoWeb-setup


text:
Q: Left-align equations in the alignat environment, like in flalign I would like to left-align a few equations inside the alignat* environment, but I am not sure how to achieve this. Essentially, what I want is something that behaves like flalignbut lets me align the terms just like alignat.
However, using fleqn to align all equations in the document is not an option for me, since I only want to left-align them in one instance.
I looked around and found this question and this one. I don't think that these answer my question though, but I am fairly new to using LaTeX, so please forgive my cluelessness in case they do.
If there is a way to create a list and then align the terms in the list that would also work for me, however I got the warning message that I cannot use lists inside a math environment, but that is the only way I know how to align equations.
Example with all the packages I use in my document:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{natbib}
\usepackage{xcolor}
\usepackage{amsmath,amsfonts}
\usepackage{amssymb}
\usepackage{mathtools}
\usepackage{cancel}
\usepackage{enumitem}
\usepackage{amsthm}
\newtheorem{innercustomthm}{Theorem} % I use this because I want to number my theorems myself
\newenvironment{customthm}[1]
  {\renewcommand\theinnercustomthm{#1}\innercustomthm}
  {\endinnercustomthm}

\begin{document}
\begin{customthm}{5.3.9}[Properties of the transpose]
\begin{alignat*}{3}
    &\textbf{\textup{(a) }} (A+B)^T &&= A^T + B^T \qquad && \forall ~n \times n \text{ matrices A and B}. \\
    &\textbf{\textup{(b) }} (kA)^T &&= kA^T  && \forall \text{ matrices A, scalars k}. \\
\end{alignat*}
\end{customthm}
\end{document}

The way it is aligned is great, but I need it to be on the left. As I mentioned above, if there is a way to make a list and align it from within that list, then that would also be great (even better maybe, since I wouldn't have to put (a), (b), etc. myself), but I couldn't figure out how to do this. Thanks a lot in advance, I hope I formulated the question clearly.

P.S.: In case you are wondering why I need this, I am only writing a summary for myself right now, but would like to get better in LaTeX, hence I'm doing it this way, two birds with one stone...

A: It seems more appropriate here to set the list of items in the theorem using a regular list. Since you're loading enumitem already, formatting of the list elements is easy. Together with eqparbox's \eqmakebox[<tag>][<align>]{<stuff>}, you can set the horizontal alignment across \items:

\documentclass{article}

\usepackage{mathtools}
\usepackage{enumitem,eqparbox}
\usepackage{amsthm}

\newtheorem{theorem}{Theorem}

\begin{document}

\begin{theorem}[Properties of the transpose]
  \begin{alignat*}{3}
    &\textbf{\textup{(a) }} (A+B)^T &&= A^T + B^T \qquad && \forall ~n \times n \text{ matrices A and B}. \\
    &\textbf{\textup{(b) }} (kA)^T &&= kA^T  && \forall \text{ matrices A, scalars k}.
  \end{alignat*}
\end{theorem}

\begin{theorem}[Properties of the transpose]
  \mbox{}
  \begin{enumerate}[label=\textbf{\upshape(\alph*)}, ref=(\alph*)]
    \item $\eqmakebox[LHS][l]{$(A+B)^T$} = \eqmakebox[RHS][l]{$A^T + B^T~$} \forall~n \times n$ matrices $A$ and $B$.
    \item $\eqmakebox[LHS][l]{$(kA)^T$}  = \eqmakebox[RHS][l]{$kA^T$}       \forall~n$ matrices $A$, scalars $k$.
  \end{enumerate}
\end{theorem}

\end{document}


text:
Q: how to make a stack trace as in zend framework? zend framework how to do a stack trace?
Stack trace:

# 0 C: \ apache \ www \ itransition \ library \ Zend \ Controller \ Front.php (954): Zend_Controller_Dispatcher_Standard-> dispatch (Object (Zend_Controller_Request_Http), Object (Zend_Controller_Response_Http))
# 1 C: \ apache \ www \ itransition \ library \ Zend \ Application \ Bootstrap \ Bootstrap.php (97): Zend_Controller_Front-> dispatch ()
# 2 C: \ apache \ www \ itransition \ library \ Zend \ Application.php (366): Zend_Application_Bootstrap_Bootstrap-> run ()
# 3 C: \ apache \ www \ itransition \ index.php (26): Zend_Application-> run ()
# 4 {main}

A: By catching a thrown exception, you can use Exception::getTraceAsString()
try
{
    throw new Exception('Just testing...');
}
catch (Exception $e)
{
    echo $e->getTraceAsString();
}


text:
Q: Getting a value from a ConcurrentDictionary If I have this ConcurrentDictionary:
public class User
{
    public string Context { get; set; }
    public bool Owner { get; set; }
}

protected static ConcurrentDictionary<User, string> OnlineUsers = new ConcurrentDictionary<User, string>();

Does anyone know how I would get the value of Owner if I already have the value of the Context? Basically I want to do a "find" using the Context. Thanks.

A: Does anything stop you from using standard Linq FirstOrDefault() method like so:
var item = OnlineUsers.FirstOrDefault(kvp => kvp.Key.Context == myContext);

A: How obout something like
var ou = OnlineUsers.First(x => x.Key.Context == "TADA");

A: It sounds like you need a Dictionary<string, User> which, when given the context as a string will tell you which User it corresponds to.  If you are going to need to perform this lookup several times, and there isn't a problem using the additional memory, it may be worth creating such a dictionary.
If you are only going to be doing the search once or twice, or the mappings will be changing so often that you can't keep the dictionary up to date, then you can simply do a linear search on the dictionary using a foreach loop, or using a LINQ method such as First or Where, as demonstrated in other answers.

A: Here you go:
ConcurrentDictionary<User, string> dict = new ConcurrentDictionary<User, string>();

dict.TryAdd(new User() { Context = "a", Ownder = false }, "aa");
dict.TryAdd(new User() { Context = "b", Ownder = false }, "bb");
dict.TryAdd(new User() { Context = "c", Ownder = true }, "cc");
dict.TryAdd(new User() { Context = "d", Ownder = false }, "dd");

IEnumerable<User> list = dict.Keys.Where(p => p.Context == "a");


text:
Q: Average not Calculating Properly I have designed a small program to calculate the average test scores for an array of students, however, for the life of me, cannot figure out why the average is not calculating properly.  What is going on?
Output:

Enter number of students in class (max 50): 3
  Enter total number of tests (max 10): 3
  Enter student 1's test scores:
  100
  100
  100
  Enter student 2's test scores:
  100
  97
  75
  Enter student 3's test scores:
  56
  45
  67
  (lldb)
  (lldb)
  (lldb)
The average score for student 1 is 33.3333.  // As you see here it should be 100 since all 3 scores were 100.
  (lldb)

Code:
const int MAX_STUDENTS = 50;
const int MAX_TESTS = 10;

int main()
{
    char studentName[50];
    int totalStudents = 0;
    int totalTests = 0;
    double totalScore = 0;
    double score[MAX_STUDENTS][MAX_TESTS];
    double averages[MAX_STUDENTS];

    std::cout << "Enter number of students in class (max " << MAX_STUDENTS << "): ";
    std::cin >> totalStudents;
    std::cout << "Enter total number of tests (max " << MAX_TESTS << "): ";
    std::cin >> totalTests;
    for (int student = 0; student < totalStudents; student++) {
        std::cout << "Enter student " << (student + 1) << "'s test scores: " << endl;
        for (int test = 0; test < totalTests; test++) {
            std::cin >> score[student][test];
        }
    }

    for (int student = 0; student < totalStudents; student++) {
        for (int test = 0; test < totalTests; test++) {
            totalScore = NULL;
            totalScore += score[student][test];
        }
        averages[student] = totalScore / totalTests;
        std::cout << endl;
        std::cout << "The average score for student " << student + 1 << " is " << averages[student] << "." << endl;
    }

    return 0;
}

A: Change
    for (int test = 0; test < totalTests; test++) {
        totalScore = NULL;
        totalScore += score[student][test];
    }

to
    totalScore = 0;
    for (int test = 0; test < totalTests; test++) {
        totalScore += score[student][test];
    }

Otherwise you are resetting the totalScore prior to each addition.

A: You always set totalScore to 0 inside the inner loop.
   for (int student = 0; student < totalStudents; student++) {
        for (int test = 0; test < totalTests; test++) {
            totalScore = NULL;
            totalScore += score[student][test];
        }

Statement
            totalScore = 0.0; // why NULL?

must be placed before the inner loop.
Also I would separate the calculation of average scores and printing the result.
So I would write the following way
for ( int student = 0; student < totalStudents; student++ )
{
    averages[student] = 0.0;
    for ( int test = 0; test < totalTests; test++ )
    {
        averages[student] += score[student][test];
    }
    averages[student] /= totalTests;
}

for ( int student = 0; student < totalStudents; student++ )
{
    std::cout << "The average score for student " << student + 1 << " is " << averages[student] << "." << endl;
}


text:
Q: How does a python package import a higher level module I am trying to understand how a lower level package 'knows' about a higher level module such that calling it doesn't result in an error. My directory structure is as follows:
.
├── foo.py
├── script.py
├── pkg
│   ├── __init__.py

My file contents are as follows:
foo.py contains:
class Foo():
    print("foo")

pkg/__init__.py contains:
from foo import Foo

script.py contains:
from pkg import Foo

foo = Foo()

From the directory where script.py is located, I can run python script.py and it results in "foo" being printed.
How is pkg/__init__.py able to successfully import Foo even though foo.py is located in a higher level directory?


text:
Q: How to pass text box value in export plugin? I am able to generate & download pdf using export plugin in grails. Now, I want to pass parameters to export plugin tag,
<export:formats formats="['excel', 'pdf']" params ="parameters to be passed here"/>

I have one text box & now I want to pass that text box value into that export tag.
Simply, I want to write some text in the text box & capture entered text box value in my export tag.
Can somebody please tell me how to do that? I am new in grails. Thank you.


text:
Q: Can org.apache.cxf.service.factory.ReflectionServiceFactoryBean be configured to cache WSDLs? I am using JBoss 7.1.1 but everytime my EAR makes a SOAP request, it takes about 2 minutes while JBoss creates each service required:
14:30:14,822 INFO  [org.apache.cxf.service.factory.ReflectionServiceFactoryBean] (http--0.0.0.0-8081-3) Creating Service {http://services.discretewireless.com/v2009_1/}AuthenticationManagerV1Port from WSDL: http://services.discretewireless.com/v2009_1/AuthenticationManagerV1.wsdl

Instead of creating the services at runtime, once each time they are used, can I configure something somewhere so that it doesn't have to download the WSDLs and ...Creating Service...from WSDL:... each time one of my beans makes a SOAP request?

A: You can download the wsdl before running your client and make it available in two different ways: First, CXF's wsdl2java generator lets you fix the location of the wsdl (wsdlLocation) on your classpath, and the wsdl can even be archived in the same jar as your stubs.  Or, second, you can instead pass an url (referencing the local file) to the service's constructor, where the url is something like 'file://path...'


text:
Q: How to retrieve data from a json array this is how my json response looks like
{
    "id": "fe4a69ef-8b8b-42ad-9c5c-9e0c3e449441",
    "createTime": "2014-04-09T11:29:26Z",
    "updateTime": "2014-04-09T11:29:26Z",
    "status": "Created",
    "transaction": {
        "amount": {
            "currencyCode": "GPP",
            "total": 122
        },
        "qrcode": "1f0e3dad99908345f7439f8ffabdfiop",
        "description": "This is the payment transaction description."
    }
}

when I try to extract values from each parameter upto status I could extract it but when I try to extract the currencyCode it shows No value for currencyCode
I saw this post and modified my code but no use yet
my code
JSONObject jObject = new JSONObject(toReturn);

         if(jObject.has("error")){
             RES_STATUS     =   AppConstants.FAIL;
         }
         else{
             AppVariables.id                    =   jObject.getString(AppVariables.id_);
             AppVariables.createTime            =   jObject.getString(AppVariables.createTime_);
             AppVariables.updateTime            =   jObject.getString(AppVariables.updateTime_);
             AppVariables.status                =   jObject.getString(AppVariables.status_);
             JSONArray jArray = jObject.getJSONArray("transaction");

             for (int i=0; i < jArray.length(); i++)
             {
                 try {
                     JSONObject oneObject = jArray.getJSONObject(i);
                     // Pulling items from the array
                     String oneObjectsItem = oneObject.getString("total");
                     String oneObjectsItem2 = oneObject.getString("currencyCode");
                     Log.e("oneObjectsItem", oneObjectsItem);
                     Log.e("oneObjectsItem2", oneObjectsItem2);
                 } catch (JSONException e) {
                     // Oops
                     Log.e("OOps", e.toString());
                 }
             }

             AppVariables.total                 =   String.valueOf(jObject.getInt(AppVariables.total_));
             AppVariables.qrcode                =   jObject.getString(AppVariables.qrcode_);

A: Try this..
"transaction": {        //this is JSONObject not array

Remove below lines
         JSONArray jArray = jObject.getJSONArray("transaction");
         for (int i=0; i < jArray.length(); i++)
         {
             try {
                 JSONObject oneObject = jArray.getJSONObject(i);
                 // Pulling items from the array
                 String oneObjectsItem = oneObject.getString("total");
                 String oneObjectsItem2 = oneObject.getString("currencyCode");
                 Log.e("oneObjectsItem", oneObjectsItem);
                 Log.e("oneObjectsItem2", oneObjectsItem2);
             } catch (JSONException e) {
                 // Oops
                 Log.e("OOps", e.toString());
             }
         }

And add below lines
        JSONObject transaction_obj = jObject.getJSONObject("transaction");
        JSONObject oneObject = transaction_obj.getJSONObject("amount");
        String oneObjectsItem = oneObject.getString("total");
        String oneObjectsItem2 = oneObject.getString("currencyCode");
        Log.e("oneObjectsItem", oneObjectsItem);
        Log.e("oneObjectsItem2", oneObjectsItem2);
        AppVariables.qrcode = transaction_ob.getString("qrcode");

A: gson is another perfect solution for json resolving.

A: transaction is not an JsonArray. That is JsonObject.Try following code. I hope this will help you
JSONObject objTransaction= jObject.getJSONObject("transaction");
String strQrcode=objTransaction.getString("qrcode");
String strDescription=objTransaction.getString("description");
JSonObject objAmount=objTransaction.getJSONObject("amount");

String strTotal=objAmount.getString("total");
String strCurrencyCode = objAmount.getString("currencyCode");


text:
Q: Design pattern for wrapping multiple apis into single api I have 3 different libraries that provide depth data as well as gesture information. I need to wrap these libraries into a single simpler to use for user api. The apis I am trying to wrap provide a set of utilities as well as information that are not equal. The core data such as depth images or color images are provided but tracking can have different method or amount of information provided may differ. For example, one api provides a list of hands being detected and each hand has internally an orientation info(l/r). Another api provides l/r hand objects with NULL if not found and info if found.
I need to wrap these apis into a single api in the same language(c++) that allows user to have to write way less code to get the core functionalities. Is there a pattern that provides best-practices for such a task? Or any examples in industry that do something similar? I understand that single tight-knit apis are better than a large api, but for my current use-case, a large api makes sense, so I need to do that.

A: As others have said, the Façade pattern is an obvious way to go. To add to the answers thought, I'd like to say, you need to think carefully about the semantics of the API you are trying to wrap when creating the simpler Façade. Syntax is the easy part.
For example, your API may require an initialisation function followed by functions which actually do the bit you are interesting in, followed by a tear down before allowing a new init. If you abstract away the init part are you potentially adding unnecessary processing with every API call (init, process, tear-down) without the user knowing that they are doing so.
Obviously, my example is completely hypothetical, but it just goes to illustrate that you need to think carefully about how the API is simplified so unintended consequences are not introduced.

A: I think what you're looking for is the Facade pattern (https://en.wikipedia.org/wiki/Facade_pattern).
Basically, you create a friendly, front-facing API for your users/developers to call.
When the facade API is called, it translates the call into one or more calls to one or more of the "source" APIs, then passes the results (maybe with some more translation) back to the caller.
Essentially, it masks the complexity of the source APIs (and gives you an opportunity to standardize the request and response data, formats, etc.).

A: It seems a mix of Abstract Factory Pattern and Façade. You would have a common interface (abstract class) and families of concrete classes which implements the API for each provider. Through the factory, you could select which provider to use.


text:
Q: Serilog Email sink enableSSL false checks I am trying to use EnableSsl = false in my EmailConnectionInfo but it seems like the smtp client being used for the smtp connection is trying to use SSL because the default SecureSocketOptions is set to Auto. When I created a client manually and used the overload with SecureSocketOptions = None it worked.
The error:
Failed to send email: MailKit.Security.SslHandshakeException: An error occurred while attempting to establish an SSL or TLS connection.

The SSL certificate presented by the server is not trusted by the system for one or more of the following reasons:
1. The server is using a self-signed certificate which cannot be verified.
2. The local system is missing a Root or Intermediate certificate needed to verify the server's certificate.
3. The certificate presented by the server is expired or invalid.

See https://github.com/jstedfast/MailKit/blob/master/FAQ.md#InvalidSslCertificate for possible solutions. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.

The workarround:
I am setting the ServerCertificateValidationCallback to true
When used in my Program.cs, it works:
.UseSerilog((hostingContext, loggerConfiguration) =>{
   Serilog.Debugging.SelfLog.Enable(Console.WriteLine);
   loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration)
   .WriteTo.Email(
      new EmailConnectionInfo {
      FromEmail = "{email}",
      ToEmail = "{email}",
      MailServer = "{SMTP IP}",
      Port = {PORT},
      EnableSsl = false,
      EmailSubject = "Something to log",
      ServerCertificateValidationCallback = (senderX, certificate, chain, sslPolicyErrors) => true
   },
   outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}",
   batchPostingLimit: 1,
   restrictedToMinimumLevel: LogEventLevel.Warning);
});

But, when I try to include all my serilog settings for Email sink in appsettings.json the "ServerCertificateValidationCallback": "(senderX, certificate, chain, sslPolicyErrors) => true" cannot be read (my assumption)
my appsettings.json
"Serilog": {
    "Using": [ "Serilog.Sinks.File","Serilog.Sinks.Email" ],
    "MinimumLevel": "Information",
    "WriteTo": [
      ...
      {
        "Name": "Email",
        "Args": {
          "connectionInfo": {
            "MailServer": "{SMTP IP}",
            "Port": {PORT},
            "EnableSsl": false,
            "FromEmail": "{email}",
            "ToEmail": "{email}",
            "EmailSubject": "Something went wrong",
            "ServerCertificateValidationCallback": "(s, cert, chain, sslPolicyErrors) => true"
          },
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}",
          "restrictedToMinimumLevel": "Warning",
          "batchPostingLimit": 1
        }
      }
    ],
    "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ]
  }
...

Any ideas?
Edit: The githut issue I opened

A: As you can see in Mailkit's source code, it uses SecureSocketOptions.StartTlsWhenAvailable when enableSsl is false. TLS is available in your Exchange server, so it's trying to use it...
If Serilog.Sinks.Email ever exposes a way of changing this behavior (issue 69 that you reported), that would be a workaround, but I believe the correct fix is to update your Exchange configuration to use the correct certificate that was installed for TLS communication on this connector.
When TLS is established inbound, the server is likely grabbing the closest match based upon name (self-signed certificate).
Your IT Administrator should be able to update the TLS certificate following the steps described on this post "Configuring the TLS Certificate Name for Exchange Server Receive Connectors".

A: I was able to get this working leveraging a few other questions and without the support for the callback being able to set this directly via configuration.  This question's answer (https://stackoverflow.com/a/59914193/116208) was particularly helpful.  If you follow his example there with a few modifications.
You can add the ServerCertificateValidationCallback = (senderX, certificate, chain, sslPolicyErrors) => true to the EmailConnectionInfo in the SerilogEmailExtension extension class
Adjust the Serilog configuration "Using" statement to include your compiled application's name so it can find the extension class instead of "MyApp":
"Using": [ "Serilog", "Serilog.Sinks.Console", "Serilog.Sinks.File", "MyApp" ],

This should let you achieve everything to be configuration driven, and still add in the callback to bypass the exception.


text:
Q: Use a thread in a QT Gui. It is destroyed I have a QT GUI . When I clic on a QPushButton, a calculation loop is called from another class which heritate from QThread. However, I have an error QThread: destroyed while thread is still running. I do not want to use pointers. I provide my minimal example below:
MainWindow.cpp
#include "MainWindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);
    QObject::connect(this->ui.pushbutton, SIGNAL(clicked()), this, SLOT(process()));
}

void MainWindow::process()
{
    ListCalc m_Calcul(this);
    m_Calcul.start(); // This is the action I would like to put in a thread !
}

MainWindow.h
#include "ListCalc.h"

using namespace std;

namespace Ui {
    class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

private:
    Ui::MainWindowClass ui;

public:
    MainWindow(QWidget *parent = Q_NULLPTR);
    ListCalc m_Calcul;

private slots:
    void process();
};

ListCalc.cpp
#include "ListCalc.h"

ListCalc::ListCalc(QMainWindow *parent)
{

}

ListCalc::~ListCalc()
{

}

void ListCalc::run()
{
    auto size = 30000;
    for (auto i = 0;i < size;++i)
    {
        std::cout<<i<<std::endl;
    }
}

ListCalc.h
class ListCalc : public QThread
{
    Q_OBJECT

public:
    ListCalc(QMainWindow *parent);
    ~ListCalc();
    void run();

};

Do you have any idea of what is the problem?


text:
Q: Add Cell in the Table View Controller In my application, there's a Navigation View(Embed In), a Table View Controller, and a View Controller. And in the ViewController.h, there are...
@property (strong, nonatomic) IBOutlet UILabel *timeDisplay;
@property (strong, nonatomic) IBOutlet UILabel *minuteDisplay;
@property (strong, nonatomic) IBOutlet UILabel *timerDisplay;
@property (strong, nonatomic) IBOutlet UILabel *titleLabel;

and more outlets. The code below is TableViewController.m file. I have a action button(plusbtn), which needs to add a cell in the table view. So, I tried to make the 'plusbtn' do it, but it didn't work. What should I do? Please help me...
#import "TableViewController.h"

#import "TableViewCell.h"

#import "ViewController.h"

@interface TableViewController ()

@property (nonatomic) ViewController *viewController;
@property (strong, nonatomic) NSMutableArray *titleArray;
@property (strong, nonatomic) NSMutableArray *tsArray;
@property (strong, nonatomic) NSMutableArray *tmArray;
@property (strong, nonatomic) NSMutableArray *ttArray;
@property (strong, nonatomic) NSString *cellplustitle;
@property (strong, nonatomic) NSString *cellplustime;
@property (strong, nonatomic) NSString *cellplusmin;
@property (strong, nonatomic) NSString *cellplussec;

@end

@implementation TableViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _cellplustitle = self.viewController.titleLabel.text;
    _cellplustime = self.viewController.timeDisplay.text;
    _cellplusmin = self.viewController.minuteDisplay.text;
    _cellplussec = self.viewController.timerDisplay.text;
    self.titleArray = [NSMutableArray new];
    self.tsArray = [NSMutableArray new];
    self.tmArray = [NSMutableArray new];
    self.ttArray = [NSMutableArray new];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return self.titleArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TableViewCell" forIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.celltitle.text = [self.titleArray objectAtIndex:indexPath.row];
    cell.cellmd.text = [self.tmArray objectAtIndex:indexPath.row];
    cell.cellsd.text = [self.tsArray objectAtIndex:indexPath.row];
    cell.celltd.text = [self.ttArray objectAtIndex:indexPath.row];

    // Configure the cell...

    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)plusbtn:(id)sender {
    [self.tableView beginUpdates];

    [self.titleArray addObject:self.cellplustitle];
    [self.tsArray addObject:self.cellplussec];
    [self.tmArray addObject:self.cellplusmin];
    [self.ttArray addObject:self.cellplustime];
    NSIndexPath *indexPathOfNewItem = [NSIndexPath indexPathForRow:(self.titleArray.count - 1) inSection:0];
                         [self.tableView insertRowsAtIndexPaths:@[indexPathOfNewItem] withRowAnimation:UITableViewRowAnimationAutomatic];

                         [self.tableView endUpdates];
                         [self.tableView scrollToRowAtIndexPath:indexPathOfNewItem atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
@end

A: ReloadData should work. If its not working if you put if between beginUpdate and endupdate, then comment rest code and simply try to reload table view after adding item in array. Like...
- (IBAction)plusbtn:(id)sender {
[self.titleArray addObject:self.cellplustitle];
[self.tsArray addObject:self.cellplussec];
[self.tmArray addObject:self.cellplusmin];
[self.ttArray addObject:self.cellplustime];
[self.tableview reloadData];}

Hope this helps?

A: you have to reload the uitableview using
[self.tableView reloadData];

Hope it helps!


text:
Q: Can't get data to object I'm trying to grap json data from mongodb, put it into a class objec and then print one parameter to console, but I get this error  :
Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: O. Path '_id', line 1, position 10.'

My json looks like this:
{ "_id" : ObjectId("5d72b79c58011725b8b31b10"), "length" : NumberLong(957608), "
chunkSize" : 64512, "uploadDate" : ISODate("2019-09-06T19:46:42.058Z"), "md5" :
"3965979118e1302a7d19f609f38ede3e", "filename" : "C:\\Users\\kbu\\Downloads\\hve
m-er-vi.jpg", "metadata" : { "Beloeb" : "", "Overskrift" : "", "Gruppe" : "", "B
eskrivelse" : "", "Dato" : "6. september 2019", "Afsender" : "Lars" } }

I suspect, it has to do with my class, but I can't figure out what.
This is my code:
    class Program
    {
        static void Main(string[] args)
        {
            var client = new MongoClient("mongodb+srv://*********:*********@kbucluster-oslh9.mongodb.net/test?retryWrites=true&w=majority");
            var database = client.GetDatabase("test");
            var collec = database.GetCollection<BsonDocument>("fs.files");

            var filter = Builders<BsonDocument>.Filter.Empty;
            var result = collec.Find(filter).ToList();

            foreach(var doc in result)
            {
                Console.WriteLine(doc.ToJson());

                RootObject bilag = JsonConvert.DeserializeObject<RootObject>(doc.ToJson());

                Console.WriteLine(bilag.ID);
            }
            Console.ReadKey();
        }
    }

    public class Metadata
    {
        public string Beloeb { get; set; }
        public string Overskrift { get; set; }
        public string Gruppe { get; set; }
        public string Beskrivelse { get; set; }
        public string Dato { get; set; }
        public string Afsender { get; set; }
    }
    public class RootObject
    {
        public string ID { get; set; }
        public string Length { get; set; }
        public string ChunkSize { get; set; }
        public string UploadDate { get; set; }
        public string MD5 { get; set; }
        public string Filename { get; set; }
        public Metadata Metadata { get; set; }
    }
}

A: You can use the following method
object dotnetObject = BsonTypeMapper.MapToDotNetValue(bsonDocument);

// Json mapped to default .Net objects
string json = Newtonsoft.Json.JsonConvert.SerializeObject(dotnetObject);

// Parsing as JObject
var jobject = JObject.Parse(json);

// Deserializing as your custom Type
var myObject = JsonConvert.DeserializeObject<MyType>(json);

A: You can't have functions in your JSON
"_id" :ObjectId("5d72b79c58011725b8b31b10"), "length" : NumberLong(957608),"uploadDate" : ISODate("2019-09-06T19:46:42.058Z")

Parse error on line 1:
{ "_id" : ObjectId("5d72b79c58
----------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'

A: 1-Wrong value _id key : "what is ObjectId method in json"?
2-wrong name _id : beacause in RootObject class ,property is ID!
3- you must remove ObjectId , NumberLong , ISODate With their braces
{ "ID" : "5d72b79c58011725b8b31b10", "Length" : "957608", "
ChunkSize" : "64512", "UploadDate" : "2019-09-06T19:46:42.058Z", "MD5" :
"3965979118e1302a7d19f609f38ede3e", "FileName" : "C:\\Users\\kbu\\Downloads\\hve
m-er-vi.jpg", "Metadata" : { "Beloeb" : "", "Overskrift" : "", "Gruppe" : "", "B
eskrivelse" : "", "Dato" : "6. september 2019", "Afsender" : "Lars" } }

A: you don't need json.net if you match the property names/types of the RootObject like this:
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
using System;

namespace StackOverflow
{
    public class Program
    {
        public class Metadata
        {
            public string Beloeb { get; set; }
            public string Overskrift { get; set; }
            public string Gruppe { get; set; }
            public string Beskrivelse { get; set; }
            public string Dato { get; set; }
            public string Afsender { get; set; }
        }

        public class RootObject
        {
            [BsonId] // need to add this
            public ObjectId ID { get; set; }
            public int length { get; set; }
            public double chunkSize { get; set; }
            public DateTime uploadDate { get; set; }
            public string md5 { get; set; }
            public string filename { get; set; }
            public Metadata metadata { get; set; }
        }

        private static void Main(string[] args)
        {
            var collection = new MongoClient("mongodb://localhost")
                                    .GetDatabase("test")
                                    .GetCollection<RootObject>("fs.files");

            var result = collection.Find(Builders<RootObject>.Filter.Empty).ToList();

            foreach (var doc in result)
            {
                Console.WriteLine(doc.ToJson());
                Console.WriteLine("");
                Console.WriteLine(doc.ID.ToString());
                Console.Read();
            }
        }
    }
}


text:
Q: How to override method and call base in stub with Microsoft Fakes I'd like to do an override with MS Fakes that would call the base code and I can't find how to do it. Here's an example
Given
public class Potato
{
   public virtual string Peel(PeelingMethod peelingMethod)
   {
      return "potato peeled";
   }
}

When I create my Stub
new StubPotato()
{
    PeelPeelingMethod = (p) =>
    {
       //Doesn't compile!
       base.Peel(p);
       Console.WriteLine("Hello world");
    }
}

How can I achieve this, I am pretty new to the MS Fakes framework so maybee there is something i don't know about it.

A: I found a solution, it is pretty disgusting but it works. I'll put it here if someone needs. I'll reuse my example (that I edited because I didn't test this answer with a method that returns void)
var stubPotato = new StubPotato()
{
    PeelPeelingMethod = (p) =>
    {
        //Base method call
        MethodInfo methodInfo = typeof(Potato).GetMethod("Peel", BindingFlags.Instance | BindingFlags.Public);
        var methodPtr = methodInfo.MethodHandle.GetFunctionPointer();
        var baseMethod = (Func<PeelingMethod,string>)Activator.CreateInstance(typeof(Func<PeelingMethod,string>), stubPotato , methodPtr);
        string baseResult = baseMethod(p);

        //Code for the "override"
        Console.WriteLine("Hello world");
    }
}


text:
Q: Changing onfocus with JavaScript I have a conditional statement that does this if a condition is met.
My if statement is fine, everything else works perfectly.
The idea is that if a certain checkbox is ticked, one of the text input will be set to a certain value and become uneditable. I am having problems with this line. Is there a better way to do this? I cannot figure out what's wrong!
document.getElementById('amount').onfocus = "this.blur()";

A: How about disabling it
document.getElementById('amount').disabled = true;

or making it read only
document.getElementById('amount').readOnly = true;

FIDDLE

A: try
onFocus = function(){return false;}

or you can use the readonly attribute in your input tag. But i'm not sure if it work in all browsers.


text:
Q: How do I do dependency injection in a python's pyramid view callable? Suppose I have a class
from pyramid.request import Request
from pyramid.view import view_config

def includeme(config):
    config.add_route('items', '/v1/items'

class MyView():
    def __init__(self, item: Item = None, booksvc: BookService = None, magazinesvc: MagazineService = None):
        self.booksvc = booksvc or BookService(self.)
        self.magazinesvc = magazine or MagazineService()
        self.item = item or Item(booksvc)

    @view_config(route_name='items', request_method='GET')
    def get_items(self):
        foo = self.item.bar()
        # do some more stuff
        return foo

How do I inject all of the dependencies (item, booksvc, and magazinesvc) to the view?

A: To do this you'll need to define a custom view mapper which is the resource that is responsible for invoking a view. I'm unaware of any view mappers that come out of the box that will do this for you so I can only point you at the docs to write one yourself.
https://docs.pylonsproject.org/projects/pyramid/en/latest/narr/hooks.html#using-a-view-mapper


text:
Q: Thymeleaf: Iterating over elements of property of object of form I have a thymeleaf form which I would like to make dynamic, without using JS. The form should fill an object of class ProjectNewDto
public class ProjectNewDto {

    private List<UsernameAndPps> usernamesAndPps;

    ...
}

Therefore holding a list of UsernameAndPps elements:
public class UsernameAndPps {
    private String username;
    private double pps;

    ...
}

The controller puts the object as an attribute of the model and intialize the list of usernamesAndPps with a single element:
@RequestMapping("/projectNewPageR")
public String projectNewPage(Model model) {
    if(!model.containsAttribute("project")) {
        ProjectNewDto project = new ProjectNewDto();
        project.setUsernamesAndPps(new ArrayList<UsernameAndPps>());
        project.getUsernamesAndPps().add(new UsernameAndPps("user",100.0));

        model.addAttribute("project",project);
    }
    return "views/projectNewPage";
}

And then I try to show it with thymeleaf as
<form id="new_project_form" action="#" th:action="@{/views/projectNewSubmit}" th:object="${project}" method="post">
    <div th:each="usernameAndPps : $(project.usernamesAndPps)">
        <input type="text" th:value="${usernameAndPps.username}"></input>
        <input type="number" th:value="${usernameAndPps.pps}"></input>
    </div>
    <button type="submit" class="btn btn-lg btn-primary btn-block">Create</button>
</form>

I have also tried with $(usernamesAndPps) instead of $(project.usernamesAndPps), but the error remains the same:
Could not parse as each: "usernameAndPps : $(project.usernamesAndPps)"

I have removed a lot of other sytle related suff, but the is still an error of some kind. Any ideas?
The next step will be to add another button to add elements to the usernamesAndPps property. Lets keep positive here.

A: Ok, I answer it, but I should delete it.
Braces instead of parentheses
<div th:each="usernameAndPps : ${project.usernamesAndPps}">


text:
Q: Django Admin: 'id' is not a callable or method of model? It's in the question. Why would my model not have the 'id' attribute? Isn't that created by default in Django?
from django.contrib import admin

# Register your models here.
from .models import Risk, Impact

class RiskAdmin(admin.ModelAdmin):
    list_display = ('id','risk_title')

admin.site.register(Risk, RiskAdmin)
admin.site.register(Impact)

As you can see, I'm trying to add 'id' to the list_display under my RiskAdmin section. However, I'm getting an error stating that 'id' is not an attribute of the model.


text:
Q: No matching function to call C++ #include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main()
 {
setlocale (LC_ALL, "rus");
string path = "MyFile.txt";
ifstream fin;
fin.open(path);

if (!fin.is_open())
{
    cout<< "Fail" << endl;
}
else
{
    cout << "Is OK!" << endl;
}
fin.close();

return 0;
 }

Выдает ошибку no matching function for call to 'std::basic_ifstream<char, std::char_traits >::open(std::string&) в строке fin.open(path);

A: Если с++11 недоступен, попробуйте path.c_str()


text:
Q: Most efficent way to save custom settings My VS2013 VB app currently saves settings to the Registry and it has grown to the point this is bothering me. So I want to save the settings (strings) to files. A bonus is they can then be on the network and used by multiple users. There may be hundreds, even thousands of lines. What is the preferred format to use? The old INI, CSV, XML? The Settings files don't appear to be a good option in this case so far as I can see.

A: I would strongly recommend creating object of a class and use serialization to XML for .NET applications. It is easy to implement, fully supported and you can import and export settings from one computer to another. you can even set your application to ready the settings from network. In addition, It will make future programming / upgrades easier.
I am listing here a working example ( Tested ). The code is in use since 2012 and working perfectly for an enterprise level application.
Note: I only included one " setting item " for demo so you add your own.
First : Settings or Options Class :
Imports System.Xml.Serialization
Imports System.IO

<Serializable()> _
Public Class Options

    Public KEYS_USE_LISTS As Boolean

    Public Sub New()
        KEYS_USE_LISTS = True
    End Sub

#Region "Methods"

    Public Sub Save(ByVal Path As String)
        Try
            Dim _XMLSerilizer As New XmlSerializer(GetType(Options))
            Dim _StreamWriter As New StreamWriter(Path)
            _XMLSerilizer.Serialize(_StreamWriter, Me)
            _StreamWriter.Close()
        Catch ex As Exception
            MsgBox("Error saving database setting." & vbCrLf & "Internal Error: " & ex.Message)
        End Try
    End Sub

    Public Function DoLoad(ByVal Path As String) As Options
        Dim _Opt As New Options
        Try
            If IO.File.Exists(Path) Then
                Dim _XMLSerilizer As New XmlSerializer(GetType(Options))
                Dim _FileStream As New FileStream(Path, FileMode.Open)

                _Opt = DirectCast(_XMLSerilizer.Deserialize(_FileStream), Options)
                _FileStream.Close()
            End If
        Catch ex As Exception
            MsgBox("Error loading database setting." & vbCrLf & "Internal Error: " & ex.Message)
        End Try
        Return _Opt
    End Function

#End Region

End Class

Second : Use it through interface ( WinForms for example )
Public Class frmOptions

    Public _options As New Options

    Private Sub frmOptions_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        If IO.File.Exists(Application.StartupPath & "/_Options.opt") Then
            _options = _options.DoLoad(Application.StartupPath & "/_Options.opt")
        End If

        chkUseList.Checked = _options.KEYS_USE_LISTS

    End Sub

    Private Sub btnOk_Click(sender As Object, e As EventArgs) Handles btnOk.Click

        If IO.File.Exists(Application.StartupPath & "/_Options.opt") Then
            _options = _options.DoLoad(Application.StartupPath & "/_Options.opt")
        End If

        _options.KEYS_USE_LISTS = chkUseList.Checked
        _options.Save(Application.StartupPath & "/_Options.opt")

        Me.DialogResult = Windows.Forms.DialogResult.OK
        Me.Close()

    End Sub

End Class


text:
Q: IOS: Store and Access large datasets efficiently I have multiple JSON files which each contain about a hundred thousand quotes.
I am trying to search through all these quotes, so I need to be able to access them quickly.
It is very slow to load all these files into memory and then parse them.
What is the fastest way to store and access this kind of data on IOS? I know the SQLDatabase would be fast, but I am not adding any data once the app is running. It is all preset.
If the built in CoreData SQLDatabase is the fastest way, how can I prestore data in there? I don't want to add anything once the app is running.
Can someone please point me in the right direction, for storing all this static data in the  way which is quickest to access?
Thanks a lot for the help.


text:
Q: Screenshot every layer from a geoJSON object, failing to zoom to extents of each layer correctly What I've been trying to do is I have a ton of geoJSON files (a few thousand) and I need to load them, change the colors of the Polygons and background to white and black, then export them as an image. Like the one below...
Though I've had a lot of trouble, I now can load all the geoJSON layers (though some of the geoJSON layers have nothing in them...so it loads up as Unknown in QGIS). I add the geojson layer to a LAYERS list that I use later, add the symbols, set the extent to that layer, and repeat.
Then, to screenshot each image, I iterate through the LAYERS list, set my extent to each layer, and screenshot it.
However, the screenshots are not correctly viewing the layer.
My code is below.
I'm not very familiar with QGIS and PyQGIS
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from qgis.core import *
import os
import sys
from time import sleep

NUMBER_OF_GEOJSON_FILES = 580
GEOJSON_DIR = "C:\\path\\to\\geojson"
IMAGE_DIR = "C:\\path\\to\\destination"
FILENAME = "filename_format_img"

#Set canvas color to black
iface.mapCanvas().setCanvasColor(QColor.fromRgb(0,0,0))

print GEOJSON_DIR
print IMAGE_DIR
print FILENAME

LAYERS = []

def loadGeoJSON():
    i = 570
    while i <= NUMBER_OF_GEOJSON_FILES:
        #Load geojson
        print(GEOJSON_DIR + FILENAME + str(i) + ".geojson")
        layer = iface.addVectorLayer(GEOJSON_DIR + FILENAME + str(i) + ".geojson", "layer", "ogr")
        LAYERS.append(layer)

        #Set symbol colors, if no symbols do nothing
        try:
            symbols = layer.rendererV2().symbols()
            symbol = symbols[0]
            symbol.setColor(QColor.fromRgb(255,255,255))
        except AttributeError:
            print "No symbols"

        #Zoom to layer
        iface.mapCanvas().setExtent(layer.extent())
        i = i + 1

def exportImages():
    i = 1
    for j in LAYERS:
        sleep(3)
        #Zoom to layer
        iface.mapCanvas().setExtent(j.extent())
        # Take screenshot
        print("Screen Shotting:  " + IMAGE_DIR + FILENAME + str(i) + ".png")
        iface.mapCanvas().saveAsImage(IMAGE_DIR + FILENAME + str(i) + ".png")
        i = i + 1

loadGeoJSON()
exportImages()

A: After setting the current layer extent, you would need to refresh the map display
iface.mapCanvas().refresh()

If you want to do a particular action when the layer is empty, you can count the features
layer.featureCount()

The function would look like:
def exportImages():
    i = 1
    for j in LAYERS:
        sleep(3)

        if j.featureCount() == 0:
          #do something with empty layer... (skip, copy a blank image etc)
        else:
          #Zoom to layer
          iface.mapCanvas().setExtent(j.extent())
          iface.mapCanvas().refresh()
          # Take screenshot
          print("Screen Shotting:  " + IMAGE_DIR + FILENAME + str(i) + ".png")
          iface.mapCanvas().saveAsImage(IMAGE_DIR + FILENAME + str(i) + ".png")
        i = i + 1


text:
Q: warning: control may reach end of non-void function [-Wreturn-type] How am I not returning any values within the following function?
bool operator<=(string a, const Zoo& z) {
// Pre: none
// Post: returns true if animal a is in Zoo z.
//       the owner does not count as an animal.

    for ( int i=0; i< z.count; i++ ) {
        if (z.cage[i] == a){
            return true;
        }

        else {
          return false;
        }
    }
}

A: Your function returns a bool but there's a potential code path (e.g. z.count is 0) where it may reach the end of the function and return nothing. Hence, the warning issued by the compiler.
Add return false; (or return true; but false seems appropriate with your current logic) at the end of your function.
As pointed out by others, your else part is also wrong. I'd rewrite it as:
bool operator<=(string a, const Zoo& z) {
// Pre: none
// Post: returns true if animal a is in Zoo z.
//       the owner does not count as an animal.

  for ( int i=0; i< z.count; i++ ) {
       if (z.cage[i] == a){
          return true;
        }
   }
   return false;
}

A: You accidentally put the "not found" case as the else branch inside of your loop body. This means that if the first item is not the one you're looking for, you already exit the loop.
This has of course two problems: if the element you're looking for is at another position, you don't find it. Also, if z.cage is empty, you don't enter the loop and no value is returned, that's what the compiler tells you with the warning.
Solve the problem by removing the else branch. Only after the loop, return false since then you know that the element hasn't been found.


text:
Q: ShouldBeUnique cannot be used for Queued Event Listeners How can I use ShouldBeUnique with Queued Event Listeners?
Queued Event Listeners Code:
namespace App\Listeners\Test;

use App\Events\Test\RollEvent;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class CapterBEventListener implements ShouldQueue, ShouldBeUnique
{
    use InteractsWithQueue;

    public $uniqueFor = 3600;

    public function handle(RollEvent $event)
    {
        echo 'RoolEventB' ,PHP_EOL;
        sleep(10);
        echo 'over--',PHP_EOL;
    }

    public function uniqid(RollEvent $event)
    {
        return 5;
    }
}

Test in tinker:
$ php artisan queue:restart
for($i = 0; $i < 2; $i++) event(new App\Events\Test\RollEvent(5))

Execution results are not unique:
> [2022-04-30 18:29:17][VlGCdjmgniuAKbFuJ6QL7t7jLuhxzEN6] Processing: App\Listeners\Test\CapterBEventListener
> RoolEventB
> over--
> [2022-04-30 18:29:27][VlGCdjmgniuAKbFuJ6QL7t7jLuhxzEN6] Processed: App\Listeners\Test\CapterBEventListener
> [2022-04-30 18:29:27][uh4p7EuDmVSVEf17SrbcoUdKNQ1xVKzo] Processing: App\Listeners\Test\CapterBEventListener
> RoolEventB
> over--
> [2022-04-30 18:29:37][uh4p7EuDmVSVEf17SrbcoUdKNQ1xVKzo] Processed: App\Listeners\Test\CapterBEventListener

Used ShouldBeUnique in unique-jobs:
namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class TestPodcast implements ShouldQueue, ShouldBeUnique
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function handle()
    {
        echo 'handle start', PHP_EOL;
        sleep(10);
        echo 'handle end', PHP_EOL;
    }

    public function uniqueId()
    {
        return 5;
    }
}

Test in tinker:
for($i = 0; $i < 2; $i++) App\Jobs\TestPodcast::dispatch();

Execution result is unique:
> [2022-05-01 10:47:30][jaEFh5PeZGVeVsDRVKD3qok5LiQ7E7ub] Processing: App\Jobs\TestPodcast
> handle start
> handle end
> [2022-05-01 10:47:30][jaEFh5PeZGVeVsDRVKD3qok5LiQ7E7ub] Processed: App\Jobs\TestPodcast

How can I use ShouldBeUnique in Queued Event Listeners


text:
Q: Algorithm for finding all nonnegative integer solutions of $x_1 + x_2 + x_3 = 4$ I need an algorithm to show all the solutions of $x_1+x_2+x_3=4$ to write a MATLAB program. I don't want to use random function. (I wrote a program with random function, but is very slow)
please help me.
I need to show something like this(this is the result with random function)
 1     3     0
 3     0     1
 0     0     4
 1     2     1
 2     2     0
 1     0     3
 0     4     0
 0     3     1
 1     1     2
 4     0     0
 0     2     2
 0     1     3
 3     1     0
 2     0     2
 2     1     1

A: Here is a solution in Python where you can set $N$ and $S$ as you want :
N = 3 # Number of variables
S = 4 # Sum of variables

def f(array,n):
    s = sum(array)
    if n == 1:
        print array + [S-s]
    else:
        for i in xrange(0,S+1-s):
            f(array + [i],n-1)

f([],N)

This should in theory be optimal since there are no if-statements that could discard any computation.

A: Use recursion on the number of terms. The first term $x_1$ can be $0$, $1$, $2$, $3,$ or $4$, and for a given choice of$~x_1$, the remaining terms run though all solutions of $x_2+x_3=4-x_1$.
The function does not have to be recursive if the depth is fixed, as in your example. Simply
for i from 0 to 4
  for j from 0 to 4-j
    print (i, j, 4-i-j)

will do (sorry I don't speak MATLAB, but I hope you get the idea). If you want the number of terms to be given in a variable, the depth is not fixed and you need recursion (with a recursive call inside a loop) to obtain the effect of an unknown number of nested loops.


text:
Q: Ruby on Rails bootstrap modal I'm trying use bootstrap modal with ajax, the problem is that when i click the screen gets darker but the modal never shows.
Any help or is there a better way of doing this?

measures/index.html.erb
 <%= link_to 'Show', measure,remote: true, class: 'static-popup-link'%>

Loading...

application.js
$(document).ready(function() {

  var clickOnPopupLink = function(){
      $('body').on('click', '.static-popup-link', function(){
      $('#myModal').modal('show');
   });
  }

  clickOnPopupLink();

});

measures_controllers.rb
def show
end

show.js.erb
$('#myModal').html("<%= j render('/measures/modal')%>");

measures/modal.html.erb

      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×          </button>

       .........

      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
     <button type="button" class="btn btn-primary">Save changes</button>

A: Removing hide class from below mentioned div will serve your purpose

Loading...


text:
Q: php libreoffice shell_exec not working I am trying to convert .docx file to .html using php shell_exec in CentOS 6.5
My php code:
 $command = "libreoffice --headless -convert-to html resume.docx 2>&1";
 $result = shell_exec($command);
 echo $result;

When I run the index.php at http://localhost/converter/ it gives me:

javaldx: Could not find a Java Runtime Environment! Warning: failed to read path from javaldx /usr/lib64/libreoffice/program/soffice.bin X11 error: Can't open display: Set DISPLAY environment variable, use -display option or check permissions of your X-Server (See "man X" resp. "man xhost" for details)`

while in terminal it is working perfectly:
cd /var/www/html/converter/
libreoffice --healdess -convert-to html resume.docx
here it creates resume.html in my /var/www/html/converter/.

A: Hi i have the same problem, i want to convert PDF's from DOCS created with PHP, i'm using OpenSuse 12.3 with LibreOffice, tried many things, finally i detect that the error is in folder:
1.- First check that you don't have disabled shell_exec in php.ini, and open_basedir don't restrict your access folders.
2.- Run the command as a simple user in shell (terminal)
export HOME=/tmp && soffice --headless --convert-to pdf --outdir /srv/www/htdocs/ /srv/www/htdocs/Creecimientos/sic/app/webroot/usuarios/2/8_Pagare_CreePersonas.docx
3.- If it works, you only have to put the correct folders in your code, when i run this code in PHP, it show me a blank page, so i check the access_log of apache for any hint:
[Java framework] Error in function createSettingsDocument (elements.cxx).
javaldx failed!
Warning: failed to read path from javaldx
terminate called after throwing an instance of 'com::sun::star::uno::RuntimeException'
Note: my error was in using export HOME=/tmp, i checked that the folder in root system has 777 for tmp, but the problem was that apache don't acces to it, maybe search for a relative folder of the script, but after test many things i only put a folder with permissons for wwwrun HOME=/srv/www/htdocs/folder_with_777
This is my final code, that works..
<?php
     function word2pdf()
        {
        echo "Procesando";
       $result = shell_exec('export HOME=/srv/www/htdocs/Creecimientos/sic/ && soffice --headless --convert-to pdf --outdir /srv/www/htdocs/Creecimientos/sic/ /srv/www/htdocs/Creecimientos/sic/app/webroot/usuarios/2/8_Pagare_CreePersonas.docx');
       echo $result;
        }

        word2pdf();
?>

In fact, it prints: convert srv/www/htdocs/Creecimientos/sic/app/webroot/usuarios/2/8_Pagare_CreePersonas.docx -> /srv/www/htdocs/Creecimientos/sic//8_Pagare_CreePersonas.pdf using writer_pdf_Export, after succes.
I made other changes before in desesperate mode, but none of them solved the problem, tried to change owner to soffice wich found it witch $ ls -l $(which libreoffice), tried with 777, etc..

A: /* This command will work on centos 6 /7 with installation of libreoffice headless package */
First install package on centos as :
yum install libreoffice-headless

/* following code work to extract text format from */
<?php
 $result = exec("export HOME=/tmp/ && /usr/bin/libreoffice --headless   --convert-to txt:Text --outdir /tmp filePath");
 var_dump($result);
?>

A: Most likely the user that LibreOffice is ran as, does not have a writeable home directory so LibreOffice fails to create it's config directory and then it cannot create it's config files and then fails to load Java, because it cannot write the default config. A bit silly I know.
Try adding this parameter: -env:UserInstallation=file:///tmp/whateverhere

A: I don't have enough reputation to comment on TD_Nijboer's answer, but the answer to his specific problem appears to be that soffice needs to be able to read & write config information somewhere. The first place it tries to do this is the libreoffice directory in ~/.config ('~' means "the current user's home directory").
In Debian, by default, the www-data user has the home directory /var/www, and does not have write permission there.
If you make sure it has permission to either create ~/.config itself, or libreoffice within an existing ~/.config, I expect it will work.

A: 2 things, 1st the command is soffice --headless,
2nd i have an similar javaldx error and it has to do with permission.
when executing as root it works fine, but php executes as www-data.
if anybody knows a good way to execute libreoffice from php please let me know.
as i'm getting an error code 77 saying:
[Java framework] Error in function createSettingsDocument (elements.cxx).
javaldx failed!
Warning: failed to read path from javaldx


text:
Q: check url without http and ".com" I would like to check if the given url is valid.
It should accept:
www.gmail.com

and should reject:
www.gmail

I tried using this /((ftp|http|https):\/\/)?(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
It works but if the given input is www.gmail it does accepts it.
Any Ideas?
UPDATE
http://jsfiddle.net/aabanaag/VktaX/

A: try this .It is working for me
<script type="text/javascript">
    function validate() {
        var url = document.getElementById("url").value;
        var pattern = new RegExp("^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.){1}([0-9A-Za-z]+\.)");
        if (pattern.test(url)) {
            alert("Url is valid");
            return true;
        }
            alert("Url is not valid!");
            return false;

    }
</script>

In jQuery
you can use url validation
<input type="text" class="url"/>

A: You could use Jquery Validate plugin for that.
$("#myform").validate({
  rules: {
    field: {
      required: true,
      url: true
    }
  }
});

You can find about it here

A: solved my problem:
found this while googling over the internet.
 /^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.){1}[0-9A-Za-z\.\-]*\.[0-9A-Za-z\.\-]*$/

var pattern1 = /^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.){1}[0-9A-Za-z\.\-]*\.[0-9A-Za-z\.\-]*$/;

var result = "www.gmail";

if (pattern1.test(result)) {
    console.log("test");
}else{
    console.log("fail");
}

It works best.


text:
Q: Show that $\zeta(2,2) = \frac{3}{4} \zeta(4)$ by integrating $\int \frac{dx}{x} \wedge \frac{dx}{x} \wedge \frac{dx}{1-x} \wedge \frac{dx}{1-x}$ On Wikipedia there's an OK discussion of multiple zeta values (MZV).  We have an identity:
$$ \zeta(2,2) = \sum_{m > n > 0} \frac{1}{m^2 \, n^2}  = \frac{3}{4}  \sum_{n > 0} \frac{1}{ n^4}  = \frac{3}{4} \zeta(4) $$
This formula might already be on the Math.Stackexchange site (link?) Also notice that somehow the zeta function turns partly into an element of $\mathbb{Q}$.  I have already found an argument using one of the special cases of the shuffle formula.
$$ \zeta(2)^2 = 2 \, \zeta(2,2) + \zeta(4)  $$
Certainly, there still a search for even more $\zeta$-functions of this kind.  Both sides of this equation have integral formulas (due to Drinfiel'd):
\begin{eqnarray*} \zeta(2,2) &\stackrel{?}{=}& \int_{1 > x_1 > x_2 > x_3  > x_4 > 0}
\frac{dx_1}{x_1} \wedge
\frac{dx_2}{1-x_2} \wedge
\frac{dx_3}{x_3} \wedge
\frac{dx_4}{1-x_4}  \tag{$*$}\\ \\
\zeta(4) &\stackrel{?}{=}& \int_{1 > x_1 > x_2 > x_3  > x_4 > 0}
\frac{dx_1}{x_1} \wedge \;\;
\frac{dx_2}{x_2} \;\;\wedge
\frac{dx_3}{x_3} \wedge
\frac{dx_4}{1-x_4} \tag{$**$}
 \end{eqnarray*}
Even now, I'm not totally convinced the integrals on the right side, represent the infinite series on the left side.  But also, I wonder if there's a stronger notion of equivalence than just that they evaluate to the same number.  We have just shown that $\zeta(2,2)$ and $\zeta(4)$ are periods These notes of José Ignacio Burgos Gil and Javier Fresán indicate the following:

From the modern point of view, periods appear
  when comparing de Rham and Betti cohomology of algebraic varieties over
  number fields.

So, my other question is whether these two 4-forms are the same.  Possibly over $\mathbb{C} \backslash \{ 0,1\}$ or $\mathbb{P}^1 \backslash \{ 0,1, \infty\}$ :
\begin{eqnarray*} \omega_1 &=&
\frac{dxt_1}{x_1} \wedge
\frac{dx_2}{1-x_2} \wedge
\frac{dx_3}{x_3} \wedge
\frac{dx_4}{1-x_4} \\ \\
\omega_2 &=&
\frac{dx_1}{x_1} \wedge \;\;
\frac{dx_2}{x_2} \;\;\wedge
\frac{dx_3}{x_3} \wedge
\frac{dx_4}{1-x_4}
 \end{eqnarray*}
And I would ask is there a sense in which $\omega_1 = \omega_2$?  Mostly I just want help with the integrals.

A: If $f(m,n)=f(n,m)$, by symmetry
$$\sum_{m>n>0}f(m,n) = \frac{1}{2}\left[\Big(\sum_{n>0}f(n)\Big)^2-\sum_{n>0}f(n)^2\right] $$
hence
$$ \zeta(2,2) =\frac{\zeta(2)^2-\zeta(4)}{2}=\frac{\frac{5}{2}\zeta(4)-\zeta(4)}{2}=\frac{3}{4}\,\zeta(4)$$
since $\zeta(4)=\frac{2}{5}\zeta(2)^2$ can be proved by considering a suitable logarithmic integral and some combinatorial manipulations (see pages 7-8-9 of my notes), without even computing an explicit form for $\zeta(2)$ or $\zeta(4)$. Similar tricks can be implemented in a more general context through the residue theorem: see Flajolet and Salvy, Euler Sums and Contour Integral Representations.

($*$) and ($**$) have very simple proofs by substitutions:
$$ \int_{0<a<b<c<d<1}\frac{d\mu}{bcd(1-a)}=\int_{(0,1)^4}\frac{d\mu}{1-ABCD}=\sum_{n\geq 0}\int_{(0,1)^4}(ABCD)^n\,d\mu=\zeta(4) $$
$$\begin{eqnarray*}\int_{0<a<b<c<d<1}\frac{d\mu}{(1-a)b(1-c)d}&=&\int_{(0,1)^4}\frac{CD\,d\mu}{(1-ABCD)(1-CD)}\\&=&\int_{(0,1)^2}\frac{\text{Li}_2(CD)}{1-CD}\,d\mu\\&=&\sum_{n\geq 1}\frac{H_n^{(2)}}{(n+1)^2}=\zeta(2,2).\end{eqnarray*}$$
In general, Beuker-Calabi substitutions are pretty useful in showing equivalences between Euler sums, devising acceleration tricks, also estimating the irrationality measure of $\zeta(2),\zeta(3),\zeta(4)$.


text:
Q: Limiting results returned from the database I want to select every photo from my database, then display them grouped by month. I have that code here:
<?php
if (isset($_COOKIE['user_id'])) {
    if (!isset($_GET['user_id'])) {
        $user_id= $_COOKIE['user_id'];
    } else {
        $user_id= $_GET['user_id'];
    }
    $connect= mysqli_connect("localhost", "root", "", "si");
    $query= "SELECT * FROM posts WHERE user_id= $user_id ORDER BY date DESC";

    $result= mysqli_query($connect, $query)
        or die('error with query');
    $date = "0";

    while ($row= mysqli_fetch_array($result)) {
        if ($date != $row['date']) {
            echo "
 ".$row['date']."

";
            $date = $row['date'];
        }
        echo '' . "
";
    }
}
?>

The only problem is that my code displays EVERY image from each month, this makes for an excessively large page. I want to limit my results to only 8 per month (or less if there isn't event 8 pictures for that month), then display a "show more..." link if there are more than 8. I know how to add a LIMIT to my initial query, but that won't work for this scenario. What can I do?
Here is how I want it to look:

A: add LIMIT $start, $numToDisplay
to your SQL statement, and use PHP to calculate the new values for the $start variable.
e.g. $pageNum = $_GET["page"] and 8 images per page means you can calculate that:
$numToDisplay = 8;
$start = ($pageNum-1)*$numToDisplay;

A: What you need to do is monitor picture count
$pickLimit = array ();
while ( $row = mysqli_fetch_array ( $result ) ) {

    if ($date != $row ['date']) {
        echo "
 " . $row ['date'] . "

";
        $date = $row ['date'];
    }

    $pickLimit [$date] = isset ( $pickLimit [$date] ) ? $pickLimit [$date] : 0;
    if ($pickLimit [$date] > 7)
        continue;

    echo '' . "
";
    $pickLimit [$date] ++;
}

A: This could be easily done using the php script whitch you already have and some css tricks, that are also used for creating an animated slider/carousel. Something like this:

    <?php foreach($images as $img) { ?>

            <img src="<?php echo $img; ?>" />

    <?php } ?>

As for the css:
#carousel {
    width: 900px; /* how much you need */
    height: 100px; /* how much you need */
    overflow: hidden;
}
#slider {
    width: auto;
    height: 100px;
}
.image {
    float: left;
}

A: This is what is known as "greatest n per group" query. If you search on here there are many examples with different solutions. Here is one of them -
SELECT *
FROM (
    SELECT
        tmp.*,
        @r := IF(@m=DATE_FORMAT(`date`, '%Y%m'), @rank + 1, 1) rank,
        @m := DATE_FORMAT(`date`, '%Y%m')
    FROM (
        SELECT *
        FROM posts
        WHERE user_id = $user_id
        ORDER BY date DESC
    ) tmp, (SELECT @m:=NULL, @r:=NULL) initvars
) tmp2
WHERE rank <= 8


text:
Q: Non-Apple RAID card for Mac PRO (TOWER) I have the following:

*

*MAC PRO (Model Number: A1186) (PCIe - SLOTS)

At present I am using the software RAID however I wish to move to the hardware raid because of the following:

*

*Performance (4 x 300gb SATA II in RAID 5)

*Redundancy (Raid 5, 1 drive can fail and system will be online)

I do not wish to use the Apple RAID card (very expensive), I would like to use an aftermarket one which is cheaper.
Questions:

*

*Does anyone have a WORKING aftermarket RAID card working in their MAC PRO (TOWER)? -(Have done some research, ROCKETRAID, need confirmation)

*If so to the above, does it work from boot?

Thanks

A: I'm pretty sure (though it's hard to prove the non-existence of a solution) that there is no such option at this time.  If there were, I would definitely expect OWC to carry it, and they don't.  Only the Apple RAID card is for sure bootable.
The workaround is to get a non-bootable RAID card and put the boot drive in the second optical bay, using either the ATA connection meant for a second optical drive or a SATA connection from the motherboard (originally intended for an internal drive but now idle because you've switched the internal drives to the RAID card).  See a full solution explained here.
Edit: It looks like the HighPoint RocketRAID 4321 is supposed to work. I'm afraid to try it.


text:
Q: How do I reference a promise returned from a chained function? I'm new to promises, and I'm not sure if I'm using them correctly. I'm trying to make a calculation with some promises, so I chained a bunch of functions together.  First I wrote it like the following, which worked, but doesn't seem like good code.
it('should verify CPC column', function() {
  ptor.findElements(protractor.By.className('aggRow')).then(function(promCells) {
    getAggCellColumn('CPC').then(function(promColCPC) {
      getAggCellColumn('Spend').then(function(promColSpend) {
        getAggCellColumn('Clicks').then(function(promColClicks) {
          promCells[promColCPC].getText().then(function(promStringCPC) {
            promCells[promColSpend].getText().then(function(promStringSpend) {
              promCells[promColClicks].getText().then(function(promStringClicks) {
                var floatCPC = parseFloat(promStringCPC);
                var floatSpend = parseFloat(promStringSpend);
                var floatClicks = parseFloat(promStringClicks);
                var result = Math.round((floatSpend / floatClicks) * 100) / 100;
                expect(floatCPC).toEqual(result);
              });
            });
          });
        });
      });
    });
  });
});

I researched promises some more and came up with the following:
it('should verify CPC column', function() {
  ptor.findElements(protractor.By.className('aggRow'))
    .then(getAggCellColumn('CPC'))
    .then(getAggCellColumn('Spend'))
    .then(getAggCellColumn('Clicks'))
    .then(promCells[promColCPC + 2].getText())
    .then(promCells[promColSpend + 2].getText())
    .then(promCells[promColClicks + 2].getText())
    .then(function(promStringClicks) {
      var floatCPC = parseFloat(promStringCPC);
      var floatSpend = parseFloat(promStringSpend);
      var floatClicks = parseFloat(promStringClicks);
      var result = Math.round((floatSpend / floatClicks) * 100) / 100;
      expect(floatCPC).toEqual(result);
    });
});

This doesn't work, but I'm trying to get the result of findElements to be promCells.  I also would like to reference the results from the getText() functions. Please let me know if I should be approaching this problem differently. Thanks!
I was also thinking about writing it like this...
it('should verify CPC column', function() {
  ptor.findElements(protractor.By.className('aggRow'))
    .then(function(promStringClicks) {
      var floatCPC = parseFloat(promCells[getAggCellColumn('CPC') + 2].getText());
      var floatSpend = parseFloat(promCells[getAggCellColumn('Spend') + 2].getText());
      var floatClicks = parseFloat(promCells[getAggCellColumn('Clicks') + 2].getText());
      var result = Math.round((floatSpend / floatClicks) * 100) / 100;
      expect(floatCPC).toEqual(result);
  });
});

A: Promises concept in JS is function chaining, with error handling. In your case, you're okay with chaining only.
So in order to chain your calls, you must pass functions, that can return some value to be used by the next function of the chain.
Note that in unit testing, the its have to know when your chain ends, so you can expect the done function and call it when your chain has finished.
You finally would have something like:
it('should verify CPC column', function(done) {
    var promStringCPC, promStringSpend, promStringClicks;
    ptor.findElements(protractor.By.className('aggRow'))
        .then(function (promCells) {
            // Do something from async result like the following...
            promStringCPC = promCells.getAggCellColumn('CPC');
            promStringSpend = promCells.getAggCellColumn('Spend');
            promStringClicks = promCells.getAggCellColumn('Clicks');

            var floatCPC = parseFloat(promStringCPC);
            var floatSpend = parseFloat(promStringSpend);
            var floatClicks = parseFloat(promStringClicks);
            var result = Math.round((floatSpend / floatClicks) * 100) / 100;
            expect(floatCPC).toEqual(result);

            // You can do async additional stuff here...
            // return asyncResultOrNestedPromise
        })
        .then(function (result) {
            // ... and use the async's result here
        })
        .then(done);
});

Note that I didn't clearly get your specific case. Anyway I'm trying to make you understand the promises concept!


text:
Q: How to get Latin squares from a finite group and a subgroup Let G be a finite group and we know its group table is a Latin square of order |G|. Now let H be any subgroup of G of index n. Then we can form G/H which is a collection of left cosets. My question is, is there any natural construction to get a Latin square of order n from G/H? If H is normal in G it is clear since G/H itself is a group. What if H is not normal in G? Not only G/H, using any properties of G and H. Not restricted to coset set. But the order should be the index.

A: I don't know of any general construction.  Perhaps the most 'natural' examples are loop transversals: Given a left transversal $X$ to $H$ in $G$ with $1 \in X$, define a binary operation on $X$ by setting $x*y$ to be the unique element of $X \cap xyH$.  Then $*$ is left-cancellative; if $X$ is in fact a left transversal to every conjugate of $H$, then $*$ is also right-cancellative and hence $X$ forms a loop.
I don't know who thought of this idea first, but I found a series of articles by E.A. Kuznetsov on the subject, for example:
http://www.quasigroups.eu/contents/download/1999/6_1.pdf


text:
Q: Vuetify v-select inside of a flexbox container has an empty input that stretches out the dropdown I am having an issue with a v-select from Vuetify appearing much wider than it should when inside of a container that has display: flex set due to an empty input stretching the dropdown out.
Here is a screenshot of the input in question taking up space:

Below is a working code snippet displaying the issue. When the dropdowns container is much larger - like the full width of a screen - the issue gets much more exaggerated and the dropdown may take up tons of space and the text might only be a small portion of it.
What I am trying to do is have the dropdown be the size of the largest text that fits inside of the dropdown, in this case "apple".

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data () {
    return {
      product: {},
      products: [{title: 'apple', upc: '123'}],
    }
  },
  created() {
    this.product = this.products[0];
  },
})
.app-container {
  display: flex;
}

.message {
  width: 200px;
}

input {
  height: 100%;
}

<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/font@4.x/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet">

  <v-app id="inspire">

      <v-select
        hide-details
        dense
        attach
        outlined
        return-object
        v-model="product"
        :items="products"
        item-text="title"
      ></v-select>

Why is there a sibling input element next to the element that contains apple that takes up a bunch of space? I only want the dropdown as wide as the longest text in the dropdown, which in this case is "apple".

  </v-app>

Finally here is a screenshot of the elusive input in dev tools:

A: What you can do is first hide the input.
.v-select__selections input {
   display: none;
}

After doing that, add the following code to change the text wrap and change the fix width of selection area.
.v-select__selection {
  width: auto;
}

.v-select__selection--comma {
  overflow: visible;
  text-overflow: unset;
  white-space: unset;
}

A: Something pretty much liked Sudam Dissanayake said.
PD: I modified your snippet... Just run it

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data () {
    return {
      product: {},
      products: [{title: 'apple', upc: '123'}, {title: 'Another fruit', upc: '456'}],
    }
  },
  created() {
    this.product = this.products[0];
  },
})
.app-container {
  display: flex;
}

.message {
  width: 200px;
}

.v-select__selections > input {
  display: none !important;
}

.v-select__selection {
  min-width: fit-content !important;
}

<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/font@4.x/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet">

  <v-app id="inspire">

      <v-select
        hide-details
        dense
        attach
        outlined
        return-object
        v-model="product"
        :items="products"
        item-text="title"
      ></v-select>

Why is there a sibling input element next to the element that contains apple that takes up a bunch of space? I only want the dropdown as wide as the longest text in the dropdown, which in this case is "apple".

  </v-app>


text:
Q: VS 2010 RDLC Reporting Conditional Page Breaks I have a report that contains a Tablix, which in turn contains multiple sub reports.
I need conditional page breaks between each page of the report, which I can achieve by adding a rectangle after the last sub report, within the Tablix.  I then set the rectangle to have a page break at the end and make its visibility dependent on a parameter passed to the report.
This all works fine and I get page breaks between repeating sections of the report, however I end up with a blank page at the end of the report when the page break condition is true.
Is there a way to maintain the conditional page breaks but not have a blank page at the end?
My report structure looks like this:
<Report>
  <Body>
    <Tablix>
      <Rectangle>
        <Rectangle>
          <SubReport>1</SubReport>
          <SubReport>2</SubReport>
        </Rectangle>
        <Rectangle>
          <SubReport>3</SubReport>
          <SubReport>4</SubReport>
        </Rectangle>
        <Rectangle>Page break rectangle with conditional visibility</Rectangle>
      </Rectangle>
    </Tablix>
  </Body>
</Report>

A: I managed to find a solution to this, although it isn't very elegant.  I basically have 2 tablix controls (containing the same sub report data, bindings etc), each nested within its own rectangle.  One with the page breaks between each instance of a group turned on, and one with this option turned off.
I then set the visibility of each parent rectangle based on a parameter, i.e. rectangle1 visibility = @PageBreak, rectangle2 visibility = !@pageBreak.
If anyone can suggest a more elegant solution I would be very interested.
Thanks.

A: My solution,
only using tablix (no rectangle)...
add new parameter for the page break,
ex: @PageBreak boolean or string, up to you.
Next, you can create group row in tablix,
and set your group on to function,
something like this:
=IIf(Parameters!PageBreak.Value=true, Fields!YourGroup.Value, "")
then OK.
*you can delete the row or column that is created when you do this, without removing the group (remove row/ column only)
Next, find your group list (usually at bottom screen, Row Groups),
and set properties Group -> PageBreak = Between
This will do.
Hope this help.