text:
Q: Error for c++ example I want to input alphabet to binary code, and output the alphabet from generated binary code.
Example
1      --> a
01     --> b
001    --> c
0001   --> d
00001  --> e
000001 --> f

a => 1
b => 01
c => 001
d => 0001
e => 00001

-------------Encode.cpp--------------------
#include "Encode.h"

Encode::Encode()
{
}

Encode::~Encode()
{
}

void Encode::inputWord()
{
    cout << "Input word: ";
    cin.getline(word, 255);
    return;
}// User input a word

char * Encode::getBuf(void)
{
    return buffer;
}// return buffer to Decode::setBuf(char* buf)

void Encode::printEncResult()
{
    int size = strlen(word);
    int buffersize = 0;
    cout << "Encoding result" << endl; // print similar binary

    for (int i = 0; i < size; i++)
    {
        if (word[i] == 'z')
        {
            for (int j = 0; j < 25; j++)
            {
                cout<<buffer[buffersize++];
            }
        }
        else
        {
            int len = (int)word[i] - (int)'a';
            for (int j = 0; j < len; j++)
            {
                cout<<buffer[buffersize++];
            }
            cout << buffer[buffersize++];
        }
    }
}// output similar binary

int Encode::encodeWord(void)
{
    int buffersize = 0;
    int size = strlen(word);

    for (int i = 0; i < size; i++)
    {
        if (word[i] == 'z')
        {
            for (int j = 0; j < 25; j++)
            {
                buffer[buffersize++] = '0';
            }
        }
        else
        {
            int len = (int)word[i] - (int)'a';
            for (int j = 0; j < len; j++)
            {
            buffer[buffersize++] = '0';
            }

            buffer[buffersize++] = '1';
        }
    }
    return 0;
}// change word to similar binary

--------Decode.cpp-------------
#include "Decode.h"

Decode::Decode()
{
}

Decode::~Decode()
{
}

void Decode::setBuf(char * buf)
{
    int i = 0;
    int size = 0;

    while (*(buf + i) == '1' || *(buf + i) == '0')
    {
        i++;
    }
    size = i;

    for(int i = 0; i < size; i++)
    {
        buffer[i] = buf[i];
    }
    return;
}// set buffer from Encode::getBuf(void)

void Decode::printWord() // print similar binary
{
    int i = 0;
    int size = 0;
    int check = 1;
    while (check)
    {
        if (word[i] >= 'a' && (int)word[i] <= 'z')
        {
            i++;
            size = i;
        }
        else
            check = 0;
    }

    cout << "Decoding result" << endl;
    for (int i = 0; i < size; i++)
    {
        if (word[i] >= 'a' && (int)word[i] <= 'z') // **this part is also strange** I can not shoten the code.
            cout<<word[i];
    }
    cout << endl;
}

int Decode::decodebin(vector<char> buffer)
{
    int buffersize = 0;
    int check = 0;
    int size = 0;
    int i = 0;
    char printval = 'a';

    while (buffer[i] == '1' || buffer[i] == '0')
    {
    i++;
    }
    size = i;

    for (int j = 0; j < size; j++) // nested loop does not work. I want save words in order
    {
        for (i = 0; i < size; i++)
        {
            if (buffer[i] == '0')
                ++printval;
            else
            {
                word[j] = printval; // In this part, word[0] does not have any value.
                printval = 'a';
            }
        }
    }
return 0;
}

In this code, I want save values in order, but word[0] does not have any value. Moreover, If I input 'bb' then, 'bbbb' saved ins word array.

A: There are some problems and consideration you need to take care of:

*

*as Fei Xiang said in the comments don't use magic numbers, use characters since you have a character array.

*int printWord function you actually get the word and print the same word, there is no conversion as your problem statement. your didn't take buffer into account.

*you are using some data validation to get your array size, this could end up a disaster(UB). you need to pass your array size to your function or use std::vector(Recommended).

*in this statement if ((int)word[i] >= 97 || (int)word[i] <= 122) as I said don't use magic number and || should be change to && otherwise you end up in an infinity loop.

Anyway by keeping your approach(using array) and function signature here's what you can do :
int Decode::decodebin(void)
{
    int buffersize = 0;
    int check = 0;
    int size = 0;
    int i = 0;
    char printval = 'a';
    while(buffer[i] == '1' || buffer[i] == '0')
    {
        i++;
        size = i;
    }
    for(int i = 0; i < size; i++)
    {
        if(buffer[i] == '0')
            ++printval;
        else
        {
            cout << printval;
            printval = 'a';
        }

    }
    return 0;
}

void Decode::printWord()
{
    int i = 0;
    int size = 0;
    int check = 1;
    while(check)
    {
        if(word[i] >= 'a' && word[i] <= 'z')
        {
            i++;
            size = i;
        }
        else
            check = 0;
    }
    cout << "Decoding result" << endl;
    for(int i = 0; i < size; i++)
    {
        int distance = word[i] - 'a';
        for(int j = 0; j < distance; ++j)
            cout << '0';
        cout << '1';
    }
    cout << endl;
}

EDIT BASED ON OP REQUIREMENT IN COMMENTS:
using std::vector you can implement your needs like this :
#include <iostream>
#include <vector>

class Decode
{
public:
    void decodebin(std::vector<char> buffer)
    {
        char printval = 'a';
        for(unsigned int i = 0; i < buffer.size(); i++)
        {
            if(buffer[i] == '0')
                ++printval;
            else
            {
                word.push_back(printval);
                printval = 'a';
            }
        }
    }

    void printWord(void)
    {
        for(auto iter = word.begin(); iter != word.end(); ++iter)
            std::cout << *iter;
        std::cout << std::endl;
    }

private:
    std::vector<char> word;
};

int main()
{
    Decode decoder;
    std::vector<char> buffer = {'0', '1', '0', '0', '0', '0', '1', '0', '0', '0', '1'};
    decoder.decodebin(buffer);
    decoder.printWord();
    return 0;
}

Here decodebin stores the given input into word member variable of Decode class. Then printWord function print word values on the screen.
std::vector has all the power of C-style array and it's nicer and easier to use. You can retrieve it's size whenever you want and you don't have to worry about the memory it's allocating.


text:
Q: how do you obtain a member of a class which is also a member of a class of the same type? I'm currently writing a program in c++ using recursion and I want to print out a vector of tuples that resides in a class member which has the same type as the class itself. Below, you can see the class "Data" which has a class member called "child" of the same type. It also has a vector of tuples I want to print out using the readTuples function.
class Data {
    public:
        vector<tuple<string, string, string>> myTuple;
        Data *child;

    void readTuples(){
        for (int i = 0; i < myTuple.size(); i++)
        {
            std::cout << "ID: " << get<0>(myTuple[i]) << "\tTYPE: " << get<1>(myTuple[i]) << "\tVALUE: " << get<2>(myTuple[i]) << "\n";
        }
    }
}

In the function below, I receive the Data object as a parameter. I add a child to the Data object using the typecheck function which returns a data object with a filled vector of tuples. I then read the vector using the readTuples function. This works...
 Data typecheck(Data data)
{
    Data* child = new Data();
    Data childData = statementList->typecheck(*child);
    child = &childData;
    data.child = child;
    data.child->readTuples();
    return data;
}

output
ID: a   TYPE: integer   VALUE: 1
ID: b   TYPE: integer   VALUE: 2
ID: c   TYPE: integer   VALUE: 3

The data object is then returned and caught in the object Data (i.e. the typecheck function has just been executed).
Data typecheck(Data data)
{
    data = block->typecheck(data);
    data.child->readTuples();

    return data;
}

But when I try to read the vector of tuples again, it crashes. The command line returns weird symbols, so I presume this has something to do with pointers and memory allocation.
Thanks in advance.

A: Data typecheck(Data data)
{
    Data* child = new Data();
    Data childData = statementList->typecheck(*child);
    child = &childData;
    data.child = child;
    data.child->readTuples();
    return data;
}

childData is a local variable whose reference you take. Once this function terminates, childData is destroyed, and any references to it invalidated. At that point, data.child points to garbage, and dereferencing it is undefined behavior.
If you want the pointer to last longer than the current function, either return it, or allocate it on the heap and store a pointer to that.

redpajama_set_name: RedPajamaStackExchange


text:
Q: XAMPP update to PHP 5.4 Hi I'm using XAMPP with PHP Version 5.3.1, how can I update to PHP 5.4 alpha 1 version?

A: I'm not sure whether you are using Windows, but if you do, try this. Works for me, except that the DLLs were located in /apache/modules and not /apache/bin.
Remember to backup your old contents and to replace your php.ini! And, by the way: I downloaded my source files from here: http://windows.php.net/snapshots/


text:
Q: Windows 10 Shortcut Target - Change Working Directory? I have this file structure:
Program_Folder
   -> Program.exe
Data_Folder
   -> Data1
   -> Data2
   -> Data3
   etc.

Adding an absolute path to each data file works but I quickly run out of characters. The limit is 260 characters, I believe. Is it possible to change the working directory once and then add all the data files?
I'm also wondering if this can be done with a relative path. Something similar to the command line "cd.." "cd Data_Folder". Can this be done?
In the shortcut:
Target: C:\Program_Folder\Program.exe C:\Data_Folder\Data1 C:\Data_Folder\Data2 C:\Data_Folder\Data3

A: Since I'm getting dislikes instead of an answer I guess I will try and answer my own question.
What I ended up doing instead of a shortcut was a batch file. I put this file in the Data_Folder making this the working directory for the batch file. Then I made a shortcut to the batch file instead. This works but it feels a bit hacky.  Anyone have a better solution?
C:\Program_Folder\Program.exe ^
Data1 ^
Data2 ^
Data3 ^


text:
Q: get the name of product with the maximum number of orders I have 2 tables orders and product as
orders has only one field (order_id)
and the products have a reference to the order_id,
how to get the name of product with the maximum number of orders
I tried this query
SELECT   MAX(mycount)
FROM
(Select products.product_name , count(orders.order_id) mycount
FROM Orders, products
WHERE products.order_id = Orders.order_id
GROUP BY orders.order_id)

but it only gave me the max value,
how to add the name field (products.product_name) to the result??


text:
Q: How can I design a predicate that returns a list of integers of length N such that none of the integers are divisible by the numbers in the list? So I have this predicate divisible that is true if I give a number that can be divided by any of the numbers in the list.
divisible([], N) :- fail.
divisible([H|T], X) :- X mod H =:= 0, !.
divisible([H|T], X) :- divisible(T, X).

My goal is to design a predicate called generateList that returns a list of positive integers of length N such that none of the integers is divisible by any of the numbers in the List D and at the same time is smaller or equal to its rank. I also don't want to include 0 in that list.
This is an example of what I'm trying to achieve.
? - generateList([3,5],5,L).
[ 1, 1, 1, 1, 1] ;
[ 1, 2, 1, 1, 1] ;
[ 1, 1, 2, 1, 1] ;
[ 1, 1, 1, 2, 1] ;
[ 1, 1, 1, 1, 2] ;
[ 1, 2, 2, 1, 1] ;
...(more solutions)

I'm trying to use the previous predicate to evaluate the numbers and print the ones that aren't divisible by the numbers in the list D and cannot be smaller than its rank.
I have the base case going which is fairly simple, however I can't seem to come up with the right combination to print the integers correctly or evaluate it.
The predicate divisible does work, but I'm also not sure if I need to change it to make it work with the new predicate.


text:
Q: Merging two android library and generate one aar Is it possible to Merge two android library and generate one aar file
I have
> :app (application)
> :library-1 (library)
> :library-2 (library)

:library-2 is dependent on :library-1 and :app dependents on :library-2
both libraries as res and package is different
I need a single aar from :library-2, :library-1. Is this possible ?

A: You need you extract java and res file from both library projects and import that file onto one project.


text:
Q: Trying to get 3 finger gestures. Geis tools shows only 2 finger support when I've used 3 on Windows 7 partition I've been trying to get touchegg to work so I can have 3 finger gestures similar to that on a MacBook. It wasn't working so I checked geis-tools for how many fingers are supported. It says 2 but then I realized I've used 3 when I use my windows 7 partition. Anybody know what the issue is?
I'm on 12.04 LTS

A: I would recommend to try again the touchegg, by now (13.04) it is only needed to install it with no further configuration, except for the definition of the gestures you like. Please take a look in this blog post: http://task3.cc/1068/os-x-like-multitouch-gestures-for-macbook-pro-running-ubuntu-12-10/


text:
Q: Adonis.js: Как получить ширину и высоту загруженной на сервер картинки? Необходимо перед сохранением изображения проверить ширину и высоту на попадания в допустимые диапазоны. Но вот беда, на сервере объект upload выглядит как-то вот так:

То есть здесь только общие для всех файлов свойства. А мне нужно достучаться до свойств изображения, в частности размеров. Подскажите, пожалуйста, как это делается в Adonis.js или хотя бы на любом другом Node.js фреймворке.

A: Как можно было догадаться, upload ничего не может знать о ширине и высоте изображения. Для решения этой задачи был задействован сторонний пакет Jimp, который понимает немало форматов изображения и может изъять из них необходимые мне метрики.


text: Q: Is there a way I can share a bluetooth mouse between two OSs on the same computer? I'm dual booting between Linux Mint 16 and Windows 8 on my laptop, and I use a bluetooth mouse. Is there any way I can hack together a solution so that my mouse will work on both OSs without having to pair the mouse again each time I reboot into a new OS?


text: Q: Is it secure to use SMTP password in .php file in WordPress website? Currently I am making feedback contact form without a plugin. Trying not to use plugins if possible. In action .php file there must be written server settings such as SMTP server, SMTP username etc. and eventually SMTP password. As it is not a Gmail, but hosting mailbox, SMTP password and mail password are the same. Says, that sending mail using SMTP is more secure. But if I will write all this data into my .php file insite WordPress platform will it be secure? What is possibility to be this data hacked?


text:
Q: How to replace and shift the string pattern in python using re? I have a snippet like
re.sub(r"""\s*(\p{LD}+)\s+NEAR/(\d)\s+(\p{LD}+)\s*""",r""""$1 $3"~$2""",'foo NEAR/4 bar')

in python.
expected output is
"foo bar"~4
but now i am getting
foo NEAR/4 bar

i am trying to convert a scala code to python.
scala code is
val near_rex = """\s*(\p{LD}+)\s+NEAR/(\d)\s+(\p{LD}+)\s*""".r;
val out = near_rex.replaceAllIn("foo NEAR/4 bar", """"$1 $3"~$2""");

scala snippet is working fine here http://www.simplyscala.com/

A: I don't know scala, so I don't know what \p{LD}+ is supposed to match but using \w to match [a-zA-Z0-9_] (foo/bar), the regexp is ok:
>>> re.sub(r"""\s*(\w+)\s+NEAR/(\d)\s+(\w+)\s*""",r""""\1 \3"~\2""",'foo NEAR/4 bar')
'"foo bar"~4'

In order to return the captured groups, you have to use \1, \2... instead of $1.

As suggested by Avinash Raj in comments, you can get rid of triples quotes by using simple ones:
re.sub(r'\s*(\w+)\s+NEAR/(\d)\s+(\w+)\s*',r'"\1 \3"~\2','foo NEAR/4 bar')

Furthermore \p{L} is not Scala-specific (credits to Amal Murali), but is used to match a unicode character belonging to the "letter" category.


text:
Q: Pandas : Add arrays as values of column I have a Pandas DataFrame df that stores some numeric values :
print(df)

       value
0          0
1          2
2          4
3          5
4          8

And I have a function that converts a numerical value to a one-hot vector
print(to_categorical(0))
[1 0 0 0 0 0 0 0 0 0]

print(to_categorical(5))
[0 0 0 0 0 5 0 0 0 0]

etc...
So, I can call my function over my columns of numeric value :
print(to_categorical(df['value'))

[[1 0 0 0 0 0 0 0 0 0]
 [0 0 1 0 0 0 0 0 0 0]
 [0 0 0 0 1 0 0 0 0 0]
 [0 0 0 0 0 1 0 0 0 0]
 [0 0 0 0 0 0 0 0 1 0]]

And now I want to store my results as a new column. Here is what I expect from my example :
df['one-hot'] = to_categorical(df['value')
print(df)

        value                    one-hot
0          0       [1 0 0 0 0 0 0 0 0 0]
1          2       [0 0 1 0 0 0 0 0 0 0]
2          4       [0 0 0 0 1 0 0 0 0 0]
3          5       [0 0 0 0 0 1 0 0 0 0]
4          8       [0 0 0 0 0 0 0 0 1 0]

But this give me an error since pandas tries to flatten my array into multiple colums. How can I do that ?

A: First I think working with lists in pandas is not good idea, but is is possible by convert to lists:
df['one-hot'] = to_categorical(df['value').tolist()


text:
Q: Can some one tell me how to make the function run once and then end? I'm a total newb when it comes to stack please forgive me I have googled over and over and read several threads on stack on how others stopped a redirect loop however, the issue I have from what I have read is I need this page to redirect to same URL + /universal which as I understand is the reason for the loop. I tried the code for checking the url but it did not stop the loop.
$(window).load(function() {
url = "{{ collection.url }}/universal";
$( location ).attr("href", url);
});

A: I would make an if-statement and check if the URL already contains the "/universal" part, something like
if(window.location.href.indexOf('/universal') < 0){
    url = "{{ collection.url }}/universal";
    $( location ).attr("href", url);
}


text:
Q: gcc compile errors when c++ code is sound My last question on here had issues that apperently were gcc not the code(code errors were solved and then I noticed issues with gcc ). I have since whipped up a short hello world program that I know is sound to test this:
#include <iostream>
using namespace std;

int main()
{
cout << "Hello, World!" << endl;
}

but gcc still throws errors.
I named the file "test.cpp" and stored it directly in my home folder then tried:
gcc ./test.cpp -o Test

gcc ~/test.cpp -o Test

gcc /home/josh/test.cpp -o Test

All 3 times with and without capitalizing "Test".
Gcc gives the following errors:
/tmp/ccre0DEJ.o: In function `main':
test.cpp:(.text+0xa): undefined reference to `std::cout'
test.cpp:(.text+0xf): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >        (std::basic_ostream<char, std::char_traits<char> >&, char const*)'
test.cpp:(.text+0x14): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >         (std::basic_ostream<char, std::char_traits<char> >&)'
test.cpp:(.text+0x1c): undefined reference to `std::ostream::operator<<(std::ostream& (*)(std::ostream&))'
/tmp/ccre0DEJ.o: In function `__static_initialization_and_destruction_0(int, int)':
test.cpp:(.text+0x4a): undefined reference to `std::ios_base::Init::Init()'
test.cpp:(.text+0x59): undefined reference to `std::ios_base::Init::~Init()'
collect2: error: ld returned 1 exit status

My question is: How can I fix Gcc? If not should I try another compiler?
EDIT: I have tried reinstallint gcc and it still fails.

A: O.K. this was a duplicate (I can usually catch that before posting).
The answer was found here: undefined reference to 'std::cout'
I had to use
g++ ~/test.cpp -o Test

instead of
gcc ~/test.cpp -o Test

NB: Actually, it is better to compile with all warnings and debug info, that is to add  -Wall -Wextra -g to your g++ or gcc command. Read more about Invoking GCC.

A: Please try to run g++ or add 'cpp flags' to the command, for example -lstdc++  which will link the code with the standard library of c++.
gcc can compile cpp code but only with the right flags.


text:
Q: Springdata elastic search not able to support empty spaces in wildcard bool query I am using org.springframework.data:spring-data-elasticsearch:4.1.0 with elasticsearch 7.8.1.
I have a requirement where I need to lookup partial search for multiple attributes. I have implemented wildcard bool queries which is working fine except it is not able to do lookup for empty spaces.
Here is my actual query:
GET /maintenance_logs/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "vinNumber.keyword": "DH34ASD7SDFF84742"
          }
        },
        {
          "term": {
            "organizationId": 1
          }
        }
      ],
      "minimum_should_match": 1,
      "should": [
        {
          "wildcard": {
            "dtcCode": {
              "value": "*Cabin*"
            }
          }
        },
        {
          "wildcard": {
            "subSystem": {
              "value": "*Cabin*"
            }
          }
        },
        {
          "wildcard": {
            "maintenanceActivity": {
              "value": "*Cabin*"
            }
          }
        },
        {
          "wildcard": {
            "description": {
              "value": "*Cabin*"
            }
          }
        }
      ]
    }
  }
}

Here is my SearchRequest:
public static SearchRequest buildSearchRequest(final String indexName,
                                                   final SearchRequestDTO dto,
                                                   final String vinNumber,
                                                   final Integer organizationId, Pageable pageable) {
        try {
            final int page = pageable.getPageNumber();
            final int size =  pageable.getPageSize();
            final int from = page <= 0 ? 0 : pageable.getPageSize();

            SearchRequest searchRequest = new SearchRequest(indexName);
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

            final QueryBuilder vinQuery = QueryBuilders.termQuery("vinNumber.keyword", vinNumber);
            final QueryBuilder orgIdQuery = QueryBuilders.termQuery("organizationId", organizationId);

            boolQueryBuilder.must(vinQuery);
            boolQueryBuilder.must(orgIdQuery);

            boolQueryBuilder.minimumShouldMatch(1);

            boolQueryBuilder.should(QueryBuilders.wildcardQuery("dtcCode", "*" + dto.getSearchTerm() + "*"));
            boolQueryBuilder.should(QueryBuilders.wildcardQuery("subSystem", "*" + dto.getSearchTerm() + "*"));
            boolQueryBuilder.should(QueryBuilders.wildcardQuery("maintenanceActivity", "*" + dto.getSearchTerm() + "*"));
            boolQueryBuilder.should(QueryBuilders.wildcardQuery("description", "*" + dto.getSearchTerm() + "*"));

            searchSourceBuilder.query(boolQueryBuilder);

            searchSourceBuilder
                    .from(from)
                    .size(size)
                    .sort(SortBuilders.fieldSort("statsDate")
                                  .order(SortOrder.DESC));

            searchRequest.source(searchSourceBuilder);
            return searchRequest;
        } catch (final Exception e) {
            e.printStackTrace();
            return null;
        }
    }

This works fine except I am unable to search for strings like "Cabin pressure".

A: If you want to be able to search a multi-token value like "Cabin pressure" to be findable with a wildcard query using "Cabin pressure" you  need to define it in the mapping as being of type keyword.
The wildcard search searches for single terms that match the wildcard expression, and "Cabin pressure" by default is split into two terms, "Cabin" and "pressure".
In Spring Data Elasticsearch the way to do this is to use @Field(type = FieldType.Keyword, but you'd either need to delete and recreate the index to have the new mapping applied, or you need to create a new index and reindex the existing one into the new. That's because index mappings cannot be updated and in your existing index the type is by default defined as text.
And, if you store "Cabin pressure" as one term - type keyword - don't forget that this will be a different thing than "cabin pressure". Keywords are not normalized, so that upper and lower case differences matter.


text:
Q: Edit default text for a file extension in Notepad++ Is it possible to make Notepad++ use a default set of text when I change the language to say php or perl? Basically I am lazy and say for perl I don't have to have to write out
#/usr/bin/perl
everytime or the  tags in php.
Edit:
I am avoiding the use of macros.

A: Notepad++ does not know what language you are intending to use when you open a new document.  You could specify a template that Notepad++ opens up from a shortcut something like
notepad++ -lperl -ro /path/to/template

You might also consider the snippets plugin to simplify the typing.


text:
Q: understanding init and method calling in python class Vehicle:
    def __init__(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity):
        self.number_of_wheels = number_of_wheels
        self.type_of_tank = type_of_tank
        self.seating_capacity = seating_capacity
        self.maximum_velocity = maximum_velocity

    @property
    def number_of_wheels(self):
        return self.number_of_wheels

    @number_of_wheels.setter
    def number_of_wheels(number):
        self.number_of_wheels = number

    def make_noise(self):
        print('VRUUUUUUUM')

tesla_model_s = Vehicle(4, 'electric', 5, 250)
print('number of wheels',tesla_model_s.number_of_wheels) # 4
tesla_model_s.number_of_wheels = 2 # setting number of wheels to 2
print('updated number of wheels',tesla_model_s.number_of_wheels) # 2
tesla_model_s.make_noise() # VRUUUUUUUM

when I run this code I got the below error.I think it might be because of getter and setter . Can anyone please help me sort this .
    Traceback (most recent call last):
      File "classes.py", line 23, in <module>
        tesla_model_s.make_noise() # VRUUUUUUUM
    AttributeError: Vehicle instance has no attribute 'make_noise'


text:
Q: Linked list in mips assembly # 1st item - head of the list!
n1_d: .word 1
n1_n: .word n2_d  # point to (beginning of) n2

# 3rd item
n3_d: .word 3
n3_n: .word n4_d

# 2nd item
n2_d: .word 2
n2_n: .word n3_d

# 5th item
n5_d: .word 5
n5_n: .word 0 # This is the last item in the list

# 4th item
n4_d: .word 4
n4_n: .word n5_d

I have a linked list in mips and I want to load every element with a logical way. For example
1, 2, 3, 4, 5
How I can do it with one loop?


text:
Q: Principal Component Analysis (PCA) before Vector Autoregressive model (VAR) The PCA is intended to convert covariates to linearly uncorrelated. On the opposite VAR model captures the linear interdependencies among covariates. Will then the PCA transformation improve VAR model or there is risk of decreasing its predictive power?

A: $$
pca: X=ST
$$
$$
VAR: S_t=\phi S_{t-1}+\epsilon_t=\hat{S_t}+\epsilon_t
$$
$$
Forecasting: \hat{X}_t=\hat{S}_tT=\phi S_{t-1}T=\phi X_{t-1} T^{-1}T=\phi X_{t-1}
$$
Couple of thoughts:
1) Performing PCA on your dependent variables won't change the predictive power, as shown above
2) if you do PCA on some set of exogenous variables (not shown above), it may give you better insight on whether all variables included in the set of exogenous variables provide predictive power, which is something you might consider doing for model selection... But it would have no affect on the predictive power on the model (it'd be equivalent to transforming your betas), so there's no reason to do it if your purpose is to strengthen your model.

A: Pure PCA will have no effect. If you

*

*run PCA,

*estimate a VAR on the principal components (PCs) and

*convert the estimated coefficients on the PCs to the coefficients on the original variables,

you will get the same coefficient values as from simply running a VAR model on the original data.
Even if you skip 3. and use the model from 2. for forecasting, you will still get the same forecasts as from the simple VAR on the original data.
The intuition is that PCs span the same space as the original variables; thus a projection on the PCs will have the same residuals and the same proportion of explained variance as a projection on the original variables.

A: It depends on how you use PCA in your analysis. If you are using it to remove variables/variance from the dataset/model, then the PCA-derived model will not retain the SAME predictive power as a fully dimensional model. That being said, different is not always worse. In fact, by squeezing more of your data's variance into fewer variables (i.e. forming principle components from the data) and removing some less informative PCs (ones capturing minuscule variance), there's a real possibility that the PCA-derived model's predictions become more accurate due to the fact that you're less likely to overfit (VARs tend to run into overfitting issues often due to model parameter count exploding...). If you keep all principle components after PCA, then the predictive power should remain constant across methods. The real tricky part can be making sense of the model in its principle component form. Evidently, there are ways to back-project pca-derived model coefficients to their full dimensional form (http://scot-dev.github.io/scot-doc/vartransform.html#covbivar1) so long as you retain all PCs after PCA (which seems utterly useless in most cases). I'm not sure you you would backproject when you remove PCs, but would love to find an answer to that question if anyone has any pointers.


text:
Q: Sorting discrete x axis in ggplot based on multiple criteria I want to create a visualization to show the racial composition of 600 classrooms in an ordered stacked bar plot. X would be the classrooms, there would be 600 vertical stacked bars with percent of each race represented by different colors. It would be sorted so that you can see roughly how many classrooms have a certain composition.
The problem is that I can't seem to find a way to order the x-axis based on multiple variables (to sort by race 1, then race, 2, etc.).
Here is some reproducible code with what I have tried.
teacher <- c(rep("a", 6), rep("b", 10), rep("c", 6))
studentrace <- c(rep("blk", 3), rep("white", 6), rep("latinx", 3),
rep("blk", 7), rep("white", 3))
my.df <- data.frame(teacher, studentrace)

library(dplyr)
bars <- my.df %>%
  group_by(teacher, studentrace) %>%
  summarise(n=n()) %>%
  mutate(percent=n/sum(n))

library(ggplot2)
ggplot(bars, aes(x=teacher, y=percent)) +
  geom_col(aes(fill=studentrace))

#best solution so far, but won't sort using multiple variables
ggplot(bars, aes(x=reorder(teacher, PERCENTWHITE), y=percent)) +
  geom_col(aes(fill=studentrace))

#where percent white is a variable I merged into my longform dataset

Here is what I got...but I want to be able to sort by x, then y, then z...
(https://drive.google.com/file/d/1zDX5eRGZlo2vf33WNlz74ybWSuaxO8jp/view?usp=sharing)
Thank you!!

A: One option is to make the order you want before to call gglot, directly in your dataset, with the function arrange() (this way you can sort according several variables), and then use in the aes() of your ggplot the function fct_inorder() from forçats library, in order to keep the same order as in your dataset.


text:
Q: Postgres/Knex "insert or update on table "locations" violates foreign key constraint" I am continuing to get the same error when I try to run seeds in Knex and Postgres. The error is error: insert or update on table "locations" violates foreign key constraint "locations_user_id_fore
ign". Can anyone figure out why it is throwing this error? I have tried changing a bunch of things. Thanks!
User Migrations
exports.up = function(knex, Promise) {
  return knex.schema.createTable('users', function(table) {
    table.increments()
    table.string('email').notNullable();
    table.string('password').notNullable();
  })
};

exports.down = function(knex, Promise) {
  return knex.schema.dropTable('users')
};

Locations Table
exports.up = function(knex, Promise) {
  return knex.schema.createTable('locations', function(table) {
    table.increments('id');
    table.string('placename').notNullable();
    table.float('latitude').notNullable();
    table.float('longitude').notNullable();
    table.integer('user_id').notNullable().references('id').inTable('users').onDelete('cascade');
  })
};

exports.down = function(knex, Promise) {
  return knex.schema.dropTable('locations')
};

User Seeds
exports.seed = function(knex, Promise) {
  // Deletes ALL existing entries
  return knex('users').del()
    .then(function () {
      // Inserts seed entries
      return knex('users').insert([
        {email: 'allie@gmail.com', password: 'p1'},
        {email: 'bob@gmail.com', password: 'p2'},
        {email: 'minnie@gmail.com', password: 'p3'}
      ]);
    });
};

Location Seeds
exports.seed = function(knex, Promise) {
  // Deletes ALL existing entries
  return knex('locations').del()
    .then(function () {
      // Inserts seed entries
      return knex('locations').insert([
        {placename: 'Himeji', latitude: 34.8394, longitude: 134.6939, user_id: 1},
        {placename: 'Long Beach', latitude: 33.7701, longitude: 118.1937, user_id: 3},
        {placename: 'Seattle', latitude: 47.6253, longitude: 122.3222, user_id: 2}
      ]);
    });
};

A: Putting as answer, as it would be too big for a comment.
Well the error message is clear enough that you have violated a foreign key constraint.
This is because for inserting a row in locations you need to give a user_id as well, which is referencing to column id in table users. If that particular user is not present in users table, you cannot insert that user_id in locations. See this line
table.integer('user_id').notNullable().references('id').inTable('users').onDelete('cascade');

So first you have to add that user in users table, then you can insert it it location.


text:
Q: WCF generate the wsdl was different with the original wsdl which was provided to create WCF Service? I got a original wsdl file from my boss and asked me to create a Dummy Web Service based on it. And then create a client to test it by using the new wsdl file which is generated from Dummy Web Service and it need to be exactly the same as the original wsdl. Unfortunately, I found that the new wsdl which was generated by the Dummy Web Service was different with the original one. Anyone could tell me why? How to get the same wsdl as the original one? Thanks!
What I did for this task:

*

*SvcUtil.exe /sc original.wsdl --> to get the C# service class and implement the concrete class for it (dummy web service)

*svcutil /t:metadata 'http://localhost/myservice/test.svc?singlewsdl' --> to get the new WSDL from the running dummy web service, but it will be different from the original one

*WSDLImp.exe to create the proxy class of Delphi client (test client)

A: That is always going to be the case. You are comparing two different WSDLs. One is a Virtual WSDL whared with your clients and used to generate a service with SvcUtil. Once you deploy the web-service, and take a look at the WSDL it shares, you now have a Concrete WSDL.
It is best practice for you to test your new service by making a service call based on the Virtual WSDL as this is the WSDL you are likely to share among your clients. SoaupUI is capable of generating and executing tests base on your Virtual WSDL.


text:
Q: Having sum problems, xslt 1.0 I've been trying to get the total amount spent by a user on products but with no success.
  Given the following XML sample, the total amount spent by the client 1 would be 21,00 but i'm getting 10,50 (this only happens if the client buys many times the same product, if he buys different products the returning amount is the expected)
XML sample:
<root>
            <sale id="1">
                <date>2014-01-01</date>
                <client>1</client>
            </sale>

            <sale id="2">
                <date>2014-01-02</date>
                <client>1</client>
            </sale>

            <sale_details saleID="1">
                <product id="1"/>
            </sale_details>

            <sale_details saleID="2">
                <product id="1"/>
            </sale_details>

            <product_details productID="1">
                <name>product x</name>
                <price>10.50</price>
            </product_details>

            <product_details productID="2">
                <name>product x</name>
                <price>5.26</price>
            </product_details>

            <client_detail clientID="1">
                <name>client 1</name>
            </client_detail>

            <client_detail clientID="2">
                <name>client 2</name>
            </client_detail>
    </root>

XSLT sample:
<xsl:template name="sum-spent-amount">
    <xsl:param name="clientID"/>
    <xsl:value-of select="sum(//gv:product_details[@productID=//gv:sale_details[@saleID=//gv:sale[gv:client=$clientID]/@id]/gv:product/@id]/gv:price)"/>
</xsl:template>

Thanks in advance!

A: Of course you're getting a result of 10.5: you are summing the unique instances of the sold products. You must sum the prices of the actual sales. Here's one way to do it:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:exsl="http://exslt.org/common"
exclude-result-prefixes="exsl">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:param name="clientID" select="1"/>

<xsl:key name="sale-by-clientID" match="sale" use="client" />
<xsl:key name="sale_detail-by-saleID" match="sale_details" use="@saleID" />
<xsl:key name="product-by-id" match="product_details" use="@productID" />

<xsl:template match="/">
    <xsl:variable name="mySaleIDs" select="key('sale-by-clientID', $clientID)/@id" />
    <xsl:variable name="prices">
        <xsl:for-each select="key('sale_detail-by-saleID', $mySaleIDs)">
            <price><xsl:value-of select="key('product-by-id', product/@id)/price"/></price>
        </xsl:for-each>
    </xsl:variable>

    <sum><xsl:value-of select="sum(exsl:node-set($prices)/price)"/></sum>
</xsl:template>

</xsl:stylesheet>

When this is applied to your input, the result is:
<?xml version="1.0" encoding="UTF-8"?>
<sum>21</sum>

A: I got to this solution using recursive template:
The template:
<xsl:template name="sum">

    <xsl:param name="nodes"/>
    <xsl:param name="total" select="0"/>

    <xsl:variable name="current" select="$nodes[1]" />
    <xsl:choose>
        <xsl:when test="$current">
            <xsl:variable name="product" select="//gv:product_details[@productID=$current/gv:product/@id]"/>
            <xsl:call-template name="sum">

                <xsl:with-param name="nodes" select="$nodes[position() > 1]"/>
                <xsl:with-param name="total" select="$total + $product/gv:price"/>

            </xsl:call-template>
        </xsl:when>
        <xsl:otherwise><xsl:value-of select="$total"/></xsl:otherwise>
    </xsl:choose>

</xsl:template>

Using the template here:
<xsl:variable name="clientID" select="1"/>
<xsl:call-template name="sum">
    <xsl:with-param name="nodes" select="//gv:sale_details[@saleID=//gv:sale[gv:client=clientID]/@id]" />
</xsl:call-template>


text:
Q: collapsible list with dynamically loaded content I have tried all kinds of lists I found all over the internet, but none of them seem to properly work. I think the reason for this might be the fact that the content of the list is dynamically loaded (with JQuery ajax).
On $(document).ready I load the list and append the html data to the div.
After that I try to make the list collapsible (the list is nested, it's a navigation for a database).
My best try so far:

function loadNavigation() {
  var _url = "http://api.writeplace.nl/idofnavigation
 var credentials = btoa("username:password!");

  $.ajax({
    headers: {
     "Authorization": "Basic " + credentials
   },
    url: _url,
    success: function(data, text) {
     //console.log(data);
     $("#container").empty();
     $("#container").append(data);
  $("#nav > li > ul ").addClass("verberg");
  $("#nav > li > ul > li > ul").addClass("verberg");
    }
  });
}

function loadPage(documentId) {

  if (!documentId) {
   documentId = "document-id";
  }

  var _url = "http://api.writeplace.nl/=" +  documentId;

 var credentials = btoa("username:password!");

  $.ajax({
    headers: {
     "Authorization": "Basic " + credentials
   },
    url: _url,
    success: function(data, text) {
     $("#tekst").empty();
     $("#tekst").append(data);
    }
  });
}

function uitvouwen(){

function uitvouwen1(){
 $("#container").on("click", "#nav > li", function(){

  $(this).children().toggleClass("verberg");
  //console.log("khbvdkvbedkvbewdkvfjbwekbfwkdjbvkejdbv");
 });
}

function uitvouwen2(){
 $("#container").on("click", "#nav > li > ul > li", function(){
  $(this).children().toggleClass("verberg");
  //console.log("gffhgfhh");

 });
}

uitvouwen2();
uitvouwen1();

}

The navigation is loaded and the most upper ul has the id nav. On document.ready I add the class  hide to #nav>li>ul and #nav>li>ul>li>ul, so the li items are set to hide by default. The problem with this list however is that if you click a link or a deeper down li item in the tree, it registers this also as a click on the levels above.
Is there a way to fix this? Or a better (cleaner) way to make collapsible nested lists with dynamic content?

A: This is an example of how I would do this. I used an data-id. attribute. This can come in handy when assigning functions to the menu. You can always travel down or up using the ids. It hides/shows the UL by finding an ancestor or itself containing a data-attribute.

$(document).ready(function() {
  $("#nav").html(loadnavigation(menu, null)); //to load the li items//
  $("#container").click(function(e){
    //e refers to the click event.
    //bind it
    var eventTarget = $(e.target);

    //we need to use closest here. If you append other HTML-elements to the li, eventTarget
    //will refer to these elements. This way, it always travels up to the
    //closest ancestor with an data-id attribute.
    eventTarget.closest("li[data-id]").children("ul").toggleClass("hide"); //find the closest ancestor (or self) that has data-id and hide its ul.

  });
});

//below is my own code just to show an example of my comment:

//I'm using a array, combined with objects to build the basic structure of the menu.
var menu = [{
  name: "list 1",
  menu: [{
    name: "sublist 1"
  }, {
    name: "sublist 2"
  }]
}, {
  name: "list 2",
  menu: [{
    name: "sublist 1",
    menu: [{
      name: "sublist 1"
    }, {
      name: "sublist 2"
    }]
  }, {
    name: "sublist 2"
  }]
}, {
  name: "list 3"
}];

function loadnavigation(obj, dataID) {
  var html = ""; //using var here is important. We want this variable to be private and within the scope of only this function.
  //this will be a recursive function.
  for (var i = 0; i < obj.length; i++) {
    var id = i;
    if (dataID != null || dataID != undefined) //we start the function at first with value null.
    {
      id = dataID + "-" + id; //separate id's from eachother with a dash
    }
    var menuItem = '
';
    menuItem += obj[i].name; //append the menu name with +=
    if (obj[i].menu) //obj has submenu
    {
      menuItem += "
" + loadnavigation(obj[i].menu, id) + "
";
    }
    menuItem += "
"; //close
    html += menuItem;
  }
  return html;
}
ul.hide {
 display: none;
}

The code should explain itself.
Why do I find the data-attribute convenient:
$("li[data-id^='1-']")

The selector above will select all children that are part of the tree branch starting with id 1.


text:
Q: labelFunction for JSON model object in AngularJS Directives I am fairly new to Angular. I want to create a custom multi-select search box in Angular which I have done partially. Refer to this plunk: http://plnkr.co/edit/5YCCdDSnpHKRU51R9vCL?p=preview
In the above plunk, I see the multi-select working for names. How do I make the same widget generic? How do I provide the functionality that the user can choose which key:value pair to display in the multi-select.
For eg:
$scope.users = [
  {name: 'Dave', id: 24},
  {name: 'Tim', id: 22},
  {name: 'Laura', id: 20}
];

Currently names are being displayed. What if I want to display ids instead of names?
Can I create something like this:
<user-info-card users="users" label="id">
<user-info-card users="users" label="name">

A: Add a new parameter in the scope of your directive
scope: {
    users: '=',
    label : '@'
  }

and use users[label] in your template
http://plnkr.co/edit/O5NeMRjpSGEISWbmiY9e?p=preview


text:
Q: Parse CSV and add only matching rows to List functionally in Scala I am reading csv scala.
Person is a case class
Case class Person(name, address)

    def getData(path:String,existingName) : List[Person] = {

      Source.fromFile("my_file_path").getLines.drop(1).map(l => {
        val data = l.split("|", -1).map(_.trim).toList
        val personName  = data(0)

        if(personName.equalsIgnoreCase(existingName)) {
          val address=data(1)
          Person(personName,address)
           //here I want to add to list

        }
        else
          Nil
       ///here return empty list of zero length

     }).toList()

}

I want to achieve this functionally in scala.

A: Here's the basic approach to what I think you're trying to do.
case class Person(name:String, address:String)

def getData(path:String, existingName:String) :List[Person] = {
  val recordPattern = raw"\s*(?i)($existingName)\s*\|\s*(.*)".r.unanchored

  io.Source.fromFile(path).getLines.drop(1).collect {
    case recordPattern(name,addr) => Person(name, addr.trim)
  }.toList
}

This doesn't close the file reader or report the error if the file can't be opened, which you really should do, but we'll leave that for a different day.

update: added file closing and error handling via Using (Scala 2.13)
import scala.util.{Using, Try}

case class Person(name:String, address:String)

def getData(path:String, existingName:String) :Try[List[Person]] =
  Using(io.Source.fromFile(path)){ file =>
    val recordPattern = raw"\s*(?i)($existingName)\s*\|\s*([^|]*)".r

    file.getLines.drop(1).collect {
      case recordPattern(name,addr) => Person(name, addr.trim)
    }.toList
  }

updated update
OK. Here's a version that:

*

*reports the error if the file can't be opened

*closes the file after it's been opened and read

*ignores unwanted spaces and quote marks

*is pre-2.13 compiler friendly

import scala.util.Try

case class Person(name:String, address:String)

def getData(path:String, existingName:String) :List[Person] = {
  val recordPattern =
    raw"""[\s"]*(?i)($existingName)["\s]*\|[\s"]*([^"|]*)*.""".r

  val file = Try(io.Source.fromFile(path))
  val res = file.fold(
    err => {println(err); List.empty[Person]},
    _.getLines.drop(1).collect {
      case recordPattern(name,addr) => Person(name, addr.trim)
    }.toList)
  file.map(_.close)
  res
}

And here's how the regex works:

*

*[\s"]* there might be spaces or quote marks

*(?i) matching is case-insensitive

*($existingName) match and capture this string (1st capture group)

*["\s]* there might be spaces or quote marks

*\| there will be a bar character

*[\s"]* there might be spaces or quote marks

*([^"|]*) match and capture everything that isn't quote or bar

*.* ignore anything that might come thereafter

A: you were not very clear on what was the problem on your approach, but this should do the trick (very close to what you have)
 def getData(path:String, existingName: String) : List[Person] = {

    val source = Source.fromFile("my_file_path")
    val lst = source.getLines.drop(1).flatMap(l => {
      val data = l.split("|", -1).map(_.trim).toList
      val personName = data.head

      if (personName.equalsIgnoreCase(existingName)) {
        val address = data(1)
        Option(Person(personName, address))
      }
      else
        Option.empty
    }).toList

    source.close()

    lst
  }

we read the file line per line, for each line we extract the personName from the first csv field, and if it's the one we are looking for we return an (Option) Person, otherwise none (Option.empty). By doing flatmap we discard the empty options (just to avoid using nils)


text:
Q: How to render only the 3rd object from an array react React newbie here. I have a component which gets an array of objects in JSON format and saves it into the state.
I am now unsure how I can render the name/description of only the 3rd object in the components render function.
I want to be able to only render the 1,2,3,4,5th object etc as well.
Any ideas?
https://codesandbox.io/s/admiring-ishizaka-rfp3k - Demo
   return (

        {name1} // Object 1 name
        {description1} // Object 1 description
        {name2} // Object 2 name
        {description2} // Object 2 description

    );

A: To give you the basic idea, you can display the name of your 3rd component on your render like this:
render() {

  return (

      {this.state.profiles.map((item, index) => {
        return(
          index === 2 ? item.name : ""
        )
      })}

  );
}

A: Please use Array map
  render() {
    const { profiles } = this.state;
    return (

        {
          profiles.map(profile => (
            {profile.name}
            {profile.description}
          ))
        }

    );
  }

A: render() {

  return (

      {this.state.profiles.map((data, i) => {
        return(
          i=== 2 ? (
{data.name}
) :(

)
        )
      })}

  );
}


text:
Q: Is fpdi shrinking template and/or adding whitespace? Using FPDI, I first use a template to create a table of contents.  I then import additional pages, which are linked to by the table of contents.  What I'm experiencing is that FPDI is shrinking the templates and possible adding white space.  I believe I have eliminated any browser added whitespace/shrinkage by merging the same documents into one via the passthru() command.
I have pasted code here: http://pastebin.com/VeLEN8nz. Line 45 - 57 is where the Table of Contents gets included as a template file.
The original file is here: http://truckingshow.com/TOC.pdf
The post-FPDI file is here: http://truckingshow.com/TOC-afterFPDI.pdf
The most noticeable difference is in the right and bottom margins.
Thank you for taking a look, please let me know if I can provide more info.

A: The document that was given to me was "Letter", not "A4" (the default for FPDF())
Instead of $pdf = new FPDI('P', 'pt') Simply using $pdf = new FPDI('P', 'pt', 'Letter') solved the problem.
Thanks!


text:
Q: How many columns in mysql So I am making a digitize notebook for a company, it has many categories so I am currently making 1 column pr categories and just storing the text at LONGTEXT, but how many columns can I have in a mysql table before it gets too bad?
It has about 70 categories, so I am just wondering if it is smart for me to split them into cat1 and cat2 or just have it in 1 column.

A: I believe you are designing something wrong. I guess you probably need one category table, and then reference that table from table where you store text.
My wild guess would be 3 tables: user, text, category. User table with some id column, text table has user_id, category_id, text columns, and category has id column.
https://dev.mysql.com/doc/refman/5.7/en/column-count-limit.html


text:
Q: Method to return the same interface implementation as passed in I've seen similar questions, but I don't really feel like I have an understanding of how to solve this. I want to make a method that takes a list of any class that implements an interface and returns an object of the same class.
I was hoping something like this would work.
public interface IHasDate {
  public Date getDate();
}

public class A implements IHasDate {
  private Date date;
  public Date getDate(){ return date; }
}

public class B implements IHasDate {
  private Date date;
  public Date getDate(){ return date; }
}

public class Util {
  public IHasDate getUpcoming(List<IHasDate> dates) {
    // logic omitted to find the object with the next upcoming date
    return dates.get(next);
  }
}

public class X {
  private List<A> aList;
  public A getUpcoming() {
    return Util.getUpcoming(aList);
  }
}

What I'm really trying to do is just avoid writing getUpcoming(List<?> aList) for each class that has a list of IHasDate's.
Is there a better strategy for what I'm trying to do?
Right now I've been able to get around it by having a function that takes a list of IHasDate's and returns the index of the upcoming object in the list, but I have to create a new list of IHasDate's from aList first and it all just feels kind of clunky.
What I was hoping for was something along these lines.
public T getUpcoming(List<T implements IHasDate> dates) {
  //...
}

A: You are sooo close.
public <T extends IHasDate> T getUpcoming(List<T> dates) {
//...
}


text:
Q: how to keep local default gateway when connecting witn VPN i used VPN to connect to my Windows server 2016 at our office.
vpn pptp and Remina. everything works very well.
but when i disconnect, the default gateway is changes and do not come back to local one. This can be prevented on Windows machine by disabling on TCP/IP properties to change the default gateway.
is there an equivalent on Ubuntu VPN. i have tried settings for Routes or Use this connection only for resources... but without success.


text:
Q: How to update Activity UI based on ListView item selection? I am creating a sample application containing an Activity [having ListView and Button] in layout file. ListView is custom containing [Label/Name and CheckBox]. I want to write some code which will change text of the Button from adapter class of ListView based on List Item CheckBox check [T/F].

A:      listView.setOnItemClickListener(new OnItemClickListener()
            {
                public void onItemClick(AdapterView<?> parent, View view, int position, long id)
                {
                    // When clicked, show a toast with the TextView text
                    AppListOfAllApps Selecteditems = (AppListOfAllApps) parent.getItemAtPosition(position);
                    if (view != null)
                    {
                        CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBox1);
                        Selecteditems = (AppListOfAllApps) checkBox.getTag();
                        //here you will get the selected item you may also get the text from it accordingly and then using using button variable just set text
button.settext("whatever");
                    }
                }
            });

A: In Activity :
public class Your_Activity extends Activity implements OnCheckListener// Implement your listener here

@Override
public void OnCheck(int position) {
    // TODO Auto-generated method stub
   // notify your activity component here
}

In Adapter class :
private OnCheckListener listener;

public interface OnCheckListener {
    public void OnCheck(int position);
}

public Your_adapter_constructor(OnCheckListener listener) {
    // TODO Auto-generated constructor stub
    this.listener = listener;
}

 // On your getView()
checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    listener.OnCheck(position);// If you want to pass some value add it here
                }
            });


text:
Q: How to automatically map a function to a newly added DOM element I'm trying to automate calling a function (initBox) on all elements with class box on the page in vanilla javascript. I have made a functional solution except that it only applies to elements that are on the page when it is loaded. If I add an element to the DOM using javascript, the function (initBox) is not called on it.
Of course I can call the function (initBox) manually after adding the element, but I would like to automate it.
I'm looking for something similar to what jQuery does for events.
For example:
$('table').on('click', 'td', function (event) {
    doSomething();
});

This event is called even if I add the TD element to the table later via javascript.
Here is my current solution:

function addBox() {
  var btn = document.getElementsByTagName('button')[0];

  var el = document.createElement('div');
  el.classList.add('box');
  el.innerText = (document.getElementsByTagName('div').length + 1);

  btn.before(el);
}

function initBox(el) {
  el.innerText += ' Initialized';
}

document.querySelectorAll('.box').forEach(initBox);
.box {
  display: inline-block;
  border: 1px solid #1f2227;
  padding: 20px;
}

button {
  padding: 20px;
}

1

2

<button onclick="addBox()">Add box</button>

A: The OP's problem can be solved just by the usage of a MutationObserver instance where the OP needs the callback from the list off added nodes just to initialize the very nodes which do match the OP's definition of a box.

function addBox() {
  var btn = document.getElementsByTagName('button')[0];

  var el = document.createElement('div');
  el.classList.add('box');
  el.innerText = (document.getElementsByTagName('div').length + 1);

  btn.before(el);
}

function initBox(el) {
  el.innerText += ' Initialized';
}
document.querySelectorAll('.box').forEach(initBox);

function initializeBoxClassDivOnly(node) {
  if (node.nodeType === 1 && node.matches('div.box')) {

    initBox(node);
  }
}
function handleNodeInsertion(mutationList/*, observer*/) {
  for (const mutation of mutationList) {
    mutation
      .addedNodes
      .forEach(initializeBoxClassDivOnly);
  }
};
const observer = new MutationObserver(handleNodeInsertion);
observer
  .observe(document.body, { childList: true, subtree: true });
.box {
  display: inline-block;
  border: 1px solid #1f2227;
  padding: 20px;
}
button {
  padding: 20px;
}

1

2

<button onclick="addBox()">Add box</button>

A: Look Into Mutation Observers, they are the new way of observing dom objects, it allows you to run a function when an item is added or removed or modified in a particular DOM element, or if you want you can go old school ( meaning you add event listeners).
Mutation Observers ( Recommended Method ) https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
Old School Evens https://developer.mozilla.org/en-US/docs/Web/API/MutationEvent
if you want me to write the code, let me know in the comments.


text:
Q: SQL Server - Write a query that groups weeks data from Fri->Thurs I am trying to separate data in my database from Thurs->Fri in the following way:
(Get last 10 weeks of data, grouped by Fri->Thurs as a week) e.g if today was 8/13/2018:

From (Fri)  To (Thur)
---------------------
8/10/2018   8/16/2018
8/3/2018    8/9/2018
7/27/2018   8/2/2018
7/20/2018   7/26/2018
7/13/2018   7/19/2018
7/6/2018    7/12/2018
6/29/2018   7/5/2018
6/22/2018   6/28/2018
6/15/2018   6/21/2018
6/8/2018    6/14/2018

I tried doing this by writing a query (more complicated than I like):
WITH Vars (d)
AS (
  SELECT DATEADD(week,-9, (DATEADD(day, - ((Datepart(WEEKDAY,GETDATE()) +1) %  7) , GETDATE()))  ) As 'd'
)
SELECT WeekNum+1  As [WeekNum], Count(*) Count
FROM
(
 SELECT (Datepart(Week, (DATEADD(day, - ((Datepart(WEEKDAY,t.DateField)+1 ) %  7), t.DateField)) ) )as WeekNum
 FROM Table as t
 WHERE (SELECT d FROM Vars) <= t.DateField

) as table

GROUP BY WeekNum
ORDER BY WeekNum ASC

But it group by's the wrong dates
How can I modify the query to return the correct data?
NOTE I want this to be a query and not a stored procedure of any kind if possible.

A: The problem in your query is the DATEPART(WEEKDAY,.... The weekday returned depends on your regional settings and is most probably using a Sunday as the start of a week.
To calculate the most recent Friday, you can use an expression like this (which does not depend on regional settings):
DATEADD(week, DATEDIFF(day, 4, GETDATE())/7, 4)

This makes use of the fact that SQL Server's "date 0" is 1/1/1900 (a Monday), so the "date 4" is 1/5/1900 (a Friday) and also takes advantage of DATEDIFF returning an integer, so dividing that by 7 is an integer division.
Assuming that your WeekNum works like desired, especially after a turn of the year, the query could be changed like this:
SELECT DATEPART(week, Friday)+1 AS WeekNum, COUNT(*) AS [Count]
FROM
(
  SELECT DATEADD(week, DATEDIFF(day, 4, t.DateField)/7, 4) AS Friday
  FROM [Table] t
  WHERE t.DateField >= DATEADD(week, DATEDIFF(day, 4, GETDATE())/7-9, 4)
) AS [table]
GROUP BY Friday
ORDER BY Friday

Also, you can easily display the dates, if you want:
SELECT Friday, DATEADD(day, 6, Friday) AS Thursday, COUNT(*) AS [Count]
FROM ... -- same as above


text:
Q: wifi reconect /etc/pm/sleep.d/ I have now Installed ubuntu on my MacBook Pro.
Everything was working OOTB, except one thing, the wlan0 won't reconnect after the system was asleep.
the only solution to get reconnected since now was running these commands:
sudo ifconfig wlan0 down ; sudo ifconfig wlan0 up

so i wrote a script called wifi.sh and placed it in /etc/pm/sleep.d/ which looks like this:
#!/bin/sh

case "${1}" in
    resume|thaw)
sleep 0
    ifconfig wlan0 down
sleep 0.2
ifconfig wlan0 up
            ;;
esac

unfortunately, this script is not running after waking up, but if i run
sudo /etc/pm/sleep.d/wifi.sh resume

it works fine.
the permissions seems also to be fine as you can see here:
jason@jason-MacBookPro:~$ ls -l /etc/pm/sleep.d/
total 20
-rwxr-xr-x 1 root root  210 Apr  6 22:43 10_grub-common
-rwxr-xr-x 1 root root  660 Mär  5  2015 10_unattended-upgrades-hibernate
-rwxr-xr-x 1 root root 1260 Mai 23  2012 novatel_3g_suspend
-rwxr-xr-x 1 root root  138 Sep 16 22:58 wifi.sh
-rwxr-xr-x 1 root root  138 Sep 16 12:42 wifi.sh~

any help would be appreciated.
thank you
Jason


text:
Q: Attempted to call an undefined method named "query" of class I working on a web socket app using ratchet and symfony 2.8 to connect to database and changing value in a certain column if someone connect to the server so I used this code to edit the query in the Chat.php file
$sql = $this->container->get('database_connection');
$users = $sql->query("UPDATE user SET onOroff= '1' WHERE UserId='2'");

but the proplem when I call it in SocketCommand.php
new Chat($this->getContainer())

I get this error
Attempted to call an undefined method named "query" of class

the chat.php code
<?php
namespace check\roomsBundle\Sockets;
use tuto\testBundle\Entity\Users;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\ORM\EntityManager;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;

class Chat extends Controller implements MessageComponentInterface  {
    protected $container;
    protected $clients;

    //protected $em;

    //protected $db;
    public function __construct(ContainerInterface $container) {
        $this->clients = new \SplObjectStorage;
        $this->container = $container;

    }

    public function onOpen(ConnectionInterface $conn) {
        $this->clients->attach($conn);

        echo "New connection! ({$conn->resourceId})\n";
        $sql = $this->container->get('database_connection');
        $users = $sql->query("UPDATE user SET onOroff= '1' WHERE UserId='2'");

    }

}

the SocketCommand.php full code
<?php
// myapplication/src/sandboxBundle/Command/SocketCommand.php
// Change the namespace according to your bundle
namespace check\roomsBundle\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

// Include ratchet libs
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
// Change the namespace according to your bundle
use check\roomsBundle\Sockets\Chat;
use Doctrine\ORM\EntityManager;
class SocketCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this->setName('sockets:start-chat')
            // the short description shown while running "php bin/console list"
            ->setHelp("Starts the chat socket demo")
            // the full command description shown when running the command with
            ->setDescription('Starts the chat socket demo')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {

        $output->writeln([
            'Chat socket',// A line
            '============',// Another line
            'Starting chat, open your browser.',// Empty line
        ]);

        $server = IoServer::factory(
            new HttpServer(
                new WsServer(
                    new Chat($this->getContainer())
                )
            ),
            8080
        );

        $server->run();
    }
}

the services.yml code
services:
     database_connection:
         class: check\roomsBundle\Sockets\Chat
         arguments: ["@service_container"]

A: services:
     database_connection:
         class: check\roomsBundle\Sockets\Chat
         arguments: ["@service_container"]

So you defined a service with id: database_connection that represents your Chat class
$sql = $this->container->get('database_connection');

And inside the same Chat class you try to get that service from container to execute sql query on it?
Code you shared with us doesn't make sense. Take a closer look at your services definition.


text:
Q: What is the simple way to synchronize to folder using .Net? What is the simple way to synchronize files between source and target directories in .Net without using other libraries?

A: You can use the Microsoft Sync Framework.
Here is an example from MSDN for synchronizing files using the above.

A: Robomojo - A .Net shell for RoboCopy.
http://robomojo.codeplex.com/
A .Net shell for RoboCopy. Copy whole directory structures with ease. Ideal for backups and deployments. Store your RoboCopy.exe commands for easy (and repeatable) use. WPF front-end, DI data access.


text:
Q: Azure Static Web Apps: How to set the version of Node.js? I want to use Node.js v12.x to build and deploy but it uses 14.15.1:
Using Node version:
v14.15.1

Using Npm version:
6.14.8

A: If you arrived here wanting to set the Node.js runtime version that is used for your API backend, refer to https://learn.microsoft.com/en-us/azure/static-web-apps/configuration#platform
In summary, you will create a staticwebapp.config.json that sits where your app_location is pointed in your github workflow (typically the root of your project) or any subfolder of app_location
You can then set the runtime like this...
{
  "platform": {
    "apiRuntime": "node:16"
  }
}

At the time of writing, your options are node:12, node:14, node:16. Reference the link above for the most up to date values.\
I'd like to answer the original question as well because I think the accepted answer is wrong. The azure CLI will say that az webapp ... can't find your project because it's a staticwebapp not a webapp.
The solution (and I'm not certain) should be to set the nodeEngines in package.json, like this:
{
  "engines": {
    "npm": ">=7.0.0",
    "node": ">=16.0.0"
  },
  "dependencies": {
    ...
  }
}

If I'm wrong about this, let me know in the comments and I'll update it.

A: You can set the desired node.js version via the Azure CLI:
az webapp config set --resource-group <resource-group-name> --name <app-name> --linux-fx-version "NODE|12.X"
For more information, see https://learn.microsoft.com/de-de/azure/app-service/configure-language-nodejs?pivots=platform-linux#set-nodejs-version


text:
Q: Добавление строки в таблицу MySql c# Хочу реализовать консольную функцию регистрации пользователя в sql таблице
делаю так:
MySqlConnection conn = new MySqlConnection(connStr);

conn.Open();

void Register()
{

    string regStr = "insert into userdata values(@login,@password,@score)";

    MySqlCommand regComm = new MySqlCommand(regStr, conn);

    Console.WriteLine("Срочно зарегистрироваться!");
    Console.WriteLine("Введите имя");
    string login = Convert.ToString(Console.ReadLine());
    Console.WriteLine("Введите пароль");
    int password = Convert.ToInt32(Console.ReadLine());
    int score = 0;

    regComm.Parameters.AddWithValue("@login", login);
    regComm.Parameters.AddWithValue("@password", password);
    regComm.Parameters.AddWithValue("@score", score);
}

но при дальнейшем просмотре таблицы в Сommand Line Client вижу что данные не добавились.
(связь моего кода с таблицей проверял, не работает именно эта функция)

A: Ваш код не работает, поскольку вы только открыли подключение, но не выполнили команду. Как я написал в комментариях последовательность такая:

*

*Открываем подключение

*Выполняем команду

*Закрываем подключение

string regStr = "insert into userdata values(@login,@password,@score)";

Console.WriteLine("Введите имя");
string login = Convert.ToString(Console.ReadLine());

Console.WriteLine("Введите пароль");
int password = Convert.ToInt32(Console.ReadLine());

int score = 0;

//Создаем объект MySqlConnection внутри using. Подключение само закроется после выполнения блока кода.
using ( MySqlConnection connection = new MySqlConnection(connStr) )
{
    //1. Открываем подключение к БД
    connection.Open();

    //Создаем объект класса MySqlCommand. В него передаем нашу sql-команду и подключение к БД
    MySqlCommand regCommand = new MySqlCommand(regStr, connection);

    regCommand.Parameters.AddWithValue("@login", login);
    regCommand.Parameters.AddWithValue("@password", password);
    regComm.Parameters.AddWithValue("@score", score);

    //2. Выполняем команду
    command.ExecuteNonQuery()
} //3. Подключение закроется после выполнения блока кода


text:
Q: "Add a page" link create new Wiki Page Is it possible in SharePoint Online to change the "Add a page" link (from the Cog menu) to create a new Wiki page instead of a Site page? I'm sure our instance used to do this.

A: If you go to your
Site Contents / Site Pages
and click on the 'Files' tab,
'New document' + down arrow in the 'Files' ribbon,
you are given the choice of the three different page content types, with 'Site Page' as the 1st choice, rather than wiki page.
It's also good practice for front-end users to go via their Site Pages library so they can check which pages have already been created, before they create a new one.


text:
Q: How and where to install a .cls in a minimal TexLive distribution (MacOsX)? I have a minimum LaTeX live installation which I don't remember how it got installed. I think it was a dependency of some other program and it got automatically installed.
Nevertheless, the content of my /usr/local/texlive/2022basic/bin/universal-darwin is the following
afm2tfm     fmtutil-sys lualatex    mktexmf     simpdftex   xdvi
bibtex      fmtutil-user    luaotfload-tool mktexpk     synctex     xdvi-xaw
dvilualatex gftodvi     luatex      mktextfm    teckit_compile  xdvipdfmx
dviluatex   gftopk      lwarpmk     mpost       tex     xelatex
dvipdfm     gftype      makeindex   mptopdf     texhash     xelatex-dev
dvipdfmx    inimf       man     pdfatfi     texlua      xelatex-unsafe
dvipdft     initex      mf      pdfetex     texluac     xetex
dvips       kpseaccess  mf-nowin    pdflatex    thumbpdf    xetex-unsafe
dvitomp     kpsereadlink    mfplain     pdftex      tlmgr
ebb     kpsestat    mft     pktogf      tlshell
etex        kpsewhich   mkindex     pktype      updmap
extractbb   latex       mktexfmt    r-mpost     updmap-sys
fmtutil     luahbtex    mktexlsr    rungs       updmap-user

whereas I don't have a texmf folder in /Users/ubaldot/Library/, nor I can see any LaTeX related environmental variable set.
However, if I run which pdflatex from the command line I get /Library/TeX/texbin/pdflatex
Problem: I am in need to install standalone.cls file, due to an external program (manimCE) that require it but I don't know how to install such a .cls file within my current setup.
I could install a whole LaTeX distribution and use some package manager for solving my problem but I would rather avoid that.
I am just wondering if I can install standalone.cls within my current setup and if so, how.
Let me know if more info are needed so I can edit this post.

A: Since you have installed the BasicTeX version of MacTeX, you simply need to install extra packages or classes manually. You can do this using the TeX Live Utility (which may have been installed with BasicTeX) which is a GUI wrapper for tlmgr or you can use tlmgr directly from the command line.
For details on using TeX Live Utility see:

*

*TeX Live Utility, don't know how to start it
To install things from the command line using tlmgr you can do the following:
sudo tlmgr install standalone

It will ask for your password, and then install it in the correct place.

A: Assuming you installed TeX Live via the MacTeX installer package you should put personal packages in or in sub-folders of ~/Library/texmf/tex/latex. The texmf/tex/latex folder hierarchy in ~/Library must be created by you since the MacTeX installer package doesn't touch your HOME folder.


text:
Q: Working with nested views using Prism with IsNavigationTarget which can return false I'm trying to find solution for the following problem. I have a WPF app, I used mvvm and prism (most recent version 7) to build it. Here is the draft of the form/dialog I work on:

MainView has region - region1, I inject SubViewA into region1 based on what is selected in treeview. This view represents treeitem content. SubViewA itslef has region - region2, and another view - SubViewB is injected into region2 based on combobox selection.
I use INavigationAware to manage injection to the region.
So to inject view into region I use from MainViewModel the following:
_regionManager.RequestNavigate(regionName, viewName, callBack, parameters);

In the SubViewAViewModel I implement INavigationAware, and to reuse created views I check if view per treeitem was created. To do it I add into parameters a treeitemId and then I check this id in IsNavigationTarget method like this:
bool IsNavigationTarget(NavigationContext navigationContext)
{
    // get id parameter from navigationContext.Parameters
    // check if subviewA for treeitemId was already shown and return true,
    // i use dictionary, where i store ids of all items that were selected in the past
    // otherwise return false.
}

The same method I use when I want to inject SubViewB into region 2 of SubViewA. Mostly when user changes dropdown selection new SubViewB is injected.
Now my question is - if I use INavigationAware in SubViewBViewModel and when IsNavigationTarget always returns true - all is good. When I try to reuse views and again chose what to return true or false, then when I select second item in treeview I got an exception: "Region with the given name is already registered" - prism complains that region2 was already registered.
I know that I can have service and always populate data from the service when View is shown, and because of that I don't need to reuse views. But it's more academic question - what is the proper way to solve it?
P.S. I tried to register scoped region manager, but I was not successful, my problem is I don't know where is the best place to create new scoped manager and how to inject it into viewmodel. Parent's ViewModel is not good place to do it, because I have to expose view. If I try to use attached behavior, then it seems, region content is updated before behavior is invoked.
P.S.2 I found an example from pluralsight (by Brian Lagunas), where he creates two shells, but it differs from what I want to achieve. He creates new scope manager per window in the moment when window is created. And also if window itself will have the same structure as I showed above, it will fail too.
P.S.3 I watched recent streams from Brian Lagunas where he is writing outlook from scratch, his approach is based on behavior, he associates some view with dependent views, it works fine, but again in his example dependent views don't contain regions.
Thank you.

A: For those who are interested in details, you have to watch the following pluralsight courses: pluralsight.pxf.io/XVxR5 & pluralsight.pxf.io/B6X99. One is about multiple shells and another is about tabbed control, which is called 'Prism Problems & Solutions: Mastering TabControl' - this course helped me.
In short, the problem is about how to inject scope region in the main viewmodel. To solve it we have override ScopedRegionNavigationContentLoader plus to control either we want to inject scoped region manager or global one we have to us marking interfaces.
I created another question which is similar to current one: please check Prism 7 throws and exception when working with nested views. It will give you more details.


text:
Q: How to select a group with its parents & child in Jquery multiselect Actually,I have a multiselect option to select,But now i can able to select a parent & there child alone,But now i want to select a Group With its parent & Child,
So if i select a group all the parent & child in the group should  have be moved with the group,So help me....
Here is my example code

India

Tamil nadu

Chennai

Trichy

Madurai

Kanya kuamri

United Kingdom

London

London1

London2

London3

London4

If i select a group (i.e) India then all the childs under this group should be moved to right column as like jquery ui multiselect option
I have attached an example screenshot below..

A: Check this fiddle
In the above fiddle only the text within clicked li and its successor li's will be displayed:
jQuery
$('ul').on('click','li',function(){
    $('#result').html($(this).text());
    return false;
});

Updated code in response to comment
HTML(slight change added class="par" to Country and State)

India

Tamil nadu

Chennai

Trichy

Madurai

Kanya kuamri

United Kingdom

London

London1

London2

London3

London4

Updated JQuery
$('ul').on('click','li',function(){
    $('#result').html($(this).html());
    if($(this).attr('class')=="par")
    {
    return false;
    }
});

Added little CSS for look.(Do CSS change as needed)
html,body{
    margin:0px;
    padding:0px;
    width:100%;
}
ul{
    width:50%;
    display:table-cell;
    border:1px solid black;
}
div{
    width:50%;
    display:table-cell;
    border:1px solid black;
}


text:
Q: Shifting an array after removing a value (Java) I made a program that makes an array of random ints and doubles in size if the user tries to add an int. Example: 1|2|3|4  if they were to add another int it would look like 1|2|3|4|5|0|0|0. I have made a method to add an int which works but now I am trying to make methods that remove one of a certain int and another that removes all of a certain int. for example removeInt(3) would give me 1|2|0|4|5|0|0|0. I have the first part working so that it shifts the zero to the end like this 1|2|4|5|0|0|0|0 but cannot get it to work for more than one of the same value. Any suggestions?
    // ****************************************************************
// IntegerList.java
//
// Define an IntegerList class with methods to create & fill
// a list of integers.
//
// ****************************************************************

public class IntegerList
{
    int[] list; //values in the list
//-------------------------------------------------------
//create a list of the given size
//-------------------------------------------------------
    public IntegerList(int size)

    {
        list = new int[size];
    }
//-------------------------------------------------------
//fill array with integers between 1 and 100, inclusive
//-------------------------------------------------------
    public void randomize()
    {
        for (int i=0; i<list.length; i++)
            list[i] = (int)(Math.random() * 100) + 1;
    }
//-------------------------------------------==----------
//print array elements with indices
//-------------------------------------------------------
    public void print()
    {
        for (int i=0; i<list.length; i++)
            System.out.println(i + ":\t" + list[i]);
    }
    public void addElement(int newVal){
        boolean full = true;
        System.out.println(list.length);
        int position = 0;
        int place;
        while(position < list.length){
            System.out.println("HERE");
                if(list[position]==0){
                    System.out.println("here");
                    full = false;
                    place = position;
                    System.out.println(place);
                }
                position = position+1;
            }
        if(full == true){
            list = increaseSize(list);
            System.out.println("L"+list.length);
            full = false;
            }

        for(int i = 0;i<list.length;i++){
            if(list[i]==0){
                if(i<position){
                    position = i;
            System.out.println(list.length);
                }
            }
        }
        list[position] = newVal;
    }
    public void removeFirst(int newVal){
        int position = 0;
        boolean removed = false;
        for(int i = 0; i<list.length;i++){
            if(list[i] == newVal){
                list[i]=0;
                position = i;
                removed = true;
                break;
            }
        }
        if(removed==true){
            for(int i = position;i<list.length;i++){
                if(i!=list.length-1){
                    list[i]=list[i+1];
                }
            }
            list[list.length-1]= 0;
        }
    }
    public void removeAll(int newVal){
        int position = 0;
        boolean removed = false;
        for(int i = 0; i<list.length;i++){
            if(list[i] == newVal){
                list[i]=0;
                position = i;
                removed = true;
            }
        }
        if(removed==true){
            for(int i = 0;i<list.length;i++){
                if(i!=list.length-1 && list[i+1]==newVal){
                    list[i]=0;
                }
                if(list[i]==newVal){
                    list[i]=0;
                }
            }
        }
        }
    public static int[] increaseSize(int[] x){
        int newLength = x.length *2;
        int[] newx = new int[newLength];
        for(int i = 0; i<x.length; i++){
            newx[i] = x[i];
        }
        return newx;
    }
    public static int[] halfSize(int[] x){
        int[] newx = new int[x.length / 2];
        for(int i = 0; i<x.length; i++){
            newx[i] = x[i];
        }
        return newx;
    }
}

A: I believe there's an easier way to implement your removeAll method. Move 2 (rather than 1) indices through your array constantly shifting the values over the items you are removing;
int dest = 0;
int source = 0;
while (source < array.length) {
    if (array[dest] != valueToRemove)
        dest++;
    array[dest] = array[source++];
}
while (dest < array.length) {
    array[dest++] = 0;
}

A: I executed your code and found out that the problem is in this piece, under removeAll()...
if(removed){
        for(int i = 0;i<list.length;i++){
            if(i!=list.length-1 && list[i+1]==newVal){
                list[i]=0;
            }
            if(list[i]==newVal){
                list[i]=0;
            }
        }
    }

If you comment out and try once, you will see the removeAll() is working and your desired number is replaced with 0s. Now why you don't simply check your numbers and shift(sorting), if they are greater than 0 to the left?


text:
Q: Placing a horizontal helper in Constraint Layout to be at the bottom of a View with a set custom margin How do I set it so that a horizontal helper in Constraint Layout is set to be at the bottom of a particular View with a margin of 16dp in between?
What I've tried (with horizontal Guideline):
<androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.30779755"
        app:layout_constraintTop_toBottomOf="@id/view2" />

It doesn't actually care about the layout_marginTop and layout_constraintTop_toBottomOf attribute. If I erase the layout_constraintGuide_percent attribute, it goes haywire and sticks to the top of the parent.
EDIT
I created that Guideline because I have a View which acts as a "background" behind multiple Views. I was hoping to constrain this background View to the bottom of this Guideline with an offset of 16dp from the last vertically aligned View (from the multiple Views). I want this background View to have a height based on the last vertically aligned View from the multiple Views, i.e. the height is determined by the bottom of the view + a 16dp margin. If I constrain the bottom of said background View to the bottom of the last vertically aligned View and add a bottom margin, the background View instead retracts 16dp from the bottom of the last vertically aligned View.

A: I would use a Space widget with a height of 16dp and a top constrained to the bottom of the lowest view. The bottom of the background view can be constrained to the bottom of the Space view to visually create the margin as follows using 64dp to accentuate the margin:
<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <View
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@android:color/holo_red_light"
        app:layout_constraintBottom_toBottomOf="@id/space"
        app:layout_constraintEnd_toEndOf="@id/view1"
        app:layout_constraintStart_toStartOf="@id/view1"
        app:layout_constraintTop_toTopOf="@+id/view1" />

    <TextView
        android:id="@+id/view1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:text="Using a Space widget"
        android:textColor="@android:color/white"
        android:textSize="30sp"
        app:layout_constraintBottom_toTopOf="@+id/view2"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_chainStyle="packed" />

    <TextView
        android:id="@+id/view2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="view2"
        android:textColor="@android:color/white"
        android:textSize="30sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/view1" />

    <Space
        android:id="@+id/space"
        android:layout_width="wrap_content"
        android:layout_height="64dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/view2" />

</androidx.constraintlayout.widget.ConstraintLayout>

I also mentioned using a Layer helper with a bottom padding of 16dp. Although this currently works with ConstraintLayout 2.0.0-beta3, I am not convinced that it should work, so use at your discretion. Here is how it looks again with a Layer using 64dp padding to accentuate the margin. You will need ConstraintLayout 2.0 or later.
<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.constraintlayout.helper.widget.Layer
        android:id="@+id/layer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_red_light"
        android:paddingBottom="64dp"
        app:constraint_referenced_ids="view2,view1"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/view1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Using a Layer"
        app:layout_constraintVertical_chainStyle="packed"
        android:textColor="@android:color/white"
        android:textSize="30sp"
        android:layout_marginBottom="16dp"
        app:layout_constraintBottom_toTopOf="@+id/view2"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/view2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="view2"
        android:textColor="@android:color/white"
        android:textSize="30sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/view1" />

</androidx.constraintlayout.widget.ConstraintLayout>


text:
Q: Yocto How to stop cmake to look in a native sysroot path for linking? I'm trying to add dlib python module into my image so far this is the recipe i'm working on...
# python3-dlib_19.21.1.bb
SUMMARY = "A toolkit for making real world machine learning and data analysis applications"
HOMEPAGE = "https://pypi.python.org/pypi/dlib"
PYPI_PACKAGE = "dlib"
LICENSE = "Boost-Software"
SRC_URI[md5sum] = "1e7e357d7d54e86267ef60f606cb40e1"
LIC_FILES_CHKSUM = "file://dlib/LICENSE.txt;md5=2c7a3fa82e66676005cd4ee2608fd7d2 \
                    file://dlib/external/libpng/LICENSE;md5=243135ddedf702158f9170807cbcfb66 \
                    file://dlib/external/pybind11/LICENSE;md5=beb87117af69fd10fbf9fb14c22a2e62 \
                    file://python_examples/LICENSE_FOR_EXAMPLE_PROGRAMS.txt;md5=064f53ab40ea2b6a4bba1324149e4fde \
"
DEPENDS = "cmake-native"

inherit  pypi setuptools3

but when do_compile() ran i got the following error message:
| [100%] Building CXX object CMakeFiles/_dlib_pybind11.dir/src/line.cpp.o
| [100%] Linking CXX shared module build_dunfell/tmp/work/aarch64-poky-linux/python3-dlib/19.21.1-r0/build/lib.linux-x86_64-3.8/_dlib_pybind11.cpython-38-aarch64-linux-gnu.so
| build_dunfell/tmp/work/aarch64-poky-linux/python3-dlib/19.21.1-r0/recipe-sysroot-native/usr/bin/aarch64-poky-linux/../../libexec/aarch64-poky-linux/gcc/aarch64-poky-linux/8.3.0/ld: build_dunfell/tmp/work/aarch64-poky-linux/python3-dlib/19.21.1-r0/recipe-sysroot-native/usr/lib/libsqlite3.so: error adding symbols: file in wrong format
| collect2: error: ld returned 1 exit status
| CMakeFiles/_dlib_pybind11.dir/build.make:445: recipe for target 'build_dunfell/tmp/work/aarch64-poky-linux/python3-dlib/19.21.1-r0/build/lib.linux-x86_64-3.8/_dlib_pybind11.cpython-38-aarch64-linux-gnu.so' failed
| make[2]: *** [build_dunfell/tmp/work/aarch64-poky-linux/python3-dlib/19.21.1-r0/build/lib.linux-x86_64-3.8/_dlib_pybind11.cpython-38-aarch64-linux-gnu.so] Error 1
| CMakeFiles/Makefile2:116: recipe for target 'CMakeFiles/_dlib_pybind11.dir/all' failed
| make[1]: *** [CMakeFiles/_dlib_pybind11.dir/all] Error 2
| Makefile:83: recipe for target 'all' failed
| make: *** [all] Error 2
| Traceback (most recent call last):
|   File "build_dunfell/tmp/work/aarch64-poky-linux/python3-dlib/19.21.1-r0/dlib-19.21.1/setup.py", line 223, in <module>
|     setup(
|   File "build_dunfell/tmp/work/aarch64-poky-linux/python3-dlib/19.21.1-r0/recipe-sysroot-native/usr/lib/python3.8/site-packages/setuptools/__init__.py", line 144, in setup
|     return distutils.core.setup(**attrs)
|   File "build_dunfell/tmp/work/aarch64-poky-linux/python3-dlib/19.21.1-r0/recipe-sysroot-native/usr/lib/python3.8/distutils/core.py", line 148, in setup
|     dist.run_commands()
|   File "build_dunfell/tmp/work/aarch64-poky-linux/python3-dlib/19.21.1-r0/recipe-sysroot-native/usr/lib/python3.8/distutils/dist.py", line 966, in run_commands
|     self.run_command(cmd)
|   File "build_dunfell/tmp/work/aarch64-poky-linux/python3-dlib/19.21.1-r0/recipe-sysroot-native/usr/lib/python3.8/distutils/dist.py", line 985, in run_command
|     cmd_obj.run()
|   File "build_dunfell/tmp/work/aarch64-poky-linux/python3-dlib/19.21.1-r0/recipe-sysroot-native/usr/lib/python3.8/distutils/command/build.py", line 135, in run
|     self.run_command(cmd_name)
|   File "build_dunfell/tmp/work/aarch64-poky-linux/python3-dlib/19.21.1-r0/recipe-sysroot-native/usr/lib/python3.8/distutils/cmd.py", line 313, in run_command
|     self.distribution.run_command(command)
|   File "build_dunfell/tmp/work/aarch64-poky-linux/python3-dlib/19.21.1-r0/recipe-sysroot-native/usr/lib/python3.8/distutils/dist.py", line 985, in run_command
|     cmd_obj.run()
|   File "build_dunfell/tmp/work/aarch64-poky-linux/python3-dlib/19.21.1-r0/dlib-19.21.1/setup.py", line 135, in run
|     self.build_extension(ext)
|   File "build_dunfell/tmp/work/aarch64-poky-linux/python3-dlib/19.21.1-r0/dlib-19.21.1/setup.py", line 175, in build_extension
|     subprocess.check_call(cmake_build, cwd=build_folder)
|   File "build_dunfell/tmp/work/aarch64-poky-linux/python3-dlib/19.21.1-r0/recipe-sysroot-native/usr/lib/python3.8/subprocess.py", line 364, in check_call
|     raise CalledProcessError(retcode, cmd)
| subprocess.CalledProcessError: Command '['cmake', '--build', '.', '--config', 'Release', '--', '-j8']' returned non-zero exit status 2.
| WARNING: exit code 1 from a shell command.
|

it looks like the problem occurs when cmake is trying to link the shared object _dlib_pybind11.cpython-38-aarch64-linux-gnu.so. Linker complains with the following error
 adding symbols: file in wrong format

i think the linker is mixing target objects with native ones, but i'm not used to cmake so i don't know how to stop it to use the path of recipe-sysroot-native and use my target sysroot, if i remove cmake-native and use only DEPENDS="cmake", setup.py fails because it can not find cmake at all...
hope you can help me or give me any idea that i can try.
BR,
Update 1
just as @Nayfe pointed out dlib/setup.py has an --set option to pass CMAKE config variables, below is a recipe that already worked for me, i can import dlib without problems.
SUMMARY = "A toolkit for making real world machine learning and data analysis applications"
HOMEPAGE = "https://pypi.python.org/pypi/dlib"
PYPI_PACKAGE = "dlib"
LICENSE = "Boost-Software"
SRC_URI[md5sum] = "1e7e357d7d54e86267ef60f606cb40e1"
LIC_FILES_CHKSUM = "file://dlib/LICENSE.txt;md5=2c7a3fa82e66676005cd4ee2608fd7d2 \
                    file://dlib/external/libpng/LICENSE;md5=243135ddedf702158f9170807cbcfb66 \
                    file://dlib/external/pybind11/LICENSE;md5=beb87117af69fd10fbf9fb14c22a2e62 \
                    file://python_examples/LICENSE_FOR_EXAMPLE_PROGRAMS.txt;md5=064f53ab40ea2b6a4bba1324149e4fde \
"
DEPENDS = "sqlite3 "

inherit pypi cmake setuptools3
INSANE_SKIP_${PN} = "already-stripped"

DISTUTILS_BUILD_ARGS_append = " \
      --set CMAKE_TOOLCHAIN_FILE=${WORKDIR}/toolchain.cmake \
"

A: Maybe recipe can be optimized but the following works

*

*python3-dlib_19.21.bb

SUMMARY = "A toolkit for making real world machine learning and data analysis applications"
HOMEPAGE = "http://dlib.net/"
SECTION = "devel/python"
LICENSE = "BSL-1.0"
LIC_FILES_CHKSUM = "file://dlib/LICENSE.txt;md5=2c7a3fa82e66676005cd4ee2608fd7d2"

DEPENDS = "sqlite3"

SRC_URI = "git://github.com/davisking/dlib"
SRCREV = "9117bd784328d9ac40ffa1f9cf487633a8a715d7"

S = "${WORKDIR}/git"

DISTUTILS_BUILD_ARGS_append = " \
      --set CMAKE_INSTALL_PREFIX:PATH=${prefix} \
      --set CMAKE_INSTALL_BINDIR:PATH=${@os.path.relpath(d.getVar('bindir'), d.getVar('prefix') + '/')} \
      --set CMAKE_INSTALL_SBINDIR:PATH=${@os.path.relpath(d.getVar('sbindir'), d.getVar('prefix') + '/')} \
      --set CMAKE_INSTALL_LIBEXECDIR:PATH=${@os.path.relpath(d.getVar('libexecdir'), d.getVar('prefix') + '/')} \
      --set CMAKE_INSTALL_SYSCONFDIR:PATH=${sysconfdir} \
      --set CMAKE_INSTALL_SHAREDSTATEDIR:PATH=${@os.path.relpath(d.getVar('sharedstatedir'), d.  getVar('prefix') + '/')} \
      --set CMAKE_INSTALL_LOCALSTATEDIR:PATH=${localstatedir} \
      --set CMAKE_INSTALL_LIBDIR:PATH=${@os.path.relpath(d.getVar('libdir'), d.getVar('prefix') + '/')} \
      --set CMAKE_INSTALL_INCLUDEDIR:PATH=${@os.path.relpath(d.getVar('includedir'), d.getVar('prefix') + '/')} \
      --set CMAKE_INSTALL_DATAROOTDIR:PATH=${@os.path.relpath(d.getVar('datadir'), d.getVar('prefix') + '/')} \
      --set PYTHON_EXECUTABLE:PATH=${PYTHON} \
      --set Python_EXECUTABLE:PATH=${PYTHON} \
      --set Python3_EXECUTABLE:PATH=${PYTHON} \
      --set LIB_SUFFIX=${@d.getVar('baselib').replace('lib', '')} \
      --set CMAKE_INSTALL_SO_NO_EXE=0 \
      --set CMAKE_TOOLCHAIN_FILE=${WORKDIR}/toolchain.cmake \
      --set CMAKE_NO_SYSTEM_FROM_IMPORTED=1 \
      --set CMAKE_LIBRARY_OUTPUT_DIRECTORY=${B} \
"

do_configure() {
    distutils3_do_configure
}

do_compile() {
    distutils3_do_compile
}

do_install() {
    distutils3_do_install
}

inherit cmake setuptools3 python3native

INSANE_SKIP_${PN} = "already-stripped"
RDEPENDS_${PN} += "python3-core"