问:
Dictionary size reduces upon increasing one element
I ran this:

```<code>import sys

diii = {'key1':1,'key2':2,'key3':1,'key4':2,'key5':1,'key6':2,'key7':1}
print sys.getsizeof(diii)
# output: 1048

diii = {'key1':1,'key2':2,'key3':1,'key4':2,'key5':1,'key6':2,'key7':1,'key8':2}
print sys.getsizeof(diii)
# output: 664
</code>```

Before asking here, I restarted my python shell and tried it online too and got the same result.

I thought a dictionary with one more element will either give same bytes as output or more, than the one containing one less element.

Any idea what am I doing wrong?

答:
Previous answers have already mentioned that you needn't worry, so I will dive into some more technical details. It's long, but please bear with me.

TLDR: this has to do with arithmetic of resizing. Each resize allocates 2**i memory, where 2**i > requested_size; 2**i >= 8, but then each insert resizes the underlying table further if 2/3 of slots are filled, but this time the new_size = old_size * 4. This way, your first dictionary ends up with 32 cells allocated while the second one with as little as 16 (as it got a bigger initial size upfront).

Answer: As @snakecharmerb noted in the comments this depends on the way that the dictionary is created. For the sake of brevity, let me refer you to this, excellent blog post which explains the differences between the dict() constructor and the dict literal {} on both Python bytecode and CPython implementation levels.

Let's start with the magic number of 8 keys. It turns out to be a constant, predefined for Python's 2.7 implementation in dictobject.h headers file
 - the minimal size of the Python dictionary:

```<code>/* PyDict_MINSIZE is the minimum size of a dictionary.  This many slots are
 * allocated directly in the dict object (in the ma_smalltable member).
 * It must be a power of 2, and at least 4.  8 allows dicts with no more
 * than 5 active entries to live in ma_smalltable (and so avoid an
 * additional malloc); instrumentation suggested this suffices for the
 * majority of dicts (consisting mostly of usually-small instance dicts and
 * usually-small dicts created to pass keyword arguments).
 */
#define PyDict_MINSIZE 8
</code>```

As such, it may differ between the specific Python implementations, but let's assume that we all use the same CPython version. However, the dict of size 8 is expected to neatly contain only 5 elements; don't worry about this, as this specific optimization is not as important for us as it seems.

Now, when you create the dictionary using the dict literal {}, CPython takes a shortcut (as compared to the explicit creation when calling dict constructor). Simplifying a bit the bytecode operation BUILD_MAP gets resolved and it results in calling the _PyDict_NewPresized function which will construct a dictionary for which we already know the size upfront:

```<code>/* Create a new dictionary pre-sized to hold an estimated number of elements.
   Underestimates are okay because the dictionary will resize as necessary.
   Overestimates just mean the dictionary will be more sparse than usual.
*/

PyObject *
_PyDict_NewPresized(Py_ssize_t minused)
{
    PyObject *op = PyDict_New();

    if (minused>5 && op != NULL && dictresize((PyDictObject *)op, minused) == -1) {
        Py_DECREF(op);
        return NULL;
    }
    return op;
}
</code>```

This function calls the normal dict constructor (PyDict_New) and requests a resize of the newly created dict - but only if it is expected to hold more than 5 elements. This is due to an optimization which allows Python to speed up some things by holding the data in the pre-allocated "smalltable", without invoking expensive memory allocation and de-allocation functions.

Then, the dictresize will try to determine the minimal size of the new dictionary. It will also use the magic number 8 - as the starting point and iteratively multiply by 2 until it finds the minimal size larger than the requested size. For the first dictionary, this is simply 8, however, for the second one (and all dictionaries created by dict literal with less than 15 keys) it is 16.

Now, in the dictresize function there is a special case for the former, smaller new_size == 8, which is meant to bring forward the aforementioned optimization (using the "small table" to reduce memory manipulation operations). However, because there is no need to resize the newly created dict (e.g. no elements were removed so far thus the table is "clean") nothing really happens.

On the contrary, when the new_size != 8, a usual procedure of reallocating the hash table follows. This ends up with a new table being allocated to store the
"big" dictionary. While this is intuitive (the bigger dict got a bigger table), this does not seem to move us forward to the observed behavior yet - but, please bear with me one more moment.

Once we have the pre-allocated dict, STORE_MAP optcodes tell the interpreter to insert consecutive key-value pairs. This is implemented with dict_set_item_by_hash_or_entry function, which - importantly - resizes the dictionary after each increase in size (i.e. successful insertion) if more than 2/3 of the slots are already used up. The size will increase x4 (in our case, for large dicts only by x2).

So here is what happens when you create the dict with 7 elements:

```<code># note 2/3 = 0.(6)
BUILD_MAP   # initial_size = 8, filled = 0
STORE_MAP   # 'key_1' ratio_filled = 1/8 = 0.125, not resizing
STORE_MAP   # 'key_2' ratio_filled = 2/8 = 0.250, not resizing
STORE_MAP   # 'key_3' ratio_filled = 3/8 = 0.375, not resizing
STORE_MAP   # 'key_4' ratio_filled = 4/8 = 0.500, not resizing
STORE_MAP   # 'key_5' ratio_filled = 5/8 = 0.625, not resizing
STORE_MAP   # 'key_6' ratio_filled = 6/8 = 0.750, RESIZING! new_size = 8*4 = 32
STORE_MAP   # 'key_7' ratio_filled = 7/32 = 0.21875
</code>```

And you end up with a dict having a total size of 32 elements in the hash table.

However, when adding eight elements the initial size will be twice bigger (16), thus we will never resize as the condition ratio_filled > 2/3 will never be satisfied!

And that's why you end up with a smaller table in the second case.

Body:
I ran this:

import sys

diii = {'key1':1,'key2':2,'key3':1,'key4':2,'key5':1,'key6':2,'key7':1}
print sys.getsizeof(diii)
# output: 1048

diii = {'key1':1,'key2':2,'key3':1,'key4':2,'key5':1,'key6':2,'key7':1,'key8':2}
print sys.getsizeof(diii)
# output: 664

Before asking here, I restarted my python shell and tried it online too and got the same result.

I thought a dictionary with one more element will either give same bytes as output or more, than the one containing one less element.

Any idea what am I doing wrong?

Body:
Previous answers have already mentioned that you needn't worry, so I will dive into some more technical details. It's long, but please bear with me.

TLDR: this has to do with arithmetic of resizing. Each resize allocates 2**i memory, where 2**i > requested_size; 2**i >= 8, but then each insert resizes the underlying table further if 2/3 of slots are filled, but this time the new_size = old_size * 4. This way, your first dictionary ends up with 32 cells allocated while the second one with as little as 16 (as it got a bigger initial size upfront).

Answer: As @snakecharmerb noted in the comments this depends on the way that the dictionary is created. For the sake of brevity, let me refer you to this, excellent blog post which explains the differences between the dict() constructor and the dict literal {} on both Python bytecode and CPython implementation levels.

Let's start with the magic number of 8 keys. It turns out to be a constant, predefined for Python's 2.7 implementation in dictobject.h headers file
 - the minimal size of the Python dictionary:

/* PyDict_MINSIZE is the minimum size of a dictionary.  This many slots are
 * allocated directly in the dict object (in the ma_smalltable member).
 * It must be a power of 2, and at least 4.  8 allows dicts with no more
 * than 5 active entries to live in ma_smalltable (and so avoid an
 * additional malloc); instrumentation suggested this suffices for the
 * majority of dicts (consisting mostly of usually-small instance dicts and
 * usually-small dicts created to pass keyword arguments).
 */
#define PyDict_MINSIZE 8

As such, it may differ between the specific Python implementations, but let's assume that we all use the same CPython version. However, the dict of size 8 is expected to neatly contain only 5 elements; don't worry about this, as this specific optimization is not as important for us as it seems.

Now, when you create the dictionary using the dict literal {}, CPython takes a shortcut (as compared to the explicit creation when calling dict constructor). Simplifying a bit the bytecode operation BUILD_MAP gets resolved and it results in calling the _PyDict_NewPresized function which will construct a dictionary for which we already know the size upfront:

/* Create a new dictionary pre-sized to hold an estimated number of elements.
   Underestimates are okay because the dictionary will resize as necessary.
   Overestimates just mean the dictionary will be more sparse than usual.
*/

PyObject *
_PyDict_NewPresized(Py_ssize_t minused)
{
    PyObject *op = PyDict_New();

    if (minused>5 && op != NULL && dictresize((PyDictObject *)op, minused) == -1) {
        Py_DECREF(op);
        return NULL;
    }
    return op;
}

This function calls the normal dict constructor (PyDict_New) and requests a resize of the newly created dict - but only if it is expected to hold more than 5 elements. This is due to an optimization which allows Python to speed up some things by holding the data in the pre-allocated "smalltable", without invoking expensive memory allocation and de-allocation functions.

Then, the dictresize will try to determine the minimal size of the new dictionary. It will also use the magic number 8 - as the starting point and iteratively multiply by 2 until it finds the minimal size larger than the requested size. For the first dictionary, this is simply 8, however, for the second one (and all dictionaries created by dict literal with less than 15 keys) it is 16.

Now, in the dictresize function there is a special case for the former, smaller new_size == 8, which is meant to bring forward the aforementioned optimization (using the "small table" to reduce memory manipulation operations). However, because there is no need to resize the newly created dict (e.g. no elements were removed so far thus the table is "clean") nothing really happens.

On the contrary, when the new_size != 8, a usual procedure of reallocating the hash table follows. This ends up with a new table being allocated to store the
"big" dictionary. While this is intuitive (the bigger dict got a bigger table), this does not seem to move us forward to the observed behavior yet - but, please bear with me one more moment.

Once we have the pre-allocated dict, STORE_MAP optcodes tell the interpreter to insert consecutive key-value pairs. This is implemented with dict_set_item_by_hash_or_entry function, which - importantly - resizes the dictionary after each increase in size (i.e. successful insertion) if more than 2/3 of the slots are already used up. The size will increase x4 (in our case, for large dicts only by x2).

So here is what happens when you create the dict with 7 elements:

# note 2/3 = 0.(6)
BUILD_MAP   # initial_size = 8, filled = 0
STORE_MAP   # 'key_1' ratio_filled = 1/8 = 0.125, not resizing
STORE_MAP   # 'key_2' ratio_filled = 2/8 = 0.250, not resizing
STORE_MAP   # 'key_3' ratio_filled = 3/8 = 0.375, not resizing
STORE_MAP   # 'key_4' ratio_filled = 4/8 = 0.500, not resizing
STORE_MAP   # 'key_5' ratio_filled = 5/8 = 0.625, not resizing
STORE_MAP   # 'key_6' ratio_filled = 6/8 = 0.750, RESIZING! new_size = 8*4 = 32
STORE_MAP   # 'key_7' ratio_filled = 7/32 = 0.21875

And you end up with a dict having a total size of 32 elements in the hash table.

However, when adding eight elements the initial size will be twice bigger (16), thus we will never resize as the condition ratio_filled > 2/3 will never be satisfied!

And that's why you end up with a smaller table in the second case.


来源: stackexchange

问:
How can I get only the first line from a string?
example:

```<code>string str = "Lorem ipsum dolor sit amet,
consetetur sadipscing elitr, sed diam nonumy eirmod tempor
invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.";

string firstline;
</code>```

How can I get just the first line from the string "str" into the string "firstline"?

答:
Single-line solution:

```<code>string firstline = str.Split(new string[] { Environment.NewLine }, 2, StringSplitOptions.RemoveEmptyEntries);
</code>```

Here the second argument (=2) means that after finding the first line, splitting the line further into an array is no longer necessary, therefore it works faster.

ContentLicense: CC BY-SA 4.0

Body:
example:

string str = "Lorem ipsum dolor sit amet,
consetetur sadipscing elitr, sed diam nonumy eirmod tempor
invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.";

string firstline;

How can I get just the first line from the string "str" into the string "firstline"?

Body:
Single-line solution:

string firstline = str.Split(new string[] { Environment.NewLine }, 2, StringSplitOptions.RemoveEmptyEntries);

Here the second argument (=2) means that after finding the first line, splitting the line further into an array is no longer necessary, therefore it works faster.


问:
is it possible to use a piece of code in a GAMS?
It is necessary to use the following piece of code in a GAMS code repeatedly (I copied this piece of code approximately 10 times or more, in different lines of the program),And has made the program very unreadable.

```<code>loop(k,s,
                 if( AG(s,k)=TG(s),

                         TG(s)= (TGT(s,k)+2*TGT(s,k-1)+3*TGT(s,k-2))/3  ; );
);
</code>```

Is there a command or a way to use this piece of code more easily?

Many Thanks!

答:
Set up the repeated code with $onecho $offecho:

```<code>$onecho > %gams.scrdir%myfile.rsp

loop(k,
     loop(s$flag,
             if( AG(s,k)=TG(s),

                     TG(s)= (TGT(s,k)+2*TGT(s,k-1)+3*TGT(s,k-2))/3  ;
                      flag=0;  );
            );
);

$offecho
</code>```

The %gams.scrdir% just saves the file to the scratch directory. (It is then deleted after the run and avoids cluttering up your main directories. You could change this to any path you want.)

To use it in your code:

```<code>$include %gams.scrdir%myfile.rsp
</code>```

Note that $onecho only stores the code in a file; GAMS won’t use the code until you call it with $include.

Body:
It is necessary to use the following piece of code in a GAMS code repeatedly (I copied this piece of code approximately 10 times or more, in different lines of the program),And has made the program very unreadable.

loop(k,s,
                 if( AG(s,k)=TG(s),

                         TG(s)= (TGT(s,k)+2*TGT(s,k-1)+3*TGT(s,k-2))/3  ; );
);

Is there a command or a way to use this piece of code more easily?

Many Thanks!

Body:
Set up the repeated code with $onecho $offecho:

$onecho > %gams.scrdir%myfile.rsp

loop(k,
     loop(s$flag,
             if( AG(s,k)=TG(s),

                     TG(s)= (TGT(s,k)+2*TGT(s,k-1)+3*TGT(s,k-2))/3  ;
                      flag=0;  );
            );
);

$offecho

The %gams.scrdir% just saves the file to the scratch directory. (It is then deleted after the run and avoids cluttering up your main directories. You could change this to any path you want.)

To use it in your code:

$include %gams.scrdir%myfile.rsp

Note that $onecho only stores the code in a file; GAMS won’t use the code until you call it with $include.


问:
How to extract arguments using regex?
I want to extract arguments (type of command-line arguments) using regex.
Here i will take the string as input and and get the arguments as groups

Basically i want the set in regex to both exclude and include some characters.

import re

ppatt=r"( --(?P<param>([^( --)]*)))"
a=[x.group("param") for x in re.finditer(ppatt,"command --m=psrmcc;ld -  --kkk gtodf --klfj")]
print(a)
```

<p>I want the output to be</p>

```['m=psrmcc;ld - ', 'kkk gtodf', 'klfj']
```

<p>but the output is</p>

```['m=psrmcc;ld', 'kkk', 'klfj']
```

答:
You can use re.split

Ex:

```<code>import re

print(re.split(r"--", "command --m=psrmcc;ld -  --kkk gtodf --klfj")[1:])
#or
print("command --m=psrmcc;ld -  --kkk gtodf --klfj".split("--")[1:])
</code>```

Output:

```<code>['m=psrmcc;ld -  ', 'kkk gtodf ', 'klfj']
</code>```

Title: How to extract arguments using regex?

Body:
I want to extract arguments (type of command-line arguments) using regex.
Here i will take the string as input and and get the arguments as groups

Basically i want the set in regex to both exclude and include some characters.

import re

ppatt=r"( --(?P<param>([^( --)]*)))"
a=[x.group("param") for x in re.finditer(ppatt,"command --m=psrmcc;ld -  --kkk gtodf --klfj")]
print(a)

I want the output to be

['m=psrmcc;ld - ', 'kkk gtodf', 'klfj']

but the output is

['m=psrmcc;ld', 'kkk', 'klfj']

Body:
You can use re.split

Ex:

import re

print(re.split(r"--", "command --m=psrmcc;ld -  --kkk gtodf --klfj")[1:])
#or
print("command --m=psrmcc;ld -  --kkk gtodf --klfj".split("--")[1:])

Output:

['m=psrmcc;ld -  ', 'kkk gtodf ', 'klfj']


问:
Passing value from PHP script to Python script
I looked at the other questions similar to this one, but can't figure this out still.

I have a basic php file that does this:

```<code>
?php
$item='example';
$tmp = exec("python testscriptphp.py .$item");
echo $tmp;
?
</code>```

While succesfully calls python that I have running on my webhostserver.  Now in my python script i want something like this:

```<code>
item=$item
print item
</code>```

Basically I'm asking how to pass variables from PHP to a python script and then back to php if necessary.

Thanks!

答:
write a php file example index.php:

```<code><?PHP
$sym = $_POST['symbols'];
echo shell_exec("python test.py .$sym");
?>
</code>```

$sym is a parameter we passining to test.py python file.
then create a python example test.py:

```<code>import sys
print(sys.argv[1])
</code>```

I hope it help you.

ContentLicense: CC BY-SA 2.5

Body:
I looked at the other questions similar to this one, but can't figure this out still.

I have a basic php file that does this:

?php
$item='example';
$tmp = exec("python testscriptphp.py .$item");
echo $tmp;
?

While succesfully calls python that I have running on my webhostserver.  Now in my python script i want something like this:

item=$item
print item

Basically I'm asking how to pass variables from PHP to a python script and then back to php if necessary.

Thanks!

Body:
write a php file example index.php:

<?PHP
$sym = $_POST['symbols'];
echo shell_exec("python test.py .$sym");
?>

$sym is a parameter we passining to test.py python file.
then create a python example test.py:

import sys
print(sys.argv[1])

I hope it help you.


问:
how to get which webservice is calling a method
I have a webservice 'mywebservice' and a web method 'mywebmethod' defined in it.
This web method calls a function 'callme()' which is defined in another class.
I want to get the service name which is calling this function and also the methodname. I want this in 'callme()' function.

--'mywebservice.asmx.cs'

```<code>[WebMethod]
public void mywebmethod
{
     callme();
}
</code>```

-- 'class1.cs'

```<code>public void callme()
{
     // --- I want service name(mywebservice) & methodname(mywebmethod) here.
}
</code>```

答:
One possible way could be to use StackTrace class (see example section to get started) to walk back to call stack to get type name & method name - this will give you the names for class/method implementing the service.

Mind you that stack trace construction is an expensive operation - as such, I would recommend to pass necessary information as parameters to the method. Further, if you could state why you need this information (service & method name), you may get an better answer to solve your actual problem.

ContentLicense: CC BY-SA 3.0

Body:
I have a webservice 'mywebservice' and a web method 'mywebmethod' defined in it.
This web method calls a function 'callme()' which is defined in another class.
I want to get the service name which is calling this function and also the methodname. I want this in 'callme()' function.

--'mywebservice.asmx.cs'

[WebMethod]
public void mywebmethod
{
     callme();
}

-- 'class1.cs'

public void callme()
{
     // --- I want service name(mywebservice) & methodname(mywebmethod) here.
}


问:
Image have margin from top in constraintlayout
I have a scrolled content, so I put a constraint layout inside a scrollview, I have a problem when put an image inside a constraint layout, but the image show a space from top such as in screenshot below, how can I remove that space?

```<code><?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

    <android.support.constraint.ConstraintLayout
            android:id="@+id/constraintLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
        <!-- have whatever children you want inside -->
        <ImageView
                app:srcCompat="@drawable/main_header"
                android:id="@+id/img_icon"
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:background="#ffccbb"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintWidth_percent="1"
                android:contentDescription="TODO" app:layout_constraintDimensionRatio="1:1"
                app:layout_constraintHorizontal_bias="0.0" app:layout_constraintVertical_bias="0.0"/>
    </android.support.constraint.ConstraintLayout>
</ScrollView>
</code>```

答: In your Imageview you have added app:layout_constraintDimensionRatio="1:1" that means it will take space 1:1, so width and height also will be 1:1. But your image app:srcCompat="@drawable/main_header" is not 1:1. So you have to add an image which has width and height of the same size. Otherwise, you can add           android:scaleType="fitXY" or android:scaleType="centerCrop" according to your expectation.

Body:
I have a scrolled content, so I put a constraint layout inside a scrollview, I have a problem when put an image inside a constraint layout, but the image show a space from top such as in screenshot below, how can I remove that space?

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

    <android.support.constraint.ConstraintLayout
            android:id="@+id/constraintLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

        <ImageView
                app:srcCompat="@drawable/main_header"
                android:id="@+id/img_icon"
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:background="#ffccbb"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintWidth_percent="1"
                android:contentDescription="TODO" app:layout_constraintDimensionRatio="1:1"
                app:layout_constraintHorizontal_bias="0.0" app:layout_constraintVertical_bias="0.0"/>
    </android.support.constraint.ConstraintLayout>
</ScrollView>


问:
Calculating polygon area with R geosphere package
I'm having trouble with the areaPolygon function in R.  Sometimes it appears to produce the correct result, and sometimes the results seem orders of magnitude off.

E.g. I have a polygon with these points:

```<code>lng <- c(-51.74768, -51.74768, -51.74735, -51.74735)
lat <- c(-0.1838690, -0.1840993, -0.1840984, -0.1838682)
</code>```

and combine them into a dataframe

```<code>data <- data.frame(lng, lat)
</code>```

Then I try to get the area:

```<code>area <- geosphere::areaPolygon(x = data)
</code>```

which comes out to 326928.8 m^2.

I was expecting something more in the 1000 m^2 range.

What's weird is that this seems to work fairly well for about half the cells I'm calculating, but not the other half.

A similar StackOverflow question noted strangely small values, due to the points being in an incorrect order.  However, when I plot, e.g.

```<code>plot(data, type="l")
</code>```

The polygon seems to be drawing correctly.

Anyone know what might be wrong here? Thanks!

答:
With your example data, result is as expected, as noted in the comments.

```<code>library(geosphere)
lng <- c(-51.74768, -51.74768, -51.74735, -51.74735)
lat <- c(-0.1838690, -0.1840993, -0.1840984, -0.1838682)
d <- cbind(lng, lat)
geosphere::areaPolygon(d)
#[1] 935.2693
</code>```

The idea that rounding plays a role seems far-fetched.

Body:
I'm having trouble with the areaPolygon function in R.  Sometimes it appears to produce the correct result, and sometimes the results seem orders of magnitude off.

E.g. I have a polygon with these points:

lng <- c(-51.74768, -51.74768, -51.74735, -51.74735)
lat <- c(-0.1838690, -0.1840993, -0.1840984, -0.1838682)

and combine them into a dataframe

data <- data.frame(lng, lat)

Then I try to get the area:

area <- geosphere::areaPolygon(x = data)

which comes out to 326928.8 m^2.

I was expecting something more in the 1000 m^2 range.

What's weird is that this seems to work fairly well for about half the cells I'm calculating, but not the other half.

A similar StackOverflow question noted strangely small values, due to the points being in an incorrect order.  However, when I plot, e.g.

plot(data, type="l")

The polygon seems to be drawing correctly.

Anyone know what might be wrong here? Thanks!

Body:
With your example data, result is as expected, as noted in the comments.

library(geosphere)
lng <- c(-51.74768, -51.74768, -51.74735, -51.74735)
lat <- c(-0.1838690, -0.1840993, -0.1840984, -0.1838682)
d <- cbind(lng, lat)
geosphere::areaPolygon(d)
#[1] 935.2693

The idea that rounding plays a role seems far-fetched.


问:
TextView inside Fragment in ViewPager is null on orientation change
I have a MainActivity inside I create ViewPager withFragments. I am using savedInstanceState to store values to set TextView after orientation changed. I also want to change value e.g. using button in MainActivity. Button works properly, but if I change the orientation then Button cannot set TextView in Fragment because TextView is now null.

MyFragment

public class MyFragment extends Fragment {

    private TextView textView;
    private String info;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.item_weather, container, false);
        textView = view.findViewById(R.id.text_view);
        Bundle bundle = getArguments();
        info = bundle.getString("info");
        setInfo(info);
        return view;

    }

    public void setInfo(String info) {
        this.info = info;
        textView.setText(info); //here is the error
    }
}
```

<p>In <code>MainActivity.java</code> in <code>OnCreate</code></p>

<pre class="lang-java prettyprint-override"><code>myFragment = new MyFragment();
viewPager = findViewById(R.id.viewpager);
viewPager.setOffscreenPageLimit(10);

List<Fragment> fragments = new ArrayList<>();
fragments.add(myFragment);

pagerAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
viewPager.setAdapter(pagerAdapter);
</code>```

MyPagerAdapter looks like this:

public class MyPageAdapter extends FragmentStatePagerAdapter {

    private List<Fragment> fragments;

    public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {
        super(fm);
        this.fragments = fragments;
    }

    @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }

    @Override
    public int getCount() {
        return fragments.size();
    }
}
```

<p>As I said everything works, but after orientation chage if I use Button I got an error:</p>

```java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
```

<p>Any ideas how to solve this?</p>

<p>edit:
full error</p>

```E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.app.myapp, PID: 15400
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at com.example.app.myapp.fragments.myFragment.setInfo(myFragment.java:53)
        at com.example.app.myapp.MainActivity.onOptionsItemSelected(MainActivity.java:195)
        at android.app.Activity.onMenuItemSelected(Activity.java:3543)
        at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:407)
        at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:195)
        at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
        at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
        at android.support.v7.app.ToolbarActionBar$2.onMenuItemClick(ToolbarActionBar.java:63)
        at android.support.v7.widget.Toolbar$1.onMenuItemClick(Toolbar.java:203)
        at android.support.v7.widget.ActionMenuView$MenuBuilderCallback.onMenuItemSelected(ActionMenuView.java:780)
        at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
        at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:171)
        at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:973)
        at android.support.v7.view.menu.MenuPopup.onItemClick(MenuPopup.java:127)
        at android.widget.AdapterView.performItemClick(AdapterView.java:318)
        at android.widget.AbsListView.performItemClick(AbsListView.java:1159)
        at android.widget.AbsListView$PerformClick.run(AbsListView.java:3136)
        at android.widget.AbsListView$3.run(AbsListView.java:4052)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
```

答:
Solution:

Ok, EpicPandaForce thanks for hints.

To solve this i used in MainActivity

```<code>@Override
    protected void onResume() {
        super.onResume();
        viewPager.setAdapter(pagerAdapter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        viewPager.setAdapter(null);
    }
</code>```

Body:
I have a MainActivity inside I create ViewPager withFragments. I am using savedInstanceState to store values to set TextView after orientation changed. I also want to change value e.g. using button in MainActivity. Button works properly, but if I change the orientation then Button cannot set TextView in Fragment because TextView is now null.

MyFragment

public class MyFragment extends Fragment {

    private TextView textView;
    private String info;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.item_weather, container, false);
        textView = view.findViewById(R.id.text_view);
        Bundle bundle = getArguments();
        info = bundle.getString("info");
        setInfo(info);
        return view;

    }

    public void setInfo(String info) {
        this.info = info;
        textView.setText(info); //here is the error
    }
}

In MainActivity.java in OnCreate

myFragment = new MyFragment();
viewPager = findViewById(R.id.viewpager);
viewPager.setOffscreenPageLimit(10);

List<Fragment> fragments = new ArrayList<>();
fragments.add(myFragment);

pagerAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
viewPager.setAdapter(pagerAdapter);

MyPagerAdapter looks like this:

public class MyPageAdapter extends FragmentStatePagerAdapter {

    private List<Fragment> fragments;

    public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {
        super(fm);
        this.fragments = fragments;
    }

    @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }

    @Override
    public int getCount() {
        return fragments.size();
    }
}

As I said everything works, but after orientation chage if I use Button I got an error:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

Any ideas how to solve this?

edit:
full error

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.app.myapp, PID: 15400
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at com.example.app.myapp.fragments.myFragment.setInfo(myFragment.java:53)
        at com.example.app.myapp.MainActivity.onOptionsItemSelected(MainActivity.java:195)
        at android.app.Activity.onMenuItemSelected(Activity.java:3543)
        at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:407)
        at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:195)
        at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
        at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
        at android.support.v7.app.ToolbarActionBar$2.onMenuItemClick(ToolbarActionBar.java:63)
        at android.support.v7.widget.Toolbar$1.onMenuItemClick(Toolbar.java:203)
        at android.support.v7.widget.ActionMenuView$MenuBuilderCallback.onMenuItemSelected(ActionMenuView.java:780)
        at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
        at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:171)
        at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:973)
        at android.support.v7.view.menu.MenuPopup.onItemClick(MenuPopup.java:127)
        at android.widget.AdapterView.performItemClick(AdapterView.java:318)
        at android.widget.AbsListView.performItemClick(AbsListView.java:1159)
        at android.widget.AbsListView$PerformClick.run(AbsListView.java:3136)
        at android.widget.AbsListView$3.run(AbsListView.java:4052)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

Body:
Solution:

Ok, EpicPandaForce thanks for hints.

To solve this i used in MainActivity

@Override
    protected void onResume() {
        super.onResume();
        viewPager.setAdapter(pagerAdapter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        viewPager.setAdapter(null);
    }


问:
Cant change the port for jetty
I am running googleappengine on SpringBoot, I want to change the port number from 8080. In springboot docs, you make the change in application.yml

```<code>server:
  port: 8090,
</code>```

or application.properties server.port=8090.

For springboot tomcat, this works, but not for springboot jetty, googleappengine.

答:
Actually the above property should have worked irrespective of the server.

Give a try with below method (Spring boot 2.0).

```<code>@Bean
public ConfigurableServletWebServerFactory webServerFactory()
{
    JettyServletWebServerFactory factory = new JettyServletWebServerFactory();
    factory.setPort(9000);
    factory.setContextPath("/myapp");
    factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notfound.html"));
    return factory;
}
</code>```

Refer configure jetty server spring boot

Title: Cant change the port for jetty

Body:
I am running googleappengine on SpringBoot, I want to change the port number from 8080. In springboot docs, you make the change in application.yml

server:
  port: 8090,

or application.properties server.port=8090.

For springboot tomcat, this works, but not for springboot jetty, googleappengine.

Body:
Actually the above property should have worked irrespective of the server.

Give a try with below method (Spring boot 2.0).

@Bean
public ConfigurableServletWebServerFactory webServerFactory()
{
    JettyServletWebServerFactory factory = new JettyServletWebServerFactory();
    factory.setPort(9000);
    factory.setContextPath("/myapp");
    factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notfound.html"));
    return factory;
}

Refer configure jetty server spring boot


问:
Python app to make a random prime number between 10^300 and 10^301
i need to make Python app to make a random prime number between 10^300 and 10^301 , i done it with this but its very slow. any solution?

```<code>
import random , math
check_prime = 0</p>

<p>print "Please wait ..."
def is_prime(n):
    import math
    n = abs(n)
    i = 2
    while i <= math.sqrt(n):
        if n % i == 0:
            return False
        i += 1<br>
    return True</p>

<p>while check_prime == 0 :
    randomnumber = random.randrange(math.pow(10,300),math.pow(10,301)-1)
    if is_prime(randomnumber):
        print randomnumber
        break
```

答: Take a look at Miller-Rabin test I am sure you will find some implementations in Python on the internet.</p>

Body:
i need to make Python app to make a random prime number between 10^300 and 10^301 , i done it with this but its very slow. any solution?

import random , math
check_prime = 0

print "Please wait ..."
def is_prime(n):
    import math
    n = abs(n)
    i = 2
    while i <= math.sqrt(n):
        if n % i == 0:
            return False
        i += 1

    return True

while check_prime == 0 :
    randomnumber = random.randrange(math.pow(10,300),math.pow(10,301)-1)
    if is_prime(randomnumber):
        print randomnumber
        break


问:
Why is `operator[]' needed when 'operator double*` seems to do the job
operator[] seems superfluous since operator double* seems to be enough.

Here is my code:

struct CStandardData
{
  inline operator double* () { return m_standardData; }
  //inline double& operator [] (size_t ix) { return m_standardData[ix]; }
  size_t  m_standardDataRefCnt{ 0 };
  double m_standardData[1];
} sd;
```

I use sd in all kinds of different situations including double *a = sd, sd[x] = 5.0, sd[x] >= sd[y], etc.  and regardless whether I have the operator [] commented out or defined, the code seems to work correctly.

In what situations would it be necessary to have operator []?

I probably should have added a bit of context:

I used the internal data double sd[], which was dynamically allocated, throughout a large base of code >5000 lines.  Then I needed to add allocation reference counting to this double array, because of a need to copy the object it was in, and pass a copy to the user (the double sd[] is >10000 elements so I did not want extra copies made).  This is the scheme that I devised to do that without having to modify the vast base of code using it, but was not sure if omitting operator [] could lead to any problems.

答:
In what situations would it be necessary to have operator []?

In situations when you want your object act as a container but not a pointer. For example this code:

```<code>MyContainer cnt;
if( cnt ) // something
</code>```

will compile if you define operator double *, but I do not want this code to compile in general for my container, because it does not make any sense.

Body:
operator[] seems superfluous since operator double* seems to be enough.

Here is my code:

struct CStandardData
{
  inline operator double* () { return m_standardData; }
  //inline double& operator [] (size_t ix) { return m_standardData[ix]; }
  size_t  m_standardDataRefCnt{ 0 };
  double m_standardData[1];
} sd;

I use sd in all kinds of different situations including double *a = sd, sd[x] = 5.0, sd[x] >= sd[y], etc.  and regardless whether I have the operator [] commented out or defined, the code seems to work correctly.

In what situations would it be necessary to have operator []?

I probably should have added a bit of context:

I used the internal data double sd[], which was dynamically allocated, throughout a large base of code >5000 lines.  Then I needed to add allocation reference counting to this double array, because of a need to copy the object it was in, and pass a copy to the user (the double sd[] is >10000 elements so I did not want extra copies made).  This is the scheme that I devised to do that without having to modify the vast base of code using it, but was not sure if omitting operator [] could lead to any problems.

Body:
In what situations would it be necessary to have operator []?

In situations when you want your object act as a container but not a pointer. For example this code:

MyContainer cnt;
if( cnt ) // something

will compile if you define operator double *, but I do not want this code to compile in general for my container, because it does not make any sense.


问:
How to get id from database that's equal DataGridView1 selected row id cell value in c#
How to get id from database that's equal DataGridView1 selected row id cell value in c#?

I have this code in vb.net, and now I have to convert it to c#.

my code

```<code>DataGridView1.Item(0, DataGridView1.CurrentRow.Index).Value
</code>```

答:
Although it's a duplicate from Getting the first cell from selected row from DataGridView in C#

getting the first cell value from selected row would be:

```<code>dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
</code>```

Body:
How to get id from database that's equal DataGridView1 selected row id cell value in c#?

I have this code in vb.net, and now I have to convert it to c#.

my code

DataGridView1.Item(0, DataGridView1.CurrentRow.Index).Value

Body:
Although it's a duplicate from Getting the first cell from selected row from DataGridView in C#

getting the first cell value from selected row would be:

dataGridView1.SelectedRows[0].Cells[0].Value.ToString();


问:
Scanf allows storing a bigger number of characters in an static array
In the code below, as you can see, the length of my array is 10. When I use scanf to read some characters into the array, it allow me to surpass that number. Why is it possible?

I already tried with strings of smaller sizes and I see what I expected: an error about "stack smashing detected".

```<code>#include<stdio.h>
int main()
{
    char nome[10];
    printf("Nome:   ");
    scanf("%s", nome);
    printf("\n\n%s\n", nome);
    return 0;
}
</code>```

答:
A precondition for the %s format specifier of scanf is that the destination array must have enough space, as you point out.

However, the fact that it may work by chance when you slightly surpass that number does not mean it will always works. It is undefined behavior.

In particular, what is most likely happening here is that you are not triggering the stack smashing detector when you only overwrite a few extra characters.

Body:
In the code below, as you can see, the length of my array is 10. When I use scanf to read some characters into the array, it allow me to surpass that number. Why is it possible?

I already tried with strings of smaller sizes and I see what I expected: an error about "stack smashing detected".

#include<stdio.h>
int main()
{
    char nome[10];
    printf("Nome:   ");
    scanf("%s", nome);
    printf("\n\n%s\n", nome);
    return 0;
}


问:
Format Repeating Decimal as a Fraction
I need to convert decimal values to their fractional equivalents, similar to this previous question.

I'm using the code posted in one of the answers as a starting point since it mostly does what I need it to do.

```<code>string ToMixedFraction(decimal x) {
int whole = (int) x;
int denominator = 64;
int numerator = (int)( (x - whole) * denominator );

if (numerator == 0)
{
    return whole.ToString();
}
while ( numerator % 2 == 0 ) // simplify fraction
{
    numerator /= 2;
    denominator /=2;
}
return string.Format("{0} {1}/{2}", whole, numerator, denominator);
}
</code>```

As I said, this code works fine for the most part, but I need to take common repeating decimal values (.3333333) and display that to the user as 1/3.

Does anyone happen to know how this might be possible to do?

答:
From Link

Take the number of digits in the repeating part as the numerator, take 9 repeating with the same number of digits and reduce the fraction.

E.g., .3 repeating is the same as 3/9. Reduce by dividing both sides by the gcd (3 in this case) and you get 1/3.

You'll need to do some extra math if you can extract a repeating decimal from a terminating decimal, e.g. .133333333.

OwnerDisplayName: Tim Lentine

Title: Format Repeating Decimal as a Fraction

Body:
I need to convert decimal values to their fractional equivalents, similar to this previous question.

I'm using the code posted in one of the answers as a starting point since it mostly does what I need it to do.

string ToMixedFraction(decimal x) {
int whole = (int) x;
int denominator = 64;
int numerator = (int)( (x - whole) * denominator );

if (numerator == 0)
{
    return whole.ToString();
}
while ( numerator % 2 == 0 ) // simplify fraction
{
    numerator /= 2;
    denominator /=2;
}
return string.Format("{0} {1}/{2}", whole, numerator, denominator);
}

As I said, this code works fine for the most part, but I need to take common repeating decimal values (.3333333) and display that to the user as 1/3.

Does anyone happen to know how this might be possible to do?

OwnerDisplayName: MSN


问:
Security for ASP.NET application
I am developing a .net based application which is for a financial institution and it has multiple roles so I am not using built in ROLE PROVIDER.

Now what i want is that when create user i just assign role and when user logs in with the assigned role he/she cannot open any form on which he/she has no rights.

How to come up with a role based security system for my application ? I would appreciate if someone can help me and guide me to come up with a strong and secure application.

Thanks

答:
If the links posted in the other answer are too many to start with, try reading that article from MS:
http://msdn.microsoft.com/en-us/magazine/cc301390.aspx</p>

Title: Security for ASP.NET application


问:
What should be the output of the custom loss function in Keras?
I am trying to build a custom loss function in Keras, but I am confused about the way it works. I am training the network on batches, and I am not sure if the output of the loss function should be an array with the same dimension as the batch or just a scalar.</p>

答:
The loss usually reduced over all dimensions of the mini-batch. If you don't apply reduction it would be performed implicitly (try removing tf.reduce_mean in custom_loss_function() and return just res). For example:

import tensorflow as tf
import numpy as np

def custom_cross_entropy(y_true, y_pred):
    res = -y_true*tf.math.log(tf.nn.softmax(y_pred))
    return tf.reduce_mean(res, axis=None)

model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Dense(2, activation=None))

model.compile(optimizer=tf.keras.optimizers.SGD(0.01),
              loss=[custom_cross_entropy],
              metrics=['accuracy'])

y_train = np.array([[1, 0], [0, 1]])
x_train = np.random.normal(size=(2, 2))

model.fit(x_train, y_train, epochs=2)

# Epoch 1/2
# 2/2 [==============================] - 0s 13ms/sample - loss: 0.2689 - accuracy: 1.0000
# Epoch 2/2
# 2/2 [==============================] - 0s 2ms/sample - loss: 0.2686 - accuracy: 1.0000
```


问:
How to extract numbers from a string and add to an array?
I want to convert this string:

```<code><5> 20825.24 </ 5> <7> 0.0 </ 7> <8> 0.0 </ 8>
</code>```

to an array with key value

I would really appreciate the help

I tried different xmlParse strategies but it is not exactly an xml.

```<code>$xml = new \SimpleXMLElement("<5>20825.24</5><7>0.0</ 7><8>0.0</8>");
</code>```

Response: String could not be parsed as XML

I expect an array like this:

```<code>[5=>20825.24,7=>0.0,8=>0.0]
</code>```

答:
```<code><?php

$subject = '<5> 20825.24 <7> 0.0 <8> 0.0';
$pattern = '/\<(\d)\>\s+(\d+\.\d+)/u';
$result = preg_match_all($pattern,$subject,$output);

$numbers = $output[1];
$output = $output[2];
$outTotal = [];

foreach ($numbers as $key => $number) {
    $outTotal[$number] = $output[$key];
}
var_dump($outTotal);
</code>```

gives:

```<code>array(3) {
  [5]=>
  string(8) "20825.24"
  [7]=>
  string(3) "0.0"
  [8]=>
  string(3) "0.0"
}
</code>```

Body:
I want to convert this string:

<5> 20825.24 </ 5> <7> 0.0 </ 7> <8> 0.0 </ 8>

to an array with key value

I would really appreciate the help

I tried different xmlParse strategies but it is not exactly an xml.

$xml = new \SimpleXMLElement("<5>20825.24</5><7>0.0</ 7><8>0.0</8>");

Response: String could not be parsed as XML

I expect an array like this:

[5=>20825.24,7=>0.0,8=>0.0]

Body:
<?php

$subject = '<5> 20825.24 <7> 0.0 <8> 0.0';
$pattern = '/\<(\d)\>\s+(\d+\.\d+)/u';
$result = preg_match_all($pattern,$subject,$output);

$numbers = $output[1];
$output = $output[2];
$outTotal = [];

foreach ($numbers as $key => $number) {
    $outTotal[$number] = $output[$key];
}
var_dump($outTotal);

gives:

array(3) {
  [5]=>
  string(8) "20825.24"
  [7]=>
  string(3) "0.0"
  [8]=>
  string(3) "0.0"
}


问:
Why can't I create a multidimensional array of arrays?
My program involves a 2-dimensional board: Square[width,height]. Each Square contains a collection of Pieces.

In the presentation layer, I want to only present the collection of Pieces in each Square and represent each Piece with its string Name. I.e. string[][width,height].

Declaring string[][,] compiles with no problem but I can't initialize the variable:

```<code>string[][,] multiArrayOfArrays; //No problemo
multiArrayOfArrays = new string[][8,8]; //Generates errors
</code>```

The following errors are generated for the second line:

```<code>CS1586  Array creation must have array size or array initializer
CS0178  Invalid rank specifier: expected ',' or ']' ModChess
CS0178  Invalid rank specifier: expected ',' or ']' ModChess
</code>```

I'm currently using List<string>[,] as a workaround but the errors vex me. Why can I successfully declare a string[][,] but not initialize it?
Note: Using VS Community 16.0.4, C# 7.3.

答:
Probably you want a string[,][] a.

```<code>string[,][] a = new string[3, 4][];
a[0, 0] = new string[10];
a[0, 1] = new string[4];
a[1, 0] = new string[6];
string s = a[0, 0][2];
</code>```

You have a special case of a jagged array, where the first array is 2-dimensional. It contains one-dimensional arrays of different sizes as elements.

The ordering of the array brackets might seem wrong, as the element type is usually on the left side of the brackets; however, if you think about on how you want to access elements, then it makes sense. First, you want to specify the 2 coordinates of the 2-dimensional board, then the single index of the pieces collection.

According to Jagged Arrays (C# Programming Guide), int[][,] jaggedArray4 = new int[3][,] "...  is a declaration and initialization of a single-dimensional jagged array that contains three two-dimensional array elements of different sizes."

Body:
My program involves a 2-dimensional board: Square[width,height]. Each Square contains a collection of Pieces.

In the presentation layer, I want to only present the collection of Pieces in each Square and represent each Piece with its string Name. I.e. string[][width,height].

Declaring string[][,] compiles with no problem but I can't initialize the variable:

string[][,] multiArrayOfArrays; //No problemo
multiArrayOfArrays = new string[][8,8]; //Generates errors

The following errors are generated for the second line:

CS1586  Array creation must have array size or array initializer
CS0178  Invalid rank specifier: expected ',' or ']' ModChess
CS0178  Invalid rank specifier: expected ',' or ']' ModChess

I'm currently using List<string>[,] as a workaround but the errors vex me. Why can I successfully declare a string[][,] but not initialize it?
Note: Using VS Community 16.0.4, C# 7.3.

Body:
Probably you want a string[,][] a.

string[,][] a = new string[3, 4][];
a[0, 0] = new string[10];
a[0, 1] = new string[4];
a[1, 0] = new string[6];
string s = a[0, 0][2];

You have a special case of a jagged array, where the first array is 2-dimensional. It contains one-dimensional arrays of different sizes as elements.

The ordering of the array brackets might seem wrong, as the element type is usually on the left side of the brackets; however, if you think about on how you want to access elements, then it makes sense. First, you want to specify the 2 coordinates of the 2-dimensional board, then the single index of the pieces collection.

According to Jagged Arrays (C# Programming Guide), int[][,] jaggedArray4 = new int[3][,] "...  is a declaration and initialization of a single-dimensional jagged array that contains three two-dimensional array elements of different sizes."


问:
Xaml - how to use ImageSource from ViewModel
I have an ObservableCollection<Item> and an Item contains both a file path and an ImageSource of some image from the disk.

public ObservableCollection<Item> Items { get; set; } = new ObservableCollection<MediaListItem>();
```

<pre class="lang-cs prettyprint-override"><code>public class Item
{
    public string Image { get; set; } // Full path to the image
    public ImageSource ImageSource { get; set; }
}
</code>```

However, I am unable to access any of the two attributes and display an image via XAML.

<ListView ItemsSource="{Binding MediaList}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout Padding="10">
                    <Image Source="{Binding ImageSource}" VerticalOptions="Fill"></Image>
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
```

Now I am confused because I am able to output the string Image via XAML through a label, but can't display an image from the path at all.

答:
You can use  ImageSource.FromFile() or ImageSource.FromUri()  like this

In Xaml

```<code><Image  Source="{Binding  ImageSource}"  Aspect="AspectFit"  ></Image>
</code>```

In Code

```<code>public ObservableCollection<Item> MediaList { get; set; } = new ObservableCollection<Item>()
        {
            new Item
            {
                ImageSource = ImageSource.FromFile("xamarin.png")
            },
            new Item
            {
                ImageSource = ImageSource.FromUri(new Uri("https://i.stack.imgur.com/4mMod.png"))
            }
        };
</code>```

The result

Update

Depending on Microsoft-Local Images

Image files can be added to each application project and referenced from Xamarin.Forms shared code...

To use a single image across all apps, the same filename must be used on every platform, and it should be a valid Android resource name (ie. only lowercase letters, numerals, the underscore, and the period are allowed).

For more information take a look at the answer here

Now if you want to display an image without adding it to each platform, you should use Converter.

For example:

Create a new folder called ImagesFolder in  shared code then add the image to it

In Code, create a new class called ByteArrayToImageSourceConverter like this

```<code>public class ByteArrayToImageSourceConverter : IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
    byte[] bytes;
    var assembly = GetType().GetTypeInfo().Assembly; // using System.Reflection;

    var stream = assembly.GetManifestResourceStream((string)value); // value = "App1.ImagesFolder.ninja.png"
    using (var ms = new MemoryStream()) // using System.IO;
    {
        stream.CopyToAsync(ms);
        bytes = ms.ToArray();
    }
    return ImageSource.FromStream(() => new MemoryStream(bytes));
  }
  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  {
    return null;
  }
}
</code>```

View Model

```<code>public ObservableCollection<Item> MediaList { get; set; } = new ObservableCollection<Item>()
{
    new Item
    {
       Image  = "App1.ImagesFolder.ninja.png"
    }
};
</code>```

In Xaml

```<code><ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
     xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
     xmlns:local="clr-namespace:App1"
     x:Class="App1.MainPage">

  <ContentPage.Resources>
    <ResourceDictionary>
       <local:ByteArrayToImageSourceConverter  x:Key="ByteArrayToImageSourceConverter" />
   </ResourceDictionary>
 </ContentPage.Resources>

 <ListView ItemsSource="{Binding MediaList}" >
    <ListView.ItemTemplate>
      <DataTemplate>
        <ViewCell>
           <Image Source="{Binding Image, Converter={StaticResource ByteArrayToImageSourceConverter}}" />
        </ViewCell>
      </DataTemplate>
   </ListView.ItemTemplate>
 </ListView>

</ContentPage>
</code>```

Related Links

ByteArrayToImageSourceConverter

Shared Resources

How to load binary images in Xamarin?

Body:
I have an ObservableCollection<Item> and an Item contains both a file path and an ImageSource of some image from the disk.

public ObservableCollection<Item> Items { get; set; } = new ObservableCollection<MediaListItem>();

public class Item
{
    public string Image { get; set; } // Full path to the image
    public ImageSource ImageSource { get; set; }
}

However, I am unable to access any of the two attributes and display an image via XAML.

<ListView ItemsSource="{Binding MediaList}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout Padding="10">
                    <Image Source="{Binding ImageSource}" VerticalOptions="Fill"></Image>
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Now I am confused because I am able to output the string Image via XAML through a label, but can't display an image from the path at all.

Body:
You can use  ImageSource.FromFile() or ImageSource.FromUri()  like this

In Xaml

<Image  Source="{Binding  ImageSource}"  Aspect="AspectFit"  ></Image>

In Code

public ObservableCollection<Item> MediaList { get; set; } = new ObservableCollection<Item>()
        {
            new Item
            {
                ImageSource = ImageSource.FromFile("xamarin.png")
            },
            new Item
            {
                ImageSource = ImageSource.FromUri(new Uri("https://i.stack.imgur.com/4mMod.png"))
            }
        };

The result

Update

Depending on Microsoft-Local Images

Image files can be added to each application project and referenced from Xamarin.Forms shared code...

To use a single image across all apps, the same filename must be used on every platform, and it should be a valid Android resource name (ie. only lowercase letters, numerals, the underscore, and the period are allowed).

For more information take a look at the answer here

Now if you want to display an image without adding it to each platform, you should use Converter.

For example:

Create a new folder called ImagesFolder in  shared code then add the image to it

In Code, create a new class called ByteArrayToImageSourceConverter like this

public class ByteArrayToImageSourceConverter : IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
    byte[] bytes;
    var assembly = GetType().GetTypeInfo().Assembly; // using System.Reflection;

    var stream = assembly.GetManifestResourceStream((string)value); // value = "App1.ImagesFolder.ninja.png"
    using (var ms = new MemoryStream()) // using System.IO;
    {
        stream.CopyToAsync(ms);
        bytes = ms.ToArray();
    }
    return ImageSource.FromStream(() => new MemoryStream(bytes));
  }
  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  {
    return null;
  }
}

View Model

public ObservableCollection<Item> MediaList { get; set; } = new ObservableCollection<Item>()
{
    new Item
    {
       Image  = "App1.ImagesFolder.ninja.png"
    }
};

In Xaml

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
     xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
     xmlns:local="clr-namespace:App1"
     x:Class="App1.MainPage">

  <ContentPage.Resources>
    <ResourceDictionary>
       <local:ByteArrayToImageSourceConverter  x:Key="ByteArrayToImageSourceConverter" />
   </ResourceDictionary>
 </ContentPage.Resources>

 <ListView ItemsSource="{Binding MediaList}" >
    <ListView.ItemTemplate>
      <DataTemplate>
        <ViewCell>
           <Image Source="{Binding Image, Converter={StaticResource ByteArrayToImageSourceConverter}}" />
        </ViewCell>
      </DataTemplate>
   </ListView.ItemTemplate>
 </ListView>

</ContentPage>

Related Links

ByteArrayToImageSourceConverter

Shared Resources

How to load binary images in Xamarin?


答:
I just checked your code on my phone and it looks good.
 One thing that I made different from you is that I have used a different image resource for the imageView.

So I think that you don't actually have a problem, I think that it's just the image and how it looks, try to change your image resource and see if this problem remains.

He is how my layout file looks like:

```<code><ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent">

<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/img_icon"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@drawable/main_header"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintDimensionRatio="1:1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>
</code>```

Title: Image have margin from top in constraintlayout

Body:
I have a scrolled content, so I put a constraint layout inside a scrollview, I have a problem when put an image inside a constraint layout, but the image show a space from top such as in screenshot below, how can I remove that space?

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

    <android.support.constraint.ConstraintLayout
            android:id="@+id/constraintLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

        <ImageView
                app:srcCompat="@drawable/main_header"
                android:id="@+id/img_icon"
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:background="#ffccbb"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintWidth_percent="1"
                android:contentDescription="TODO" app:layout_constraintDimensionRatio="1:1"
                app:layout_constraintHorizontal_bias="0.0" app:layout_constraintVertical_bias="0.0"/>
    </android.support.constraint.ConstraintLayout>
</ScrollView>

Body:
I just checked your code on my phone and it looks good.
 One thing that I made different from you is that I have used a different image resource for the imageView.

So I think that you don't actually have a problem, I think that it's just the image and how it looks, try to change your image resource and see if this problem remains.

He is how my layout file looks like:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent">

<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/img_icon"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@drawable/main_header"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintDimensionRatio="1:1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>


问:
Enabling Integer Overflow in Python
I'd like to create a 2D environment in which the top & bottom and left & right are connected  (similar to a Torus or Doughnut). However, rather than doing a check on an object's x/y coordinate every frame, I'd like to simulate it using integer overflow.

While normal iteration (as shown in the sample code below) can be done, it may be slightly more effective (though dangerous) to simply enable overflow on some variables, especially when dealing with hundreds or thousands of objects in each frame/iteration.

I can find some examples which also simulate integer overflow in Python like this. However, I'm looking for something that can overflow just by enabling overflow in certain variables and skipping the checks in general.

```<code># With normal checking of every instance
import random

width = 100
height = 100

class item():
    global width, height

    def __init__(self):
        self.x = random.randint(0, width)
        self.y = random.randint(0, height)

items = [item for _ in range(10)] # create 10 instances

while True:
    for obj in items:
        obj.x += 10
        obj.y += 20
        while obj.x > width:
            obj.x -= width
        while obj.y > height:
            obj.y -= height
        while obj.x < width:
            obj.x += width
        while obj.y < height:
            obj.y += height
</code>```

I'd like to simulate integer overflow for only some certain classes/objects. Is there a way to have some variables automatically overflow and loop back to their min/max values?

答:
With a descriptor you can You can define the behavior you want for your object attributes. Reading between the lines it sounds like you want your attributes to exhibit a value = value % maximum behaviour.

```<code>from weakref import WeakKeyDictionary

class MaxValue:
    '''A descriptor whose value will be: value modulo maximum.'''
    def __init__(self, maximum, default=0):
        self.maximum = maximum
        self.default = default
        self.data = WeakKeyDictionary()

    def __get__(self, instance, owner):
        return self.data.get(instance, self.default)

    def __set__(self, instance, value):
        self.data[instance] = value % self.maximum
</code>```

Descriptors should be class attributes. For your example class:

```<code>import random
width = 100
height = 100

class Item:
##    global width, height
    x = MaxValue(width)
    y = MaxValue(height)

    def __init__(self):
        self.x = random.randint(0, width)
        self.y = random.randint(0, height)
    def __str__(self):
        return f'({self.x:>3},{self.y:>3})'
</code>```

Example:

```<code>items = [Item() for _ in range(5)]
print(','.join(f'{item}' for item in items))
for n in range(15):
    for item in items:
        item.x += 10
        item.y += 20
    print(','.join(f'{item}' for item in items))

>>>
( 74,  6),( 49, 19),( 56, 10),( 72, 16),( 83, 16)
( 84, 26),( 59, 39),( 66, 30),( 82, 36),( 93, 36)
( 94, 46),( 69, 59),( 76, 50),( 92, 56),(  3, 56)
(  4, 66),( 79, 79),( 86, 70),(  2, 76),( 13, 76)
( 14, 86),( 89, 99),( 96, 90),( 12, 96),( 23, 96)
( 24,  6),( 99, 19),(  6, 10),( 22, 16),( 33, 16)
( 34, 26),(  9, 39),( 16, 30),( 32, 36),( 43, 36)
( 44, 46),( 19, 59),( 26, 50),( 42, 56),( 53, 56)
( 54, 66),( 29, 79),( 36, 70),( 52, 76),( 63, 76)
( 64, 86),( 39, 99),( 46, 90),( 62, 96),( 73, 96)
( 74,  6),( 49, 19),( 56, 10),( 72, 16),( 83, 16)
( 84, 26),( 59, 39),( 66, 30),( 82, 36),( 93, 36)
( 94, 46),( 69, 59),( 76, 50),( 92, 56),(  3, 56)
(  4, 66),( 79, 79),( 86, 70),(  2, 76),( 13, 76)
( 14, 86),( 89, 99),( 96, 90),( 12, 96),( 23, 96)
( 24,  6),( 99, 19),(  6, 10),( 22, 16),( 33, 16)
>>>
</code>```

Not my idea - picked this up at Python Descriptors Demystified

Each instance of MaxValue needs to keep track (or know) the value for each instance of Item - Item.x needs to know the x value for Item instances a, b, c,... . A dictionary is convenient for that and a WeakKeyDictionary is used so that if the dictionary is the only reference to an Item instance, then that instance can be garbage collected.

This solution alleviates the need to write a getter/setter for each attribute that shares a behaviour.

Title: Enabling Integer Overflow in Python

Body:
I'd like to create a 2D environment in which the top & bottom and left & right are connected  (similar to a Torus or Doughnut). However, rather than doing a check on an object's x/y coordinate every frame, I'd like to simulate it using integer overflow.

While normal iteration (as shown in the sample code below) can be done, it may be slightly more effective (though dangerous) to simply enable overflow on some variables, especially when dealing with hundreds or thousands of objects in each frame/iteration.

I can find some examples which also simulate integer overflow in Python like this. However, I'm looking for something that can overflow just by enabling overflow in certain variables and skipping the checks in general.

# With normal checking of every instance
import random

width = 100
height = 100

class item():
    global width, height

    def __init__(self):
        self.x = random.randint(0, width)
        self.y = random.randint(0, height)

items = [item for _ in range(10)] # create 10 instances

while True:
    for obj in items:
        obj.x += 10
        obj.y += 20
        while obj.x > width:
            obj.x -= width
        while obj.y > height:
            obj.y -= height
        while obj.x < width:
            obj.x += width
        while obj.y < height:
            obj.y += height

I'd like to simulate integer overflow for only some certain classes/objects. Is there a way to have some variables automatically overflow and loop back to their min/max values?

Body:
With a descriptor you can You can define the behavior you want for your object attributes. Reading between the lines it sounds like you want your attributes to exhibit a value = value % maximum behaviour.

from weakref import WeakKeyDictionary

class MaxValue:
    '''A descriptor whose value will be: value modulo maximum.'''
    def __init__(self, maximum, default=0):
        self.maximum = maximum
        self.default = default
        self.data = WeakKeyDictionary()

    def __get__(self, instance, owner):
        return self.data.get(instance, self.default)

    def __set__(self, instance, value):
        self.data[instance] = value % self.maximum

Descriptors should be class attributes. For your example class:

import random
width = 100
height = 100

class Item:
##    global width, height
    x = MaxValue(width)
    y = MaxValue(height)

    def __init__(self):
        self.x = random.randint(0, width)
        self.y = random.randint(0, height)
    def __str__(self):
        return f'({self.x:>3},{self.y:>3})'

Example:

items = [Item() for _ in range(5)]
print(','.join(f'{item}' for item in items))
for n in range(15):
    for item in items:
        item.x += 10
        item.y += 20
    print(','.join(f'{item}' for item in items))

>>>
( 74,  6),( 49, 19),( 56, 10),( 72, 16),( 83, 16)
( 84, 26),( 59, 39),( 66, 30),( 82, 36),( 93, 36)
( 94, 46),( 69, 59),( 76, 50),( 92, 56),(  3, 56)
(  4, 66),( 79, 79),( 86, 70),(  2, 76),( 13, 76)
( 14, 86),( 89, 99),( 96, 90),( 12, 96),( 23, 96)
( 24,  6),( 99, 19),(  6, 10),( 22, 16),( 33, 16)
( 34, 26),(  9, 39),( 16, 30),( 32, 36),( 43, 36)
( 44, 46),( 19, 59),( 26, 50),( 42, 56),( 53, 56)
( 54, 66),( 29, 79),( 36, 70),( 52, 76),( 63, 76)
( 64, 86),( 39, 99),( 46, 90),( 62, 96),( 73, 96)
( 74,  6),( 49, 19),( 56, 10),( 72, 16),( 83, 16)
( 84, 26),( 59, 39),( 66, 30),( 82, 36),( 93, 36)
( 94, 46),( 69, 59),( 76, 50),( 92, 56),(  3, 56)
(  4, 66),( 79, 79),( 86, 70),(  2, 76),( 13, 76)
( 14, 86),( 89, 99),( 96, 90),( 12, 96),( 23, 96)
( 24,  6),( 99, 19),(  6, 10),( 22, 16),( 33, 16)
>>>

Not my idea - picked this up at Python Descriptors Demystified

Each instance of MaxValue needs to keep track (or know) the value for each instance of Item - Item.x needs to know the x value for Item instances a, b, c,... . A dictionary is convenient for that and a WeakKeyDictionary is used so that if the dictionary is the only reference to an Item instance, then that instance can be garbage collected.

This solution alleviates the need to write a getter/setter for each attribute that shares a behaviour.


问:
Reading last printed line and delete it with a "if" statement
I am working on a TCP chatroom with python 2.7, my server should manage multiple clients (I used select module) and used threads for clients, I have a problem on what I am printing.
Since my raw_input in the client has text in it, it gets easily ugly when the other thread in charge of printing other clients messages gets triggered .

My code's results looks like this : (on client's window)

WELCOME TO CHATROOM
you are connected
your pseudo is PSEUDO
other_user joined the chatroom
```

<p>and the my  raw_input() pops out and it goes like this :</p>

<p><code>* < your message > * :e chatroom</code></p>

<p>Or sometimes I get another user's message over Raw_input text</p>

<p>because it replaces the last line printed, I figured I could delete the last printed line if it's equal to my raw_input text to print an unexpected message over it and then reprint my Raw_input but I don't know to implement it.</p>

<p>I have tried moving my cursor with "\x1b["-like commands and deleting last printed line but those commands are not working for me.</p>

```class Sender(Thread):
    """would send messages to the server"""

    def __init__(self,  socket, username):
        Thread.__init__(self)
        self.socket = socket
        self.username = username

    def run(self):
        while 1:
            message = raw_input("* < your message > * :")
            self.socket.send(message)

class Receiver(Thread):
    import  sys

    def __init__(self,socket):
        Thread.__init__(self)
        self.connexion = socket

    def run(self) :
        while 1:
            message_received = self.connexion.recv(4096)
            message_received = message_received.decode()
            sys.stdout.write("\r" + message_received)
            sys.stdout.flush()
            if message_recu =='' or message_recu.upper() == "OFF":
                break
        self._Thread__stop()
        print "\nClient arrete. Connexion interrompue."
        self.connexion.close()
```

答:
For \b and \r to work you need to be ending your print statements with a space instead of a newline.

EG:
print 'hello there', the , at the end of the print statement defines that it wont go forwards one line, but instead end it with a space. Then you can use another print statement to delete the text.

EG:

print '\r ' this would go to the beginning of the line and replace it with a space, then you can output text over it.

Body:
I am working on a TCP chatroom with python 2.7, my server should manage multiple clients (I used select module) and used threads for clients, I have a problem on what I am printing.
Since my raw_input in the client has text in it, it gets easily ugly when the other thread in charge of printing other clients messages gets triggered .

My code's results looks like this : (on client's window)

WELCOME TO CHATROOM
you are connected
your pseudo is PSEUDO
other_user joined the chatroom

and the my  raw_input() pops out and it goes like this :

* < your message > * :e chatroom

Or sometimes I get another user's message over Raw_input text

because it replaces the last line printed, I figured I could delete the last printed line if it's equal to my raw_input text to print an unexpected message over it and then reprint my Raw_input but I don't know to implement it.

I have tried moving my cursor with "\x1b["-like commands and deleting last printed line but those commands are not working for me.

class Sender(Thread):
    """would send messages to the server"""

    def __init__(self,  socket, username):
        Thread.__init__(self)
        self.socket = socket
        self.username = username

    def run(self):
        while 1:
            message = raw_input("* < your message > * :")
            self.socket.send(message)

class Receiver(Thread):
    import  sys

    def __init__(self,socket):
        Thread.__init__(self)
        self.connexion = socket

    def run(self) :
        while 1:
            message_received = self.connexion.recv(4096)
            message_received = message_received.decode()
            sys.stdout.write("\r" + message_received)
            sys.stdout.flush()
            if message_recu =='' or message_recu.upper() == "OFF":
                break
        self._Thread__stop()
        print "\nClient arrete. Connexion interrompue."
        self.connexion.close()


问:
How to find all assemblies that reference a specific dll?
I've a directory with a large number of dlls. I need to find all those that reference a specific dll.

I'm thinking about the following solution :

Loop the assemblies and invoke each one with ildasm

Dump the manifest into a text file

Search the text files for the required assembly name.

Yet this solution feels immensely wrong to me.  Is there a better way to achieve it?

答:
Download IlSpy.exe, and open the assembly whose references you want to see, it will list all referenced assemblies.

https://github.com/icsharpcode/ILSpy/releases


问:
Trying to parse json, can't seem to parse arrays inside of an array
I've been trying to parse a part of this JSON file: https://opendata.brussels.be/api/records/1.0/search/?dataset=traffic-volume&rows=3&facet=level_of_service

I wanna get records->fields->geo_shape->coordinates but I can't seem to print these arrays inside of the "coordinates" array.. I thought it might be because the arrays inside of the coordinates do not have names, so I don't know how to make a variable for them. Got this code currently:

```<code>import UIKit
import Foundation

struct Geoshape : Codable {
    let coordinates: Array<...>
}
struct Field : Codable {
    let geo_shape: Geoshape
    let level_of_service: String
}
struct Record: Codable {
    let fields: Field
}

struct Traffic: Codable{
    let records: Array<Record>
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func clickRefresh(_ sender: Any) {
        guard let url = URL(string: "https://opendata.brussels.be/api/records/1.0/search/?dataset=traffic-volume&rows=3&facet=level_of_service") else { return }
        let session = URLSession.shared
        let task = session.dataTask(with: url){ (data, response, error) in
            if let response = response {
                print(response)
            }
         if let data = data {

            let traffic = try? JSONDecoder().decode(Traffic.self, from: data)
            print(traffic)

            }

        }
        task.resume()
    }
}
</code>```

Clearly the Array<...> needs to be changed but I don't know to what. I've tried making an extra struct with just 1 variable (which is another array of the type Double: Double) but that does not seem to work. I was able to print everything just fine up to the point I tried to go into the coordinates array.

Anyone can help me?

答:
Replace

```<code>let coordinates: Array<...>
</code>```

with

```<code>let coordinates:[[Double]]
</code>```

Body:
I've been trying to parse a part of this JSON file: https://opendata.brussels.be/api/records/1.0/search/?dataset=traffic-volume&rows=3&facet=level_of_service

I wanna get records->fields->geo_shape->coordinates but I can't seem to print these arrays inside of the "coordinates" array.. I thought it might be because the arrays inside of the coordinates do not have names, so I don't know how to make a variable for them. Got this code currently:

import UIKit
import Foundation

struct Geoshape : Codable {
    let coordinates: Array<...>
}
struct Field : Codable {
    let geo_shape: Geoshape
    let level_of_service: String
}
struct Record: Codable {
    let fields: Field
}

struct Traffic: Codable{
    let records: Array<Record>
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func clickRefresh(_ sender: Any) {
        guard let url = URL(string: "https://opendata.brussels.be/api/records/1.0/search/?dataset=traffic-volume&rows=3&facet=level_of_service") else { return }
        let session = URLSession.shared
        let task = session.dataTask(with: url){ (data, response, error) in
            if let response = response {
                print(response)
            }
         if let data = data {

            let traffic = try? JSONDecoder().decode(Traffic.self, from: data)
            print(traffic)

            }

        }
        task.resume()
    }
}

Clearly the Array<...> needs to be changed but I don't know to what. I've tried making an extra struct with just 1 variable (which is another array of the type Double: Double) but that does not seem to work. I was able to print everything just fine up to the point I tried to go into the coordinates array.

Anyone can help me?

Body:
Replace

let coordinates: Array<...>

with

let coordinates:[[Double]]


问:
Image have margin from top in constraintlayout
I have a scrolled content, so I put a constraint layout inside a scrollview, I have a problem when put an image inside a constraint layout, but the image show a space from top such as in screenshot below, how can I remove that space?

```<code><?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

    <android.support.constraint.ConstraintLayout
            android:id="@+id/constraintLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
        <!-- have whatever children you want inside -->
        <ImageView
                app:srcCompat="@drawable/main_header"
                android:id="@+id/img_icon"
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:background="#ffccbb"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintWidth_percent="1"
                android:contentDescription="TODO" app:layout_constraintDimensionRatio="1:1"
                app:layout_constraintHorizontal_bias="0.0" app:layout_constraintVertical_bias="0.0"/>
    </android.support.constraint.ConstraintLayout>
</ScrollView>
</code>```

答: Try this,  remove app:layout_constraintTop_toTopOf="parent"  in your ImageView it works!


问:
Cannot access or assign login username variable - mysql - php
I cannot find a way to access the username I used to log in with on my php web form.

I have had a look at these posts but I think my case varies slightly as they both declare the username variable at the top. I simply log in using a sql query.

Here is the login script

<?php
$uname=$_POST['uname'];
$password=$_POST['password'];
session_start();

$con=mysqli_connect("localhost","root","g7trj98o6fyr5","login");//mysqli("localhost","username of database","password of database","database name")
$result=mysqli_query($con,"SELECT * FROM `login_info` WHERE `uname`='$uname' && `password`='$password'");
$count=mysqli_num_rows($result);
if($count==1)
{
    echo "Login success";
    $_SESSION['log']=1;
    header("refresh:2;url=welcome.php");

}
else
{
    echo "please fill proper details";
    header("refresh:2;url=index.php");
}
?>
```

<p>I'm expecting to be able to do a if check using the currently logged in user to differentiate them from all other users online.</p>

<p>I have this if check which should only put the edit button next to the user who is logged in.</p>

<pre class="lang-php prettyprint-override"><code>while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['uname'] . "</td>";
echo "<td>" . $row['clickrate'] . "</td>";
if($logedInUsername == $row['uname'])
    echo "<td>" . $row['yourword'] . " edit</td>";
else
    echo "<td>" . $row['yourword'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
</code>```

welcome.php (where the if statement is)

<?php

function add_ant(&$connection)
{
    mysqli_query($connection, "UPDATE `login_info` SET `clickrate`=`clickrate`+'1' WHERE `uname`='rvbvakama' && `password`='pass'");
}

session_start();

if(isset($_SESSION['log']))
{

$_SESSION['uname'] = $_POST['uname'];

echo "";
$con=mysqli_connect("localhost","root","pass","login"); //mysqli("localhost","username of database","password of database","database name")

if(array_key_exists('add',$_POST))
{
   add_ant($con);
}

$result = mysqli_query($con,"SELECT * FROM login_info");
if (!$result)
{
    printf("Error: %s\n", mysqli_error($con));
    exit();
}

echo "

username
clickrate
yourword

";

while($row = mysqli_fetch_array($result))
{
echo "
";
echo "" . $row['uname'] . "	";
echo "" . $row['clickrate'] . "	";
if($logedInUsername == $_SESSION['uname'])
    echo "" . $row['yourword'] . " edit	";
else
    echo "" . $row['yourword'] . "	";
echo "
";
}
echo "
";
?>

<!DOCTYPE html>

<title></title>

Add ants

<button type='button' name="add">ADD</button>

logout

<?php
}
else
{
    echo "please fill proper details";
    header("refresh:2;url=index.php");
}

?>
```

Thanks.

答:
Not safe, but put:

```<code><?php
$uname=$_POST['uname'];
$password=$_POST['password'];
session_start();

$con=mysqli_connect("localhost","root","g7trj98o6fyr5","login");//mysqli("localhost","username of database","password of database","database name")
$result=mysqli_query($con,"SELECT * FROM `login_info` WHERE `uname`='$uname' && `password`='$password'");
$count=mysqli_num_rows($result);
if($count==1)
{
    echo "Login success";
    $_SESSION['log']=1;
    $_SESSION['uname'] = $_POST['uname'];
    header("refresh:2;url=welcome.php");

}
else
{
    echo "please fill proper details";
    header("refresh:2;url=index.php");
}
?>
</code>```

and then check:

```<code>if($logedInUsername == $_SESSION['uname'])
...
</code>```

also you need to set $logedInUsername to $row['uname'] in welcome.php
or check

```<code>if($row['uname'] == $_SESSION['uname'])
</code>```

Body:
I cannot find a way to access the username I used to log in with on my php web form.

I have had a look at these posts but I think my case varies slightly as they both declare the username variable at the top. I simply log in using a sql query.

Here is the login script

<?php
$uname=$_POST['uname'];
$password=$_POST['password'];
session_start();

$con=mysqli_connect("localhost","root","g7trj98o6fyr5","login");//mysqli("localhost","username of database","password of database","database name")
$result=mysqli_query($con,"SELECT * FROM `login_info` WHERE `uname`='$uname' && `password`='$password'");
$count=mysqli_num_rows($result);
if($count==1)
{
    echo "Login success";
    $_SESSION['log']=1;
    header("refresh:2;url=welcome.php");

}
else
{
    echo "please fill proper details";
    header("refresh:2;url=index.php");
}
?>

I'm expecting to be able to do a if check using the currently logged in user to differentiate them from all other users online.

I have this if check which should only put the edit button next to the user who is logged in.

while($row = mysqli_fetch_array($result))
{
echo "
";
echo "" . $row['uname'] . "	";
echo "" . $row['clickrate'] . "	";
if($logedInUsername == $row['uname'])
    echo "" . $row['yourword'] . " edit	";
else
    echo "" . $row['yourword'] . "	";
echo "
";
}
echo "
";
?>

welcome.php (where the if statement is)

<?php

function add_ant(&$connection)
{
    mysqli_query($connection, "UPDATE `login_info` SET `clickrate`=`clickrate`+'1' WHERE `uname`='rvbvakama' && `password`='pass'");
}

session_start();

if(isset($_SESSION['log']))
{

$_SESSION['uname'] = $_POST['uname'];

echo "";
$con=mysqli_connect("localhost","root","pass","login"); //mysqli("localhost","username of database","password of database","database name")

if(array_key_exists('add',$_POST))
{
   add_ant($con);
}

$result = mysqli_query($con,"SELECT * FROM login_info");
if (!$result)
{
    printf("Error: %s\n", mysqli_error($con));
    exit();
}

echo "

username
clickrate
yourword

";

while($row = mysqli_fetch_array($result))
{
echo "
";
echo "" . $row['uname'] . "	";
echo "" . $row['clickrate'] . "	";
if($logedInUsername == $_SESSION['uname'])
    echo "" . $row['yourword'] . " edit	";
else
    echo "" . $row['yourword'] . "	";
echo "
";
}
echo "
";
?>

<!DOCTYPE html>

<title></title>

Add ants

<button type='button' name="add">ADD</button>

logout

<?php
}
else
{
    echo "please fill proper details";
    header("refresh:2;url=index.php");
}

?>

Thanks.

Body:
Not safe, but put:

<?php
$uname=$_POST['uname'];
$password=$_POST['password'];
session_start();

$con=mysqli_connect("localhost","root","g7trj98o6fyr5","login");//mysqli("localhost","username of database","password of database","database name")
$result=mysqli_query($con,"SELECT * FROM `login_info` WHERE `uname`='$uname' && `password`='$password'");
$count=mysqli_num_rows($result);
if($count==1)
{
    echo "Login success";
    $_SESSION['log']=1;
    $_SESSION['uname'] = $_POST['uname'];
    header("refresh:2;url=welcome.php");

}
else
{
    echo "please fill proper details";
    header("refresh:2;url=index.php");
}
?>

and then check:

if($logedInUsername == $_SESSION['uname'])
...

also you need to set $logedInUsername to $row['uname'] in welcome.php
or check

if($row['uname'] == $_SESSION['uname'])


问:
How to select an element place after an a element?
I have the following HTML code. Why this isn't working if I would like to select the  element if clicked?

$('input[name="USR_NewPassword"] span > a').on('click', function(event) {
  alert()
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="password" name="USR_NewPassword" class="form-control" maxlength="50" required>
<span class="input-group-addon">
        <i class="fa fa-eye"></i>
    </span></code>```

答:
Your selection is wrong. Use next with find.

$('input[name="USR_NewPassword"]').next('span').find('a').on('click', function(event) {
  alert();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="password" name="USR_NewPassword" class="form-control" maxlength="50" required>
<span class="input-group-addon">
    <i class="fa fa-eye">icon</i>
</span></code>```

Body:
I have the following HTML code. Why this isn't working if I would like to select the  element if clicked?

$('input[name="USR_NewPassword"] span > a').on('click', function(event) {
  alert()
});

<input type="password" name="USR_NewPassword" class="form-control" maxlength="50" required>

Body:
Your selection is wrong. Use next with find.

$('input[name="USR_NewPassword"]').next('span').find('a').on('click', function(event) {
  alert();
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="password" name="USR_NewPassword" class="form-control" maxlength="50" required>
<span class="input-group-addon">
    <a href="#"><i class="fa fa-eye">icon</i></a>
</span>


问:
/bin/bash^M: bad interpreter: No such file or directory
I am facing
 /bin/bash^M: bad interpreter: No such file or directory
issue and I have already got the solution for it from this stack flow answer

-bash: ./my_script: /bin/bash^M: bad interpreter: No such file or directory

which works fine.

My question is every time when I restart my ubuntu machine I have to redo everything
That is I execute
dos2unix -k -o filename
every time I start my system.

Is there any way this can be just once?

Please note: I had to create a new question because I was not able to ask the question or comment in the existing question due to less reputation

答:
This is a very common problem of running a bash script from a file saved with Microsoft OS machine (a virtual machine maybe?) such as Windows or DOS.

So you know the fix to your problem.

Now you should prevent your problem reoccurring every time you login. Identify how the file is generated/copied/damaged by another resource. Like .bash_profile script or crontab script or any other management deamon.


问:
Adding a suffix to names when storing results in a loop
I am making some plots in R in a for-loop and would like to store them using a name to describe the function being plotted, but also which data it came from.

So when I have a list of 2 data sets "x" and "y" and the loop has a structure like this:

```<code>x = matrix(
  c(1,2,4,5,6,7,8,9),
  nrow=3,
  ncol=2)

y = matrix(
  c(20,40,60,80,100,120,140,160,180),
  nrow=3,
  ncol=2)

data <- list(x,y)

for (i in data){
  ??? <- boxplot(i)
}
</code>```

I would like the ??? to be "name" + (i) + "_" separator. In this case the 2 plots would be called "plot_x" and "plot_y".

I tried some stuff with paste("plot", names(i), sep = "_") but I'm not sure if this is what to use, and where and how to use it in this scenario.

答:
We can create an empty list with the length same as that of the 'data' and then store the corresponding output from the for loop by looping over the sequence of 'data'

```<code>out <- vector('list', length(data))
for(i in seq_along(data)) {
      out[[i]] <- boxplot(data[[i]])
  }

str(out)
#List of 2
# $ :List of 6
#  ..$ stats: num [1:5, 1:2] 1 1.5 2 3 4 5 5.5 6 6.5 7
#  ..$ n    : num [1:2] 3 3
#  ..$ conf : num [1:2, 1:2] 0.632 3.368 5.088 6.912
#  ..$ out  : num(0)
#  ..$ group: num(0)
#  ..$ names: chr [1:2] "1" "2"
# $ :List of 6
#  ..$ stats: num [1:5, 1:2] 20 30 40 50 60 80 90 100 110 120
#  ..$ n    : num [1:2] 3 3
#  ..$ conf : num [1:2, 1:2] 21.8 58.2 81.8 118.2
#  ..$ group: num(0)
#  ..$ names: chr [1:2] "1" "2"
</code>```

If required, set the names of the list elements with the object names

```<code>names(out) <- paste0("plot_", c("x", "y"))
</code>```

It is better not to create multiple objects in the global environment.  Instead as showed above, place the objects in a list

Body:
I am making some plots in R in a for-loop and would like to store them using a name to describe the function being plotted, but also which data it came from.

So when I have a list of 2 data sets "x" and "y" and the loop has a structure like this:

x = matrix(
  c(1,2,4,5,6,7,8,9),
  nrow=3,
  ncol=2)

y = matrix(
  c(20,40,60,80,100,120,140,160,180),
  nrow=3,
  ncol=2)

data <- list(x,y)

for (i in data){
  ??? <- boxplot(i)
}

I would like the ??? to be "name" + (i) + "_" separator. In this case the 2 plots would be called "plot_x" and "plot_y".

I tried some stuff with paste("plot", names(i), sep = "_") but I'm not sure if this is what to use, and where and how to use it in this scenario.

Body:
We can create an empty list with the length same as that of the 'data' and then store the corresponding output from the for loop by looping over the sequence of 'data'

out <- vector('list', length(data))
for(i in seq_along(data)) {
      out[[i]] <- boxplot(data[[i]])
  }

str(out)
#List of 2
# $ :List of 6
#  ..$ stats: num [1:5, 1:2] 1 1.5 2 3 4 5 5.5 6 6.5 7
#  ..$ n    : num [1:2] 3 3
#  ..$ conf : num [1:2, 1:2] 0.632 3.368 5.088 6.912
#  ..$ out  : num(0)
#  ..$ group: num(0)
#  ..$ names: chr [1:2] "1" "2"
# $ :List of 6
#  ..$ stats: num [1:5, 1:2] 20 30 40 50 60 80 90 100 110 120
#  ..$ n    : num [1:2] 3 3
#  ..$ conf : num [1:2, 1:2] 21.8 58.2 81.8 118.2
#  ..$ group: num(0)
#  ..$ names: chr [1:2] "1" "2"

If required, set the names of the list elements with the object names

names(out) <- paste0("plot_", c("x", "y"))

It is better not to create multiple objects in the global environment.  Instead as showed above, place the objects in a list