问:
Scraping dynamic content using python-Scrapy
Disclaimer: I've seen numerous other similar posts on StackOverflow and tried to do it the same way but was they don't seem to work on this website.

I'm using Python-Scrapy for getting data from koovs.com.

However, I'm not able to get the product size, which is dynamically generated. Specifically, if someone could guide me a little on getting the 'Not available' size tag from the drop-down menu on this link, I'd be grateful.

I am able to get the size list statically, but doing that I only get the list of sizes but not which of them are available.

答:
I faced that problem and solved easily by following these steps

pip install splash

pip install scrapy-splash

pip install scrapyjs

download and install docker-toolbox

open docker-quickterminal and enter

```<code>$ docker run -p 8050:8050 scrapinghub/splash
</code>```

To set the SPLASH_URL check the default ip configured in the docker machine by entering
 $ docker-machine ip default (My IP was 192.168.99.100)

```<code>SPLASH_URL = 'http://192.168.99.100:8050'
DOWNLOADER_MIDDLEWARES = {
    'scrapyjs.SplashMiddleware': 725,
}

DUPEFILTER_CLASS = 'scrapyjs.SplashAwareDupeFilter'
</code>```

That's it!

Body:
I faced that problem and solved easily by following these steps

pip install splash

pip install scrapy-splash

pip install scrapyjs

download and install docker-toolbox

open docker-quickterminal and enter

$ docker run -p 8050:8050 scrapinghub/splash

To set the SPLASH_URL check the default ip configured in the docker machine by entering
 $ docker-machine ip default (My IP was 192.168.99.100)

SPLASH_URL = 'http://192.168.99.100:8050'
DOWNLOADER_MIDDLEWARES = {
    'scrapyjs.SplashMiddleware': 725,
}

DUPEFILTER_CLASS = 'scrapyjs.SplashAwareDupeFilter'

That's it!


来源: stackexchange

问:
Deleting Elements of a file in vc++
```<code>CStringArray myArray;
myArray.copy(copiedsomeelements);
CString file1="myfile1";
CString file2="myfile2";
FILE *fp1,*fp2;
CString linetocompare="mytext";
fp1 = fopen(myfile1, "rb");
fread(data, 1280, 1, fp1);
fclose(fp1);
TCHAR * pch = _tcstok(data, _T("\r\n"));

fp2 = fopen(myfile2, "w"); //open new file

for (int m = 0; m < myArray.GetCount(); m++)
{
        CString temp(pch);
        if (strcmp(myArray.GetAt(m), linetocompare) != NULL)
        {
                fprintf(fp2, "%s", temp);
                fwrite("\r\n", 1, 1, fp2);
        }
        pch = _tcstok(NULL, _T("\r\n"));
}
fclose(fp2);
remove(myfile1); //remove old file
rename(myfile2, myfile1);
</code>```

The above code that works fine for me but not all the time. Sometimes it writes the "myfile2" as it is without comparing "linetocomapare" element.
Please help me with this.
Let me know if any clarifications are required. Thank you.

答:
MFC has a CStdioFile class that wraps the narly FILE stuff and can handle line feeds. Here's a couple of convenience functions for loading/saving text files:

```<code>void ReadTextFileContents(CString const& filePath,
    CArray<CString>& lines,
    UINT openFlags = CFile::modeRead | CFile::shareDenyWrite)
{
    CStdioFile file(filePath, openFlags);

    try
    {
        CString line;
        while (file.ReadString(line))
            lines.Add(line);
        file.Close();
    }
    catch (...)
    {
        file.Abort();
        throw;
    }
}

void WriteTextFileContents(CString const& filePath,
    CArray<CString> const& lines,
    UINT openFlags = CFile::modeCreate | CFile::modeWrite |
    CFile::shareExclusive)
{
    CStdioFile file(filePath, openFlags);

    try
    {
        for (INT_PTR i = 0, count = lines.GetCount(); i < count; ++i)
        {
            file.WriteString(lines[i]);
            if (i < (count - 1))
            {
                // NOTE: The default mode for CStdioFile is text mode
                // MSDN: Text mode provides special processing for carriage
                // return-linefeed pairs. When you write a newline character
                // (0x0A) to a text-mode CStdioFile object, the byte pair
                // (0x0D, 0x0A) is sent to the file. When you read, the
                // byte pair (0x0D, 0x0A) is translated to a single 0x0A
                // byte.
                file.WriteString(_T("\n"));
            }
        }
        file.Close();
    }
    catch (...)
    {
        file.Abort();
        throw;
    }
}
</code>```

Now you can do this:

```<code>    try
    {
        CArray<CString> lines;
        ReadTextFileContents(fileName, lines);

        // Do what you want with lines, remove items, copy to
        // another array, etc.

        // Now write them somewhere
        WriteTextFileContents(fileName2, lines);
    }
    catch (CException* ex)
    {
        // Grab and display error message here
        //ex->GetErrorMessage();

        ex->Delete();
    }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Deleting Elements of a file in vc++

Body:
CStringArray myArray;
myArray.copy(copiedsomeelements);
CString file1="myfile1";
CString file2="myfile2";
FILE *fp1,*fp2;
CString linetocompare="mytext";
fp1 = fopen(myfile1, "rb");
fread(data, 1280, 1, fp1);
fclose(fp1);
TCHAR * pch = _tcstok(data, _T("\r\n"));

fp2 = fopen(myfile2, "w"); //open new file

for (int m = 0; m < myArray.GetCount(); m++)
{
        CString temp(pch);
        if (strcmp(myArray.GetAt(m), linetocompare) != NULL)
        {
                fprintf(fp2, "%s", temp);
                fwrite("\r\n", 1, 1, fp2);
        }
        pch = _tcstok(NULL, _T("\r\n"));
}
fclose(fp2);
remove(myfile1); //remove old file
rename(myfile2, myfile1);

The above code that works fine for me but not all the time. Sometimes it writes the "myfile2" as it is without comparing "linetocomapare" element.
Please help me with this.
Let me know if any clarifications are required. Thank you.

Body:
MFC has a CStdioFile class that wraps the narly FILE stuff and can handle line feeds. Here's a couple of convenience functions for loading/saving text files:

void ReadTextFileContents(CString const& filePath,
    CArray<CString>& lines,
    UINT openFlags = CFile::modeRead | CFile::shareDenyWrite)
{
    CStdioFile file(filePath, openFlags);

    try
    {
        CString line;
        while (file.ReadString(line))
            lines.Add(line);
        file.Close();
    }
    catch (...)
    {
        file.Abort();
        throw;
    }
}

void WriteTextFileContents(CString const& filePath,
    CArray<CString> const& lines,
    UINT openFlags = CFile::modeCreate | CFile::modeWrite |
    CFile::shareExclusive)
{
    CStdioFile file(filePath, openFlags);

    try
    {
        for (INT_PTR i = 0, count = lines.GetCount(); i < count; ++i)
        {
            file.WriteString(lines[i]);
            if (i < (count - 1))
            {
                // NOTE: The default mode for CStdioFile is text mode
                // MSDN: Text mode provides special processing for carriage
                // return-linefeed pairs. When you write a newline character
                // (0x0A) to a text-mode CStdioFile object, the byte pair
                // (0x0D, 0x0A) is sent to the file. When you read, the
                // byte pair (0x0D, 0x0A) is translated to a single 0x0A
                // byte.
                file.WriteString(_T("\n"));
            }
        }
        file.Close();
    }
    catch (...)
    {
        file.Abort();
        throw;
    }
}

Now you can do this:

    try
    {
        CArray<CString> lines;
        ReadTextFileContents(fileName, lines);

        // Do what you want with lines, remove items, copy to
        // another array, etc.

        // Now write them somewhere
        WriteTextFileContents(fileName2, lines);
    }
    catch (CException* ex)
    {
        // Grab and display error message here
        //ex->GetErrorMessage();

        ex->Delete();
    }


问:
Python sort strings with dot/separated numbers and strings at the end
I have an array of dicts like:

array_x =
[{'title': 'Copy -- @1.1 true files'}, {'title': 'Copy -- @1.11 true files'}, {'title': 'Copy -- @1.3 true files'}, {'title': 'Copy -- @1.2 true files'}, {'title': 'Copy -- @1.12 true files'}, {'title': 'Copy -- @1.22 true files'}, {'title': 'After -- @1.1 copy files'}]

I want to sort them by the key 'title', i try to use the comun sort function and some like this:

array_x.sort(key=lambda s: list(map(str, s['title'].split('.'))))

but doesn't work, i want some like this:

[{'title': 'After -- @1.1 copy files'}, {'title': 'Copy -- @1.1 true files'}, {'title': 'Copy -- @1.2 true files'}, {'title': 'Copy -- @1.3 true files'}, {'title': 'Copy -- @1.11 true files'}, {'title': 'Copy -- @1.12 true files'}, {'title': 'Copy -- @1.22 true files'}]

I'm using Python 3.6.1

答:
How about this: discard everything before and including the @ sign, then convert each period-separated section into ints. That should fix the problem of the digit sequences being sorted lexicographically.

```<code>>>> array_x = [{'title': 'Copy -- @1.1'}, {'title': 'Copy -- @1.11'}, {'title': 'Copy -- @1.3'}, {'title': 'Copy -- @1.2'}, {'title': 'Copy -- @1.12'}, {'title': 'Copy -- @1.22'}, {'title': 'After -- @1.1'}]
>>> array_x.sort(key=lambda s: list(map(int, s['title'].rpartition("@")[2].split('.'))))
>>> array_x
[{'title': 'After -- @1.1'}, {'title': 'Copy -- @1.1'}, {'title': 'Copy -- @1.2'}, {'title': 'Copy -- @1.3'}, {'title': 'Copy -- @1.11'}, {'title': 'Copy -- @1.12'}, {'title': 'Copy -- @1.22'}]
</code>```

Edit: if you can't guarantee that the string ends with digit sequences, then instead of rpartition, try using re.findall to extract the digits from anywhere in the string:

```<code>>>> import re
>>> array_x = [{'title': 'Copy -- @1.1 copy file'}, {'title': 'Copy -- @1.11 true files'}, {'title': 'Copy -- @1.3 true files'}, {'title': 'Copy -- @1.2'}, {'title': 'Copy -- @1.12'}, {'title': 'Copy -- @1.22'}, {'title': 'After -- @1.1'}]
>>> array_x.sort(key=lambda s: list(map(int, re.findall(r"\d+", s['title']))))
>>> array_x
[{'title': 'Copy -- @1.1 copy file'}, {'title': 'After -- @1.1'}, {'title': 'Copy -- @1.2'}, {'title': 'Copy -- @1.3 true files'}, {'title': 'Copy -- @1.11 true files'}, {'title': 'Copy -- @1.12'}, {'title': 'Copy -- @1.22'}]
</code>```

Edit part 2: if you want to break ties based on the textual content of the title, put it in a tuple with the numeric list content:

```<code>>>> array_x.sort(key=lambda s: (list(map(int, re.findall(r"\d+", s['title']))), s['title']))
>>> array_x
[{'title': 'After -- @1.1'}, {'title': 'Copy -- @1.1 copy file'}, {'title': 'Copy -- @1.2'}, {'title': 'Copy -- @1.3 true files'}, {'title': 'Copy -- @1.11 true files'}, {'title': 'Copy -- @1.12'}, {'title': 'Copy -- @1.22'}]
</code>```

Body:
How about this: discard everything before and including the @ sign, then convert each period-separated section into ints. That should fix the problem of the digit sequences being sorted lexicographically.

>>> array_x = [{'title': 'Copy -- @1.1'}, {'title': 'Copy -- @1.11'}, {'title': 'Copy -- @1.3'}, {'title': 'Copy -- @1.2'}, {'title': 'Copy -- @1.12'}, {'title': 'Copy -- @1.22'}, {'title': 'After -- @1.1'}]
>>> array_x.sort(key=lambda s: list(map(int, s['title'].rpartition("@")[2].split('.'))))
>>> array_x
[{'title': 'After -- @1.1'}, {'title': 'Copy -- @1.1'}, {'title': 'Copy -- @1.2'}, {'title': 'Copy -- @1.3'}, {'title': 'Copy -- @1.11'}, {'title': 'Copy -- @1.12'}, {'title': 'Copy -- @1.22'}]

Edit: if you can't guarantee that the string ends with digit sequences, then instead of rpartition, try using re.findall to extract the digits from anywhere in the string:

>>> import re
>>> array_x = [{'title': 'Copy -- @1.1 copy file'}, {'title': 'Copy -- @1.11 true files'}, {'title': 'Copy -- @1.3 true files'}, {'title': 'Copy -- @1.2'}, {'title': 'Copy -- @1.12'}, {'title': 'Copy -- @1.22'}, {'title': 'After -- @1.1'}]
>>> array_x.sort(key=lambda s: list(map(int, re.findall(r"\d+", s['title']))))
>>> array_x
[{'title': 'Copy -- @1.1 copy file'}, {'title': 'After -- @1.1'}, {'title': 'Copy -- @1.2'}, {'title': 'Copy -- @1.3 true files'}, {'title': 'Copy -- @1.11 true files'}, {'title': 'Copy -- @1.12'}, {'title': 'Copy -- @1.22'}]

Edit part 2: if you want to break ties based on the textual content of the title, put it in a tuple with the numeric list content:

>>> array_x.sort(key=lambda s: (list(map(int, re.findall(r"\d+", s['title']))), s['title']))
>>> array_x
[{'title': 'After -- @1.1'}, {'title': 'Copy -- @1.1 copy file'}, {'title': 'Copy -- @1.2'}, {'title': 'Copy -- @1.3 true files'}, {'title': 'Copy -- @1.11 true files'}, {'title': 'Copy -- @1.12'}, {'title': 'Copy -- @1.22'}]


问:
Rewrite the algorithm in java stream with less effort?
I was learning about Streams in Java 8.

For example, If I have to double a number:

```<code>Arrays.stream(intArray).map(e->e*2).forEach(System.out::println);
</code>```

If I have to square a number, then I can use below:

```<code>Arrays.stream(intArray).map(e->e*e).forEach(System.out::println);
</code>```

But If I have to apply both functions on same Integer array using "andThen" method java.util.function.Function, I am doing it via:

```<code>  Function<Integer, Integer> times2 = e -> e * 2;

  Function<Integer, Integer> squared = e -> e * e;

 Arrays.stream(intArray).map(times2.andThen(squared)).forEach(System.out::println);
</code>```

Is it possible to rewrite this (3 statements) in single line like :

```<code>Arrays.stream(intArray).map(e->e*2.andThen(f->f*f)).forEach(System.out::println);
</code>```

This is giving me a compiler error. Is it possible to do it?

答:
If you absolutely must use the .andThen method, then the other answers here are what you are looking for. But if you are looking for a simple way to combine two functions in a single-line fluent stream operation, then just calling .map twice is the most readable and compact form that I can think of:

```<code>Arrays.stream(intArray).map(e->e*2).map(f->f*f).forEach(System.out::println);
</code>```

Body:
I was learning about Streams in Java 8.

For example, If I have to double a number:

Arrays.stream(intArray).map(e->e*2).forEach(System.out::println);

If I have to square a number, then I can use below:

Arrays.stream(intArray).map(e->e*e).forEach(System.out::println);

But If I have to apply both functions on same Integer array using "andThen" method java.util.function.Function, I am doing it via:

  Function<Integer, Integer> times2 = e -> e * 2;

  Function<Integer, Integer> squared = e -> e * e;

 Arrays.stream(intArray).map(times2.andThen(squared)).forEach(System.out::println);

Is it possible to rewrite this (3 statements) in single line like :

Arrays.stream(intArray).map(e->e*2.andThen(f->f*f)).forEach(System.out::println);

This is giving me a compiler error. Is it possible to do it?

Body:
If you absolutely must use the .andThen method, then the other answers here are what you are looking for. But if you are looking for a simple way to combine two functions in a single-line fluent stream operation, then just calling .map twice is the most readable and compact form that I can think of:

Arrays.stream(intArray).map(e->e*2).map(f->f*f).forEach(System.out::println);


问:
Write jpeg file directly to lmdb
I managed to write numpy arrays to lmdb, howewer solution is far from perfection, but actually my X is just jpg image, so my question is how to directly write jpeg file to lmdb?

Seems like pycaffe doing similar thing but it use caffe specific Datum and I need some general solution without dependencies.

答:
Here is example that write image as numpy array and directly as encoded jpg.

As we can see store jpg directly is more efficient in terms of storage.

```<code>du -sh *
184K  temp.db
120K  temp_jpg.db
</code>```

```<code>import numpy as np
import lmdb
import cv2

n_samples= 2

def create_random_image(filename):
    img= (np.random.rand(100,120,3)*255).astype(np.uint8)

    cv2.imwrite(filename,img)

def write_lmdb(filename):
    print 'Write lmdb'

    lmdb_env = lmdb.open(filename, map_size=int(1e9))

    X= cv2.imread('random_img.jpg')
    y= np.random.rand(1).astype(np.float32)*10.0

    for i in range(n_samples):
        with lmdb_env.begin(write=True) as lmdb_txn:
            lmdb_txn.put('X_'+str(i), X)
            lmdb_txn.put('y_'+str(i), y)

            print 'X.shape:',X.shape
            print 'y:',y

def read_lmdb(filename):
    print 'Read lmdb'

    lmdb_env = lmdb.open(filename)
    lmdb_txn = lmdb_env.begin()
    lmdb_cursor = lmdb_txn.cursor()

    #also can do it without iteration via txn.get('key1')?

    n_counter=0
    with lmdb_env.begin() as lmdb_txn:
        with lmdb_txn.cursor() as lmdb_cursor:
            for key, value in lmdb_cursor:
                print key
                if('X' in key):
                    print 'X.shape', np.fromstring(value, dtype=np.uint8).shape
                if('y' in key):
                    print np.fromstring(value, dtype=np.float32)

                n_counter=n_counter+1

    print 'n_samples',n_counter

def write_lmdb_jpg(filename):
    print 'Write lmdb'

    lmdb_env = lmdb.open(filename, map_size=int(1e9))

    X= cv2.imread('random_img.jpg')
    y= np.random.rand(1).astype(np.float32)*10.0

    for i in range(n_samples):
        with lmdb_env.begin(write=True) as lmdb_txn:
            lmdb_txn.put('X_'+str(i), cv2.imencode('.jpg', X)[1])
            lmdb_txn.put('y_'+str(i), y)

            print 'X.shape', cv2.imencode('.jpg', X)[1].shape
            print 'y:',y

def read_lmdb_jpg(filename):
    print 'Read lmdb'

    lmdb_env = lmdb.open(filename)
    lmdb_txn = lmdb_env.begin()
    lmdb_cursor = lmdb_txn.cursor()

    #also can do it without iteration via txn.get('key1')?

    n_counter=0
    with lmdb_env.begin() as lmdb_txn:
        with lmdb_txn.cursor() as lmdb_cursor:
            for key, value in lmdb_cursor:
                print key
                if('X' in key):
                    X_str= np.fromstring(value, dtype=np.uint8)
                    print 'X_str.shape', X_str.shape
                    X= cv2.imdecode(X_str, cv2.CV_LOAD_IMAGE_COLOR)
                    print 'X.shape', X.shape
                if('y' in key):
                    print np.fromstring(value, dtype=np.float32)

                n_counter=n_counter+1

    print 'n_samples',n_counter

create_random_image('random_img.jpg')

#Write as numpy array
write_lmdb('temp.db')
read_lmdb('temp.db')

#Write as encoded jpg
write_lmdb_jpg('temp_jpg.db')
read_lmdb_jpg('temp_jpg.db')
</code>```

Title: Write jpeg file directly to lmdb

Body:
Here is example that write image as numpy array and directly as encoded jpg.

As we can see store jpg directly is more efficient in terms of storage.

du -sh *
184K  temp.db
120K  temp_jpg.db

import numpy as np
import lmdb
import cv2

n_samples= 2

def create_random_image(filename):
    img= (np.random.rand(100,120,3)*255).astype(np.uint8)

    cv2.imwrite(filename,img)

def write_lmdb(filename):
    print 'Write lmdb'

    lmdb_env = lmdb.open(filename, map_size=int(1e9))

    X= cv2.imread('random_img.jpg')
    y= np.random.rand(1).astype(np.float32)*10.0

    for i in range(n_samples):
        with lmdb_env.begin(write=True) as lmdb_txn:
            lmdb_txn.put('X_'+str(i), X)
            lmdb_txn.put('y_'+str(i), y)

            print 'X.shape:',X.shape
            print 'y:',y

def read_lmdb(filename):
    print 'Read lmdb'

    lmdb_env = lmdb.open(filename)
    lmdb_txn = lmdb_env.begin()
    lmdb_cursor = lmdb_txn.cursor()

    #also can do it without iteration via txn.get('key1')?

    n_counter=0
    with lmdb_env.begin() as lmdb_txn:
        with lmdb_txn.cursor() as lmdb_cursor:
            for key, value in lmdb_cursor:
                print key
                if('X' in key):
                    print 'X.shape', np.fromstring(value, dtype=np.uint8).shape
                if('y' in key):
                    print np.fromstring(value, dtype=np.float32)

                n_counter=n_counter+1

    print 'n_samples',n_counter

def write_lmdb_jpg(filename):
    print 'Write lmdb'

    lmdb_env = lmdb.open(filename, map_size=int(1e9))

    X= cv2.imread('random_img.jpg')
    y= np.random.rand(1).astype(np.float32)*10.0

    for i in range(n_samples):
        with lmdb_env.begin(write=True) as lmdb_txn:
            lmdb_txn.put('X_'+str(i), cv2.imencode('.jpg', X)[1])
            lmdb_txn.put('y_'+str(i), y)

            print 'X.shape', cv2.imencode('.jpg', X)[1].shape
            print 'y:',y

def read_lmdb_jpg(filename):
    print 'Read lmdb'

    lmdb_env = lmdb.open(filename)
    lmdb_txn = lmdb_env.begin()
    lmdb_cursor = lmdb_txn.cursor()

    #also can do it without iteration via txn.get('key1')?

    n_counter=0
    with lmdb_env.begin() as lmdb_txn:
        with lmdb_txn.cursor() as lmdb_cursor:
            for key, value in lmdb_cursor:
                print key
                if('X' in key):
                    X_str= np.fromstring(value, dtype=np.uint8)
                    print 'X_str.shape', X_str.shape
                    X= cv2.imdecode(X_str, cv2.CV_LOAD_IMAGE_COLOR)
                    print 'X.shape', X.shape
                if('y' in key):
                    print np.fromstring(value, dtype=np.float32)

                n_counter=n_counter+1

    print 'n_samples',n_counter

create_random_image('random_img.jpg')

#Write as numpy array
write_lmdb('temp.db')
read_lmdb('temp.db')

#Write as encoded jpg
write_lmdb_jpg('temp_jpg.db')
read_lmdb_jpg('temp_jpg.db')


问:
java.upcasting
i have this example:

```<code>class One
{
    public void testOne(){System.out.println("One!!!");}
    public void testTwo(){System.out.println("One!!!");}
}
public class Jenia extends One
{
    static void test(One o) {o.testOne(); o.testTwo();}
    public static void main(String args[])
    {
        test(new One());
    }
}
</code>```

Results:

```<code>One!!!
One!!!
</code>```

ok, no questions.

than, i try modified my code:

only this method:

```<code>public static void main(String args[])
    {
        test(new Jenia());
        }
</code>```

results:

```<code>One!!!
One!!!
</code>```

ok, we have this results because - here upcasting(Jenia-One).

its all ok too, but, modified again:
 in class Jenia override methodtestOne`:

```<code>public void testOne(){System.out.println("Two!!!");}
</code>```

so i have this code:

```<code>class One
{
    public void testOne(){System.out.println("One!!!");}
    public void testTwo(){System.out.println("One!!!");}
}
public class Jenia extends One
{
    public void testOne(){System.out.println("Two!!!");}

    static void test(One o){o.testOne(); o.testTwo();}
    public static void main(String args[])
    {
        test(new Jenia());
    }
}
</code>```

and results:

```<code>Two!!!
One!!!
</code>```

my question: why Two!!! ?? why we not lost override methods?

答:
See the explanation in comments</p>

```<code>class One
{
    public void testOne(){System.out.println("One!!!");}//method one
    public void testTwo(){System.out.println("One!!!");}//method two
}
public class Jenia extends One
{
    public void testOne(){System.out.println("Two!!!");}//method 3

static void test(One o){o.testOne(); o.testTwo();}//method 4
    public static void main(String args[])
    {
        test(new Jenia());//calls method 4 which in turns calls 3 and 2.
        }
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: java.upcasting

Body:
i have this example:

class One
{
    public void testOne(){System.out.println("One!!!");}
    public void testTwo(){System.out.println("One!!!");}
}
public class Jenia extends One
{
    static void test(One o) {o.testOne(); o.testTwo();}
    public static void main(String args[])
    {
        test(new One());
    }
}

Results:

One!!!
One!!!

ok, no questions.

than, i try modified my code:

only this method:

public static void main(String args[])
    {
        test(new Jenia());
        }

results:

One!!!
One!!!

ok, we have this results because - here upcasting(Jenia-One).

its all ok too, but, modified again:
 in class Jenia override methodtestOne`:

public void testOne(){System.out.println("Two!!!");}

so i have this code:

class One
{
    public void testOne(){System.out.println("One!!!");}
    public void testTwo(){System.out.println("One!!!");}
}
public class Jenia extends One
{
    public void testOne(){System.out.println("Two!!!");}

    static void test(One o){o.testOne(); o.testTwo();}
    public static void main(String args[])
    {
        test(new Jenia());
    }
}

and results:

Two!!!
One!!!

my question: why Two!!! ?? why we not lost override methods?

Body:
See the explanation in comments

class One
{
    public void testOne(){System.out.println("One!!!");}//method one
    public void testTwo(){System.out.println("One!!!");}//method two
}
public class Jenia extends One
{
    public void testOne(){System.out.println("Two!!!");}//method 3

static void test(One o){o.testOne(); o.testTwo();}//method 4
    public static void main(String args[])
    {
        test(new Jenia());//calls method 4 which in turns calls 3 and 2.
        }
    }
}


问:
Angular2 - The selector "my-app" did not match any elements (only on first load)
Does anyone know why I get this error when the page loads the first time in my Angular2 app?  It clears away and doesn't come back as I navigate through my app.  If I hit CTRL+F5 it tends to come back (though not every single time!). This routing for this app looks like this:

```<code>AppComponent.ts
  LoginComponent.ts
  DashboardComponent(Parent route with its own child routes)
    MainDashboardComponent
    EmployeesComponent
</code>```

The top level index.html file has the <my-app></my-app> tag in it that the error complains about periodically so I'm confused how it could be that it wouldn't see that tag on the page!

Error Details:

EXCEPTION: The selector "my-app" did not match any elementsBrowserDomAdapter.logError @ angular2.dev.js:22823BrowserDomAdapter.logGroup @ angular2.dev.js:22834ExceptionHandler.call @ angular2.dev.js:1163(anonymous function) @ angular2.dev.js:12481NgZone._notifyOnError @ angular2.dev.js:13405collection_1.StringMapWrapper.merge.onError @ angular2.dev.js:13309run @ angular2-polyfills.js:141(anonymous function) @ angular2.dev.js:13328zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:1511lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:1523lib$es6$promise$$internal$$publish @ angular2-polyfills.js:1494(anonymous function) @ angular2-polyfills.js:243microtask @ angular2.dev.js:13360run @ angular2-polyfills.js:138(anonymous function) @ angular2.dev.js:13328zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$asap$$flush @ angular2-polyfills.js:1305
  angular2.dev.js:22823 STACKTRACE:BrowserDomAdapter.logError @ angular2.dev.js:22823ExceptionHandler.call @ angular2.dev.js:1165(anonymous function) @ angular2.dev.js:12481NgZone._notifyOnError @ angular2.dev.js:13405collection_1.StringMapWrapper.merge.onError @ angular2.dev.js:13309run @ angular2-polyfills.js:141(anonymous function) @ angular2.dev.js:13328zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:1511lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:1523lib$es6$promise$$internal$$publish @ angular2-polyfills.js:1494(anonymous function) @ angular2-polyfills.js:243microtask @ angular2.dev.js:13360run @ angular2-polyfills.js:138(anonymous function) @ angular2.dev.js:13328zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$asap$$flush @ angular2-polyfills.js:1305
  angular2.dev.js:22823 Error: The selector "my-app" did not match any elements
      at new BaseException (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:7104:21)
      at DomRenderer.selectRootElement (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:13724:15)
      at HostViewFactory.viewFactory_HostAppComponent0 [as viewFactory] (viewFactory_HostAppComponent:72:18)
      at AppViewManager_.createRootHostView (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:9226:34)
      at http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:12246:46
      at Zone.run (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:138:17)
      at Zone.run (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:13328:32)
      at zoneBoundFn (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:111:19)
      at lib$es6$promise$$internal$$tryCatch (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:1511:16)
      at lib$es6$promise$$internal$$invokeCallback (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:1523:17)

-----async gap-----
  Error
      at _getStacktraceWithUncaughtError (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:2195:26)
      at Zone.fork (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:2253:40)
      at Zone.bind (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:109:48)
      at bindArguments (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:980:29)
      at lib$es6$promise$promise$$Promise.obj.(anonymous function) [as then] (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:1000:37)
      at DynamicComponentLoader_.loadAsRoot (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:12245:49)
      at di_1.provide.useFactory (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:12343:39)
      at Injector._instantiate (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:11354:19)
      at Injector._instantiateProvider (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:11287:21)
      at Injector._new (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:11277:19)

-----async gap-----
  Error
      at _getStacktraceWithUncaughtError (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:2195:26)
      at Zone.fork (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:2253:40)
      at NgZone._createInnerZone (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:13316:39)
      at new NgZone (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:13182:32)
      at createNgZone (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:12365:12)
      at PlatformRef_.application (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:12440:31)
      at Object.bootstrap (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:24543:64)
      at execute (http://localhost:3000/app/main.js:15:23)
      at ensureEvaluated (http://localhost:3000/node_modules/systemjs/dist/system.src.js:3202:26)
      at Object.execute (http://localhost:3000/node_modules/systemjs/dist/system.src.js:3323:13)BrowserDomAdapter.logError @ angular2.dev.js:22823ExceptionHandler.call @ angular2.dev.js:1166(anonymous function) @ angular2.dev.js:12481NgZone._notifyOnError @ angular2.dev.js:13405collection_1.StringMapWrapper.merge.onError @ angular2.dev.js:13309run @ angular2-polyfills.js:141(anonymous function) @ angular2.dev.js:13328zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:1511lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:1523lib$es6$promise$$internal$$publish @ angular2-polyfills.js:1494(anonymous function) @ angular2-polyfills.js:243microtask @ angular2.dev.js:13360run @ angular2-polyfills.js:138(anonymous function) @ angular2.dev.js:13328zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$asap$$flush @ angular2-polyfills.js:1305

答:
I had the same Problem. I check index.html and app tag was missing. If you have selector as my-app than my -app tag should be present

```<code><html>
<head>
  <meta charset="utf-8">
  <title>InvoiceAngularUIFinal</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app>Loading...</app>
</body>
</html>
</code>```

Body:
Does anyone know why I get this error when the page loads the first time in my Angular2 app?  It clears away and doesn't come back as I navigate through my app.  If I hit CTRL+F5 it tends to come back (though not every single time!). This routing for this app looks like this:

AppComponent.ts
  LoginComponent.ts
  DashboardComponent(Parent route with its own child routes)
    MainDashboardComponent
    EmployeesComponent

The top level index.html file has the <my-app></my-app> tag in it that the error complains about periodically so I'm confused how it could be that it wouldn't see that tag on the page!

Error Details:

EXCEPTION: The selector "my-app" did not match any elementsBrowserDomAdapter.logError @ angular2.dev.js:22823BrowserDomAdapter.logGroup @ angular2.dev.js:22834ExceptionHandler.call @ angular2.dev.js:1163(anonymous function) @ angular2.dev.js:12481NgZone._notifyOnError @ angular2.dev.js:13405collection_1.StringMapWrapper.merge.onError @ angular2.dev.js:13309run @ angular2-polyfills.js:141(anonymous function) @ angular2.dev.js:13328zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:1511lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:1523lib$es6$promise$$internal$$publish @ angular2-polyfills.js:1494(anonymous function) @ angular2-polyfills.js:243microtask @ angular2.dev.js:13360run @ angular2-polyfills.js:138(anonymous function) @ angular2.dev.js:13328zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$asap$$flush @ angular2-polyfills.js:1305
  angular2.dev.js:22823 STACKTRACE:BrowserDomAdapter.logError @ angular2.dev.js:22823ExceptionHandler.call @ angular2.dev.js:1165(anonymous function) @ angular2.dev.js:12481NgZone._notifyOnError @ angular2.dev.js:13405collection_1.StringMapWrapper.merge.onError @ angular2.dev.js:13309run @ angular2-polyfills.js:141(anonymous function) @ angular2.dev.js:13328zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:1511lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:1523lib$es6$promise$$internal$$publish @ angular2-polyfills.js:1494(anonymous function) @ angular2-polyfills.js:243microtask @ angular2.dev.js:13360run @ angular2-polyfills.js:138(anonymous function) @ angular2.dev.js:13328zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$asap$$flush @ angular2-polyfills.js:1305
  angular2.dev.js:22823 Error: The selector "my-app" did not match any elements
      at new BaseException (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:7104:21)
      at DomRenderer.selectRootElement (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:13724:15)
      at HostViewFactory.viewFactory_HostAppComponent0 [as viewFactory] (viewFactory_HostAppComponent:72:18)
      at AppViewManager_.createRootHostView (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:9226:34)
      at http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:12246:46
      at Zone.run (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:138:17)
      at Zone.run (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:13328:32)
      at zoneBoundFn (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:111:19)
      at lib$es6$promise$$internal$$tryCatch (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:1511:16)
      at lib$es6$promise$$internal$$invokeCallback (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:1523:17)

-----async gap-----
  Error
      at _getStacktraceWithUncaughtError (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:2195:26)
      at Zone.fork (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:2253:40)
      at Zone.bind (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:109:48)
      at bindArguments (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:980:29)
      at lib$es6$promise$promise$$Promise.obj.(anonymous function) [as then] (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:1000:37)
      at DynamicComponentLoader_.loadAsRoot (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:12245:49)
      at di_1.provide.useFactory (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:12343:39)
      at Injector._instantiate (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:11354:19)
      at Injector._instantiateProvider (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:11287:21)
      at Injector._new (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:11277:19)

-----async gap-----
  Error
      at _getStacktraceWithUncaughtError (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:2195:26)
      at Zone.fork (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:2253:40)
      at NgZone._createInnerZone (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:13316:39)
      at new NgZone (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:13182:32)
      at createNgZone (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:12365:12)
      at PlatformRef_.application (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:12440:31)
      at Object.bootstrap (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:24543:64)
      at execute (http://localhost:3000/app/main.js:15:23)
      at ensureEvaluated (http://localhost:3000/node_modules/systemjs/dist/system.src.js:3202:26)
      at Object.execute (http://localhost:3000/node_modules/systemjs/dist/system.src.js:3323:13)BrowserDomAdapter.logError @ angular2.dev.js:22823ExceptionHandler.call @ angular2.dev.js:1166(anonymous function) @ angular2.dev.js:12481NgZone._notifyOnError @ angular2.dev.js:13405collection_1.StringMapWrapper.merge.onError @ angular2.dev.js:13309run @ angular2-polyfills.js:141(anonymous function) @ angular2.dev.js:13328zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:1511lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:1523lib$es6$promise$$internal$$publish @ angular2-polyfills.js:1494(anonymous function) @ angular2-polyfills.js:243microtask @ angular2.dev.js:13360run @ angular2-polyfills.js:138(anonymous function) @ angular2.dev.js:13328zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$asap$$flush @ angular2-polyfills.js:1305

Body:
I had the same Problem. I check index.html and app tag was missing. If you have selector as my-app than my -app tag should be present

<html>
<head>
  <meta charset="utf-8">
  <title>InvoiceAngularUIFinal</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app>Loading...</app>
</body>
</html>


问:
Does system("CLS") also clear my variable storage in c++
I was working on a project to make ball/object hit game in c++.
I used system("cls"); to clear the screen and display Game Over message. User scores are being reset to zero 0. while removing system("cls"); doesn't effect the score of user. Is there any good way to clear the screen without clearing the values of vairables?

Here is an example code. This is the function for level 2 of my game.
I have commented on the line which is causing me this problem.

```<code>    int level_2(string user_name,int scores)
{
    system("CLS");
    for(int i=5;i>0;i--)
    {
        cout<< "\n\n\n\n\n_________________________________\n";
        cout<< "|                               |\n";
        cout<< "| level 2 starts in "<<i<<" seconds\t|\n";
        cout<< "|                               |\n";
        cout<< "_________________________________\n";
        Sleep(1000);
        system("CLS");
    }
    system("CLS");
string s = "=======";
string h = "       ";
int i=5, x=10, y=29;
cout << "Press Arrow Keys to move, press q to quit\tWelcome "<<user_name<<"!\n";
cout<< "_________________________________\n";
for(int i=0;i<31;i++)
cout<< "|                               |\n";
cout<< "_________________________________\n";
int x1 = rand() % 19 + 1,
y1 = rand() % 19+ 1,
x2 = rand() % 19 + 1,
y2 = rand() % 19 + 1,
x3=2,
y3=2,
incX=-1,
incY=-1,
incXX=1,
incYY=1,
speed=70;
while (true){

    gotoxy(x, y);
    cout << s;
    if (kbhit())
    {
        gotoxy(x, y);
        cout << h;
        i = getch();
        if (i == 'q')
        {
            break;
        }
        if (i == UP && y>UPLIMIT)
            y=y-2;
        else if (i == DOWN && y<LOWLIMIT)
            y=y+2;
        if (i == LEFT && x>LEFTLIMIT)
            x = x - 3;
        else if (i == RIGHT && x<RIGHTLIMIT-6)
            x = x + 3;
    }
    drawObject(x3, y3);
    print_scores(scores);
    hideObject(x3, y3);
    if(y1<LOWLIMIT)
    drawObject(x1, y1);
    if(y2<LOWLIMIT)
    drawObject(x2, y2);
    Sleep(speed);// to slow down the process
    hideObject(x1, y1);
    hideObject(x2, y2);
    if (x1 == RIGHTLIMIT)   incX = -1;
    if (x1 == LEFTLIMIT)    incX = 1;
    if (y1 == LOWLIMIT)
    {
        incY = 0;
        speed=40;
    }
    if (x1>x-2 && x1<x+7 )
    {   if(y1==y-1)
        {
            incY=-1;
            scores=scores+10;
            total_scores=total_scores+10;
        }
    }
    if (y1 == UPLIMIT)  incY = 1;
    x1 += incX;
    y1 += incY;

    if (x2 == RIGHTLIMIT)   incXX = -1;
    if (x2 == LEFTLIMIT)    incXX = 1;
    if (y2 == LOWLIMIT )
    {
        incYY = 0;
        speed=40;
    }
    if (x2>x-2 && x2<x+7 )
    {   if(y2==y-1){
        incYY=-1;
        scores=scores+10;
        total_scores=total_scores+10;
        }
    }
    if (y2 == UPLIMIT)  incYY = 1;
    x2 += incXX;
    y2 += incYY;

    speed=speed-1;
    if (speed<25)
    speed=25;
if(incY==0 && incYY==0)
{
    system("cls");
    cout<<"\n\n\n\tG";Sleep(50);cout<<"a";Sleep(50);cout<<"m";Sleep(50);cout<<"e";Sleep(50);cout<<" ";Sleep(50);cout<<"O";Sleep(50);cout<<"v";Sleep(50);cout<<"e";Sleep(50);cout<<"r";
    system("pause>nul");
    system("cls");     //this line is clearing my scores
    break;
}
if(incY==0 && incYY==0)
break;
if(scores>=score2)
{
    ofstream out("records.txt");
    out<<scores;
    out.close();
    ofstream out1("total_scores.txt");
    out1<<total_scores;
    out1.close();
    break;
    }
    }
}
</code>```

答: system("cls") don't clear the value of variables. If you have problems with it, save the variables in a file before you clear the screen and load after the system("cls") line.

Body:
I was working on a project to make ball/object hit game in c++.
I used system("cls"); to clear the screen and display Game Over message. User scores are being reset to zero 0. while removing system("cls"); doesn't effect the score of user. Is there any good way to clear the screen without clearing the values of vairables?

Here is an example code. This is the function for level 2 of my game.
I have commented on the line which is causing me this problem.

    int level_2(string user_name,int scores)
{
    system("CLS");
    for(int i=5;i>0;i--)
    {
        cout<< "\n\n\n\n\n_________________________________\n";
        cout<< "|                               |\n";
        cout<< "| level 2 starts in "<<i<<" seconds\t|\n";
        cout<< "|                               |\n";
        cout<< "_________________________________\n";
        Sleep(1000);
        system("CLS");
    }
    system("CLS");
string s = "=======";
string h = "       ";
int i=5, x=10, y=29;
cout << "Press Arrow Keys to move, press q to quit\tWelcome "<<user_name<<"!\n";
cout<< "_________________________________\n";
for(int i=0;i<31;i++)
cout<< "|                               |\n";
cout<< "_________________________________\n";
int x1 = rand() % 19 + 1,
y1 = rand() % 19+ 1,
x2 = rand() % 19 + 1,
y2 = rand() % 19 + 1,
x3=2,
y3=2,
incX=-1,
incY=-1,
incXX=1,
incYY=1,
speed=70;
while (true){

    gotoxy(x, y);
    cout << s;
    if (kbhit())
    {
        gotoxy(x, y);
        cout << h;
        i = getch();
        if (i == 'q')
        {
            break;
        }
        if (i == UP && y>UPLIMIT)
            y=y-2;
        else if (i == DOWN && y<LOWLIMIT)
            y=y+2;
        if (i == LEFT && x>LEFTLIMIT)
            x = x - 3;
        else if (i == RIGHT && x<RIGHTLIMIT-6)
            x = x + 3;
    }
    drawObject(x3, y3);
    print_scores(scores);
    hideObject(x3, y3);
    if(y1<LOWLIMIT)
    drawObject(x1, y1);
    if(y2<LOWLIMIT)
    drawObject(x2, y2);
    Sleep(speed);// to slow down the process
    hideObject(x1, y1);
    hideObject(x2, y2);
    if (x1 == RIGHTLIMIT)   incX = -1;
    if (x1 == LEFTLIMIT)    incX = 1;
    if (y1 == LOWLIMIT)
    {
        incY = 0;
        speed=40;
    }
    if (x1>x-2 && x1<x+7 )
    {   if(y1==y-1)
        {
            incY=-1;
            scores=scores+10;
            total_scores=total_scores+10;
        }
    }
    if (y1 == UPLIMIT)  incY = 1;
    x1 += incX;
    y1 += incY;

    if (x2 == RIGHTLIMIT)   incXX = -1;
    if (x2 == LEFTLIMIT)    incXX = 1;
    if (y2 == LOWLIMIT )
    {
        incYY = 0;
        speed=40;
    }
    if (x2>x-2 && x2<x+7 )
    {   if(y2==y-1){
        incYY=-1;
        scores=scores+10;
        total_scores=total_scores+10;
        }
    }
    if (y2 == UPLIMIT)  incYY = 1;
    x2 += incXX;
    y2 += incYY;

    speed=speed-1;
    if (speed<25)
    speed=25;
if(incY==0 && incYY==0)
{
    system("cls");
    cout<<"\n\n\n\tG";Sleep(50);cout<<"a";Sleep(50);cout<<"m";Sleep(50);cout<<"e";Sleep(50);cout<<" ";Sleep(50);cout<<"O";Sleep(50);cout<<"v";Sleep(50);cout<<"e";Sleep(50);cout<<"r";
    system("pause>nul");
    system("cls");     //this line is clearing my scores
    break;
}
if(incY==0 && incYY==0)
break;
if(scores>=score2)
{
    ofstream out("records.txt");
    out<<scores;
    out.close();
    ofstream out1("total_scores.txt");
    out1<<total_scores;
    out1.close();
    break;
    }
    }
}


问:
How do I create a method for filling a matrix without knowing the type of the input
I want to create a method that reads input from the console and fills it, example:

3 4

A B B D

E B B B

I J B B

The first line reads the dimensions and the rest are the input in the matrix (there is no empty line in between i just cant paste it otherwise).
I wrote this :

```<code>  static void Main(string[] args)
    {
        var input = Console.ReadLine();
        char[,] matrix = ReadAndFillMatrix(input);
    }

  private static char[,] ReadAndFillMatrix(string input)
        {
            var size=input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
            var rows = size[0];
            var cols = size[1];
            var matrix = new char[rows, cols];
            for (int i = 0; i < rows; i++)
            {
                var line = Console.ReadLine()
               .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
               .Select(char.Parse)
               .ToArray();
                for (int j = 0; j < cols; j++)
                {
                    matrix[i, j] = line[j];
                }
            }

            return matrix;
        }
</code>```

So far so good, but what do I do when the matrix is not made of chars, but of integers for example?

The question: Do I have to create a different method for each type of matrix or is there some something I'm missing?

PS: I want to be able to use it in multiple places for different matrices not just the one

答:
Try creating a jagged array of type var. Check this question for the solution.

Storing an array of a different type into a jagged array

In that array, you can store each row as a new array. And that will happen at runtime, so you can do a TypeOf to find the exact type of data. Or you can keep it all as var.

Body:
I want to create a method that reads input from the console and fills it, example:

3 4

A B B D

E B B B

I J B B

The first line reads the dimensions and the rest are the input in the matrix (there is no empty line in between i just cant paste it otherwise).
I wrote this :

  static void Main(string[] args)
    {
        var input = Console.ReadLine();
        char[,] matrix = ReadAndFillMatrix(input);
    }

  private static char[,] ReadAndFillMatrix(string input)
        {
            var size=input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
            var rows = size[0];
            var cols = size[1];
            var matrix = new char[rows, cols];
            for (int i = 0; i < rows; i++)
            {
                var line = Console.ReadLine()
               .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
               .Select(char.Parse)
               .ToArray();
                for (int j = 0; j < cols; j++)
                {
                    matrix[i, j] = line[j];
                }
            }

            return matrix;
        }

So far so good, but what do I do when the matrix is not made of chars, but of integers for example?

The question: Do I have to create a different method for each type of matrix or is there some something I'm missing?

PS: I want to be able to use it in multiple places for different matrices not just the one


问:
write.csv formatting dates r
I have a dataframe with a date column 'StartDate' formatted as:
2014-12-31

I want to write a CSV that has StartDate formatted the same way. However, write.csv() writes StartDate in the format
12/31/2014.

How can I prevent this behavior?

Thks.

答:
It would be helpful for me,

```<code>require ("dplyr", "readr")
    write_tsv (
                 data %>%
                 replace (
                          sapply (data, function(x)inherits(x, "Date")),
                          format (
                                    data [sapply(data, function(x)inherits(x, "Date"))],
                                    "%Y/%m/%d"
                          )
                  )
</code>```

but I need in txt format (because I used it with a next SQL parser in R)

Title: write.csv formatting dates r

Body:
It would be helpful for me,

require ("dplyr", "readr")
    write_tsv (
                 data %>%
                 replace (
                          sapply (data, function(x)inherits(x, "Date")),
                          format (
                                    data [sapply(data, function(x)inherits(x, "Date"))],
                                    "%Y/%m/%d"
                          )
                  )

but I need in txt format (because I used it with a next SQL parser in R)


问:
iOS Development: Is there ever a time when it's appropriate for an app to kill itself?
I've been developing iOS apps for enterprise use for several years now. It was an adjustment from having spent many (!) years developing desktop apps. One of the first things I learned very early on was that it is frowned upon for an app to kill itself. The posters in the Apple dev forum were downright hostile about it, which is a reason I never go there anymore.

Now I have an app that has very critical functions, and it requires that the user accept the terms and conditions before using the app, and that the app will not function if the terms have not been accepted. The choice is there to accept or to decline, but it seems like the best thing to do when the user actively declines is to kill the app entirely.

My question is, under those circumstances, would there be anything wrong with that? Will I be damned to developers hell for eternity?

答: Why kill an app on a declying? I would rather just leave a user at the same screen with no actions before he puts acceptance checkbox, disabling all buttons</p>


问:
File upload from <input type="file">
Using angular 2 beta, I cannot seem to get an <input type="file"> to work.

Using diagnostic, I can see two-way binding for other types such as text.

```<code><form>
    {{diagnostic}}
    <div class="form-group">
        <label for="fileupload">Upload</label>
        <input type="file" class="form-control" [(ngModel)]="model.fileupload">
    </div>
</form>
</code>```

In my TypeScript file, I have the following diagnostic line:

```<code>get diagnostic() { return JSON.stringify(this.model); }
</code>```

Could it be that it is the issue of not being JSON? The value is null.

I cannot really verify the value of the input. Уven though the text next to "Choose file ..." updates, I cannot see differences in the DOM for some reason.

答:
There is a slightly better way to access attached files. You could use template reference variable to get an instance of the input element.

Here is an example based on the first answer:

```<code>@Component({
  selector: 'my-app',
  template: `
    <div>
      <input type="file" #file (change)="onChange(file.files)"/>
    </div>
  `,
  providers: [ UploadService ]
})

export class AppComponent {
  onChange(files) {
    console.log(files);
  }
}
</code>```

Here is an example app to demonstrate this in action.

Template reference variables might be useful, e.g. you could access them via @ViewChild directly in the controller.

ContentLicense: CC BY-SA 4.0

Title: File upload from <input type="file">

Body:
Using angular 2 beta, I cannot seem to get an <input type="file"> to work.

Using diagnostic, I can see two-way binding for other types such as text.

<form>
    {{diagnostic}}

        Upload
        <input type="file" class="form-control" [(ngModel)]="model.fileupload">

</form>

In my TypeScript file, I have the following diagnostic line:

get diagnostic() { return JSON.stringify(this.model); }

Could it be that it is the issue of not being JSON? The value is null.

I cannot really verify the value of the input. Уven though the text next to "Choose file ..." updates, I cannot see differences in the DOM for some reason.

Body:
There is a slightly better way to access attached files. You could use template reference variable to get an instance of the input element.

Here is an example based on the first answer:

@Component({
  selector: 'my-app',
  template: `
    <div>
      <input type="file" #file (change)="onChange(file.files)"/>
    </div>
  `,
  providers: [ UploadService ]
})

export class AppComponent {
  onChange(files) {
    console.log(files);
  }
}

Here is an example app to demonstrate this in action.

Template reference variables might be useful, e.g. you could access them via @ViewChild directly in the controller.


问:
C# Combobox item text change?
I'm making the combobox which contains list of added Home adresses from DB, I'm trying to implement the option to change the text of what the current adress is called in combobox. For examples its now adressID fetched from db, but I'd like to add a option to call it for example "Adress 1" instead of just adressID.. I've tried some options from before suggested examples from google, but I get this error: Items collection cannot be modified when the DataSource property is set. because im using datasource. Anyone have an idea on how could this be fixed?

This is my code:

```<code>        private void getAdr()
    {
        string connStr = "Data Source=MARINCHI\\SQLEXPRESS;Initial Catalog=login1;Integrated Security=True";
        SqlConnection conn = new SqlConnection(connStr);
        conn.Open();

        SqlCommand getAdr = new SqlCommand("SELECT adressID, userID, adress, floor,city, state, country, zipcode FROM userAdress where userID = @userID", conn);
        SqlParameter parUserID = new SqlParameter("@userID", Login.id);
        getAdr.Parameters.Add(parUserID);
        getAdr.ExecuteNonQuery();
        SqlDataAdapter da = new SqlDataAdapter(getAdr);
        DataTable dt = new DataTable();
        da.Fill(dt);

        comboBox1.DataSource = dt;
        comboBox1.DisplayMember = "adressID";
        comboBox1.ValueMember = "adressID";

        textBox5.DataBindings.Add("Text", dt, "adress");
        textBox6.DataBindings.Add("Text", dt, "floor");
        textBox7.DataBindings.Add("Text", dt, "city");
        textBox8.DataBindings.Add("Text", dt, "state");
        textBox9.DataBindings.Add("Text", dt, "country");
        textBox10.DataBindings.Add("Text", dt, "zipcode");

        comboBox1.Items[comboBox1.SelectedIndex] = "Adress 1";

    }
</code>```

答: I think you should implement the TextChanged event of the combobox. When the user changes the addressID you should update your DB by using SqlCommand and then reload the datasource to refresh the combobox items.</p>

Title: C# Combobox item text change?

Body:
I'm making the combobox which contains list of added Home adresses from DB, I'm trying to implement the option to change the text of what the current adress is called in combobox. For examples its now adressID fetched from db, but I'd like to add a option to call it for example "Adress 1" instead of just adressID.. I've tried some options from before suggested examples from google, but I get this error: Items collection cannot be modified when the DataSource property is set. because im using datasource. Anyone have an idea on how could this be fixed?

This is my code:

        private void getAdr()
    {
        string connStr = "Data Source=MARINCHI\\SQLEXPRESS;Initial Catalog=login1;Integrated Security=True";
        SqlConnection conn = new SqlConnection(connStr);
        conn.Open();

        SqlCommand getAdr = new SqlCommand("SELECT adressID, userID, adress, floor,city, state, country, zipcode FROM userAdress where userID = @userID", conn);
        SqlParameter parUserID = new SqlParameter("@userID", Login.id);
        getAdr.Parameters.Add(parUserID);
        getAdr.ExecuteNonQuery();
        SqlDataAdapter da = new SqlDataAdapter(getAdr);
        DataTable dt = new DataTable();
        da.Fill(dt);

        comboBox1.DataSource = dt;
        comboBox1.DisplayMember = "adressID";
        comboBox1.ValueMember = "adressID";

        textBox5.DataBindings.Add("Text", dt, "adress");
        textBox6.DataBindings.Add("Text", dt, "floor");
        textBox7.DataBindings.Add("Text", dt, "city");
        textBox8.DataBindings.Add("Text", dt, "state");
        textBox9.DataBindings.Add("Text", dt, "country");
        textBox10.DataBindings.Add("Text", dt, "zipcode");

        comboBox1.Items[comboBox1.SelectedIndex] = "Adress 1";

    }


问:
How to create a list of list and then perform a vectorised function over it
I'm looking for two specific help point in this request
 1) how to create a list of list given my data base (all.df) below
 2) how to vectorise a function over this list of list

I'm trying to generate a forecast at a customer / product level using the Prophet library.
Im struggling to vectorise the operation.
I currently run a for loop, which I want to avoid and speed-up my calculations.

Data for the analysis

```<code>set.seed(1123)
df1 <- data.frame(
  Date     = seq(dmy("01/01/2017"), by = "day", length.out = 365*2),

  Customer = "a",
  Product  =  "xxx",
  Revenue  = sample(1:100, 365*2, replace=TRUE))

df2 <- data.frame(
  Date     = seq(dmy("01/01/2017"), by = "day", length.out = 365*2),

  Customer = "a",
  Product  =  "yyy",
  Revenue  = sample(25:200, 365*2, replace=TRUE))

df3 <- data.frame(
  Date     = seq(dmy("01/01/2017"), by = "day", length.out = 365*2),

  Customer = "b",
  Product  =  "xxx",
  Revenue  = sample(1:100, 365*2, replace=TRUE))

df4 <- data.frame(
  Date     = seq(dmy("01/01/2017"), by = "day", length.out = 365*2),

  Customer = "b",
  Product  =  "yyy",
  Revenue  = sample(25:200, 365*2, replace=TRUE) )

all.df <- rbind(df1, df2, df3, df4)
</code>```

This is my forecast function

```<code>daily_forecast <- function(df, forecast.days = 365){

# fit actuals into prophet
m <- prophet(df,
             yearly.seasonality = TRUE,
             weekly.seasonality = TRUE,
             changepoint.prior.scale = 0.55)  # default value is 0.05

# create dummy data frame to hold prodictions
future <- make_future_dataframe(m, periods = forecast.days, freq = "day")

# run the prediction
forecast <- predict(m, future)

### Select the date and forecast from the model and then merge with actuals
daily_fcast     <- forecast %>% select(ds, yhat) %>% dplyr::rename(Date = ds, fcast.daily = yhat)
actual.to.merge <- df %>% dplyr::rename(Date = ds, Actual.Revenue = y)
daily_fcast     <- merge(actual.to.merge, daily_fcast, all = TRUE)

}
</code>```

Currently, I work through one customer/product at a time using a for loop

```<code>x <- df1 %>% select(-c(Customer, Product)) %>%
  dplyr::rename(ds = Date, y = Revenue) %>%
  daily_forecast()
</code>```

I would like to instead, vectorise the whole operation:

1-Create a list of list, i.e. split the all.df by:

a) Product and then

b) by customer

2-Then have the daily_forecast function map over the list of list created in 1) above

I would very much like to use functions out of purrr.

Body:
I'm looking for two specific help point in this request
 1) how to create a list of list given my data base (all.df) below
 2) how to vectorise a function over this list of list

I'm trying to generate a forecast at a customer / product level using the Prophet library.
Im struggling to vectorise the operation.
I currently run a for loop, which I want to avoid and speed-up my calculations.

Data for the analysis

set.seed(1123)
df1 <- data.frame(
  Date     = seq(dmy("01/01/2017"), by = "day", length.out = 365*2),

  Customer = "a",
  Product  =  "xxx",
  Revenue  = sample(1:100, 365*2, replace=TRUE))

df2 <- data.frame(
  Date     = seq(dmy("01/01/2017"), by = "day", length.out = 365*2),

  Customer = "a",
  Product  =  "yyy",
  Revenue  = sample(25:200, 365*2, replace=TRUE))

df3 <- data.frame(
  Date     = seq(dmy("01/01/2017"), by = "day", length.out = 365*2),

  Customer = "b",
  Product  =  "xxx",
  Revenue  = sample(1:100, 365*2, replace=TRUE))

df4 <- data.frame(
  Date     = seq(dmy("01/01/2017"), by = "day", length.out = 365*2),

  Customer = "b",
  Product  =  "yyy",
  Revenue  = sample(25:200, 365*2, replace=TRUE) )

all.df <- rbind(df1, df2, df3, df4)

This is my forecast function

daily_forecast <- function(df, forecast.days = 365){

# fit actuals into prophet
m <- prophet(df,
             yearly.seasonality = TRUE,
             weekly.seasonality = TRUE,
             changepoint.prior.scale = 0.55)  # default value is 0.05

# create dummy data frame to hold prodictions
future <- make_future_dataframe(m, periods = forecast.days, freq = "day")

# run the prediction
forecast <- predict(m, future)

### Select the date and forecast from the model and then merge with actuals
daily_fcast     <- forecast %>% select(ds, yhat) %>% dplyr::rename(Date = ds, fcast.daily = yhat)
actual.to.merge <- df %>% dplyr::rename(Date = ds, Actual.Revenue = y)
daily_fcast     <- merge(actual.to.merge, daily_fcast, all = TRUE)

}

Currently, I work through one customer/product at a time using a for loop

x <- df1 %>% select(-c(Customer, Product)) %>%
  dplyr::rename(ds = Date, y = Revenue) %>%
  daily_forecast()

I would like to instead, vectorise the whole operation:

1-Create a list of list, i.e. split the all.df by:

a) Product and then

b) by customer

2-Then have the daily_forecast function map over the list of list created in 1) above

I would very much like to use functions out of purrr.

Body:
Here is how I would do what you're asking with purrr:

library(tidyverse)
library(lubridate)
library(prophet)

res <-
  all.df %>%
  split(.$Customer) %>%
  map(~ split(.x, .x$Product)) %>%
  at_depth(2, select, ds = Date, y = Revenue) %>%
  at_depth(2, daily_forecast)
str(res)
# List of 2
#  $ a:List of 2
# ..$ xxx:'data.frame': 1095 obs. of  3 variables:
# .. ..$ Date          : Date[1:1095], format: "2017-01-01" ...
# .. ..$ Actual.Revenue: int [1:1095] 76 87 87 56 83 17 19 72 92 35 ...
# .. ..$ fcast.daily   : num [1:1095] 55.9 57.9 51.9 51.9 54 ...
# ..$ yyy:'data.frame': 1095 obs. of  3 variables:
# .. ..$ Date          : Date[1:1095], format: "2017-01-01" ...
# .. ..$ Actual.Revenue: int [1:1095] 62 87 175 186 168 190 30 192 119 170 ...
# .. ..$ fcast.daily   : num [1:1095] 121 121 119 119 116 ...
# $ b:List of 2
# ..$ xxx:'data.frame': 1095 obs. of  3 variables:
# .. ..$ Date          : Date[1:1095], format: "2017-01-01" ...
# .. ..$ Actual.Revenue: int [1:1095] 71 94 81 32 85 59 59 55 50 50 ...
# .. ..$ fcast.daily   : num [1:1095] 51.9 54.2 54.5 53.1 51.9 ...
# ..$ yyy:'data.frame': 1095 obs. of  3 variables:
# .. ..$ Date          : Date[1:1095], format: "2017-01-01" ...
# .. ..$ Actual.Revenue: int [1:1095] 105 46 153 136 59 59 34 72 70 85 ...
# .. ..$ fcast.daily   : num [1:1095] 103.3 103.3 103.1 103.1 91.5 ...

But the following would be more natural to me (keeping everything in a dataframe):

res_2 <-
  all.df %>%
  rename(ds = Date, y = Revenue) %>%
  nest(ds, y) %>%
  transmute(Customer, Product, res = map(data, daily_forecast)) %>%
  unnest()
# # A tibble: 4,380 × 5
#    Customer Product       Date Actual.Revenue fcast.daily
#      <fctr>  <fctr>     <date>          <int>       <dbl>
# 1         a     xxx 2017-01-01             76    55.93109
# 2         a     xxx 2017-01-02             87    57.92577
# 3         a     xxx 2017-01-03             87    51.92263
# 4         a     xxx 2017-01-04             56    51.86267
# 5         a     xxx 2017-01-05             83    54.04588
# 6         a     xxx 2017-01-06             17    52.75289
# 7         a     xxx 2017-01-07             19    52.35083
# 8         a     xxx 2017-01-08             72    53.91887
# 9         a     xxx 2017-01-09             92    55.81202
# 10        a     xxx 2017-01-10             35    49.78302
# # ... with 4,370 more rows


问:
Is there a way to verify that all model relationships are successfully eager loaded in Sqlalchemy?
I'm familiar with the joinedload and subqueryload options in Sqlalchemy, and I'm using them to query a large result set that's later expunged from the session and cached.

Is there a way to verify that every possible relationship from the top-level model on down is eager-loaded at this point?

答:
The following iterator will iterate over all relationships reachable from a given model.  It yields a tuple of (model_class, relationship_name).  You can modify to look at prop.lazy or similar, or use this to construct loader options to lazy load the right things, or whatever seems appropriate.

```<code>from sqlalchemy import inspect

def recursive_relations(model, already_traversed = None):
    if not already_traversed: already_traversed = set()
    inspection = inspect(model)
    already_traversed.add(model)
    for name, prop in inspection.relationships.items():
        yield (model, name)
        if prop.mapper.class_ not in already_traversed:
            already_traversed.add(prop.mapper.class_)
            yield from recursive_relations(prop.mapper.class_, already_traversed)
</code>```

Body:
The following iterator will iterate over all relationships reachable from a given model.  It yields a tuple of (model_class, relationship_name).  You can modify to look at prop.lazy or similar, or use this to construct loader options to lazy load the right things, or whatever seems appropriate.

from sqlalchemy import inspect

def recursive_relations(model, already_traversed = None):
    if not already_traversed: already_traversed = set()
    inspection = inspect(model)
    already_traversed.add(model)
    for name, prop in inspection.relationships.items():
        yield (model, name)
        if prop.mapper.class_ not in already_traversed:
            already_traversed.add(prop.mapper.class_)
            yield from recursive_relations(prop.mapper.class_, already_traversed)


问:
How i can shift one row of data frame to first row?
How i can shift one raw of data frame to first raw, i want the id raw be the first raw. in R.</p>

```<code>Sepal.Length Sepal.Width Petal.Length Petal.Width Species

5.1         3.5          1.4         0.2         setosa
4.9         3.0          1.4         0.2         setosa
4.7         3.2          1.3         0.2         setosa
4.6         3.1          1.5         0.2         setosa
5.0         3.6          1.4         0.2         setosa
id           A            B           C            D
</code>```

答:
We can use grepl to create a logical vector based on the 'id' in 'Sepal.Length', then set the column names of the dataset by extracting that row while removing the row from the original dataset

```<code>i1 <- grepl("id", df1$Sepal.Length)
setNames(df1[!i1,], unlist(df1[i1,]))
#   id   A   B   C      D
#1 5.1 3.5 1.4 0.2 setosa
#2 4.9 3.0 1.4 0.2 setosa
#3 4.7 3.2 1.3 0.2 setosa
#4 4.6 3.1 1.5 0.2 setosa
#5 5.0 3.6 1.4 0.2 setosa
</code>```

Body:
How i can shift one raw of data frame to first raw, i want the id raw be the first raw. in R.

Sepal.Length Sepal.Width Petal.Length Petal.Width Species

5.1         3.5          1.4         0.2         setosa
4.9         3.0          1.4         0.2         setosa
4.7         3.2          1.3         0.2         setosa
4.6         3.1          1.5         0.2         setosa
5.0         3.6          1.4         0.2         setosa
id           A            B           C            D

Body:
We can use grepl to create a logical vector based on the 'id' in 'Sepal.Length', then set the column names of the dataset by extracting that row while removing the row from the original dataset

i1 <- grepl("id", df1$Sepal.Length)
setNames(df1[!i1,], unlist(df1[i1,]))
#   id   A   B   C      D
#1 5.1 3.5 1.4 0.2 setosa
#2 4.9 3.0 1.4 0.2 setosa
#3 4.7 3.2 1.3 0.2 setosa
#4 4.6 3.1 1.5 0.2 setosa
#5 5.0 3.6 1.4 0.2 setosa


问:
JQuery GET request won't get correct data from php echo
I am trying to fill a table using a jquery .get request, the url being a php file. The php gets data from a database, then it should return a json array back to the jquery, array which will fill the table. While the length of the array is returned as it should, the table cells are empty.

Here is my get.php function:

```<code><?php
$mysqli=new mysqli("localhost:3306","root","","leagues");
if (mysqli_connect_errno())
{
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$return_arr = array();
$query = "SELECT * FROM league";

if ($result = $mysqli->query($query)) {
    while ($row = $result->fetch_row())
    {
        $return_arr[] = $row;
    }
}
$mysqli->close();
header('Content-Type: application/json');
echo json_encode($return_arr);
?>
</code>```

And here is my jquery get function

```<code>$.get('php/get.php',function(responseJson)
    {
        if(responseJson!=null)
        {
            $("#tableleague").find("tr:gt(0)").remove();
            var table1 = $("#tableleague");
            $.each(responseJson, function(key,value) {
                var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
                rowNew.children().eq(0).text(value['teams']);
                rowNew.children().eq(1).text(value['playedgames']);
                rowNew.children().eq(2).text(value['wongames']);
                rowNew.children().eq(3).text(value['tiegames']);
                rowNew.children().eq(4).text(value['lostgames']);
                rowNew.children().eq(5).text(value['scoredgoal']);
                rowNew.children().eq(6).text(value['receivedgoal']);
                rowNew.children().eq(7).text(value['points']);
                rowNew.appendTo(table1);
            });
        }
    });
</code>```

Here is how my webpage looks, with the php file response shown.

Since the response is ok, what am I doing wrong that the cells aren't filled? Thank you.

答:
If you look at your JSON data, you can see that there are no keys such as teams or playedgames. This is because you used fetch_row() in the PHP. Change that to fetch_assoc():

```<code>while ($row = $result->fetch_assoc())
</code>```

This will give you $row with the field names as keys instead of using numerical keys that fetch_row() provides.

Body:
I am trying to fill a table using a jquery .get request, the url being a php file. The php gets data from a database, then it should return a json array back to the jquery, array which will fill the table. While the length of the array is returned as it should, the table cells are empty.

Here is my get.php function:

<?php
$mysqli=new mysqli("localhost:3306","root","","leagues");
if (mysqli_connect_errno())
{
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$return_arr = array();
$query = "SELECT * FROM league";

if ($result = $mysqli->query($query)) {
    while ($row = $result->fetch_row())
    {
        $return_arr[] = $row;
    }
}
$mysqli->close();
header('Content-Type: application/json');
echo json_encode($return_arr);
?>

And here is my jquery get function

$.get('php/get.php',function(responseJson)
    {
        if(responseJson!=null)
        {
            $("#tableleague").find("tr:gt(0)").remove();
            var table1 = $("#tableleague");
            $.each(responseJson, function(key,value) {
                var rowNew = $("

");
                rowNew.children().eq(0).text(value['teams']);
                rowNew.children().eq(1).text(value['playedgames']);
                rowNew.children().eq(2).text(value['wongames']);
                rowNew.children().eq(3).text(value['tiegames']);
                rowNew.children().eq(4).text(value['lostgames']);
                rowNew.children().eq(5).text(value['scoredgoal']);
                rowNew.children().eq(6).text(value['receivedgoal']);
                rowNew.children().eq(7).text(value['points']);
                rowNew.appendTo(table1);
            });
        }
    });

Here is how my webpage looks, with the php file response shown.

Since the response is ok, what am I doing wrong that the cells aren't filled? Thank you.

Body:
If you look at your JSON data, you can see that there are no keys such as teams or playedgames. This is because you used fetch_row() in the PHP. Change that to fetch_assoc():

while ($row = $result->fetch_assoc())

This will give you $row with the field names as keys instead of using numerical keys that fetch_row() provides.


问:
Tables with schema using SqliteDialect.Provider
In my test project I register a connection using ":memory" connection string and SqliteDialect.Provider as provider. When trying to run tests that execute arbitrary sql (I have a complex join statement so I cannot use a typed query) I get an error that the table do not exist. In my query I print "SELECT * FROM xxx.Table1" but when looking at the code generated from a typed query I can see that it is "SELECT * FROM xxx_Table1". I need to use schemas for the production code, so is there a way to force ORMLite for Sqlite to generate schemas and not just name prefixes when using the attribute [Schema("xxx")] on my domain models?</p>

答:
SQLite doesn't have schemas so they're simulated by prefixing the schema name before the table name. However this should be a transparent implementation detail for SQLite :memory: DBs as the same table name will be used when creating or querying the table.

If you're creating Custom SQL you should use the tableName returned from:

```<code>var modelDef = typeof(Table1).GetModelMetadata();
var tableName = db.GetDialectProvider().GetTableName(modelDef);
var sql = $"SELECT * FROM {tableName}";
</code>```

Body:
SQLite doesn't have schemas so they're simulated by prefixing the schema name before the table name. However this should be a transparent implementation detail for SQLite :memory: DBs as the same table name will be used when creating or querying the table.

If you're creating Custom SQL you should use the tableName returned from:

var modelDef = typeof(Table1).GetModelMetadata();
var tableName = db.GetDialectProvider().GetTableName(modelDef);
var sql = $"SELECT * FROM {tableName}";


问:
How to dynamically change CSS elements to be HTTPS or HTTP
I have CSS with background-image's elements that refer to another site.
Problem is, that in IE you can't have resources if you are in HTTP while they are in HTTPS and vise versa.

I am using ASP.NET and I want to find a way of letting the CSS know about if it was requested in HTTPS or NOT...

And I MUST use absolute... (its on a different site)

Thanks!

答:
The solution would be if you can use relative url instead of absolute in your CSS file while pointing background images.

The problem will gone.

something like:-

```<code>#div
{
  background-image:url(../images/img1.png);
}
</code>```

Body:
The solution would be if you can use relative url instead of absolute in your CSS file while pointing background images.

The problem will gone.

something like:-

#div
{
  background-image:url(../images/img1.png);
}


问:
How to add mutiple ViewModels to user controls in main window
This my first attempt at implementing the MVVM model so apologies in advance. I have a main window which has its own ViewModel. The Main Window then has three user controls which i which loads depending on what selected in the navigation menu. However the data context is not changing to the correct view model.

MainWindow.xaml

```<code><Window.DataContext>
    <VM:MainVM></VM:MainVM>
</Window.DataContext>

<Window.Resources>
    <DataTemplate x:Key="View1Template" DataType="{x:Type VM:CustomerVM}">
        <View:Customers  DataContext="{Binding VM:CustomerVM}" />
    </DataTemplate>

    <DataTemplate x:Key="View2Template" DataType="{x:Type VM:SuppliersVM}">
        <View:Suppliers DataContext="{Binding VM:Suppliers}"/>
    </DataTemplate>
</Window.Resources>

<ContentControl  Margin="0,135,0,10" Grid.Column="1">
    <ContentControl.Style>
        <Style TargetType="{x:Type ContentControl}">
            <Setter Property="ContentTemplate"  Value="{StaticResource View1Template}" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding SwitchView}" Value="0">
                    <Setter Property="ContentTemplate" Value="{StaticResource View1Template}" />
                </DataTrigger>
                <DataTrigger Binding="{Binding SwitchView}" Value="1">
                    <Setter Property="ContentTemplate" Value="{StaticResource View2Template}" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ContentControl.Style>
</ContentControl>
</code>```

this has its own ViewModel and navigation loads the view correctly, however i have a command which runs on load and its not performing. This just populates a listview. I know it works because if i remove the datacontext of the window and set it as CustomerVM the listview is populated however navigation no longer works because MainVM has been removed.

Customer.xaml

```<code><i:Interaction.Triggers>
    <i:EventTrigger EventName="Loaded">
        <i:InvokeCommandAction Command="{Binding LoadCustomersCommand}" />
    </i:EventTrigger>
</i:Interaction.Triggers>
<Grid>
    <TextBox Tag="Search Customers" x:Name="searchTextBox" Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" HorizontalAlignment="Left" Height="40" Margin="10,9,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="340" Padding="5,6,0,0" FontSize="16"/>
    <Label Content="{Binding Path=SearchText}" Margin="430,0,436,263" />
    <ListView ItemsSource="{Binding Customers}" x:Name="customerListBox" Margin="10,57,10,10"  AlternationCount="2"   >
        <ListView.View>
            <GridView>
                <GridViewColumn Header="ID" Width="Auto" DisplayMemberBinding="{Binding id}" />
                <GridViewColumn Header="NAME" Width="Auto" DisplayMemberBinding="{Binding name}"  />
                <GridViewColumn Header="ADDRESS" Width="Auto" DisplayMemberBinding="{Binding address1}" />
                <GridViewColumn Header="ADDRESS 2" Width="150" DisplayMemberBinding="{Binding address2}" />
                <GridViewColumn Header="TOWN" Width="150" DisplayMemberBinding="{Binding town}" />
                <GridViewColumn Header="COUNTY" Width="150" DisplayMemberBinding="{Binding county}" />
                <GridViewColumn Header="POSTCODE" Width="150" DisplayMemberBinding="{Binding postcode}" />
                <GridViewColumn Header="PHONE" Width="150" DisplayMemberBinding="{Binding phone}" />
                <GridViewColumn Header="EMAIL" Width="150" DisplayMemberBinding="{Binding email}" />
            </GridView>
        </ListView.View>
    </ListView>
</Grid>
</code>```

CustomerVM.cs

```<code>private string _searchText;
private readonly ObservableCollection<Customer> _customers = new ObservableCollection<Customer>();

public string Title = "Customers";

public string SearchText
{
    get { return _searchText; }
    set
    {
        _searchText = value;
        RaisePropertyChangedEvent("SearchText");
    }
}

public IEnumerable<Customer> Customers
{
    get { return _customers; }
}

public ICommand LoadCustomersCommand
{
    get { return new DelegateCommand(LoadCustomers); }
}

public void LoadCustomers()
{
    Customer cus = new Customer { id = 1, name = "sam" };
    _customers.Add(cus);

}
</code>```

MainVM.cs

```<code>public ICommand NavigationClick
{
    get { return new DelegateCommand(Navigate); }
}

public void Navigate()
{
    SwitchView = 1;
}
</code>```

答:
I think there are several things going on here. We'll begin with the one that's most clear to me at the outset.

A DataContext is an object -- generally an instance of a viewmodel class. A DataTemplate is used to display an instance of a viewmodel class. Its DataContext is inherited by the controls that it contains. This is probably what you want:

```<code><Window.Resources>
    <DataTemplate DataType="{x:Type VM:CustomerVM}">
        <View:Customers />
    </DataTemplate>

    <DataTemplate DataType="{x:Type VM:SuppliersVM}">
        <View:Suppliers />
    </DataTemplate>
</Window.Resources>
</code>```

Secondly, you have to populate your ContentControl with an actual instance of one child viewmodel or another.

One way you've found is to give each view a <DataContext> element in the XAML that creates a viewmodel instance:

```<code><DataContext>
    <VM:CustomerVM />
</DataContext>
</code>```

But then how does the main viewmodel interact with its children? One solution is to use an MVVM framework that adds a byzantine "locator" that halfway solves the problem with a mess of kludges and workarounds. Much effort is spent satisfying the framework's demands.

That design puts the views in charge of everything, but views have no logic. They have no business being in charge. The "brain" of your application is broken into a dozen little pieces that are hidden from each other.

The other way is "viewmodel centric design": Design your application as a set of viewmodels. Child viewmodels are properties of parent viewmodels. MainVM can easily find its child SupplierVM because MainVM created it and owns it. Instead of the viewmodels being isolated appendages dangling from the views, the views are isolated appendages of the viewmodels -- which is absolutely fine, because views pretty much just sit there anyway.

Everything with WPF is easier this way.

You've got three viewmodels here: A parent, MainVM, and two children, CustomerVM and SupplierVM. Within the main view, you want to display one child or the other at a time.

So we'll give MainVM an instance of each child:

```<code>public MainVM()
{
    Customer = new CustomerVM();
    Supplier = new SupplierVM();
}

public CustomerVM Customer {
    get { return _customerVM; }
    private set { _customerVM = value; }
}
public SupplierVM Supplier {
    get { return _supplierVM; }
    private set { _supplierVM = value; }
}

public INotifyPropertyChanged _selectedChild;
public INotifyPropertyChanged SelectedChild {
    get { return _selectedChild; }
    set {
        if (value != _selectedChild) {
            _selectedChild = value;
            //  I don't know how you raise PropertyChanged; if it doesn't look
            //  like this, let me know.
            OnPropertyChanged();
        }
    }
}

public void Navigate()
{
    SelectedChild = Customer;
}
</code>```

In the XAML, the content control is much simplified. Whatever you put in SelectedChild will be displayed in the content control. How does it know what template to use?

Simple: We took the x:Key attribute off the data templates above, but we left the DataType attributes. That makes them into what's called "implicit data templates": Wherever they are in scope, they will be used automatically by any ContentControl that needs to display an object of one of those types. Anywhere in this Window, if you tell XAML "here's a CustomerVM; show it to the user", XAML will use the first of the above two datatemplates to display it.

```<code><ContentControl
    Content="{Binding SelectedChild}"
    Margin="0,135,0,10"
    Grid.Column="1"
    />
</code>```

You can get rid of the SwitchView property. What you did certainly works (and as you've found, doing something that works in XAML isn't always easy), but this way is easier and more conventional.

Body:
This my first attempt at implementing the MVVM model so apologies in advance. I have a main window which has its own ViewModel. The Main Window then has three user controls which i which loads depending on what selected in the navigation menu. However the data context is not changing to the correct view model.

MainWindow.xaml

<Window.DataContext>
    <VM:MainVM></VM:MainVM>
</Window.DataContext>

<Window.Resources>
    <DataTemplate x:Key="View1Template" DataType="{x:Type VM:CustomerVM}">
        <View:Customers  DataContext="{Binding VM:CustomerVM}" />
    </DataTemplate>

    <DataTemplate x:Key="View2Template" DataType="{x:Type VM:SuppliersVM}">
        <View:Suppliers DataContext="{Binding VM:Suppliers}"/>
    </DataTemplate>
</Window.Resources>

<ContentControl  Margin="0,135,0,10" Grid.Column="1">
    <ContentControl.Style>

        </Style>
    </ContentControl.Style>
</ContentControl>

this has its own ViewModel and navigation loads the view correctly, however i have a command which runs on load and its not performing. This just populates a listview. I know it works because if i remove the datacontext of the window and set it as CustomerVM the listview is populated however navigation no longer works because MainVM has been removed.

Customer.xaml

<Grid>
    <TextBox Tag="Search Customers" x:Name="searchTextBox" Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" HorizontalAlignment="Left" Height="40" Margin="10,9,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="340" Padding="5,6,0,0" FontSize="16"/>

    <ListView ItemsSource="{Binding Customers}" x:Name="customerListBox" Margin="10,57,10,10"  AlternationCount="2"   >
        <ListView.View>
            <GridView>
                <GridViewColumn Header="ID" Width="Auto" DisplayMemberBinding="{Binding id}" />
                <GridViewColumn Header="NAME" Width="Auto" DisplayMemberBinding="{Binding name}"  />
                <GridViewColumn Header="ADDRESS" Width="Auto" DisplayMemberBinding="{Binding address1}" />
                <GridViewColumn Header="ADDRESS 2" Width="150" DisplayMemberBinding="{Binding address2}" />
                <GridViewColumn Header="TOWN" Width="150" DisplayMemberBinding="{Binding town}" />
                <GridViewColumn Header="COUNTY" Width="150" DisplayMemberBinding="{Binding county}" />
                <GridViewColumn Header="POSTCODE" Width="150" DisplayMemberBinding="{Binding postcode}" />
                <GridViewColumn Header="PHONE" Width="150" DisplayMemberBinding="{Binding phone}" />
                <GridViewColumn Header="EMAIL" Width="150" DisplayMemberBinding="{Binding email}" />
            </GridView>
        </ListView.View>
    </ListView>
</Grid>

CustomerVM.cs

private string _searchText;
private readonly ObservableCollection<Customer> _customers = new ObservableCollection<Customer>();

public string Title = "Customers";

public string SearchText
{
    get { return _searchText; }
    set
    {
        _searchText = value;
        RaisePropertyChangedEvent("SearchText");
    }
}

public IEnumerable<Customer> Customers
{
    get { return _customers; }
}

public ICommand LoadCustomersCommand
{
    get { return new DelegateCommand(LoadCustomers); }
}

public void LoadCustomers()
{
    Customer cus = new Customer { id = 1, name = "sam" };
    _customers.Add(cus);

}

MainVM.cs

public ICommand NavigationClick
{
    get { return new DelegateCommand(Navigate); }
}

public void Navigate()
{
    SwitchView = 1;
}

Body:
I think there are several things going on here. We'll begin with the one that's most clear to me at the outset.

A DataContext is an object -- generally an instance of a viewmodel class. A DataTemplate is used to display an instance of a viewmodel class. Its DataContext is inherited by the controls that it contains. This is probably what you want:

<Window.Resources>
    <DataTemplate DataType="{x:Type VM:CustomerVM}">
        <View:Customers />
    </DataTemplate>

    <DataTemplate DataType="{x:Type VM:SuppliersVM}">
        <View:Suppliers />
    </DataTemplate>
</Window.Resources>

Secondly, you have to populate your ContentControl with an actual instance of one child viewmodel or another.

One way you've found is to give each view a <DataContext> element in the XAML that creates a viewmodel instance:

<DataContext>
    <VM:CustomerVM />
</DataContext>

But then how does the main viewmodel interact with its children? One solution is to use an MVVM framework that adds a byzantine "locator" that halfway solves the problem with a mess of kludges and workarounds. Much effort is spent satisfying the framework's demands.

That design puts the views in charge of everything, but views have no logic. They have no business being in charge. The "brain" of your application is broken into a dozen little pieces that are hidden from each other.

The other way is "viewmodel centric design": Design your application as a set of viewmodels. Child viewmodels are properties of parent viewmodels. MainVM can easily find its child SupplierVM because MainVM created it and owns it. Instead of the viewmodels being isolated appendages dangling from the views, the views are isolated appendages of the viewmodels -- which is absolutely fine, because views pretty much just sit there anyway.

Everything with WPF is easier this way.

You've got three viewmodels here: A parent, MainVM, and two children, CustomerVM and SupplierVM. Within the main view, you want to display one child or the other at a time.

So we'll give MainVM an instance of each child:

public MainVM()
{
    Customer = new CustomerVM();
    Supplier = new SupplierVM();
}

public CustomerVM Customer {
    get { return _customerVM; }
    private set { _customerVM = value; }
}
public SupplierVM Supplier {
    get { return _supplierVM; }
    private set { _supplierVM = value; }
}

public INotifyPropertyChanged _selectedChild;
public INotifyPropertyChanged SelectedChild {
    get { return _selectedChild; }
    set {
        if (value != _selectedChild) {
            _selectedChild = value;
            //  I don't know how you raise PropertyChanged; if it doesn't look
            //  like this, let me know.
            OnPropertyChanged();
        }
    }
}

public void Navigate()
{
    SelectedChild = Customer;
}

In the XAML, the content control is much simplified. Whatever you put in SelectedChild will be displayed in the content control. How does it know what template to use?

Simple: We took the x:Key attribute off the data templates above, but we left the DataType attributes. That makes them into what's called "implicit data templates": Wherever they are in scope, they will be used automatically by any ContentControl that needs to display an object of one of those types. Anywhere in this Window, if you tell XAML "here's a CustomerVM; show it to the user", XAML will use the first of the above two datatemplates to display it.

<ContentControl
    Content="{Binding SelectedChild}"
    Margin="0,135,0,10"
    Grid.Column="1"
    />

You can get rid of the SwitchView property. What you did certainly works (and as you've found, doing something that works in XAML isn't always easy), but this way is easier and more conventional.


问:
Facebook default video player into Android webview
I want to stream facebook video using default video player of facebook in my app. On click of video i want to open webview in my app and play facebook video by using their own video player and all default control. How will i achieve it? Is their any other way to achieve the video streaming. But i want to stream video using facebook default player and not on any other player. How can i achieve this? Any help will be appreciated</p>

答:
Did you already double check dev facebook docs embedded-video-player/api, where you can find this following full code example:

```<code><html>
<head>
  <title>Your Website Title</title>
</head>
<body>

  <!-- Load Facebook SDK for JavaScript -->
  <div id="fb-root"></div>
  <script>
    window.fbAsyncInit = function() {
      FB.init({
        appId      : '{your-app-id}',
        xfbml      : true,
        version    : 'v2.5'
      });

      // Get Embedded Video Player API Instance
      var my_video_player;
      FB.Event.subscribe('xfbml.ready', function(msg) {
        if (msg.type === 'video') {
          my_video_player = msg.instance;
        }
      });
    };

    (function(d, s, id){
       var js, fjs = d.getElementsByTagName(s)[0];
       if (d.getElementById(id)) {return;}
       js = d.createElement(s); js.id = id;
       js.src = "//connect.facebook.net/en_US/sdk.js";
       fjs.parentNode.insertBefore(js, fjs);
     }(document, 'script', 'facebook-jssdk'));
  </script>

  <!-- Your embedded video player code -->
  <div
    class="fb-video"
    data-href="https://www.facebook.com/facebook/videos/10153231379946729/"
    data-width="500"
    data-allowfullscreen="true"></div>

</body>
</html>
</code>```

Assuming that you put this code in your webview, it will normally work like a charm.

Body:
Did you already double check dev facebook docs embedded-video-player/api, where you can find this following full code example:

<html>
<head>
  <title>Your Website Title</title>
</head>
<body>

  <!-- Load Facebook SDK for JavaScript -->
  <div id="fb-root"></div>
  <script>
    window.fbAsyncInit = function() {
      FB.init({
        appId      : '{your-app-id}',
        xfbml      : true,
        version    : 'v2.5'
      });

      // Get Embedded Video Player API Instance
      var my_video_player;
      FB.Event.subscribe('xfbml.ready', function(msg) {
        if (msg.type === 'video') {
          my_video_player = msg.instance;
        }
      });
    };

    (function(d, s, id){
       var js, fjs = d.getElementsByTagName(s)[0];
       if (d.getElementById(id)) {return;}
       js = d.createElement(s); js.id = id;
       js.src = "//connect.facebook.net/en_US/sdk.js";
       fjs.parentNode.insertBefore(js, fjs);
     }(document, 'script', 'facebook-jssdk'));
  </script>

  <!-- Your embedded video player code -->
  <div
    class="fb-video"
    data-href="https://www.facebook.com/facebook/videos/10153231379946729/"
    data-width="500"
    data-allowfullscreen="true"></div>

</body>
</html>

Assuming that you put this code in your webview, it will normally work like a charm.


问:
Print more than one result in SQL Data Reader
I have a Stored Procedure that will return more than 1 value from a table. However, I'm only able to print 1 result, can someone please tell me what am I doing wrong

vb.net Code

```<code>reader = cmd_loadMacro.ExecuteReader()
        reader.Read()
        MacroKey = reader.GetString(0)
        MacroValue = reader.GetString(1)
</code>```

My query does return results when i execute it SSMS, I should have 5 rows back, but only 1 row is returned

Latest attempt  (This brings 0 results back)

`reader.Read()

```<code>        If reader.HasRows Then
            While reader.Read()
                MacroKey = reader.GetString(0)
                MacroValue = reader.GetString(1)
            End While
        End If`
</code>```

答:
Remove the If reader.HasRows Then bit that surrounds your loop and try it again.

I've had problems with reader.HasRows in the past returning unexpected results.

Body:
I have a Stored Procedure that will return more than 1 value from a table. However, I'm only able to print 1 result, can someone please tell me what am I doing wrong

vb.net Code

reader = cmd_loadMacro.ExecuteReader()
        reader.Read()
        MacroKey = reader.GetString(0)
        MacroValue = reader.GetString(1)

My query does return results when i execute it SSMS, I should have 5 rows back, but only 1 row is returned

Latest attempt  (This brings 0 results back)

`reader.Read()

        If reader.HasRows Then
            While reader.Read()
                MacroKey = reader.GetString(0)
                MacroValue = reader.GetString(1)
            End While
        End If`


问:
how to open screen on full screen
how i can open my asp.net program on full screen (like i press F11)

Through C# code ?

thanks

答:
I think OP is talking about asp.net application so the "program" here  is browser.

If it is true, you need client-side javascript to do that. something like this:

```<code><script language="JavaScript1.2">
top.window.moveTo(0,0);
if (document.all)
    { top.window.resizeTo(screen.availWidth,screen.availHeight); }
else if (document.layers || document.getElementById) {
    if (top.window.outerHeight < screen.availHeight || top.window.outerWidth < screen.availWidth)
    {
        top.window.outerHeight = top.screen.availHeight;
            top.window.outerWidth = top.screen.availWidth;
    }
 }
</script>
</code>```

document.all works for Internet Explorer while document.layers works for Other browsers.

top refers to the window that is on top of all other windows in the window object hierarchy.

top.window.moveTo(0,0) will display the top window at these coordinates ie. the upper left corner of the screen.

resizeTo(x,y) will resize the window to the size specified.

availWidth and availHeight are properties of the screen object which can detect the available screen space.

Hope this helps...

Title: how to open screen on full screen

Body:
I think OP is talking about asp.net application so the "program" here  is browser.

If it is true, you need client-side javascript to do that. something like this:

<script language="JavaScript1.2">
top.window.moveTo(0,0);
if (document.all)
    { top.window.resizeTo(screen.availWidth,screen.availHeight); }
else if (document.layers || document.getElementById) {
    if (top.window.outerHeight < screen.availHeight || top.window.outerWidth < screen.availWidth)
    {
        top.window.outerHeight = top.screen.availHeight;
            top.window.outerWidth = top.screen.availWidth;
    }
 }
</script>

document.all works for Internet Explorer while document.layers works for Other browsers.

top refers to the window that is on top of all other windows in the window object hierarchy.

top.window.moveTo(0,0) will display the top window at these coordinates ie. the upper left corner of the screen.

resizeTo(x,y) will resize the window to the size specified.

availWidth and availHeight are properties of the screen object which can detect the available screen space.

Hope this helps...