text:
Q: How to implement factory design pattern I am trying to apply the factory design pattern to a real world problem in an application. I am using data objects (kind of like ORM but not quite) where an object represents a row from the database and its properties are the columns. Having said this - I have 3 different types of users which all extend the base class User and are all kept in the same database table of users. I have an extra column type that I use to determine the type of user.
So to fetch a user with id 1 I would use this code:
$user = User::getByPK(1);

However the different types of users have different properties and methods and I need to get the appropriate instance, which is where I am stuck. I created a factory class but I am not quite sure how to call it. I need to have the information about the user from the database before I can determine what type of user it is, however I need to instantiate the appropriate class and these two things are kind of dependant of each other.
Here is what I made - I get the appropriate instance but all of the information for the user is kept in the base class.
class UserFactory {

    public function getUser($type) {

        switch($type) {
            case User::ORDINARY:
                return new OrdinaryUser();

            case User::MODERATOR:
                return new Moderator();

            case User::ADMINISTRATOR:
                return new Administrator();
        }
    }
}

$user = User::getByPK(1); // Has all the information

$factory = new UserFactory();

$object = $factory->getUser($user->type); // Is instance of Administrator

What is the proper way to use the factory pattern in this case?

A: The idea of the factory pattern is to decouple and encapsulate the logic required to create an instance of an object, from the object itself. This separates concerns.
You currently have a static method on your User class that is responsible for fetching the user information from the database. This couples your User object to your database. It's also very rigid.

*

*What if your users are stored in a different type of database?

*What if your users are stored in an XML file?

*What if your users are stored in a key/value store?

*What if you want to create a mock repository of users for writing tests?

The factory pattern allows you to abstract these concerns away, and provide alternate implementations of a factory depending on your needs (assuming you had a common interface for each implementation). Maybe the way you create a user changes, but you don't want to also change everywhere you've needed to create a user - just how the user is created. Isolating this code into a factory allows for this.
A factory might take an instance to your DAL as well, if you've abstracted your DAL. (I'll be using IDataAccessLayer as a placeholder for your preferred DAL)
class UserFactory {
    private IDataAccessLayer $dataAccessLayer;

    public function __constructor($dataAccessLayer) {
        $this->dataAccessLayer = $dataAccessLayer;
    }

    public function createUser($userId) {
        $userDataSet = $this->dataAccessLayer->someQuery($userId);

        switch ($userDataSet->type) {
            case UserType::Administrator:
                return createAdministrator($userDataSet);
            case UserType::Moderator:
                return createModerator($userDataSet);
            case UserType::Ordinary:
                return createOrdinaryUser($userDataSet);
        }
    }

    private function createAdministrator($userDataSet) { /* Create and return an administrator */ }
    private function createModerator($userDataSet) { /* Create and return a moderator */ }
    private function createOrdinaryUser($userDataSet) { /* Create and return an ordinary user */ }
}

You'd then use this like:
$factory = new UserFactory($dataAccessLayer);
$factory->createUser(1);

(Bear with me, I haven't coded PHP in some years, so some of my syntax may be off, but the idea is the same)
Now, personally, it looks like you need to get even more granular here. I'd create a UserRepository following the Repository pattern. This is because the factory shouldn't really be accessing the database in my opinion. It should just use the data from the database to create the user. The repository pattern should be responsible for getting the data from the database, and then feeding that data to the factory pattern to get an object.
class UserRepository {
    private IDataAccessLayer $dataAccessLayer;

    public function __constructor($dataAccessLayer) {
        $this->dataAccessLayer = $dataAccessLayer;
    }

    public function getUserById($id) {
        $userData = $this->dataAccessLayer->fetch(someQuery);

        $factory = new UserFactory();
        return $factory->createUser($userData);
    }
}

Then you'd have a simpler factory:
class UserFactory {
    public function createUser($userData) {
        switch ($userData->type) {
            case UserType::Administrator:
                return createAdministrator($userData);
            case UserType::Moderator:
                return createModerator($userData);
            case UserType::Ordinary:
                return createOrdinaryUser($userData);
        }
    }

    private function createAdministrator($userDataSet) { /* Create and return an administrator */ }
    private function createModerator($userDataSet) { /* Create and return a moderator */ }
    private function createOrdinaryUser($userDataSet) { /* Create and return an ordinary user */ }
}

And from your code, you'd have something like:
$userRepository = new UserRepository($dataAccessLayer); //This is probably done somewhere higher in your code.
$userRepository->getUserById(1);

You'll probably want to go ahead and create the following interfaces and implement these as well. This will allow you to enforce your contract, as well as set yourself up to be able to swap out implementations if you need.
public interface IUserRepository {
    function getUserById($userId);
}

and
public interface IUserFactory {
    function createUser($userData);
}


text:
Q: Passing a 2D array to a function in C++ gives me the following error #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

\\Errors:
\\'n' was not declared in this scope
\\ expected ')' before ',' token
\\ expected unqualified-id before 'int'
void abst_diff(int arr[][n], int n){
int sum_1=0;
int sum_2=0;

for(int a_i = 0; a_i < n; a_i++)
    sum_1 = sum_1 + a[a_i][a_i];

for(int a_i = 0, a_j = n-1; a_i < n; a_i++, a_j--)
    sum_2 = sum_2 + a[a_i][a_j];

sum_2=abs(sum_2-sum_1);
cout << sum_2;

}

int main(){
int n;
cin >> n;
int arr[n][n];
for(int a_i = 0;a_i < n;a_i++){
   for(int a_j = 0;a_j < n;a_j++){
      cin >> arr[a_i][a_j];
   }
}
abst_diff(arr,n);
return 0;
}

Can someone please help me identify the error here in this code. its a fairly simple logic. the errors that i'm getting are for the line:
     void abst_diff(int arr[][n], int n){

A: You can't assign a variable to define the size of an array.May Be you could use a macro.
#define SIZE 50

Or you could use dynamic variable.
Ex:
#include<iostream>

using namespace std;

int main()
{
    int n ,*a;
    cout<<"Enter size of array= ";
    cin>>n;
    a=new int[n];       //allocate memory
    for(int i=0;i<n;i++)
        *(a+i)=i;
    for(int i=0;i<n;i++)
        cout<<*(a+i)<<endl;
    return 0;
}

And
void abst_diff(int arr[][**n**], int n)

You can't give the size here too.
#include <vector>
#include <cmath>
#include <cstdio>
#include <iostream>
#include <algorithm>

using namespace std;

void abst_diff(int arr[50][50], int n){
int sum_1=0;
int sum_2=0;

for(int a_i = 0; a_i < n; a_i++)
    sum_1 = sum_1 + arr[a_i][a_i];

for(int a_i = 0, a_j = n-1; a_i < n; a_i++, a_j--)
    sum_2 = sum_2 + arr[a_i][a_j];

sum_2=abs(sum_2-sum_1);
cout << sum_2;

}

int main(){
int n;
cin >> n;
int arr[50][50];
for(int a_i = 0;a_i < n;a_i++){
   for(int a_j = 0;a_j < n;a_j++){
      cin >> arr[a_i][a_j];
   }
}
abst_diff(arr,n);
return 0;
}

Please comment using '/' not '\'.

A: i was actually looking to pass a dynamic variable (which is the array), not a defined variable of fixed size.
I took your first advise and managed to come up with a solution of my own:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cstring>

using namespace std;

int **createArr(int **array, int n){

array = new int*[n];
for (int row=0; row<n; row++) {
    array[row] = new int[n];
}
return array;

}

void abst_diff(int **arr,int n){
int sum_1=0;
int sum_2=0;

for(int a_i = 0; a_i < n; a_i++)
    sum_1 = sum_1 + *(*(arr+a_i)+a_i);//arr[a_i][a_i];

for(int a_i = 0, a_j = n-1; a_i < n; a_i++, a_j--)
    sum_2 = sum_2 + arr[a_i][a_j];

sum_2=abs(sum_2-sum_1);
cout << sum_2;

}

int main(){
int n;
cin >> n;
int **arr=createArr(arr,n);
for(int a_i = 0;a_i < n;a_i++){
   for(int a_j = 0;a_j < n;a_j++){
      cin >> arr[a_i][a_j];
   }
}
abst_diff(arr,n);
return 0;
}

This program calculates the abs. difference between the sum of the diagonals. My issue was just passing a dynamic variable to a function.
Thanks for your help! :)
PS. '\' was an honest mistake.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Counterexample of which the solution of Laplace equation is in Hilbert space $H^{2}(\Omega)$ of infinite strip domain. I study by myself about Elliptic Problem in specific domain written by P. Grisvard.(Chapter 4)
Let's denote $H^{2}=W^{2,2}$.

Let's assume $u$ is a weak solution in $H^{2}$such that  $$
 \begin{cases}
 -\triangle u+au=f & \text{in }\Omega,\\ u=0 & \text{on }\partial\Omega, \end{cases} $$ where $f\in L^{2}(\Omega)$.

Moreover, we fix $\Omega=\{(x,y)|x\in\mathbb{R},\ 0<y<h\}$ which
is an infinite strip. In the textbook, the following is satisfied
:
$$
\|u\|_{H^{2}(\Omega)}\leq C\|f\|_{L^{2}(\Omega)},
$$
 for some constant $C$ only when $a>0$.

What if $a=0$? In other words, if $-\triangle u=f$ in $\Omega$, is
  above statement still hold? If not, I'm looking for the counterexamples

A: The statement does hold for $a=0,$ where it becomes a form of Poisson's equation.
Consider the extension of $u$ to $\overline u:\mathbb R\times (\mathbb R/2h)\to\mathbb C$ that is odd in the $y$-direction, i.e. $\overline u(x,y)=-\overline u(x,-y).$ By a similar argument as in the proof of the Sobolev extension theorem, this extension is still in $H^2,$ so in fact it must satisfy the equation $-\Delta \overline u=\overline f$ where $\overline f$ is the extension of $f$ that is odd in the $y$-direction. This extension is defined on an abelian group so has a Fourier transform. I will drop the overlines from now on - they were just used to justify the Fourier transform.
The Fourier transform $\hat u$ can be thought of as satisfying
$$u(x,y)=\int \sum_{k=1}^\infty \hat u(p,k) e^{i p x}\sin(\pi k y/h) dp$$
so that the $x$ derivative becomes multiplication by $ip$, and the $y$ derivative is like multiplication by $\pi k/h$ (and switching $\sin\mapsto \cos\mapsto-\sin$), so
$$\|u\|^2_{H_2(\Omega)}\geq C\int \sum_{k=1}^\infty |\hat u(p,k)|^2 (1+p^2+( k/h)^2+p^4+p^2( k/h)^2+( k/h)^4) dp$$
and
$$\|f\|^2_{L_2(\Omega)}\leq C\int \sum_{k=1}^\infty |\hat u(p,k)|^2 (p^4+(k/h)^4) dp$$
where the $C$'s may be different - I am using $C$ to ignore constant factors, and with the right constants these would be equalities. These easily give $\|u\|_{H_2(\Omega)}\leq C(1+h^2) \|f\|_{L_2(\Omega)}$ for some $C$. (Use $1\leq h^2(k/h)^2$ and some "$2ab\leq a^2+b^2$" inequalities.)


text:
Q: How to round percentage of barchart in MPAndroidChart Xamarin? public class YourValueFormatter : IValueFormatter
{

    public IntPtr Handle
    {
        get;
    }
    public void Dispose()
    {
        throw new NotImplementedException();
    }

    private DecimalFormat mFormat;

    public YourValueFormatter() {
        mFormat = new DecimalFormat("###,###,###"); // use no decimals
    }

    public String GetFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {

        // This method never called.
        return Math.Round(value)+"";
    }

}

This is how I am setting formatter to data
data.SetValueFormatter(new YourValueFormatter());

also tried to set it on dataset like this
dataset.ValueFormatter=new YourValueFormatter();

Tried in many ways but nothing getting work for me.
I want to round bar value like this
2.00 TO 2% (Predefined percentage formatter formate like this 2.0% but I need 2%)
or
420.0 to 420
lib version : 2.2.3.2

A: You have to inherit from Java.Lang.Object, when you implement java interfaces.If you have a look at the build output, you'll find something like:

Type 'YourValueFormatter' implements IValueFormatter but does not inherit from Java.Lang.Object. It is not supported.

Correct
public class YourValueFormatter : Java.Lang.Object, IValueFormatter
{
    private DecimalFormat mFormat;

    public YourValueFormatter() {
        mFormat = new DecimalFormat("###,###,###"); // use no decimals
    }

    public String GetFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler)
    {
        // This method never called.
        return Math.Round(value)+"";
    }
}

Your GetFormattedValue should now get called.


text:
Q: How do I set up Minecraft on split screen for Playstation 3? Me and my friend want to play Minecraft on the same PS3, but I don't know how to set up split screen.
How can I play split-screen on Minecraft for my Playstation 3?

A: Create a world and uncheck the Online game checkbox.  Then, start the game.  With the second controller, the other player should be able to sign in using another account on the PS3.
The Wiki shows how to do this (for the Xbox 360, though the process should be the same for PS3).
Note you need to be on a 720p resolution or be using an HDMI cable.


text:
Q: Changing the background colour of lines in the stack I have just changed the colour scheme of my Visual Studio 2008 environment to have a dark backround with light text.
This is so much easier on the eyes.
The only problem is lines that are on the call stack... Those lines that are referred to in this thread here in visual studio some lines of code have light grey background while debugging
These lines have a bright grey background, which against my light text means I cannot read the text at all. I have been through every single colour in Tools -> Options -> Fonts and Colours and cannot find one that matches.
How can I change the background for lines on the current call stack?
Edit
Ok this is seriously doing my head in now!
I have tried with several different styles from here : Studio Styles. They all have the same problem.
I have just fired up VS2005 and I am getting the same problem.
Here is a screen shot of what is going on :

What is going on!??

A: I had the same problem and found vs2010 c# debugging highlight color:
Tools → Options → Fonts and Colors → Text Editor → Read-only Region

I only get the color from Call Return New Context when I double-click a different entry in the Call Stack window.

A: Tools → Options → Fonts and Colors → Text Editor → Call Return New Context

This one does it for me, not sure what 'Call Return' (without new context) is for.


text:
Q: Best way to extend a container in full screen I have researched a bit and saw many examples about how developers use this technique to full screen a container and the most used are:
.container {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

and
html, body{
 height: 100%;
 margin: 0;
}

.container {
  min-height: 100%;
  margin: 0;
}

These are the most used methods to extend a div in full screen when the container is the child of body.
If you ask me, the method using absolute position is not a very good idea because if you put other elements inside you can not relate to it because they have an absolute position.
The method using HTML and body 100% seems to be a little bit rudimentary.
So, what is the best way to extend a container?


text:
Q: Program doesnt write to file and crashes when loading So i need to write and read to and from a binary file, but cant seem to do it, and when using readFromFile, the program crashes. I need help write to binary file, and then reading from it and resuming my work later after turning off the program.I have no idea what i am doing wrong, and i have googled for a long time now, but with no results. Here is the code of my program:
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>

typedef struct{
    char *subjName;
    char *lectName;
    char *lectSurname;
    int credits;
    int num_students;
}Subject;

typedef struct{
        Subject **subjs;
        int num_subjs;
}Subjects;

int numOfSubjs=0;

void listInput();
void listEdit();
void listDelete();
void listPrint();
int userChoice(int select);
int enterNumber(char *name);
void saveToFile(Subjects *subjects);
void readFromFile(Subjects *subjects);

int main() {

    Subjects *subjects = malloc(sizeof(Subjects));
    subjects->num_subjs = 0;
    subjects->subjs = NULL;
    readFromFile(subjects);
    int r=1;
    while(r!=0){
        int select=userChoice(select);
        switch(select){
            case 1:
            listPrint(subjects);
            break;

            case 2:
            listInput(&subjects);
            break;

            case 3:
            listDelete(subjects);
            break;

            case 4:
            listEdit(subjects);
            break;

            case 0:
            r=0;
            break;
        }
    }
    saveToFile(subjects);
    return 0;
}

int userChoice(int select){                                                 // menu options
    int choice,input=0;
    printf("(1). View all the data\n");
    printf("(2). Enter new data\n");
    printf("(3). Delete data\n");
    printf("(4). Edit data\n");
    printf("(0). Exit\n");
    printf("-----------------------------\n");

    while(input!=1){
        choice = enterNumber("menu");
        if(choice>4 || choice<0){
            printf("Invalid input \n");
        }
        else
            input = 1;
    }
    return choice;
}

void listPrint(Subjects *subjects){                         // print data
    int i;
    for(i=0; i< numOfSubjs; i++){
        printf("%d, %s, %s, %s, %d, %d\n",i+1, subjects->subjs[i]->subjName, subjects->subjs[i]->lectName, subjects->subjs[i]->lectSurname, subjects->subjs[i]->credits, subjects->subjs[i]->num_students);
    }
    printf("Number of entries: %d \n", numOfSubjs);
}

char *getln()                                               //dynamically allocate input string
{
    char *line = NULL, *tmp = NULL;
    size_t size = 0, index = 0;
    int ch = 1;

    while (ch) {
        ch = getc(stdin);
        if (ch == '\n')
            ch = 0;

        if (size <= index) {
            size += 1;
            tmp = realloc(line, size);
            if (!tmp) {
                free(line);
                line = NULL;
                break;
            }
            line = tmp;
        }

        line[index++] = ch;
    }

    return line;
}

void saveToFile(Subjects *subjects){
    FILE *data;
    data = fopen("data.bin","wb");
    printf("%s", subjects->subjs[0]);
    for(int i=0; i<numOfSubjs; i++){
        fwrite(&subjects->subjs[i],sizeof(Subject*),1,data);
    }
    fclose(data);
}

void readFromFile(Subjects *subjects){
    FILE *data;
    int i=0;
    data = fopen("data.bin","rb");
    while(!feof(data))
    {
         fread(&subjects->subjs[i],sizeof(Subject*),1,data);
         i++;
    }
    fclose(data);
}

int isText(char *str,char *name){                                   // check if is text
    for(int i = 0; i < strlen(str);i++){
        if((str[i]<'A' || str[i]>'z') && str[i]!=' '){
            printf("Error, %s must be a text \n",name);
            return 0;
        }
    }
    return 1;
}

int enterNumber(char *name){                                // enter number and check if is number
    int input=0, crash=0, num=0;
        while(input!=1)
        {
             crash=0;
             printf("Enter the number of %s\n", name);
             scanf("%d", &num);
             while(getchar()!='\n')
             {
                crash++;
             }
             if(crash>0 || num<0)
                printf("Error, enter a not negative number of %s\n", name);
             else if(crash==0)
                input=1;
        }
    return num;
}

void listInput(Subjects **p_subjects){                              // input new data

    Subject *new_subj = malloc(sizeof(Subject));
    new_subj->subjName = NULL;
    new_subj->lectName = NULL;
    new_subj->lectSurname = NULL;
    new_subj->credits = 0;
    new_subj->num_students = 0;

    do{
        printf("Enter the name of the subject \n");
        new_subj->subjName = getln();
    }while(!isText(new_subj->subjName,"Subject name"));

    do{
        printf("Enter the name of the lecturer \n");
        new_subj->lectName = getln();
        new_subj->lectName[0] &= '_';
    }while(!isText(new_subj->lectName,"Lecturer's name"));

    do{

        printf("Enter the surname of the lecturer\n");
        new_subj->lectSurname = getln();
        new_subj->lectSurname[0] &= '_';                                            //Convert to uppercase if lowercase
    }while(!isText(new_subj->lectSurname,"Lecturer's name"));

    new_subj->credits = enterNumber("credits");

    new_subj->num_students = enterNumber("students");

    (*p_subjects)->subjs = realloc((*p_subjects)->subjs,sizeof(Subject*)*(++(*p_subjects)->num_subjs));
    (*p_subjects)->subjs[(*p_subjects)->num_subjs-1] = new_subj;
    numOfSubjs++;
    printf("Added a new entry.\n\n");
}

void listDelete(Subjects *subjects){                                                // delete entries
    int del;
    if(numOfSubjs==0)
        printf("Number of entries is 0, can't delete anything\n");
    else{
        printf("Enter 0 to exit. Number of subjects : %d \n", numOfSubjs);
        while(1){
            del = enterNumber("entry which you would like to delete");
            if(del<=numOfSubjs && del>0){
                    for(int i = del-1; i<numOfSubjs-1; i++){
                        subjects->subjs[i]=subjects->subjs[i+1];
                        subjects->subjs = realloc(subjects->subjs,sizeof(Subject*)*(--subjects->num_subjs));
                    }
                numOfSubjs--;
                break;
            }
            if(del>numOfSubjs)
                printf("Error, input a number between 1 and %d (or enter 0 to exit)\n", numOfSubjs);
            else
                break;
        }
    }
}
void listEdit(Subjects *subjects){                                                                  // edit entries
    int choice=0, editEntry=0, editSubj=0;
    if(numOfSubjs == 0)
        printf("Number of entries is 0, can't edit anthing\n");
    else{
        while(1){
            printf("Number of entry must be between 1 and %d \n", numOfSubjs);
            choice = enterNumber("entry you would like to edit.");
            if(choice>0 && choice<=numOfSubjs){
                while(1){
                    editEntry = enterNumber("what would you like to edit\n 1 - Subject name\n 2 - Lecturer's name\n 3 - Lecturer's surname\n 4 - Number of credits\n 5 - Number of students");
                        if(editEntry>0 && editEntry <=5){
                            switch(editEntry){
                                case 1:
                                    do{
                                        printf("Enter the name of the subject \n");
                                        subjects->subjs[choice-1]->subjName = getln();
                                    }while(!isText(subjects->subjs[choice-1]->subjName,"Subject name"));
                                    break;
                                case 2:
                                    do{
                                        printf("Enter Lecturer's name \n");
                                        subjects->subjs[choice-1]->lectName = getln();
                                    }while(!isText(subjects->subjs[choice-1]->lectName,"Lecturer's name"));
                                    break;
                                case 3:
                                    do{
                                        printf("Enter Lecturer's surname \n");
                                        subjects->subjs[choice-1]->lectSurname = getln();
                                    }while(!isText(subjects->subjs[choice-1]->lectSurname,"Lecturer's surname"));
                                    break;
                                case 4:
                                    subjects->subjs[choice-1]->credits = enterNumber("credits");
                                    break;
                                case 5:
                                    subjects->subjs[choice-1]->num_students = enterNumber("students");
                                    break;

                            }
                        }
                    break;
                }
            }
            break;
        }
    }
}

A: &subjects->subjs[i], This is Undefined behavior. Accessing garbage value. You need to properly initialize it proper memory address. You ddin't do it anywhere.
(*subjects).subjs or subjects->subjs -> This is not pointing anywhere. It is NULL.
Also here you don't need the double pointer. A single pointer would do the thing you want to do.
typedef struct{
        Subject *subjs;
        int num_subjs;
}Subjects;

For single pointer this would be like
Subjects *subjects = malloc(sizeof(Subjects));
subjects->num_subjs = 10;
subjects->subjs = malloc(subjects->num_subjs * sizeof Subject);
subjects->subjs[0].subjName = malloc(40);

Each of the malloc should be checked with it's return Value. If it's NULL then it would be error to proceed further or access it.
And free() it accordingly when you are done working with it.

Some basic things:-
  typedef struct{
          Subject *subjs;
          int num_subjs;
  }Subjects;

Now let's look a bit in the code.
Op asked why OP should initialize and isn;t subjects->num_subjs = 0;
    subjects->subjs = NULL; not enough?
A pointer is a variable that is supposed to hold address. here Subject* will hold the address of the variables of type Subject.
Now here initially you initialized it.
You have allocated a memory and assigned it's address to the Subject* variable subjects.
Now let's see what else you do.
subjects->num_subjs = 0;
subjects->subjs = NULL;

You initialized it. And then you try to access it(subjects->subjs[i]). Can you tell me where it points to? (subject->subjs)?
Answer is nope. It is pointing to nowhere. It contains NULL value now. Don't you think you should tell it how many subject you want to hold and allocate accordingly? Yes you should and that's what I did precisely in the example shown.
Whenever you have a pointer variable ask yourself what it contains - and if the value is something you know about, not some random garbage value.


text:
Q: Finding sibling items between headers I'm trying to scrape some documentation for data files composed in XML. I had been writing the XSD manually by reading the pages and typing it out, but it has occurred to me that this is a prime case for page scraping. The general format (as far as I can tell based on a random sample) is something like the following:

     The "show" Child Element

        allowstack

        (Optional) Boolean – Indicates whether the user is allowed to stack items within the table, subject to the restrictions imposed for each item. Default: "yes".

        agentlist

        (Optional) Id – If set to a tag group id, only picks with the agent pick's identity tag from that group are shown in the table. Default: None.

        allowmove

        (Optional) Boolean – Indicates whether picks in this table can be moved out of this table, if the user drags them around. Default: "yes".

        listpick

        (Optional) Id – Unique id of the pick to take the table's list expression from (see listfield, below). Note that this does not work when used with portals. Default: None.

        listfield

        (Optional) Id – Unique id of the field to take the table's list expression from (see listpick, above). Note that this does not work when used with portals. Default: None.

    The "show" element also possesses child elements that define additional behaviors of the table. The list of these child elements is below and must appear in the order shown. Click on the link to access the details for each element.

         list

        An optional "list" element may appear as defined by the given link. This element defines a

         List Tag Expression

        for the table.

There's a pretty clear pattern of each file having a number of elements defined by a header followed by text followed by a table (generally the attributes), and possibly another set of text and a table (for the child elements). I think I can reach a reasonable solution by simply using next or next-sibling to step through items and trying to scan the text to determine if the following table is attributes or classes, but it feels a bit weird that I can't just grab everything in between two header tags and then scan that.

A: You can search for multiple elements at the same time, for example
 and
. You can then make a note of each
 contents before processing each
.
For example:
soup = BeautifulSoup(html, "html.parser")

for el in soup.find_all(['h2', 'table']):
    if el.name == 'h2':
        h2 = el.get_text(strip=True)
        h2_id = el.span['id']
    else:
        for tr in el.find_all('tr'):
            row = [td.get_text(strip=True) for td in tr.find_all('td')]
            print([h2, h2_id, *row])


text:
Q: PHP - Prepared Statement Query doesn't work the second time So, I'm working with PHP and prepared statements sent to a MySQL database. I've ran into a problem that I can't quite debug. Here is my code:

        // Check if the input username is in the database
  $stmtQuery = "SELECT * FROM updatedplayers WHERE Player=?;";
  $preparedStmt = $dbc->prepare($stmtQuery);
  $preparedStmt->bind_param("s", $setUsername);

  $preparedStmt->execute();
  $preparedStmt->bind_result($resultUUID, $resultUsername);
  $preparedStmt->fetch();

  // If it's not, kill the page.
  if ($resultUUID == null) {

   incorrect();
  }

  $stmtQuery = "SELECT Password, Salt FROM logins WHERE UUID=?;";
  echo 'flag1 ';
  $preparedStmt = $dbc->prepare($stmtQuery);
  echo 'flag2 ';
  $preparedStmt->bind_param("s", $resultUUID);
  echo 'flag3 ';

The fist prepared statement works fine, it's at the line $preparedStmt->bind_param("s", $resultUUID);. There are also a couple other prepared statements before these, so I know I'm doing this correctly, but I'm not too sure about the last statement.
The code just seems to stop running after echo 'flag2 ';, which I put there to find the specific line. I don't get any error messages, it just doesn't print out flag3.
I've tried replacing $resultUUID with a static string, yet I get the same outcome. Also, I know my SQL statement is correctly formatted, I've tested within the console manually.
That's pretty much it, I'd love to hear some criticism, as I am new to PHP. Also, is there any way to get a better idea about the errors I get, instead of trying to pinpoint the error myself? Thanks!

A: So, adding ini_set('display_error', 1);, suggested by @user2182349, gave me a little more insight, I got "Fatal error: Call to a member function bind_param() on boolean".
After some research, I tried adding mysqli_report(MYSQLI_REPORT_ALL);, which ended up throwing "No index used in query/prepared statement".
I did some research on that to realize that it wasn't a problem, just MySQLI reporting unnecessary errors (which is what I asked it to do lol). In order to get a better, more insightful stack trace, I used mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);.
This threw "Commands out of sync; you can't run this command now". Again, more research taught me to use $preparedStmt->store_result();, in order to allow for another prepared statement to run.
Big thanks to all y'alls' help, hope this can help someone too.

A: You should be able to use a single select statement similar to this:
SELECT u.UUID, u.Username, l.Password, l.Salt
    FROM updatedplayers AS u
    JOIN logins AS l ON (u.UUID = l.UUID)
    WHERE u.Player = ?

Check the case of the field names to be sure they match the database.
At the top of the file, add ini_set('display_errors',1);.  If you have any PHP errors, they will be displayed.  Also check the return values from the database calls and use the error display functions.

A: I would suggest you should start using PDO... I have issues encountered with mysqli prepared statement years ago. Since then, PDO gives me no headaches when it comes to multiple queries at a time.
You should try PDO.. :-) it's more efficient.
http://php.net/manual/en/intro.pdo.php
http://php.net/manual/en/class.pdostatement.php
Or you can do the following "if you want alternative solution"..
//Close connection
$preparedStmt->close();

//AND OPEN YOUR CONNECTION AGAIN TO PREPARE NEW QUERIES..

$stmtQuery = "SELECT Password, Salt FROM logins WHERE UUID=?;";
echo 'flag1 ';
$preparedStmt = $dbc->prepare($stmtQuery);
echo 'flag2 ';
$preparedStmt->bind_param("s", $resultUUID);
echo 'flag3 ';

A: I think you need to close the prepared statement before you use the variable for another query:
$preparedStmt->close();

Or use another variable name like $preparedStmt2 for the second query.


text:
Q: Spring 4 with Java Config and no xml I'm working on a Spring 4 based Java application.  This application is being deployed to Apache Tomcat.  This application runs at a URL of http://localhost:8080/test.  I can't get the GET method defined in the controller class to run.  I'm pretty sure it's a configure issue.  See what I am doing wrong?  This does work when I run the app at the root URL of http://localhost:8080/, but this is not an option for me.  First Class involved:
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class TestWebInitializer extends
   AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/test" };
    }

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[] { RootConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[] { WebConfig.class };
    }
}

2nd class involved:
import static org.springframework.web.bind.annotation.RequestMethod.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@SuppressWarnings("unused")
@Controller
@RequestMapping({"/test"})
public class TestController {

    @RequestMapping(method=GET)
    public String home() {
        //TODO: Convert System.out.println to log4j
        System.out.println("HomeController.home()!");

        return "home";
    }
}

A: @hzpz is correct, getServletMappings() controlls which paths within your application's context root gets handled by the servlet (instead of other servlets in the same WAR). Your config matched the bold part:
http://localhost:8080/context_root/test
To change the context root, you should change the name of the WAR (from ROOT.war) or change the config file of your application server.
The application server also strips any matched portion of the context root and servlet mapping pattern, so if your application is correctly deployed to be the app at http://localhost:8080/test (i.e. with a context root of /test), its servlets will only see a path after the /test, so your @RequestMapping should handle "/".

A: If you are using Tomcat - go to server.xml inside tomcat and place below code there.
<Context
  docBase="<yourApp>"
  path="/"
  reloadable="true"
/>


text:
Q: Terminal error output RE: editing .conf file in Xbuntu [owned by uid 1000 istead of 0] Was curious as to the terminal error output from running sudo Kate. I read in a forum that directed me to open my notepad using gksudo. Realizing that this had not been installed I just went ahead and tried to open my notepad editor with sudo and edit the .conf file (which worked, by that I mean it saved the new .conf file without root access error, but left me with "lines of unknown errors"). I have no problem running sudo on my Raspberry PI to open and edit text files using nano.
What caused the error lines, and how to fix them if easily answered?
skratch@Slick:~$ sudo kate
[sudo] password for skratch:
QDBusConnection: session D-Bus connection created before QCoreApplication. Application may misbehave.
Error: "/var/tmp/kdecache-skratch" is owned by uid 1000 instead of uid 0.
Error: "/tmp/kde-skratch" is owned by uid 1000 instead of uid 0.
Error: "/tmp/ksocket-skratch" is owned by uid 1000 instead of uid 0.
Error: "/tmp/kde-skratch" is owned by uid 1000 instead of uid 0.
kdeinit4: Shutting down running client.
Connecting to deprecated signal QDBusConnectionInterface::serviceOwnerChanged(QString,QString,QString)
Error: "/tmp/ksocket-skratch" is owned by uid 1000 instead of uid 0.
Error: "/tmp/kde-skratch" is owned by uid 1000 instead of uid 0.
QDBusConnection: session D-Bus connection created before QCoreApplication. Application may misbehave.
QDBusConnection: session D-Bus connection created before QCoreApplication. Application may misbehave.
Error: "/var/tmp/kdecache-skratch" is owned by uid 1000 instead of uid 0.
kbuildsycoca4 running...
Error: "/var/tmp/kdecache-skratch" is owned by uid 1000 instead of uid 0.
Error: "/var/tmp/kdecache-skratch" is owned by uid 1000 instead of uid 0.
QDBusConnection: session D-Bus connection created before QCoreApplication. Application may misbehave.
QDBusConnection: session D-Bus connection created before QCoreApplication. Application may misbehave.
Error: "/var/tmp/kdecache-skratch" is owned by uid 1000 instead of uid 0.
Bus::open: Can not get ibus-daemon's address.
IBusInputContext::createInputContext: no connection to ibus-daemon
QDBusConnection: session D-Bus connection created before QCoreApplication. Application may misbehave.
QDBusConnection: session D-Bus connection created before QCoreApplication. Application may misbehave.
Error: "/var/tmp/kdecache-skratch" is owned by uid 1000 instead of uid 0.
QObject::connect: Cannot connect (null)::resourceScoreUpdated(QString, QString, QString, double) to NepomukPlugin::resourceScoreUpdated(QString, QString, QString, double)
QObject::connect: Cannot connect (null)::recentStatsDeleted(QString, int, QString) to NepomukPlugin::deleteRecentStats(QString, int, QString)
QObject::connect: Cannot connect (null)::earlierStatsDeleted(QString, int) to NepomukPlugin::deleteEarlierStats(QString, int)
QDBusConnection: name 'org.kde.kglobalaccel' had owner '' but we thought it was ':1.8'
Error: "/tmp/kde-skratch" is owned by uid 1000 instead of uid 0.

A: Uid 1000 is you. Uid 0 is root. Take a loot at output of ls -l /var/tmp . There's some folders that you have ownership of, and some that root owns. If you're not owner of a file and permissions are drwx------, you can't open it, simple as that. When you called kate with root privileges, kate needed to access folders that are owned by you, but the program was executed from root's perspective. Hence the errors


text:
Q: Error parsing JSON data. JSONException: End of input at character Here is my php code fragment for parsing.
$result=mysql_query($qry);

    $Json="{";
    for($i=1;$i<=$count;$i++)
    {
    $row = mysql_fetch_row($result)
    $newRow=setJson($i,$row);
    if($i!=$count)
    $Json=$Json.$newRow.",";
    else
    $Json=$Json.$newRow;
    }
    $Json=$Json."}";

    $response["success"]=1;
    $response["count"]=$count;
    $response["rows"]=$Json;

    echo json_encode($response);

Function for creating new row
function setJson($i,$row)
{
$setRow="\""$i."\":[".$row."]";
return $setRow;
}

I have developed this using php.
I am trying to parse MySQL result to the following format. For each row in DB. I need to update it to SQLite DB in my app.
    {
    "success":1,
    "error":0,
    "rows":{
            "1":["abc","123"],
            "2":["xxx","909"],
            "3":["bcn","1bc"]
        }
}

{
  "tag": "syncMe",
  "success": 1,
  "error": 0,
  "count": "8",
  "rows": "{
\"1\":[\"Porotta\",\"22\",\"652+2\",\"veg\",\"dinner\"],
\"2\":[\"chicken curry\",\"90\",\"sdaS\",\"veg\",\"dinner\"],
\"3\":[\"Assd\",\"12\",\"looo\",\"veg\",\"dinner\"]}"
}

How can i remove the slashes in the JSON String.??

A: pass your result to one array variable using for loop.
Then use json_encode(array_variable);
it will give proper json format..
Why you need to format yourself manually.
You can try this way ..
Note: some values i hard coded..
for($i=1;$i<=$count;$i++)
{
    $Json[$i]=array("abc","123");
}
$response["success"]=1;
    $response["count"]=3;
    $response["rows"]=$Json;

var_dump( json_encode($response));

A: function setJson($i,$row)
{
$itemname=$row["item_name"];
$price=$row["price"];
$contents=$row["contents"];
$type=$row["type_of_item"];
$catagory=$row["catagory"];
//$setRow[]=array("\"".$i."\"" => $row);
$setRow="\"".$i."\":[".$itemname."\",\"".$price."\",\"".$contents."\",\"".$type."\",\"".$catagory."\"]";
return $setRow;
}

This function parsed my JSON to my requirement.


text:
Q: Restricting a collapsible item to stay collapsed based on a certain click I have collapsible anchor tag (data_1) which when clicked toggles between collapsing and expanding a div element as shown below -

data_1

   data_2
   data_3

It works as expected. But I want to add in some other functionality such that when I click the span element (glyphicon-eye-open) inside the collapsible anchor tag, a javascript method must be invoked.
I know that by adding onclick = function1() inside the span element does the trick, but it also does the expansion of the collapsible anchor tag. I don't want the anchor element to be expanded when I click the span element only.
How do I achieve this? Any help would be appreciated.
JS Fiddle: https://jsfiddle.net/joshirohit66/v81gofLq/11/

window.clickme = function() {
  alert("clicked span but not anchor");
  return false;
}
.list-group.list-group-root {
  padding: 0;
  overflow: hidden;
}

.list-group.list-group-root .list-group {
  margin-bottom: 0;
}

.list-group.list-group-root .list-group-item {
  border-radius: 0;
  border-width: 1px 0 0 0;
}

.list-group.list-group-root>.list-group-item:first-child {
  border-top-width: 0;
}

.list-group.list-group-root>.list-group>.list-group-item {
  padding-left: 30px;
}

.list-group.list-group-root>.list-group>.list-group>.list-group-item {
  padding-left: 45px;
}

.list-group-item .glyphicon {
  margin-right: 5px;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

     data_1

      Item 1.1

      Item 1.2

A: I've added a comment to the javascript to show how/where to stop the propagation.

$('.list-group-item .glyphicon').on('click', function (e) {
  //stop the propagation of the click on the icon(s)
  e.stopPropagation();
  console.log('clicked span but not anchor');
});
.list-group.list-group-root {
  padding: 0;
  overflow: hidden;
}

.list-group.list-group-root .list-group {
  margin-bottom: 0;
}

.list-group.list-group-root .list-group-item {
  border-radius: 0;
  border-width: 1px 0 0 0;
}

.list-group.list-group-root>.list-group-item:first-child {
  border-top-width: 0;
}

.list-group.list-group-root>.list-group>.list-group-item {
  padding-left: 30px;
}

.list-group.list-group-root>.list-group>.list-group>.list-group-item {
  padding-left: 45px;
}

.list-group-item .glyphicon {
  margin-right: 5px;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

     data_1

      Item 1.1

      Item 1.2


text:
Q: Probability question about convolution I'm preparing for Probability Theory and Mathematical Statistics exam and I've got some struggles with one exercise.
https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-041-probabilistic-systems-analysis-and-applied-probability-fall-2010/exams/MIT6_041F10_quiz02_s08_sol.pdf
I'm analyzing Question 1 c)

I just don't understand where did bounders $[3.5,4]$ come from:
Can anyone help me?

A: The function $f_Y(4.5-\alpha)$ only has support on $\alpha \in [3.5, 4.5]$ and $f_X(\alpha)$ only has support on $\alpha \in [0, 4]$ so their product only has support on $\alpha \in [3.5,4]$. Try plotting the functions to see this better.


text:
Q: Are there any conventions for printing optional values? Suppose I want to overload operator<< for an optional<T> class template. How would I print the "absent value", and how would I print a "real value" x?
none
some x

or
[]
[x]

Or should I literally print nothing for the first case and x for the second? How is this normally handled?

A: I like the option of print None and Some x.  I think that this immediately describes what's going on (especially for people familiar with Haskell).
Personally, I would not use the [] and [x] alternative, because many languages use the square brackets to denote some sort of list. If I were to see that output, I would immediately be thinking that a list had been printed, as opposed to an optional type.

A: In the absence of any context, I would think of an optional as a special case of a collection, that either is empty or has one member.
You probably already have a convention for how to print collections or compound objects, but something like {} if it's empty or {x} if it has the value x would seem reasonable. If you print out an empty vector as none and a vector with three elements as some x y z, then by all means apply the same convention to an optional type :-)

A: I'm not aware of any specific convention. Personally I'd print (null) when the value is missing and the actual value otherwise.

A: It depends on the type. If you want a string to be printed, it could be "" or "Fred". If it is an array, it could be {} or { 1, 2, 3 }.
Following this video or the code attached in the web page can help you.  Pretty Printer

A: The choice of behavior should probably be based on why you're implementing an output operator. If it is mostly for debugging purposes it is important to provide a visual clue that a value is missing. Printing an existing value between square brackets or just the open and closed brackets if the value is missing is a valid approach, given that square brackets are often used to indicate optionality, e.g. in command help messages.
On the other hand if this is meant to be a general purpose output operator the best approach is probably to print existing values as you would for the non-optional underlying type and the empty string for missing values.

A: The UNIX and the Echo.

There dwelt in the land of New Jersey the UNIX, a fair maid whom savants traveled far to admire. Dazzled by her purity, all sought to expose her, one for her virginal grace, another polished civility, yet another for her agility in performing exacting tasks seldom accomplished even in much richer lands. So large of heart and accomodating of nature was she that the UNIX adopted all but the unsufferably rich of her suitors. Soon many offspring grew and prospered and spread to the ends of the earth.
Nature herself smiled and answered to the UNIX more eagerly than to other mortal beings. Humbler folk, who knew little of more courtly manners, delighted in her echo, so precise and crystal clear they scarce believed she could be answered by the same rocks and woods that so garbled their own shouts into the wilderness. And the compliant UNiX obliged with perfect echoes of what ever she was asked. When one impatient swain asked the UNIX, 'Echo nothing', the UNIX obligingly opened her mouth, echoed nothing, and closed it again.
'Whatever do you mean,' the youth demanded, 'opening your mouth like that? Henceforth never open your mouth when you are supposed to echo nothing!' And the UNIX obliged.
'But I want a perfect performance, even when you echo nothing,' pleaded a sensitive youth, 'and no echoes can come from a closed mouth.' Not wishing to offend either one, the UNIX agreed to say different nothings for the impatient youth and the sensitive youth. She called the sensitive nothing '\n.'
Yet now when she said '\n,'she was really not saying nothing so she had to open her mouth twice, once to say '\n,' and once to say nothing, and so she did not please the sensitive youth, who said forthwith, 'The \n sounds like a perfect nothing to me, but the second ruins it. I want you to take back one of them.' So the UNiX, who could not abide offending, agreed to undo some echoes and called that '\c'. Now the sensitive youth could hear a perfect echo of nothing by asking for '\n' and '\c' together.
But they say that he died of a surfeit of notation before he ever heard one.
-- Doug McIlroy


text:
Q: DKIM fails at reply to email i have a problem with dkim and reply to an email. If i send a email to google everthing is OK:
   Authentication-Results: mx.google.com;
   dkim=pass header.i=@klh.de;
   spf=pass (google.com: domain of xx.xxx@klh.de designates 213.214.14.217 as permitted sender) smtp.mailfrom=xx.xxx@klh.de;
   dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=klh.de
   Received: from localhost (localhost [127.0.0.1]) by mx.klh.de (Postfix) with ESMTP id 21328124736 for <xxx@gmail.com>; Fri, 13 Jan 2017 11:14:34 +0100 (CET)
   DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=klh.de; s=201611; t=1484302474; bh=/PcOn/Jx9dciEPOjrIgSPkSriQjwDzxCFVJSYG0Twe4=; h=Date:From:To:Subject:References:In-Reply-To:From; b=mOMITyTzK7VS2pkJtlpF1hkN1ZK94MfVri+bpbQ3iaglhWtIzbK54T/d1oFI377rZ
 3CUgdBPITu//iWvLM+nXacCt9PA68o4aKiZJ/ROue3OBBKe2Hsv7hViYbrWWmedeVx
 AKAIgcm/MLtfWjCXqta2EF93KAG2PbQC65uoZMyA=

but if i answer to an email send originally from a google user the dkim failed:
   Authentication-Results: mx.google.com;
   dkim=fail header.i=@klh.de;
   spf=pass (google.com: domain of xx.xxx@klh.de designates 213.214.14.217 as permitted sender) smtp.mailfrom=xx.xxx@klh.de;
   dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=klh.de
   Received: from localhost (localhost [127.0.0.1]) by mx.klh.de (Postfix) with ESMTP id 401451201B6 for <xxxx@gmail.com>; Fri, 13 Jan 2017 10:52:36 +0100 (CET)
  DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=klh.de; s=201611; t=1484301156; bh=nQbpY6Q0JdxvJ9ALEm7aToUJOYq5u0rDOOKM7egvk+s=; h=Date:From:To:Subject:References:In-Reply-To:From; b=U2Hs92VT0XeogRtMZnG7ME5wrXsykq8v5yOwfdAgCNhC+Bnd+K7kdPLT/NizVg2AI
 gY97ArCjm8jIdk6XsAmBdEWj/HXVYp3ELOTOBv1MqdPp/jqQl2TdyZEZ8YXwgyR1+4
 3oKLfQ3J7Ro0o5PiLr2CFrxjm9DuWAorvSiH4m2A=

This only occurs when i reply to an email that communication i haven't started. If i send a email and the google user replies and i answer to this email everthing is fine and dkim pass.

A: Great you've pinpointed a repeatable scenario. Just cc the email to multiple free DKIM testing addresses (as you send it to google expecting a fail) and hopefully one of them will give you some clue.
Also update opendkim to the most recent version to rule multiple bugs already fixed.


text:
Q: issues with merging CSS stylesheets? Essentially, I want to use the vertical timeline from CodyHouse in a project hosted on a Bootstrap template. I've migrated the HTML content, but the CSS files are causing issues. For example:

*

*it distorts the navigation bar and header spacing

*there should be a bounce animation for the elements of the timeline - no go.

*I can't see any of the p text of the timeline

How can I edit/arrange the stylesheets appropriately so that the timeline inherits the font/background style of the Bootstrap but maintains the animation from CodyHouse?

A: Kinda hard to really pinpoint what your issues are with no code offered by you for inspection, but....
You'll really need to use your browser's inspect/page-debug functions on your page to see how both the bootstrap stylesheet and the vertical timeline's stylesheet are doing things to your page.
Bootstrap has it's own default color scheme, you can easily change it by just looking for the corresponding bootstrap elements and then overriding them in your custom stylesheet
If you're linking to three different styles sheets (boostrap, timeline, and your custom one), there can obviously be a conflict right there. Let's say on boostrap it's doing one thing to the nav bar and the top spacing, while your custom css is doing another thing and affect bottom spaces - see what I mean? You should really inspect those css files to see what they are affecting exactly.
Also, is the vertical timeline plugin you are using based on bootstrap 4? If it's built around bootstrap 3 that could be another issue as well. BS4 is still relatively new and many plugins that were based on BS3 may require further alteration.

A: Looking at the rules within styles.css ...you'll probably want to remove the generic rules - all those under 'Primary style' and then the first few under 'Resource style' where it makes reference to stuff within header{...}.
Also don't include the other stylesheets, reset.css and demo.css


text:
Q: Set zero axes in R How can one force the visualisation of the zero axes y=0, x=0 in R, removing the external ones siding the plot? I want to obtain the same effect that one can have for example in Gnuplot with set xzeroaxis, set yzeroaxis.

A: You can do this using by suppressing the default axes by using axes=FALSE and then using axis to draw horizontal and vertical lines to represent the axes.
# example plot
plot(-2:2, -2:2, axes=FALSE)

# add yaxis at position zero and rotate labels 45deg
axis(side=2, pos=0, las=1, lty="dashed")

# x axis
axis(side=1, at=c(-2,-1,1,2), pos=0, lty="dashed")

This produces

A: Actually, I have solved my own question as follows:
f<-function(x) x^3-2*x

# take the axes off first
plot(f,-2,2, axes=FALSE)

# re-set the axes at a given point (pos=0)
axis(1, pos=0, at=c(-2,-1,0,1,2))
axis(2, pos=0, at=c(-4,-2,2,4))

produces the below, which is what I had in mind (labels and the rest can be then adjusted at will).


text:
Q: XSLT 2.0 --- Order of document collection() I have a directory of multiple XML files to be merged. The files are named in the order they should be merged, such as: file1.xml, file2.xml, file3.xml ..the number of files varies.
This code has worked in merging the files:
<xsl:for-each select="
    collection(iri-to-uri('/home/book/?select=*.html;recurse=yes'))">
    <xsl:apply-templates select="node()|@*"/>
</xsl:for-each>

Concern/Question: Has this merged the files in order by coincidence? Do I need to recode to enforce an ordered reading of the files? If so, any suggestions?
(using Saxon)
UPDATE: I believe Ian's reply to be correct, that is: no guarantee of ordering. I'm working on code like this (to be refactored and validated). I'm not sure this is a robust approach though.
<!-- load the directory file names into a variable -->
<xsl:variable name="file-names">
    <collection>
        <xsl:for-each select="collection('/home/book/?select=*.html')">
            <file>
                <xsl:value-of select="tokenize(document-uri(.), '/')[last()]"/>
            </file>
        </xsl:for-each>
    </collection>
</xsl:variable>

<!-- open the files in a sorted order -->
<xsl:template match="/">
    <xsl:for-each select="$file-names/collection/file">
        <xsl:sort select="replace(., '[^\d]', '')" data-type="number" />
        <xsl:variable name="filename" select="concat('/home/book/', . )"/>
        <xsl:copy-of select="doc($filename)"/>
    </xsl:for-each>
</xsl:template>

A: Looking at the source code for the default collection URI resolver it delegates to File.listFiles, which provides no guarantee of the ordering (in general, though it may be more consistent on some platforms than on others).

A: The <xsl:sort select="tokenize(document-uri(.), '/')[last()]"/> line works fine for a process I use that had a similar need (to sort the output transformed XML by filename input). Note that I've adapted Martin's line by closing the select with the quote mark " and by applying the self-closing tag.


text:
Q: Partially filled orbitals and strongly correlated electrons Interesting behavior of strong correlation between electrons occur in metals with partially filled d or f orbitals (transition metals). Why these strong correlations do not appear with elements with incomplete p or s orbital for example ?

A: At a fundamental level, many of the interesting properties of transition metals and transition metal compounds can be understood qualitatively from the simple but elegant Hubbard model.
The basic idea is that electronic structure is a competition between kinetic energy and electron-electron repulsion. For solids that have s and p orbitals only, there is a lot of overlap between the valence orbitals of neighboring atoms. Having a lot of overlap means that the system resembles an electron gas, in which case kinetic energy is in some sense more important than e-e interactions. This is why simple metals such as sodium behave a lot like Fermi gasses.
On the other hand, d and f orbitals are more tightly bound to the nucleus because the electrons in the higher s and p shells do not screen the nucleus very well. In this case there is not so much overlap between the d and f orbitals and the neighboring sites, and so e-e interactions become more important relative to kinetic energy. These interactions result in strong correlations between electrons and interesting behavior such as metal-insulator transitions.
One small aside: you can make correlation important in s and p systems if you stretch them to reduce the overlap between orbitals. For example, the stretched H2+ ion is a pathological case for which many electron structure methods such as DFT will actually have serious problems. See Phys. Rev. B 56, 16021 (1997).

A: It isn't transition metals that display the strongly correlated behaviour, it's materials like transition metal oxides. The link you provided in the comments makes this clear.
The d and f orbitals are not populated in the order you expect. For example the 4s atomic orbital is populated before the 3d, and the 5p and 6s are populated before the 4f. That means the electrons in d and f orbitals tend to be screened by electrons in higher shells e.g. the 3d electron density lies nearer the nucleus than the 4s electron density and is partially screened by it.
This screening means, and there is considerable hand waving here, that in the sort of materials described in the Wikipedia article the d and f orbitals don't give you the free electron bands you get in metals. Instead you find these materials tend to be on the cusp between metals and insulators. It's because the electrons are neither free nor tightly bound that you get the strong electron correlations.
Later: if anyone is still interested, the f orbitals are even more deeply buried behind s and p orbitals than the d orbitals are. That's why the lanthanides are chemically so similar (and hard to separate). Since the f orbitals are almost completely screened they do not affect the chemical properties of the atoms very much. The d orbitals are screened to a lesser extent, so there is more variation in chemistry along a row of the transition metals than along the lanthanides.


text:
Q: How does java source code ultimately interact with files? I have been wondering about how the java compiler/interpreter manages to provide an interaction between bytecode/source code and file input and output.
I understand that InputStream and OutputStream are the super-classes of all file i/o classes, but after reading through them, they provide no implementation for the basic file interaction methods (read() and write(byte b)). My initial idea was that perhaps the compiler would translate these methods into certain bytecode operations (that return a byte from a file or write a byte to a file) that only occur in this instance, but this may not be correct.
If Java were compiled to assembly, then I understand that a certain instruction would be translated into platform-specific file i/o code (e.g. cout << ... in C), but this is obviously (afaik) not the case with Java since it's compiled to bytecode.
Can anyone enlighten me?

A: Like all classes, and since they are not interfaces, what will happen is that there will be an invokevirtual on the method, nothing else (there are 5 invocation opcodes in the JVM: invokevirtual, invokeinterface, invokespecial, invokestatic and invokedynamic).
Now, of course, the JRE will certainly have some native methods to deal with OS-level stuff (when dealing with File*Streams for instance); and for what it matters, the actual *Stream implementations may differ from OS to OS, and from JRE to JRE as well. All that matters is that the method does what its contract says it does.
After that, at runtime, the JIT may replace it with more efficient code (even native code). But InputStream and OutputStream are classes like any other; such details are of no relevance to the Java developer but, of course, of the utmost importance to the JDK developer ;)

A: File I/O is provided by the operating system. Writing a file on Linux works differently than writing a file on Windows. Even low-level languages like C usually provide an abstraction layer in the standard library to make it look the same, but the generated binary code for either platform calls completely different operating system functions. That means any file I/O is in the end an operating-system specific task. OS abstraction in Java is provided by the Java Virtual Machine.
The implementation of all Java standard classes (like java.io.FileOutputStream) is shipped with your OS-specific Java Virtual Machine (the software you get when you click on "Free Java Download" on java.com). The JVM can implement the methods of these classes in Java, or can choose to implement a method native which looks like this.
This means that the method is implemented in the programming language the JVM is written in. When the class does something which must be provided by a call to the operating system (like file IO), it can only be implemented natively.

A: The InputStream and OutputStream classes do not provide any implementation themselves. They both are abstract classes that require derived classes to provide an implementation. For example, the read() method of the InputStream class is an abstract method:
public abstract int read() throws IOException

Now, a derived class can provide an implementation in any way it sees fit, but you are correct that low-level operations such as operations which require access to system calls ultimately need some bootstrapping code which cannot be implemented in pure Java alone.
For example, if you have a look at the source code for FileInputStream, you will see its read() method is declared native:
public
class  FileInputStream extends InputStream
{
    /* (...) */

    public native int read() throws IOException;

    /* (...) */
}

Since FileInputStream is a core Java class, the JVM may be taking some shortcuts, but the typical way to implement native methods is through the Java Native Interface (JNI). The JNI makes it possible to provide an implementation of a Java method written in a different language such as C.
How does this all fit together? When you are compiling a class which uses the read() method of FileInputStream, as far as the compiler is concerned, you are just using some method of some class, and the bytecode will be the same as for any other method and class. At runtime, when your call is executed, the JVM, having previously loaded the FileInputStream class, knows the method you are calling is a native method, and calls its native implementation.


text:
Q: Problem computing Lie algebra of unitriangular matrices Let $G$ the Lie group of the upper unitriangular matrices, i.e.
\begin{align}
G : = \{ A= (a_{ij})_{ij} \, \, |\,  a_{ii} = 1 \, \, \, \forall \, i \, \, \text{and} \, \, a_{ij} = 0 \, \, \forall \, i>j \}
\end{align}
Computing the Lie algebra of G.
I think that the result is the set of the strictly upper triangular matrices. I tried also to prove that
\begin{align}
LG = \{A= (a_{ij})_{ij} \, \, |\,  a_{ij} = 0 \, \, \forall \, i\geq j \}
\end{align}
The proof of $ \, "\supseteq \, "$ I think's it's okay, but I have some problem to show the inclusion $\, "\subseteq " \, $.
Any suggestions? Thanks in advance!

A: Yes, $\mathfrak g$ is the space of strictly upper triangular matrices. If $M$ is such a matrix, then it is clear that$$(\forall t\in\mathbb{R}):e^{tM}\in G.\tag1$$On the other hand, if $(1)$ holds then, differentiating $e^{tM}$ and taking $t=0$, one gets that $M$ is upper triangular. But if one of the entries of the main diagonal of $M$ was not $0$, the entry at the same position of $e^{tM}$ would not be $1$. Therefore, $M$ us strictly upper triangular.

A: There is no need to mess with the exponential map if you make the simple observation that $G$ is the affine subspace $I+\{\text{strictly upper-triangular matrices}\}$ in $\operatorname{End}(\mathbb{R}^n)$. Thus the tangent space at identity corresponds is canonically identified with the tangent space to the vector subspace of strictly upper-triangular matrices at $0$, which is of course the space of strictly upper triangular matrices.


text:
Q: Select rows based on a window of 10 days with an offset I have a table with 3 columns including a timestamp called startson:

events ( eventid number, name varchar2, startson timestamp )

I have a variable that is a number which is an offset that says what the startson boundry should be in my where clause.
For example:
if my_var = 0 (select events that started in the last 10 days)
if my_var = 1 (select events that started 20 days ago up until 10 days ago)
if my_var = 2 (select events that started 30 days ago up until 20 days ago)
if my_var = 3 (select events that started 40 days ago up until 30 days ago)
.. and so on

Here's what I've tried:
select *
from events
where startson >= (sysdate-(10*my_var))
and startson <= (sysdate-(10*my_var+10))
order by startson asc

This doesn't return any rows even though I know there are hundreds of rows with some starting in the last 10 days.

A: Here you have a minus sign after your multiplication sign.
(sysdate-(10*-my_var))

In your case you will end up with something like
(sysdate -(10 * -1)) that will give you (sysdate + 10 days)

Maybe you should have something more like
(sysdate-(10*my_var))

And you should invert the  "<=" and ">=" conditions for
where startson <= (sysdate-(10*my_var))
and startson >= (sysdate-(10*my_var+10))

A: Here's the basic formula if I understood the problem correctly:
-- between last 10 days --
WHERE startson BETWEEN trunc(SYSDATE) AND (trunc(SYSDATE) - INTERVAL '10' DAY)

To get all intervals in a single select:
SELECT start_date, ten_days_ago, twenty_days_ago, thirty_days_ago, fourty_days_ago
  FROM
(
 SELECT trunc(SYSDATE) start_date
     , (trunc(SYSDATE) - INTERVAL '10' DAY) ten_days_ago
     , (trunc(SYSDATE) - INTERVAL '20' DAY) twenty_days_ago
     , (trunc(SYSDATE) - INTERVAL '30' DAY) thirty_days_ago
     , (trunc(SYSDATE) - INTERVAL '40' DAY) fourty_days_ago
  FROM dual
)
--WHERE your_column BETWEEN twenty_days_ago AND ten_days_ago
/


text:
Q: Efficient design for a auto refresh mobile app I was presented this problem few days back. Requirement was to design a mobile app which serves sports content to the user (say soccer).
The app will allow the user to subscriber to specific team.
Based on user's team selection, the apps serves only content related to that team on the user's home screen.
Of course user has option to see content for all teams (via menu options).
Special focus was on how would the content on user's home screen get refreshed automatically and should also take into consideration that user has (or has not) subscribed to a specific team.
To the last question, I suggested following 2 solutions:
1) The app can send tiny requests to the server which would only contain user's identifier, user's team selection. Based on the team selection in the input request, the server would return only the content related to the team.
2) If the content volume is less and the number of distinct teams are few then broadcast all the information and let the app do the necessary filtering (of course this is less efficient compared to #1).
Sharing this on forum to get other possible design decisions. In case this is not the right forum, please answer in comments and I'll post in appropriate forum.
Thanks

A: Basically when you want to do an auto-refresh system you have only two way :
1 :  The client send request(s) periodically. This is enough if :

*

*The interval of refreshing is not too short

*You don't expect your application to run for millions of people

*Computing the result don't cost too much

This can be implemented with just a naïve use of some query on a database server-side. Of course if you need some more performance you can have some intermediary layers.
2 : Pushing result from servers : this is a bit trickier to architecture properly but here is somme good points :

*

*You send only new data to clients

*Performance wise it's the best

However the limits are more important :

*

*Handling lost of connexions is a bit harder

*You need to catch every events that update the datas in order to push your refresh to the clients.

But because there are more than you that need this architure solution exists : here is the one that fits the best for you in the Javaworld :
JMS : Java Message Service, which is a Message Oriented Middleware (MOM).
JMS is a specification with different implementation, personnaly i would go for activeMQ which is the Apache one. Here is a topic about that : Which JMS implementation do you use?
If you don't/can't use JMS then just remember this : Messare-Oriented-Middleware. Google that should help you to find what you need.

A: Definitely option 1).
We developed something similar in other industry where users are interested in getting information about states of different resources. The architecture is like this:

*

*Server keeps all users subscriptions. That's where you keep things like: SubscribedUserId, EventType (win, loss, numberOfPointsChanged, all, whatever the case might be), deliveryChannel (http notification, email, push notification for mobiles)

*Whenever something happens with the resource, we put message in a queue. Message contains things like: teamEventIsFor, subscriberUser, deliveryChannel, deliveryAddress, etc...

*Separate windows service(s) (one that handles all deliveryTypes [email, http, push] or one for each channel) consume queue messages and deliver actual content to users. In your case, it would be through push notifications.

Now, having on mind that push notifications are not guaranteed delivery (although you get pretty good delivery rate overall) you might also want to implement some kind of a http resource where mobile app could poll from time to time to check if there are some news for that particular user  (that's optional).

A: You have a third option:
3) Follow a publish-subscribe pattern.
To implement this you could use an system such as Amazon Simple Notification Service (SNS). First you would need to set up a platform application containing your API key (for Android) or private key and APNS certificate (for iOS).
When a user starts your app for the first time, the app would ask the user to authorise push notifications access, contact your server and send a token (which is used to register an endpoint on the SNS platform application).
This allows you the ability to send push notifications to the app running on the user's device (which can be handled silently, or be displayed as a real time notification that there is new data available).
You can then set up Topics for each team, that a given user can choose to subscribe to. When the user selects a team, the app sends a request to your server to subscribe to the topic, which you forward to AWS using their API. If a user wants to unsubscribe from a topic you once again forward this request to AWS.
This allows you to send updates for each team to the appropriate topic and have this information distributed -only- to users who subscribe, scalably, and in real time. Your server will only need to ping the topic once and AWS will handle delivery to each user.
Of course, you will need to implement logic to handle the notification, subscribe, register etc. but it does allow your users to receive updates in real time.
Reviewing your options:
1) Easiest to implement and probably necessary for new installs who have not yet registered. You will need this either way so I would recommend you implement this method initially. Your servers will be under load proportional to users however so it would be worthwhile to consider option 3) as you scale (and using a HTTP cache such as varnish or squid to minimise compute and database load)
2) It's not necessary to broadcast this information to -all- of your users but it is effectively publish-subscribe with a single topic (all users). It would be more efficient to only notify users that care.
3) This is the most scalable option and has the added advantage of being real-time. You would be able to notify the user of an update even if they are not using your app at the time. Under a publish-subscribe architecture you will we able to notify only the users concerned with your information, and once updated you can set a timeout value that prevents the user updating from your server until XX time. This way if updates are more frequent than your timeout value users will never need to hit your server.


text:
Q: Strip YouTube Embed Code Down to URL Only Please help!
I need to strip the following code so that it only uses the "value" part
$<object width="360" height="226"><param name="movie" value="http://www.youtube.com/v/IkZuQ-aTIs0"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/IkZuQ-aTIs0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="360" height="226"></embed></object>

So in this case it would strip it down to http://www.youtube.com/v/IkZuQ-aTIs0
The catch is that this is dynamic so it is pulling these embed codes for different files so they are changing.
Please help :D

A: <?php

$string = '<object width="360" height="226"><param name="movie" value="http://www.youtube.com/v/IkZuQ-aTIs0"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/IkZuQ-aTIs0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="360" height="226"></embed></object>';

preg_match_all('#http://www.youtube.com/v/([\w\-]+){11}#is', $string, $matches);

print_r( array_unique($matches[0]) );

?>

A: The best way is to use a DOM parser.
http://php.net/manual/en/class.domdocument.php
$doc = new DOMDocument();
$doc->loadHTML('<object width="360" height="226"><param name="movie" value="http://www.youtube.com/v/IkZuQ-aTIs0"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/IkZuQ-aTIs0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="360" height="226"></embed></object>');

A: $string = '<object width="360" height="226"><param name="movie" value="http://www.youtube.com/v/IkZuQ-aTIs0"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/IkZuQ-aTIs0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="360" height="226"></embed></object>';

$start = strpos($string, 'value="');
$string = substr($string, $start + 7);
$end = strpos($string, '" ');
$string = substr($string, 0, $end);

echo $string;

little more complex than webartos, but will grab any value, instead of just the youtube link


text:
Q: Errors in align environment The following block of code comes up with 10 errors.
\begin{align}
\|\tau(\textbf{x})-\tau(\textbf{y})\| &= \|\textbf{x}-\textbf{y}\| \\
\|\tau(\textbf{x})-\tau(\textbf{y})\|^2 &= \|\textbf{x}-\textbf{y}\|^2 \\
(\tau(\textbf{x})-\tau(\textbf{y})) \cdot (\tau(\textbf{x})-     \tau(\textbf{y})) &= (\textbf{x}-\textbf{y}\) \cdot (\textbf{x}-\textbf{y}) \\
\|\tau(\textbf{x})\|^2 - 2(\tau(\textbf{x}) \cdot \tau(\textbf{y})) +     \|\tau(\textbf{y})\|^2 &= \|\textbf{x}\|^2 - 2(\textbf{x} \cdot \textbf{y}) + \|\textbf{y}\|^2 \\
-2(\tau(\textbf{x}) \cdot \tau(\textbf{y})) &= -2(\textbf{x} \cdot \textbf{y}) \\
\tau(\textbf{x}) \cdot \tau(\textbf{y}) &= \textbf{x} \cdot \textbf{y}   \text{ , proving the Lemmma.} \\
\end{align}

The errors are:
! Missing } inserted,
! Missing $ inserted,
! Missing { inserted,
! Missing } inserted,
! Missing { inserted,
! Missing $ inserted,
! Missing \endgroup inserted,
! undefined control sequence, ! Misplaced \omit,
! Missing { inserted.

Each of the errors are apparently in the line with \end{align}. I can't for the life of me see what's wrong with the code. Any help would be greatly appreciated.

A: Your main error has been mentioned in comments already. I tried to improve your code a bit. The most important suggestion is to use a custom command for your bold symbols. Like this, you can change the appearance for all occurrences with an ease. And the code will look nicer and will be easier to read.
% arara: pdflatex

\documentclass{article}
\usepackage{mathtools}
\DeclarePairedDelimiterX{\norm}[1]{\lVert}{\rVert}{#1}
\usepackage{bm}
% define a command with a name more telling than mine in order to have nicer syntax and flexibility afterwards.
\newcommand*{\wtistb}[1]{\boldsymbol{#1}} % whatever this is supposed to be

\begin{document}
\begin{align}
    \norm{\tau(\wtistb{x})-\tau(\wtistb{y})} &= \norm{\wtistb{x}-\wtistb{y}} \\
    \norm{\tau(\wtistb{x})-\tau(\wtistb{y})}^2 &= \norm{\wtistb{x}-\wtistb{y}}^2 \\
    \bigl(\tau(\wtistb{x})-\tau(\wtistb{y})\bigr) \cdot \bigl(\tau(\wtistb{x}) - \tau(\wtistb{y})\bigr) &= (\wtistb{x}-\wtistb{y}) \cdot (\wtistb{x}-\wtistb{y}) \\ % fixed \) here
    \norm{\tau(\wtistb{x})}^2 - 2 \bigl(\tau(\wtistb{x}) \cdot \tau(\wtistb{y})\bigr) + \norm{\tau(\wtistb{y})}^2 &= \norm{\wtistb{x}}^2 - 2(\wtistb{x} \cdot \wtistb{y}) + \norm{\wtistb{y}}^2 \\
    -2 \bigl(\tau(\wtistb{x}) \cdot \tau(\wtistb{y})\bigr) &= -2(\wtistb{x} \cdot \wtistb{y}) \\
    \tau(\wtistb{x}) \cdot \tau(\wtistb{y}) &= \wtistb{x} \cdot \wtistb{y} \text{,\qquad proving the Lemmma.} % removed \\ here
\end{align}
\end{document}


text:
Q: How to solve the problem that the Jenkins pipeline syntax on the remote server cannot git clone the project I want to deploy jenkins on a remote server, when I push the code to the repository, Jenkins builds automatically.
I have uploaded ssh to github and can connect using terminal.
ssh -T git@github.com
Hi admin! You've successfully authenticated, but GitHub does not provide shell access.
In jenkins, I use Pipeline script from SCM to monitor git push events.
Credentials I choose to use SSH Username with private key, and fill in the private key of the ubuntu remote server, but when I try to build,an error occurs.
The error message is as follows:
Started by user iyao
hudson.plugins.git.GitException: Command "git fetch --tags --force --progress --prune -- origin +refs/heads/iyaomz:refs/remotes/origin/iyaomz" returned status code 128:
stdout:
stderr: git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:2675)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandWithCredentials(CliGitAPIImpl.java:2099)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.access$500(CliGitAPIImpl.java:85)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl$1.execute(CliGitAPIImpl.java:619)
    at jenkins.plugins.git.GitSCMFileSystem$BuilderImpl.build(GitSCMFileSystem.java:366)
    at jenkins.scm.api.SCMFileSystem$Builder.build(SCMFileSystem.java:584)
    at jenkins.scm.api.SCMFileSystem.of(SCMFileSystem.java:219)
    at jenkins.scm.api.SCMFileSystem.of(SCMFileSystem.java:191)
    at jenkins.scm.api.SCMFileSystem.of(SCMFileSystem.java:174)
    at org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition.create(CpsScmFlowDefinition.java:118)
    at org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition.create(CpsScmFlowDefinition.java:70)
    at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:311)
    at hudson.model.ResourceController.execute(ResourceController.java:101)
    at hudson.model.Executor.run(Executor.java:442)
Finished: FAILURE

A: Make sure your credentials include the user Git:

As noted in JENKINS-20879, try with a passphrase-less private key (one which is not created encrypted).


text:
Q: config.json Not Being Found on ASP.NET Core Startup in Debug I have created a basic WebAPI project via Yeoman (note: I have this same issue with a "real" project I am working on, but yo demonstrates the problem as well) targeted at netcoreapp1.0 on OSX.
On the command line, it restores, builds, and runs fine via dotnet restore, dotnet build, dotnet run.
When I am in Visual Studio Code and use Debug, however, I always receive the error: "The configuration file 'config.json' was not found and is not optional." which points at the first line of my Main method.
Here is my Program.cs entry point:
public static void Main(string[] args)
{
    var host = new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .Build();

    host.Run();
}

Here is project.json:
{
  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.0",
      "type": "platform"
    },
    "Microsoft.AspNetCore.Mvc": "1.0.0",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0",
    "Microsoft.Extensions.Configuration.CommandLine": "1.0.0",
    "Microsoft.Extensions.Logging": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.Extensions.Logging.Debug": "1.0.0",
    "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0"
  },

  "tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "Views",
      "Areas/**/Views",
      "appsettings.json",
      "web.config"
    ]
  },

  "scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  },

  "tooling": {
    "defaultNamespace": "WebAPIApplication"
  }
}

Adding Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace WebAPIApplication
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("config.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"config.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseMvc();
        }
    }
}

If any other information is required, please let me know and I would be happy to add it.
As Gerardo suggested, printing out Directory.GetCurrentDirectory() I get two different outputs.
From command line (which works): ~/Projects/Path/WebApiApplication/
From debug in VSCode: ~/Projects/Path
What I also noticed is that output is going to ~/Projects/Path/WebApiApplication/bin/Debug/netcoreapp1.0/ but no files are going with it (including config.json).

A: It seems like dotnet run is being run standing on the project folder and works correctly, but VS Code debug-mode is not.
This is configured in VS Code in a config file .vscode\launch.json.
Find the line that says:
       "cwd": "${workspaceRoot}",

and change it to:
        "cwd": "${workspaceRoot}/MyProjectFolder",

You need to change the startup folder (cwd) so that it matches the location of your project.json/config.json/ etc.
More Info here: Visual Studio Code Launch Configurations

A: Move .vscode folder INSIDE of "YourSolution/src/YourProject" directory, by mistake opened the project in VSCode in YourSolution directory and by tweaking configuration like the suggested answer ran the application, but with configuration problems.
So in VSCode you have to open the project from inside YourProject and default config will run properly.


text:
Q: Is there anyway to clean this SQL/JS up? I am working on a bot that sends users riddles when the join a discord server, the code below selects a random riddle from one table, saves it in another table with the user's (who the riddle has been sent to) id, before sending them a message with the riddle in.
Does anyone know if there is a better way to do this than what I have done, because it feels a bit ugly/inefficent having a query in a query.
client.on('guildMemberAdd', member => {
  connection.query('SELECT riddle FROM riddles AS riddle ORDER BY RAND() LIMIT 1', function (error, results, fields) {
    if (error) throw error;

    connection.query('INSERT INTO cache VALUES (?, ?)', [member.id, results[0].riddle], function (error, results, fields) {
      if (error) throw error;
    });

    member.send(results[0].riddle);
  });
});

Thanks.

A: To be honest, that's a pretty good way to go about it. Though you probably want to send the riddle only after you've ensured it's been saved to the database.


text:
Q: How to use has_scope gem in a view in rails 4? I'm trying to add a clickable link that will sort a page of links alphabetically using has_scope gem. What exactly would i put in my view to make this work?

Model  Links.rb
 scope :abc, -> { order("links.title ASC") }

Links_Controller.rb
 has_scope :abc

 def index
    @links = apply_scopes(Link).all
 end

Index.html.erb

    <%= render partial: "shared/link", collection: @links %>

_link.html.erb

    <a class="link-title" href="<%= link.url %>" target="_blank"><%= link.title %>

<%= link.url %>

<%= link.description %>

        <% link.tags.any? %>
            <% link.tags.each do |tag| %>

                    <%= link_to tag_path(tag) do %>
                        #<%= tag.name %>
                    <% end %>

        <% end %>

A: You need to pass a title param to the scope.
Change the scope in the model to scope :abc, -> title { order("links.title ASC") }
or
scope :abc, -> title { order(title: :asc) }
You could do something like this in the partial

    <a class="link-title" href="<%= link.url %>" target="_blank"><%= link.title %>

<%= link.url %>

<%= link.description %>

  <% end %>

    <%= link_to 'Order ASC', tag_path(:abc => true) %>

A: Since has_scope works off of url params you will need to add the params on a link_to
<%= link_to "title", links_path(abc: true) %>


text:
Q: Convert Html to Image in Swift iOS I am working on an App which requires preview of various html files that are loaded from web. I  have a preview of those html pages.However, when the number of images increase, there is a delay to load UIWebView which significantly increase the time to load the app.
I am looking to by-pass it by converting the html to images(its for the purpose of preview) and then loading it on UIImageView.
How do I convert html(it might be local or web resource) to a image ?


text:
Q: How to format this obscure character vector into datetime (or POSIX) objects in R? I have the following character vector:
times <- c("2020-04-15T03:30:05.197Z", "2020-04-15T03:30:05.366Z", "2020-04-15T03:30:05.530Z")

I need to first convert it to a lubridate datetime object or a POSIXct object - I'm not picky. The following does not work:
as_datetime(link_log$createdAt,
            format = "%Y-%m-%d%T%H:%M:%S")

To be honest, I'm not sure what's going on with the end of each element. What is the .197Z, .366Z, .530Z? I am assuming these are the problem!

A: The anytime package was written to make this automatic: no need for format strings or conversions:
R> times <- c("2020-04-15T03:30:05.197Z", "2020-04-15T03:30:05.366Z",
+             "2020-04-15T03:30:05.530Z")
R> anytime::anytime(times)
[1] "2020-04-15 03:30:05.197 CDT" "2020-04-15 03:30:05.365 CDT"
[3] "2020-04-15 03:30:05.529 CDT"
R>

You can pass in character or factor or numeric or ... formats, and as long as the format is sensible and common (i.e. we ignore two-digit years) it should work. It even allows for different formats. It also runs faster than most alternatives requiring a format or hint.

A: lubridate's ymd_hms seems to work.
options(digits.secs=6)
lubridate::ymd_hms(times)

#[1] "2020-04-15 03:30:05.197 UTC" "2020-04-15 03:30:05.366 UTC"
#    "2020-04-15 03:30:05.529 UTC"


text:
Q: How to count the number of instances where the wind directions is < (-3.54) for >= 5 consecutive days in a season I have a data set of U wind direction recorded every day from 1993 to 2016. I would like to know how many instances there are in a season (let's say Autumn; from March to May) where U is <(-3.54) for >= 5 days. I have looked at previous questions and answers on stack overflow, but I haven't been able to find an example to guide me. Any help would be appreciated.
A section of my data set looks like this:
```````````````````````````````
Year Month Day           U
1   1993     1   1   2.2752712
2   1993     1   2  -2.3828683
3   1993     1   3  -6.5054070
4   1993     1   4  -6.5550585
5   1993     1   5  -0.8896707
6   1993     1   6  -2.2694185
7   1993     1   7   1.6020930
8   1993     1   8   4.4161047
9   1993     1   9  -3.4612790
10  1993     1  10  -4.1855815
11  1993     1  11   4.3345735
12  1993     1  12   6.7505038
13  1993     1  13   2.7704460
14  1993     1  14  -0.3126935
15  1993     1  15  -5.2111823
16  1993     1  16   0.1577910
17  1993     1  17   3.2431200
18  1993     1  18   4.1351938
19  1993     1  19   8.8824225
20  1993     1  20  11.5171123
21  1993     1  21   8.4929847
22  1993     1  22  -0.6879845
23  1993     1  23   9.1634883
24  1993     1  24   8.0907365
25  1993     1  25  -5.9970930
26  1993     1  26 -11.9065697
27  1993     1  27  -0.0509885
28  1993     1  28  -0.9271122
29  1993     1  29  -1.2506782
30  1993     1  30   2.8655622
31  1993     1  31   5.1648452
32  1993     2   1  -0.6710272
33  1993     2   2  -0.1745542
34  1993     2   3   7.1772285
35  1993     2   4  -1.2568218
36  1993     2   5  -1.4439727
37  1993     2   6   0.6784107
38  1993     2   7   8.6756010
39  1993     2   8   1.5709885
40  1993     2   9  -6.4978875
41  1993     2  10   0.8981590
42  1993     2  11  -5.4501548
43  1993     2  12  -2.0549033
44  1993     2  13  -0.9364535
45  1993     2  14   2.3316280
46  1993     2  15   8.4644767
47  1993     2  16   4.2322285
48  1993     2  17  -4.2141278
49  1993     2  18  -7.1285853
50  1993     2  19  -3.9616670
51  1993     2  20   3.0711045
52  1993     2  21   0.8550193
53  1993     2  22   2.7637208
54  1993     2  23  -4.0326550
55  1993     2  24  -6.9834690
56  1993     2  25  -7.1804845
57  1993     2  26   2.7410468
58  1993     2  27   0.9994572
59  1993     2  28  -2.1881782
60  1993     3   1  -1.6012982
61  1993     3   2   0.4499225
62  1993     3   3  -2.4872480
63  1993     3   4  -2.1658527
64  1993     3   5  -1.4132365
65  1993     3   6   2.2400198
66  1993     3   7  -3.1068022
67  1993     3   8  -0.5415117
68  1993     3   9   0.9616280
69  1993     3  10  -7.1419960
70  1993     3  11   1.2279457
71  1993     3  12   6.1011240
72  1993     3  13   4.9892440
73  1993     3  14   4.8197285
74  1993     3  15   1.6525583
75  1993     3  16  -9.0284302
76  1993     3  17  -3.3607170
77  1993     3  18   5.7897092
78  1993     3  19  -2.5350580
79  1993     3  20  -3.1431975
80  1993     3  21   6.2275968
81  1993     3  22   0.9624417
82  1993     3  23  -8.9311823
83  1993     3  24  -9.6640115
84  1993     3  25  -9.7974420
85  1993     3  26  -3.8447093
86  1993     3  27   1.6185270
87  1993     3  28  -4.5626552
88  1993     3  29  -7.6756202
89  1993     3  30   5.4181783
90  1993     3  31   5.9135658
91  1993     4   1   3.4654847
92  1993     4   2  -2.1095738
93  1993     4   3  -9.3131203
94  1993     4   4  -8.1391280
95  1993     4   5 -10.7533140
96  1993     4   6   6.1808530
97  1993     4   7   5.7693025
98  1993     4   8   0.3322870
99  1993     4   9  10.3273835
100 1993     4  10   5.7872480
101 1993     4  11   0.8317830
102 1993     4  12  -0.7549225
103 1993     4  13  11.9887015
104 1993     4  14   4.1117440
105 1993     4  15   1.2044572
106 1993     4  16   1.3899808
107 1993     4  17  11.2100388
108 1993     4  18   8.2815310
109 1993     4  19  -0.8285080
110 1993     4  20  -5.7935273
111 1993     4  21  -4.0424420
112 1993     4  22  -0.5786045
113 1993     4  23   0.3742055
114 1993     4  24  -0.4698642
115 1993     4  25  -0.3981780
116 1993     4  26   5.5060660
117 1993     4  27   5.0961628
118 1993     4  28   4.3308137
119 1993     4  29   7.8211433
120 1993     4  30   1.4068415
121 1993     5   1  -6.0343218
122 1993     5   2   2.5626165
123 1993     5   3  -0.2517055
124 1993     5   4  -0.3624998
125 1993     5   5   5.4518413
126 1993     5   6   8.0799417
127 1993     5   7   9.6727713
128 1993     5   8   6.9166862
129 1993     5   9   5.1044767
130 1993     5  10  -3.5812015
131 1993     5  11  -0.6386435
132 1993     5  12   3.8953680
133 1993     5  13   2.2846125
134 1993     5  14   6.8920930
135 1993     5  15   6.3412790
136 1993     5  16   9.9857557
137 1993     5  17   4.9041085
138 1993     5  18   1.2711628
139 1993     5  19  -0.8744572
140 1993     5  20  -1.7563565
141 1993     5  21   7.7133918
142 1993     5  22   1.8609305
143 1993     5  23   5.0106588
144 1993     5  24   2.2513178
145 1993     5  25   9.8685660
146 1993     5  26  17.1051357
147 1993     5  27  15.9958140
148 1993     5  28  11.9747288
149 1993     5  29  10.4338953
150 1993     5  30   9.8273450
151 1993     5  31   2.9315697
152 1993     6   1  -4.8080815
153 1993     6   2   7.4390697
154 1993     6   3   9.7631200
155 1993     6   4   3.0179265
156 1993     6   5  -0.9081978
157 1993     6   6   0.8990115
158 1993     6   7  -1.6712595
159 1993     6   8  -6.6958335
160 1993     6   9   3.0657173
161 1993     6  10   2.8695543
162 1993     6  11  14.8854070
163 1993     6  12   6.0319572
164 1993     6  13  -0.8188955
165 1993     6  14  -2.1511820
166 1993     6  15   2.8237210
167 1993     6  16   6.0374808
168 1993     6  17   5.7747092
169 1993     6  18   3.7086240
170 1993     6  19  11.2165893
171 1993     6  20  13.0581202
172 1993     6  21  10.7091860
173 1993     6  22   5.5876357
174 1993     6  23   7.3413180
175 1993     6  24  -3.0820543
176 1993     6  25  -0.4195735
177 1993     6  26   2.3836045
178 1993     6  27  -3.6750388
179 1993     6  28  10.1507362
180 1993     6  29  11.7455232
181 1993     6  30   4.6698065
```````````````````````````````

A: You can do:
with(rle(Data$U < -3.54), sum(values==TRUE & lengths>=5))

You want to explore only some months:
D <- subset(Data, Month %in% 3:5)
with(rle(D$U < -3.54), sum(values==TRUE & lengths>=5))

There is no such sequence.
To have some data in the result I changed the task a little bit:
R <- rle(D$U > -3.54)
Rdat <- with(R, data.frame(values, lengths))
Rdat$start <- 1 + cumsum(c(0, head(Rdat$lengths, -1)))
Ri <- subset(Rdat, values==TRUE & lengths>=5)
cbind(D[Ri$start,], Ri$lengths)

The result are the starting days of the sequences.
#> cbind(D[Ri$start,], Ri$lengths)
#    Year Month Day          U Ri$lengths
#60  1993     3   1 -1.6012982          9
#70  1993     3  11  1.2279457          5
#76  1993     3  17 -3.3607170          6
#96  1993     4   6  6.1808530         14
#112 1993     4  22 -0.5786045          9
#122 1993     5   2  2.5626165          8
#131 1993     5  11 -0.6386435         21

A: Here's a way with dplyr that also keeps the first day of each instance.
library(dplyr)

df %>%
  filter(Month %in% 3:5) %>%
  mutate(threshold = U > -3.54,
         group = cumsum(threshold != lag(threshold, default = FALSE))) %>%
  group_by(group) %>%
  mutate(n_days = n()) %>%
  summarise_all(first) %>%
  filter(threshold, n_days >= 5) %>%
  select(-group, -threshold) -> instances

instances
# A tibble: 7 x 5
   Year Month   Day      U n_days
  <int> <int> <int>  <dbl>  <int>
1  1993     3     1 -1.60       9
2  1993     3    11  1.23       5
3  1993     3    17 -3.36       6
4  1993     4     6  6.18      14
5  1993     4    22 -0.579      9
6  1993     5     2  2.56       8
7  1993     5    11 -0.639     21

nrow(instances)
[1] 7