问:
drupal 8 create an page in admin section in admin/structure/customformdatalisting
I am trying to create a custom admin page in drupal 8 admin
i have create a custom module name custom_admin also I have added the below code in

```<code>"custom_admin.routing.xml"
custom_admin.contactformlisting:
  path: '/admin/structure/contactformlisting'
  defaults:
    _content:
'\Drupal\custom_admin\Controller\AdminController::contactformlisting'
    _title: 'Contact Form Listing'
requirements:
    _permission: 'administer contact forms listing'
   _access: 'TRUE'
</code>```

custom_admin_permissions.yml

```<code>administer contact forms listing:
  title: 'Administer contact forms listing'
</code>```

in custom_admin.links,menu.yml

```<code>custom_admin.contactformlisting:
  title: Contact Form Data Listing
  description: 'This is a contact form listing page link`enter code here`'
  parent: system.admin_structure
  route_name: custom_admin.contactformlisting
</code>```

But still revceving Page not Found can anybody help me in these

答:
Not sure if it's just a typo above, but the file "custom_admin.routing.xml" should be custom_admin.routing.yml* (yml instead of xml). The permissions yml needs to be module_name.permissions.yml - you have module_name_permissions.yml (underscore instead of period).

I also notice some spacing issues in the routing file for _access:(again not sure if just a typo here), but yml format is very specific. They need to all be indented 2 spaces.

If it's still not working, I would suggest removing the _access property altogether from the routing yml and set _permission: TRUE temporarily, just to remove any other variables that could be interfering.

Body:
I am trying to create a custom admin page in drupal 8 admin
i have create a custom module name custom_admin also I have added the below code in

"custom_admin.routing.xml"
custom_admin.contactformlisting:
  path: '/admin/structure/contactformlisting'
  defaults:
    _content:
'\Drupal\custom_admin\Controller\AdminController::contactformlisting'
    _title: 'Contact Form Listing'
requirements:
    _permission: 'administer contact forms listing'
   _access: 'TRUE'

custom_admin_permissions.yml

administer contact forms listing:
  title: 'Administer contact forms listing'

in custom_admin.links,menu.yml

custom_admin.contactformlisting:
  title: Contact Form Data Listing
  description: 'This is a contact form listing page link`enter code here`'
  parent: system.admin_structure
  route_name: custom_admin.contactformlisting

But still revceving Page not Found can anybody help me in these


来源: stackexchange

问:
Get context attribute value from console
I'm reading with dev. tools console with this code $('#basis > td')[1] this code line: € 11,85

With $('#basis > td')[1].textContent i read the content of 	, also € 11,85.

How can i read the value of context? - i want to get 11.84689, but i can't find anywhere, how to fetch context attribute value...

答:
I changed your question a little bit to illustrate on how you can retrieve multiple context values. I take that you were using > in an attempt to retrieve more values. Please try this:</p>

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table id="basis">
    <td class="EURO" context="11.84689" align="right">€ 11,85</td>
    <td class="EURO" context="12.84689" align="right">€ 12,85</td>
    <td class="EURO" context="13.84689" align="right">€ 13,85</td>
    <td class="EURO" context="14.84689" align="right">€ 14,85</td>
    <td class="EURO" context="15.84689" align="right">€ 15,85</td>
</table>

<script>
    $('#basis td:first').each(function() {
        console.log($(this).attr('context'));
    });
</script>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I changed your question a little bit to illustrate on how you can retrieve multiple context values. I take that you were using > in an attempt to retrieve more values. Please try this:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table id="basis">
    <td class="EURO" context="11.84689" align="right">€ 11,85</td>
    <td class="EURO" context="12.84689" align="right">€ 12,85</td>
    <td class="EURO" context="13.84689" align="right">€ 13,85</td>
    <td class="EURO" context="14.84689" align="right">€ 14,85</td>
    <td class="EURO" context="15.84689" align="right">€ 15,85</td>
</table>

<script>
    $('#basis td:first').each(function() {
        console.log($(this).attr('context'));
    });
</script>


问:
c++ How could I properly predefined array of char*?
I am doing it that way:

```<code>int argc = 9;
char* argv[argc];

argv[0] = "c:/prog.exe";
</code>```

but I get notice, that it is deprecated. What is better way?

答:
Other than what everyone else has pointed out about const string literals being assigned to non-const char pointers and the weirdness of declaring argv and argc outside of main()'s parameter list, there is an additional problem with this line here:

char* argv[argc];

You can only use integer constant expressions for array sizes in C++; an integer constant expression being a literal integer in the source of your program (like "5" or "10"), an enumerations value (like "red" from "enum colors {red, green, blue};"), a sizeof expression, or an int variable declared with const:

```<code>// can hold 30 ints
int myarray1[30];

// can hold as many ints as myarray1 is wide in bytes
int myarray2[sizeof(myarray1)];

// C++ does not support variable-length arrays like C99 does, so if an int
// variable is used to specify array size, it must be marked const:
const int myarray3_size = 42;
int myarray3[myarray3];
</code>```

Many C++ compilers implement C99-style variable-length arrays, so you may not get any complaint when you use them, but they are still best avoided if you want to write portable code.

Body:
I am doing it that way:

int argc = 9;
char* argv[argc];

argv[0] = "c:/prog.exe";

but I get notice, that it is deprecated. What is better way?

Body:
Other than what everyone else has pointed out about const string literals being assigned to non-const char pointers and the weirdness of declaring argv and argc outside of main()'s parameter list, there is an additional problem with this line here:

char* argv[argc];

You can only use integer constant expressions for array sizes in C++; an integer constant expression being a literal integer in the source of your program (like "5" or "10"), an enumerations value (like "red" from "enum colors {red, green, blue};"), a sizeof expression, or an int variable declared with const:

// can hold 30 ints
int myarray1[30];

// can hold as many ints as myarray1 is wide in bytes
int myarray2[sizeof(myarray1)];

// C++ does not support variable-length arrays like C99 does, so if an int
// variable is used to specify array size, it must be marked const:
const int myarray3_size = 42;
int myarray3[myarray3];

Many C++ compilers implement C99-style variable-length arrays, so you may not get any complaint when you use them, but they are still best avoided if you want to write portable code.

ContentLicense: CC BY-SA 2.5


问:
Can I use Rails gem from another gem?
I am developing a simple gem. as part of it, I want data-caching to which I need rails gem. I included the required statements in gemspec. But still, it is not loading Rails. I am getting below error</p>

```<code>NameError:
   uninitialized constant FormattingHelper::Rails
</code>```

答:
Instead of using Rails for caching, I used below class and fixed the problem</p>

```<code>ActiveSupport::Cache
</code>```

Title: Can I use Rails gem from another gem?

Body:
I am developing a simple gem. as part of it, I want data-caching to which I need rails gem. I included the required statements in gemspec. But still, it is not loading Rails. I am getting below error

NameError:
   uninitialized constant FormattingHelper::Rails

Body:
Instead of using Rails for caching, I used below class and fixed the problem

ActiveSupport::Cache


问:
Match number in python using re
I got many data wrote in this form(read from file):

```<code>(31265+0j)
(-5613.54281374+404.957401125j)
(1371.65134844+2671.06617046j)
...
</code>```

And yet I want to extract the numerical part, like [31265, 0] or [-5613.54281374 , 404.957401125] , I coded in python in the way I thought it would work:

```<code>re.findall(r'.*([\+|\-]?\d+.?\d+)([\+|\-]?\d+.?\d+).*', tempStr)
</code>```

But it does not work, it gave me this:

```<code>[]
[('26', '5+0')]
[('11', '25')]
...
</code>```

What's wrong with it? Is it something about lazy mode? And how should I fix it?

========================Update========================
For me, this question is solved, but I still wonder what's wrong with the regular expression part, is there someone willing to help me point out what's wrong with the regex pattern?

答:
Using .real and .imag will give you the output you desire</p>

```<code>   foo = (31265 + 0j)
   bar = [foo.real , bar.imag]
   #>>>[31265.0 , 0.0]
</code>```

Title: Match number in python using re

Body:
I got many data wrote in this form(read from file):

(31265+0j)
(-5613.54281374+404.957401125j)
(1371.65134844+2671.06617046j)
...

And yet I want to extract the numerical part, like [31265, 0] or [-5613.54281374 , 404.957401125] , I coded in python in the way I thought it would work:

re.findall(r'.*([\+|\-]?\d+.?\d+)([\+|\-]?\d+.?\d+).*', tempStr)

But it does not work, it gave me this:

[]
[('26', '5+0')]
[('11', '25')]
...

What's wrong with it? Is it something about lazy mode? And how should I fix it?

========================Update========================
For me, this question is solved, but I still wonder what's wrong with the regular expression part, is there someone willing to help me point out what's wrong with the regex pattern?

Body:
Using .real and .imag will give you the output you desire

   foo = (31265 + 0j)
   bar = [foo.real , bar.imag]
   #>>>[31265.0 , 0.0]


问:
Cubic Root of Pandas DataFrame
I understand how to take cubic root of both positive and negative numbers. But when trying to use apply-lambda method to efficiently process all elements of a dataframe, I run into an ambiguity issue. Interestingly, this error does not arise with equalities, so I am wondering what could be wrong with the code:

```<code>sample[columns]=sample[columns].apply(lambda x: (-1)*np.power(-x,1./3) if x<0 else np.power(x,1./3))
</code>```

答:
It doesn't have to be complicated, simply use NumPys cube-root function: np.cbrt:

```<code>df[columns] = np.cbrt(df[columns])
</code>```

It requires NumPy >= 1.10 though.

For older versions you could use np.absolute and np.sign instead of using conditionals:

```<code>df[columns] = df[columns].apply(lambda x: np.power(np.absolute(x), 1./3) * np.sign(x))
</code>```

This calculates the cube root of the absolute and then changes the sign appropriatly.

Title: Cubic Root of Pandas DataFrame

Body:
I understand how to take cubic root of both positive and negative numbers. But when trying to use apply-lambda method to efficiently process all elements of a dataframe, I run into an ambiguity issue. Interestingly, this error does not arise with equalities, so I am wondering what could be wrong with the code:

sample[columns]=sample[columns].apply(lambda x: (-1)*np.power(-x,1./3) if x<0 else np.power(x,1./3))

Body:
It doesn't have to be complicated, simply use NumPys cube-root function: np.cbrt:

df[columns] = np.cbrt(df[columns])

It requires NumPy >= 1.10 though.

For older versions you could use np.absolute and np.sign instead of using conditionals:

df[columns] = df[columns].apply(lambda x: np.power(np.absolute(x), 1./3) * np.sign(x))

This calculates the cube root of the absolute and then changes the sign appropriatly.


问:
Duplicate None or other Python sigletons
First of all: This question covers practically zero use cases, and is only about morbid curiosity. That being said:

I started wondering not so long ago if it was possible to duplicate the None object from Python (or any other singleton like True or Ellipsis). By "duplicate", I mean create an exact copy that is not another reference to the same object. That is:

```<code>>>> noneBis == None
True
>>> noneBis is None
False
</code>```

Why I think this would be possible, is because of the core philosophy of Python: Everything is an object. And an object can be copied.

I have tried several ways (some more convoluted than others) and couldn't do it:

```<code>>>> copy.deepcopy(None) is None
True
>>> types.NoneType()
TypeError: cannot create NoneType instances
>>> object.__new__(type(None))
TypeError: object.__new__(NoneType) is not safe, use NoneType.__new__()
>>> types.NoneType.__new__(types.NoneType)
TypeError: object.__new__(NoneType) is not safe, use NoneType.__new__()
</code>```

This seems pretty hardened and mad-scientist-proof to me, but I am not sure I have tried hard enough. (I have tested this in Python 2.7, but since Python 3+ have been designed to be even more foolproof than Python 2, my guess is the results won't be better.)

Can you actually create a separate duplicate of a Python singleton?

答:
If you could create a "duplicate copy" of a singleton, it wouldn't really be a singleton anymore, would it ?

wrt/ builtin singletons (like None) which are implemented in C (or whatever the language for a given implementation), I don't think you can ever expect to "clone" them except by either fork Python or some similarly extreme method. Also note that since the Python language specs explicitely garantees that None is a singleton, this wouldn't be Python anymore ;)

Now if all you want is something that is a singleton and compares equal to None while not being None, here's a possible (python 2.7.x) implementation:

```<code>def __mknone():
    _instance = [None]

    class NotNoneType(object):
        def __new__(cls):
            if _instance[0] is not None:
                raise TypeError("cannot create 'NotNoneType' instances")
            _instance[0] =  object.__new__(cls)
            return _instance[0]

        def __eq__(self, other):
            if other is None:
                return True
            return other == _instance[0]

        def __nonzero__(self):
            return False

    return NotNoneType()

NotNone = __mknone()
NotNoneType = type(NotNone)
del __mknone
</code>```

Tell me if you manage to create another instance of NotNoneType BTW ;)

Body:
First of all: This question covers practically zero use cases, and is only about morbid curiosity. That being said:

I started wondering not so long ago if it was possible to duplicate the None object from Python (or any other singleton like True or Ellipsis). By "duplicate", I mean create an exact copy that is not another reference to the same object. That is:

>>> noneBis == None
True
>>> noneBis is None
False

Why I think this would be possible, is because of the core philosophy of Python: Everything is an object. And an object can be copied.

I have tried several ways (some more convoluted than others) and couldn't do it:

>>> copy.deepcopy(None) is None
True
>>> types.NoneType()
TypeError: cannot create NoneType instances
>>> object.__new__(type(None))
TypeError: object.__new__(NoneType) is not safe, use NoneType.__new__()
>>> types.NoneType.__new__(types.NoneType)
TypeError: object.__new__(NoneType) is not safe, use NoneType.__new__()

This seems pretty hardened and mad-scientist-proof to me, but I am not sure I have tried hard enough. (I have tested this in Python 2.7, but since Python 3+ have been designed to be even more foolproof than Python 2, my guess is the results won't be better.)

Can you actually create a separate duplicate of a Python singleton?

Body:
If you could create a "duplicate copy" of a singleton, it wouldn't really be a singleton anymore, would it ?

wrt/ builtin singletons (like None) which are implemented in C (or whatever the language for a given implementation), I don't think you can ever expect to "clone" them except by either fork Python or some similarly extreme method. Also note that since the Python language specs explicitely garantees that None is a singleton, this wouldn't be Python anymore ;)

Now if all you want is something that is a singleton and compares equal to None while not being None, here's a possible (python 2.7.x) implementation:

def __mknone():
    _instance = [None]

    class NotNoneType(object):
        def __new__(cls):
            if _instance[0] is not None:
                raise TypeError("cannot create 'NotNoneType' instances")
            _instance[0] =  object.__new__(cls)
            return _instance[0]

        def __eq__(self, other):
            if other is None:
                return True
            return other == _instance[0]

        def __nonzero__(self):
            return False

    return NotNoneType()

NotNone = __mknone()
NotNoneType = type(NotNone)
del __mknone

Tell me if you manage to create another instance of NotNoneType BTW ;)


问:
Joining a KTable with a KStream and nothing arrives in the output topic
I leftjoin a KStream with a KTable, but I don't see any output to the output topic:

```<code>  val stringSerde: Serde[String] = Serdes.String()
  val longSerde: Serde[java.lang.Long] = Serdes.Long()
  val genericRecordSerde: Serde[GenericRecord] = new GenericAvroSerde()

  val builder = new KStreamBuilder()

  val networkImprStream: KStream[Long, GenericRecord] = builder
    .stream(dfpGcsNetworkImprEnhanced)

  // Create a global table for advertisers. The data from this global table
  // will be fully replicated on each instance of this application.
  val advertiserTable: GlobalKTable[java.lang.Long, GenericRecord]= builder.globalTable(advertiserTopicName, "advertiser-store")

  // Join the network impr stream to the advertiser global table. As this is global table
  // we can use a non-key based join with out needing to repartition the input stream
  val networkImprWithAdvertiserNameKStream: KStream[java.lang.Long, GenericRecord] = networkImprStream.leftJoin(advertiserTable,
    (_, networkImpr) => {
      println(networkImpr)
      networkImpr.get("advertiserId").asInstanceOf[java.lang.Long]
    },
    (networkImpr: GenericRecord, adertiserIdToName: GenericRecord) => {
      println(networkImpr)
      networkImpr.put("advertiserName", adertiserIdToName.get("name"))
      networkImpr
    }
  )

  networkImprWithAdvertiserNameKStream.to(networkImprProcessed)

  val streams = new KafkaStreams(builder, streamsConfiguration)
  streams.cleanUp()
  streams.start()
  // usually the stream application would be running forever,
  // in this example we just let it run for some time and stop since the input data is finite.
  Thread.sleep(15000L)
</code>```

If I bypass the join and directly output the input topic to the output, I see messages arriving. I've already changed the join to a left join, added some printlns to see when the key is extracted (nothing is printed on the console though). Also I use the kafka streams reset tool every time, so starting from the beginning. I am running out of ideas here. Also I've added some test access to the store and it works and contains keys from the stream (although this should not prohibit any output because of the left join).

答:
In my source stream the key is null. Although I am not using this key to join the table this key must not be null. So creating an intermediate stream with a dummy key it works. So even I have a global KTable here the restrictions for the keys for the stream messages also apply here:
http://docs.confluent.io/current/streams/developer-guide.html#kstream-ktable-join

Input records for the stream with a null key or a null value are ignored and do not trigger the join.

Body:
I leftjoin a KStream with a KTable, but I don't see any output to the output topic:

  val stringSerde: Serde[String] = Serdes.String()
  val longSerde: Serde[java.lang.Long] = Serdes.Long()
  val genericRecordSerde: Serde[GenericRecord] = new GenericAvroSerde()

  val builder = new KStreamBuilder()

  val networkImprStream: KStream[Long, GenericRecord] = builder
    .stream(dfpGcsNetworkImprEnhanced)

  // Create a global table for advertisers. The data from this global table
  // will be fully replicated on each instance of this application.
  val advertiserTable: GlobalKTable[java.lang.Long, GenericRecord]= builder.globalTable(advertiserTopicName, "advertiser-store")

  // Join the network impr stream to the advertiser global table. As this is global table
  // we can use a non-key based join with out needing to repartition the input stream
  val networkImprWithAdvertiserNameKStream: KStream[java.lang.Long, GenericRecord] = networkImprStream.leftJoin(advertiserTable,
    (_, networkImpr) => {
      println(networkImpr)
      networkImpr.get("advertiserId").asInstanceOf[java.lang.Long]
    },
    (networkImpr: GenericRecord, adertiserIdToName: GenericRecord) => {
      println(networkImpr)
      networkImpr.put("advertiserName", adertiserIdToName.get("name"))
      networkImpr
    }
  )

  networkImprWithAdvertiserNameKStream.to(networkImprProcessed)

  val streams = new KafkaStreams(builder, streamsConfiguration)
  streams.cleanUp()
  streams.start()
  // usually the stream application would be running forever,
  // in this example we just let it run for some time and stop since the input data is finite.
  Thread.sleep(15000L)

If I bypass the join and directly output the input topic to the output, I see messages arriving. I've already changed the join to a left join, added some printlns to see when the key is extracted (nothing is printed on the console though). Also I use the kafka streams reset tool every time, so starting from the beginning. I am running out of ideas here. Also I've added some test access to the store and it works and contains keys from the stream (although this should not prohibit any output because of the left join).


问:
prediction plot with intervals
I was attempting to create a prediction interval that includes the prediction for my model ( negative binomial). The model is :

```<code>Call:
glm.nb(formula = TOT.N ~ D.PARK + OPEN.L + L.WAT.C + sqrt(L.P.ROAD),
    init.theta = 4.979895131, link = log)

Deviance Residuals:
     Min        1Q    Median        3Q       Max
-3.08218  -0.70494  -0.09268   0.55575   1.67860

Coefficients:
                 Estimate Std. Error z value Pr(>|z|)
(Intercept)     4.032e+00  3.363e-01  11.989  < 2e-16 ***
D.PARK         -1.154e-04  1.061e-05 -10.878  < 2e-16 ***
OPEN.L         -1.085e-02  3.122e-03  -3.475  0.00051 ***
L.WAT.C         1.597e-01  7.852e-02   2.034  0.04195 *
sqrt(L.P.ROAD)  4.924e-01  3.101e-01   1.588  0.11231
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

(Dispersion parameter for Negative Binomial(4.9799) family taken to be 1)

    Null deviance: 197.574  on 51  degrees of freedom
Residual deviance:  51.329  on 47  degrees of freedom
AIC: 383.54

Number of Fisher Scoring iterations: 1
</code>```

I have firslt created an observed vs. predicted plot (below). From this plot i would say that the predicted data seems to fit well the actual data.

Then i am attempting to make prediction plot with condifence intervals. For this i have decided to let the variable OPEN.L to vary, while other variables are kept constant - on their mean. The code I have used is the following:

```<code>  varying OPEN.L
  minOPEN.L <- min(OPEN.L)
  maxOPEN.L <- max(OPEN.L)
  grid <- seq(minOPEN.L, maxOPEN.L, 1)
  mean.D.PARK <- mean(D.PARK)

  new <- data.frame(D.PARK = mean.D.PARK, OPEN.L = grid, L.WAT.C = mean.L.WAT.C, L.P.ROAD = mean.L.P.ROAD)

  confidece.kills <- predict(final.model, new, se = T, interval = "confidence")
  predict.kills <- predict(final.model, new, se = T, interval = "prediction")

  par(mfrow=c(1, 2), pty="m")
  matplot(grid, predict.kills$fit ,lty=c(1,2,2),type="l",lwd=3,
          xlab="OPEN.L",ylab="TOT.N",
          cex.lab=1.5,cex.axis=1.3)
</code>```

There is nothing to see on the plot (below):

dput(head(road.data, 55))

```<code>    dput(head(road.data, 55))
structure(list(TOT.N = c(22L, 14L, 65L, 55L, 88L, 104L, 49L,
66L, 26L, 47L, 35L, 55L, 44L, 30L, 33L, 29L, 34L, 64L, 76L, 32L,
34L, 32L, 35L, 22L, 34L, 25L, 18L, 14L, 14L, 7L, 7L, 17L, 10L,
3L, 6L, 5L, 2L, 3L, 2L, 2L, 7L, 3L, 5L, 4L, 7L, 12L, 7L, 14L,
10L, 4L, 11L, 3L), OPEN.L = c(22.684, 24.657, 30.121, 50.277,
43.609, 31.385, 24.81, 56.228, 48.735, 15.633, 9.999, 39.942,
10.382, 2.507, 0.738, 15.725, 43.866, 45.102, 39.46, 19.988,
13.369, 6.848, 2.946, 3.219, 3.218, 34.168, 22.839, 7.258, 8.513,
23.394, 26.945, 71.436, 62.203, 82.391, 97.574, 94.947, 89.294,
68.779, 62.173, 67.834, 67.618, 83.357, 70.684, 30.907, 26.687,
9.571, 26.687, 16.478, 26.365, 39.609, 33.511, 24.438), MONT.S = c(0,
0, 0.258, 1.783, 2.431, 0, 0, 0, 1.108, 0, 0, 0, 0, 0, 0, 0,
0, 0, 5.235, 3.658, 5.049, 0.224, 9.426, 0, 0, 0, 0, 0, 0.763,
7.134, 0, 0, 1.039, 4.326, 0, 0, 0, 0, 0, 0, 0, 1.455, 0, 0,
0, 4.347, 0, 1.376, 4.347, 1.796, 0, 0.259), POLIC = c(4.811,
2.224, 1.946, 0.625, 0.791, 0.054, 0.022, 11.263, 1.238, 0.119,
0.024, 0, 0.038, 0, 0, 0, 0.06, 0.125, 1.7, 0, 0.308, 0.364,
0.013, 0, 0, 0, 0.529, 0.313, 0.063, 0.202, 0, 0, 0, 0, 0.206,
0.259, 0.278, 0.812, 0.03, 0.018, 0.206, 0.375, 0.086, 0.05,
0.06, 0, 0.06, 0, 0, 0.044, 1.861, 0.151), D.PARK = c(250.214,
741.179, 1240.08, 1739.885, 2232.13, 2724.089, 3215.511, 3709.401,
4206.477, 4704.176, 5202.328, 5700.669, 6199.342, 6698.151, 7187.762,
7668.833, 8152.155, 8633.224, 9101.411, 9573.578, 10047.63, 10523.939,
11002.496, 11482.896, 11976.232, 12470.968, 12968.285, 13465.914,
13961.321, 14432.954, 14904.995, 15377.983, 15854.389, 16335.936,
16810.109, 17235.045, 17673.064, 18167.269, 18656.949, 19149.507,
19645.717, 20141.987, 20640.729, 21138.903, 21631.542, 22119.102,
22613.647, 23113.45, 23606.088, 24046.886, 24444.874, 24884.803
), SHRUB = c(0.406, 0.735, 0.474, 0.607, 0.173, 0.325, 0.055,
0.092, 1.744, 0, 0.67, 0.783, 0, 0.178, 0, 0, 0.094, 0.107, 0.702,
0.827, 1.025, 0, 0.01, 0.012, 0.088, 0.02, 0.087, 0.116, 0.062,
0, 0, 0.033, 0.133, 0.047, 0.077, 0.182, 0.067, 0.208, 0.063,
0.122, 0.038, 0.095, 0, 0.02, 0.064, 0.137, 0.064, 0.214, 0.14,
0.622, 0, 0.18), WAT.RES = c(0.043, 0.182, 0.453, 0.026, 0, 0.039,
0.114, 0.224, 0.177, 0, 6.309, 2.26, 0.137, 0, 0, 0.402, 0.077,
0.042, 0, 0.479, 0.36, 0, 0.078, 0, 0, 0, 0.188, 0, 0, 0, 0.213,
2.452, 0.061, 0, 0, 0, 0.284, 0.579, 0.215, 0, 0, 0, 0.127, 0,
0.198, 0.473, 0.198, 0, 0, 0, 0, 0.319), L.WAT.C = c(583, 1419,
2005, 1924, 2167, 2391, 1165, 2428, 2416, 211, 292, 650, 1896,
2194, 1375, 0, 1655, 1702, 2721, 1694, 1192, 589, 476, 345, 1621,
1023, 357, 0, 0, 7, 878, 883, 1921, 1479, 1237, 1898, 3951, 1931,
1365, 591, 868, 1198, 2334, 3525, 3087, 2444, 3087, 3934, 2214,
2122, 1290, 2471), L.P.ROAD = c(1975, 1761, 1250, 666, 653, 1309,
685, 677, 664, 654, 696, 678, 652, 665, 655, 627, 1159, 2201,
2290, 1617, 866, 640, 620, 645, 853, 1370, 631, 603, 609, 605,
1374, 685, 594, 1075, 595, 676, 684, 733, 1739, 891, 730, 652,
668, 645, 602, 571, 602, 953, 765, 1578, 2960, 1407), D.WAT.COUR = c(735,
134.052, 269.029, 48.751, 126.102, 344.444, 95.133, 243.23, 187.084,
236.004, 15.184, 118.865, 332.257, 28.498, 168.818, 560, 104.839,
204.943, 256.812, 566.152, 689.823, 694, 300, 132.934, 253.305,
34.119, 515.233, 825, 1165, 1025, 754.938, 585, 137.112, 80.916,
35.426, 43, 31.01, 290.029, 68.496, 405, 785, 257, 118.579, 237.041,
45.832, 44.744, 120.855, 24.313, 178.837, 21.336, 111.764, 225.514
)), .Names = c("TOT.N", "OPEN.L", "MONT.S", "POLIC", "D.PARK",
"SHRUB", "WAT.RES", "L.WAT.C", "L.P.ROAD", "D.WAT.COUR"), row.names = c(NA,
-52L), class = c("tbl_df", "tbl", "data.frame"))
</code>```

How can i obtain the prediction plot with the corresponding prediction intervals?

any input - comments, constructive critique, tipps - is appriciated. thanks

答:
You can approximate the interval yourself like this:

```<code>attach(road.data)
library("MASS")
final.model <- glm.nb(formula = TOT.N ~ D.PARK + OPEN.L + L.WAT.C + sqrt(L.P.ROAD),
       init.theta = 4.979895131, link = log)

minOPEN.L <- min(OPEN.L)
maxOPEN.L <- max(OPEN.L)
grid <- seq(minOPEN.L, maxOPEN.L, 1)
mean.D.PARK <- mean(D.PARK)
mean.L.WAT.C <- mean(L.WAT.C)
mean.L.P.ROAD <- mean(L.P.ROAD)

new <- data.frame(D.PARK = mean.D.PARK, OPEN.L = grid, L.WAT.C = mean.L.WAT.C, L.P.ROAD = mean.L.P.ROAD)

predict.kills <- predict(final.model, new, se = T, interval = "prediction")

alpha <- 0.05 ## you want a 95% interval
z <- qnorm(1 - alpha / 2)
lower <- predict.kills$fit - z * predict.kills$se.fit
upper <- predict.kills$fit + z * predict.kills$se.fit

par(mfrow=c(1, 2), pty="m")
matplot(grid, cbind(predict.kills$fit, lower, upper) ,lty=c(1,2,2),type="l",lwd=3,
        xlab="OPEN.L",ylab="log(TOT.N)",
        cex.lab=1.5,cex.axis=1.3)

matplot(grid, exp(cbind(predict.kills$fit, lower, upper)) ,lty=c(1,2,2),type="l",lwd=3,
        xlab="OPEN.L",ylab="TOT.N",
        cex.lab=1.5,cex.axis=1.3)
</code>```

And you will get your result like this:

Title: prediction plot with intervals

Body:
I was attempting to create a prediction interval that includes the prediction for my model ( negative binomial). The model is :

Call:
glm.nb(formula = TOT.N ~ D.PARK + OPEN.L + L.WAT.C + sqrt(L.P.ROAD),
    init.theta = 4.979895131, link = log)

Deviance Residuals:
     Min        1Q    Median        3Q       Max
-3.08218  -0.70494  -0.09268   0.55575   1.67860

Coefficients:
                 Estimate Std. Error z value Pr(>|z|)
(Intercept)     4.032e+00  3.363e-01  11.989  < 2e-16 ***
D.PARK         -1.154e-04  1.061e-05 -10.878  < 2e-16 ***
OPEN.L         -1.085e-02  3.122e-03  -3.475  0.00051 ***
L.WAT.C         1.597e-01  7.852e-02   2.034  0.04195 *
sqrt(L.P.ROAD)  4.924e-01  3.101e-01   1.588  0.11231
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

(Dispersion parameter for Negative Binomial(4.9799) family taken to be 1)

    Null deviance: 197.574  on 51  degrees of freedom
Residual deviance:  51.329  on 47  degrees of freedom
AIC: 383.54

Number of Fisher Scoring iterations: 1

I have firslt created an observed vs. predicted plot (below). From this plot i would say that the predicted data seems to fit well the actual data.

Then i am attempting to make prediction plot with condifence intervals. For this i have decided to let the variable OPEN.L to vary, while other variables are kept constant - on their mean. The code I have used is the following:

  varying OPEN.L
  minOPEN.L <- min(OPEN.L)
  maxOPEN.L <- max(OPEN.L)
  grid <- seq(minOPEN.L, maxOPEN.L, 1)
  mean.D.PARK <- mean(D.PARK)

  new <- data.frame(D.PARK = mean.D.PARK, OPEN.L = grid, L.WAT.C = mean.L.WAT.C, L.P.ROAD = mean.L.P.ROAD)

  confidece.kills <- predict(final.model, new, se = T, interval = "confidence")
  predict.kills <- predict(final.model, new, se = T, interval = "prediction")

  par(mfrow=c(1, 2), pty="m")
  matplot(grid, predict.kills$fit ,lty=c(1,2,2),type="l",lwd=3,
          xlab="OPEN.L",ylab="TOT.N",
          cex.lab=1.5,cex.axis=1.3)

There is nothing to see on the plot (below):

dput(head(road.data, 55))

    dput(head(road.data, 55))
structure(list(TOT.N = c(22L, 14L, 65L, 55L, 88L, 104L, 49L,
66L, 26L, 47L, 35L, 55L, 44L, 30L, 33L, 29L, 34L, 64L, 76L, 32L,
34L, 32L, 35L, 22L, 34L, 25L, 18L, 14L, 14L, 7L, 7L, 17L, 10L,
3L, 6L, 5L, 2L, 3L, 2L, 2L, 7L, 3L, 5L, 4L, 7L, 12L, 7L, 14L,
10L, 4L, 11L, 3L), OPEN.L = c(22.684, 24.657, 30.121, 50.277,
43.609, 31.385, 24.81, 56.228, 48.735, 15.633, 9.999, 39.942,
10.382, 2.507, 0.738, 15.725, 43.866, 45.102, 39.46, 19.988,
13.369, 6.848, 2.946, 3.219, 3.218, 34.168, 22.839, 7.258, 8.513,
23.394, 26.945, 71.436, 62.203, 82.391, 97.574, 94.947, 89.294,
68.779, 62.173, 67.834, 67.618, 83.357, 70.684, 30.907, 26.687,
9.571, 26.687, 16.478, 26.365, 39.609, 33.511, 24.438), MONT.S = c(0,
0, 0.258, 1.783, 2.431, 0, 0, 0, 1.108, 0, 0, 0, 0, 0, 0, 0,
0, 0, 5.235, 3.658, 5.049, 0.224, 9.426, 0, 0, 0, 0, 0, 0.763,
7.134, 0, 0, 1.039, 4.326, 0, 0, 0, 0, 0, 0, 0, 1.455, 0, 0,
0, 4.347, 0, 1.376, 4.347, 1.796, 0, 0.259), POLIC = c(4.811,
2.224, 1.946, 0.625, 0.791, 0.054, 0.022, 11.263, 1.238, 0.119,
0.024, 0, 0.038, 0, 0, 0, 0.06, 0.125, 1.7, 0, 0.308, 0.364,
0.013, 0, 0, 0, 0.529, 0.313, 0.063, 0.202, 0, 0, 0, 0, 0.206,
0.259, 0.278, 0.812, 0.03, 0.018, 0.206, 0.375, 0.086, 0.05,
0.06, 0, 0.06, 0, 0, 0.044, 1.861, 0.151), D.PARK = c(250.214,
741.179, 1240.08, 1739.885, 2232.13, 2724.089, 3215.511, 3709.401,
4206.477, 4704.176, 5202.328, 5700.669, 6199.342, 6698.151, 7187.762,
7668.833, 8152.155, 8633.224, 9101.411, 9573.578, 10047.63, 10523.939,
11002.496, 11482.896, 11976.232, 12470.968, 12968.285, 13465.914,
13961.321, 14432.954, 14904.995, 15377.983, 15854.389, 16335.936,
16810.109, 17235.045, 17673.064, 18167.269, 18656.949, 19149.507,
19645.717, 20141.987, 20640.729, 21138.903, 21631.542, 22119.102,
22613.647, 23113.45, 23606.088, 24046.886, 24444.874, 24884.803
), SHRUB = c(0.406, 0.735, 0.474, 0.607, 0.173, 0.325, 0.055,
0.092, 1.744, 0, 0.67, 0.783, 0, 0.178, 0, 0, 0.094, 0.107, 0.702,
0.827, 1.025, 0, 0.01, 0.012, 0.088, 0.02, 0.087, 0.116, 0.062,
0, 0, 0.033, 0.133, 0.047, 0.077, 0.182, 0.067, 0.208, 0.063,
0.122, 0.038, 0.095, 0, 0.02, 0.064, 0.137, 0.064, 0.214, 0.14,
0.622, 0, 0.18), WAT.RES = c(0.043, 0.182, 0.453, 0.026, 0, 0.039,
0.114, 0.224, 0.177, 0, 6.309, 2.26, 0.137, 0, 0, 0.402, 0.077,
0.042, 0, 0.479, 0.36, 0, 0.078, 0, 0, 0, 0.188, 0, 0, 0, 0.213,
2.452, 0.061, 0, 0, 0, 0.284, 0.579, 0.215, 0, 0, 0, 0.127, 0,
0.198, 0.473, 0.198, 0, 0, 0, 0, 0.319), L.WAT.C = c(583, 1419,
2005, 1924, 2167, 2391, 1165, 2428, 2416, 211, 292, 650, 1896,
2194, 1375, 0, 1655, 1702, 2721, 1694, 1192, 589, 476, 345, 1621,
1023, 357, 0, 0, 7, 878, 883, 1921, 1479, 1237, 1898, 3951, 1931,
1365, 591, 868, 1198, 2334, 3525, 3087, 2444, 3087, 3934, 2214,
2122, 1290, 2471), L.P.ROAD = c(1975, 1761, 1250, 666, 653, 1309,
685, 677, 664, 654, 696, 678, 652, 665, 655, 627, 1159, 2201,
2290, 1617, 866, 640, 620, 645, 853, 1370, 631, 603, 609, 605,
1374, 685, 594, 1075, 595, 676, 684, 733, 1739, 891, 730, 652,
668, 645, 602, 571, 602, 953, 765, 1578, 2960, 1407), D.WAT.COUR = c(735,
134.052, 269.029, 48.751, 126.102, 344.444, 95.133, 243.23, 187.084,
236.004, 15.184, 118.865, 332.257, 28.498, 168.818, 560, 104.839,
204.943, 256.812, 566.152, 689.823, 694, 300, 132.934, 253.305,
34.119, 515.233, 825, 1165, 1025, 754.938, 585, 137.112, 80.916,
35.426, 43, 31.01, 290.029, 68.496, 405, 785, 257, 118.579, 237.041,
45.832, 44.744, 120.855, 24.313, 178.837, 21.336, 111.764, 225.514
)), .Names = c("TOT.N", "OPEN.L", "MONT.S", "POLIC", "D.PARK",
"SHRUB", "WAT.RES", "L.WAT.C", "L.P.ROAD", "D.WAT.COUR"), row.names = c(NA,
-52L), class = c("tbl_df", "tbl", "data.frame"))

How can i obtain the prediction plot with the corresponding prediction intervals?

any input - comments, constructive critique, tipps - is appriciated. thanks

Body:
You can approximate the interval yourself like this:

attach(road.data)
library("MASS")
final.model <- glm.nb(formula = TOT.N ~ D.PARK + OPEN.L + L.WAT.C + sqrt(L.P.ROAD),
       init.theta = 4.979895131, link = log)

minOPEN.L <- min(OPEN.L)
maxOPEN.L <- max(OPEN.L)
grid <- seq(minOPEN.L, maxOPEN.L, 1)
mean.D.PARK <- mean(D.PARK)
mean.L.WAT.C <- mean(L.WAT.C)
mean.L.P.ROAD <- mean(L.P.ROAD)

new <- data.frame(D.PARK = mean.D.PARK, OPEN.L = grid, L.WAT.C = mean.L.WAT.C, L.P.ROAD = mean.L.P.ROAD)

predict.kills <- predict(final.model, new, se = T, interval = "prediction")

alpha <- 0.05 ## you want a 95% interval
z <- qnorm(1 - alpha / 2)
lower <- predict.kills$fit - z * predict.kills$se.fit
upper <- predict.kills$fit + z * predict.kills$se.fit

par(mfrow=c(1, 2), pty="m")
matplot(grid, cbind(predict.kills$fit, lower, upper) ,lty=c(1,2,2),type="l",lwd=3,
        xlab="OPEN.L",ylab="log(TOT.N)",
        cex.lab=1.5,cex.axis=1.3)

matplot(grid, exp(cbind(predict.kills$fit, lower, upper)) ,lty=c(1,2,2),type="l",lwd=3,
        xlab="OPEN.L",ylab="TOT.N",
        cex.lab=1.5,cex.axis=1.3)

And you will get your result like this:


问:
How to check application state under swift UI Test

Some background

I am currently writing a UI Test for a settings pane, and click on buttons to enable certain permissions such as push notifications and location services.

However, if the alert for the permission has been displayed before (regardless of the user allowing or denying access to the permission), the alert will not display again, and will just take the user to the settings app. Unfortunately, these settings do not reset, meaning the first time I run the UI tests, alerts will show; and on all subsequent UI test runs, the buttons will take me to the settings app unless I reset the device before the tests begin.

My issue

Thus, my test needs to know if the app went into the background, and attempt to foreground it to continue the testing:

```<code>if app.state == background {
    foregroundApp()
}

// continue with other tests
</code>```

Is there any way to determine if the app is in the background?

What I tried

I researched methods to determine the state of the application (running/background/etc) from a UI test, and was not able to find much. I tried to check whether certain elements exist:

```<code>if (app.navigationBars.element.exists) ...
</code>```

but this gives me runtime errors[1] if the user is taken to the settings page because the app under test is in the background, and the test cannot lookup the navigationBars (or other elements).

I tried using some of the methods from Facebook's private headers for XCUIApplication() and XCUIElement().

XCUIApplication().state always returns 3 no matter what state the app is currently in, and any attempts to call XCUIApplication().resolve() to foreground the app give me the same errors as before[1]

I tried to rewrite the logic to foreground the app before resuming the tests, but methods such as XCUIApplication().launch() kill the app before restarting, which I cannot do. Only siri service seems to work for me, but I cannot access the siri service through the corporate proxy, and modifying proxy permissions is not possible.

Is there any other way to check the app state?

Errors

[1] This error is printed every time I try to do something involving state. I do not call snapshotView anywhere, and thus the suggestion to use afterScreenUpdates is useless.

```<code>Failure to get snapshot within 15.0s
Cannot snapshot view (<UIKeyboardImpl: 0x7febcc75d000; frame = (0 0;
  414 226); layer = <CALayer: 0x608000625720>>) with
  afterScreenUpdates:NO, because the view is not in a window. Use
  afterScreenUpdates:YES.`
</code>```

tl;dr

I need to check whether the app I am UI testing has entered the background (i.e. user pressed the home button). Checking for existence of particular elements such as navigation bars doesn't work, neither do most methods from Facebook's private headers for XCUIApplication/XCUIElement. Foregrounding the app also causes issues, and relaunching the app is not an option; neither is siri service.

答: You can do this in Swift 4, using XCUIApplication.state, which will give you information about the state of the app - whether it's in the foreground or background etc. however, it's not possible to find this information in Swift 3 and below. Essentially, UI testing in Swift 3 doesn't support leaving the app.

Body:
Some background

I am currently writing a UI Test for a settings pane, and click on buttons to enable certain permissions such as push notifications and location services.

However, if the alert for the permission has been displayed before (regardless of the user allowing or denying access to the permission), the alert will not display again, and will just take the user to the settings app. Unfortunately, these settings do not reset, meaning the first time I run the UI tests, alerts will show; and on all subsequent UI test runs, the buttons will take me to the settings app unless I reset the device before the tests begin.

My issue

Thus, my test needs to know if the app went into the background, and attempt to foreground it to continue the testing:

if app.state == background {
    foregroundApp()
}

// continue with other tests

Is there any way to determine if the app is in the background?

What I tried

I researched methods to determine the state of the application (running/background/etc) from a UI test, and was not able to find much. I tried to check whether certain elements exist:

if (app.navigationBars.element.exists) ...

but this gives me runtime errors[1] if the user is taken to the settings page because the app under test is in the background, and the test cannot lookup the navigationBars (or other elements).

I tried using some of the methods from Facebook's private headers for XCUIApplication() and XCUIElement().

XCUIApplication().state always returns 3 no matter what state the app is currently in, and any attempts to call XCUIApplication().resolve() to foreground the app give me the same errors as before[1]

I tried to rewrite the logic to foreground the app before resuming the tests, but methods such as XCUIApplication().launch() kill the app before restarting, which I cannot do. Only siri service seems to work for me, but I cannot access the siri service through the corporate proxy, and modifying proxy permissions is not possible.

Is there any other way to check the app state?

Errors

[1] This error is printed every time I try to do something involving state. I do not call snapshotView anywhere, and thus the suggestion to use afterScreenUpdates is useless.

Failure to get snapshot within 15.0s
Cannot snapshot view (<UIKeyboardImpl: 0x7febcc75d000; frame = (0 0;
  414 226); layer = <CALayer: 0x608000625720>>) with
  afterScreenUpdates:NO, because the view is not in a window. Use
  afterScreenUpdates:YES.`

tl;dr

I need to check whether the app I am UI testing has entered the background (i.e. user pressed the home button). Checking for existence of particular elements such as navigation bars doesn't work, neither do most methods from Facebook's private headers for XCUIApplication/XCUIElement. Foregrounding the app also causes issues, and relaunching the app is not an option; neither is siri service.


问:
TypeError: 'in <string>' requires string as left operand, not method PYTHON
When trying to run my code, I am presented with a TypeError.
It states: TypeError:'in'requires string as left operand, not method.

I am not sure what this means exactly, or how to fix it.

The code the error is created in is:

```<code>from tkinter import *
from tkinter import messagebox

def saveCustomer() :

    ClientID = ClientIDVar.get()
    ClientID = ClientID.ljust(50)
    Surname = SurnameVar.get()
    Surname = Surname.ljust(50)
    Forename = ForenameVar.get()
    Forename = Forename.ljust(50)
    Age = AgeVar.get()
    Age = Age.ljust(50)
    Gender = GenderVar.get()
    Gender = Gender.ljust(50)

    #lengthcheck
    ClientID = ClientIDVar.get()
    if len(ClientID) > 5 :
        messagebox.showerror("Error","Too many characters in ClientID")
        return
    Surname = SurnameVar.get()
    if len(Surname) > 20 :
        messagebox.showerror("Error","Too many characters in Surname")
        return
    Forename = ForenameVar.get()
    if len(Forename) > 15 :
        messagebox.showerror("Error","Too many characters in Forename")
        return
    Age = AgeVar.get()
    if len(Age) > 2 :
        messagebox.showerror("Error","Too many characters in Age")
        return
    Gender = GenderVar.get()
    if len(Gender) > 2 :
        messagebox.showerror("Error","Too many characters in Gender")
        return
    #presencecheck
    if ClientID == "":
        messagebox.showerror("Error","Please enter characters into ClientID")
        return
    if Surname == "":
        messagebox.showerror("Error","Please enter characters into Surname")
        return
    if Forename == "":
        messagebox.showerror("Error","Please enter characters into Forename")
        return
    if Age == "":
       messagebox.showerror("Error","Please enter characters into Age")
        return
    if Gender == "":
        messagebox.showerror("Error","Please enter characters into Gender")
        return
    #rangecheck
    if (int(Age) < 18) or (int(Age) > 99):
        messagebox.showerror("Error","Please enter an age between 18 and 99")
        return
    #typecheck
    if not ClientID.isnumeric():
        messagebox.showerror("Error","Please enter alphabetical characters and numerical values into ClientID")
        return
    if not Surname.isalpha():
        messagebox.showerror("Error","Please enter alphabetical characters into Surname")
        return
    if not Forename.isalpha():
        messagebox.showerror("Error","Please enter alphabetical characters into Forename")
        return
    if not Age.isnumeric():
        messagebox.showerror("Error","Please enter numerical values into Age")
        return
    if not Gender.isalpha():
        messagebox.showerror("Error","Please enter alphabetical characters and numerical values into Gender")
        return

    #open the file to append - if it's not there it'll be created
    fileObject = open("Customers.txt","a")
    # write to the file with a newline character at the end
    fileObject.write(ClientID + Surname + Forename + Age + Gender + "\n")
    fileObject.close()

    return

def searchCustomer() :
    Found = "N"
    ClientID = ClientIDVar.get
    # try opening the file for reading
    try:
        fileObject=open("Customers.txt","r")

    # if it's not there then say
    except IOError:
        messagebox.showerror("Error","No file to read")

    # if we did open it then let's carry on!
    else:
        while True:

            recordVar=fileObject.readline()
            # Python keeps reading till EOF then returns a blank
            if recordVar=="":
                fileObject.close()
                break

            if ClientID in recordVar[0:50] and not ClientID=="" :
                Found = "T"
                messagebox.showinfo("Information",str(RecordVar))
                break

    if Found == "F":
        messagebox.showerror("Error","No Customer found.")
    return

def makeWindow():
    #declared my globals here as this is the 1st routine called
    # the other routines have to be in front of this one as they get called by it
    # and the parser would get upset if they weren't there

    global ClientIDVar, SurnameVar, ForenameVar, AgeVar, GenderVar

    #here's my window
    win = Tk()
    win.wm_title("FitnessCentre")
    #split into two sections then further split into a grid
    frame1=Frame(win)
    frame1.pack()

    Label(frame1, text="Fitness Leisure Centre", font=("Helvetica 12             bold")).grid(row=0, column=0)

    Label(frame1, text="ClientID").grid(row=1, column=0, sticky=W)
    ClientIDVar=StringVar()
    title= Entry(frame1, textvariable=ClientIDVar)
    title.grid(row=1,column=1,sticky=W)

    Label(frame1, text="Surname").grid(row=2, column=0, sticky=W)
    SurnameVar=StringVar()
    genre= Entry(frame1, textvariable=SurnameVar)
    genre.grid(row=2,column=1,sticky=W)

    Label(frame1, text="Forename").grid(row=3, column=0, sticky=W)
    ForenameVar=StringVar()
    director= Entry(frame1, textvariable=ForenameVar)
    director.grid(row=3,column=1,sticky=W)

    Label(frame1, text="Age").grid(row=4, column=0, sticky=W)
    AgeVar=StringVar()
    leadactor= Entry(frame1, textvariable=AgeVar)
    leadactor.grid(row=4,column=1,sticky=W)

    Label(frame1, text="Gender").grid(row=5, column=0, sticky=W)
    GenderVar=StringVar()
    duration= Entry(frame1, textvariable=GenderVar)
    duration.grid(row=5,column=1,sticky=W)

    frame2 = Frame(win)
    frame2.pack()

    # build my buttons in the other frame then pack them side by side
    b1= Button(frame2, text=" Save ", command=saveCustomer)
    b2= Button(frame2, text=" Search ", command=searchCustomer)
    b1.pack(side=LEFT); b2.pack(side=LEFT)

    return win

#main program!
win = makeWindow()
win.mainloop()
</code>```

The complete error message I received was:

```<code>Exception in Tkinter callback
Traceback (most recent call last):

if ClientID in recordVar[0:50] and not ClientID=="" :
TypeError: 'in <string>' requires string as left operand, not method
</code>```

答:
Quoting from question:

TypeError: 'in' requires string as left operand, not method.

So somewhere you are using the in operator with a method on the left, not a string as expected. Had you posted the entire error/stack trace (as you should have done) we might have seen which line is causing the error. With a quick scan of your code I'd guess the error is here:

```<code>ClientID = ClientIDVar.get
</code>```

Presumably you wanted to return the value of the ClientIDVar, not its get method (which is what you got). So it's a simple fix -- call the function properly:

```<code>ClientID = ClientIDVar.get()
</code>```

Body:
When trying to run my code, I am presented with a TypeError.
It states: TypeError:'in'requires string as left operand, not method.

I am not sure what this means exactly, or how to fix it.

The code the error is created in is:

from tkinter import *
from tkinter import messagebox

def saveCustomer() :

    ClientID = ClientIDVar.get()
    ClientID = ClientID.ljust(50)
    Surname = SurnameVar.get()
    Surname = Surname.ljust(50)
    Forename = ForenameVar.get()
    Forename = Forename.ljust(50)
    Age = AgeVar.get()
    Age = Age.ljust(50)
    Gender = GenderVar.get()
    Gender = Gender.ljust(50)

    #lengthcheck
    ClientID = ClientIDVar.get()
    if len(ClientID) > 5 :
        messagebox.showerror("Error","Too many characters in ClientID")
        return
    Surname = SurnameVar.get()
    if len(Surname) > 20 :
        messagebox.showerror("Error","Too many characters in Surname")
        return
    Forename = ForenameVar.get()
    if len(Forename) > 15 :
        messagebox.showerror("Error","Too many characters in Forename")
        return
    Age = AgeVar.get()
    if len(Age) > 2 :
        messagebox.showerror("Error","Too many characters in Age")
        return
    Gender = GenderVar.get()
    if len(Gender) > 2 :
        messagebox.showerror("Error","Too many characters in Gender")
        return
    #presencecheck
    if ClientID == "":
        messagebox.showerror("Error","Please enter characters into ClientID")
        return
    if Surname == "":
        messagebox.showerror("Error","Please enter characters into Surname")
        return
    if Forename == "":
        messagebox.showerror("Error","Please enter characters into Forename")
        return
    if Age == "":
       messagebox.showerror("Error","Please enter characters into Age")
        return
    if Gender == "":
        messagebox.showerror("Error","Please enter characters into Gender")
        return
    #rangecheck
    if (int(Age) < 18) or (int(Age) > 99):
        messagebox.showerror("Error","Please enter an age between 18 and 99")
        return
    #typecheck
    if not ClientID.isnumeric():
        messagebox.showerror("Error","Please enter alphabetical characters and numerical values into ClientID")
        return
    if not Surname.isalpha():
        messagebox.showerror("Error","Please enter alphabetical characters into Surname")
        return
    if not Forename.isalpha():
        messagebox.showerror("Error","Please enter alphabetical characters into Forename")
        return
    if not Age.isnumeric():
        messagebox.showerror("Error","Please enter numerical values into Age")
        return
    if not Gender.isalpha():
        messagebox.showerror("Error","Please enter alphabetical characters and numerical values into Gender")
        return

    #open the file to append - if it's not there it'll be created
    fileObject = open("Customers.txt","a")
    # write to the file with a newline character at the end
    fileObject.write(ClientID + Surname + Forename + Age + Gender + "\n")
    fileObject.close()

    return

def searchCustomer() :
    Found = "N"
    ClientID = ClientIDVar.get
    # try opening the file for reading
    try:
        fileObject=open("Customers.txt","r")

    # if it's not there then say
    except IOError:
        messagebox.showerror("Error","No file to read")

    # if we did open it then let's carry on!
    else:
        while True:

            recordVar=fileObject.readline()
            # Python keeps reading till EOF then returns a blank
            if recordVar=="":
                fileObject.close()
                break

            if ClientID in recordVar[0:50] and not ClientID=="" :
                Found = "T"
                messagebox.showinfo("Information",str(RecordVar))
                break

    if Found == "F":
        messagebox.showerror("Error","No Customer found.")
    return

def makeWindow():
    #declared my globals here as this is the 1st routine called
    # the other routines have to be in front of this one as they get called by it
    # and the parser would get upset if they weren't there

    global ClientIDVar, SurnameVar, ForenameVar, AgeVar, GenderVar

    #here's my window
    win = Tk()
    win.wm_title("FitnessCentre")
    #split into two sections then further split into a grid
    frame1=Frame(win)
    frame1.pack()

    Label(frame1, text="Fitness Leisure Centre", font=("Helvetica 12             bold")).grid(row=0, column=0)

    Label(frame1, text="ClientID").grid(row=1, column=0, sticky=W)
    ClientIDVar=StringVar()
    title= Entry(frame1, textvariable=ClientIDVar)
    title.grid(row=1,column=1,sticky=W)

    Label(frame1, text="Surname").grid(row=2, column=0, sticky=W)
    SurnameVar=StringVar()
    genre= Entry(frame1, textvariable=SurnameVar)
    genre.grid(row=2,column=1,sticky=W)

    Label(frame1, text="Forename").grid(row=3, column=0, sticky=W)
    ForenameVar=StringVar()
    director= Entry(frame1, textvariable=ForenameVar)
    director.grid(row=3,column=1,sticky=W)

    Label(frame1, text="Age").grid(row=4, column=0, sticky=W)
    AgeVar=StringVar()
    leadactor= Entry(frame1, textvariable=AgeVar)
    leadactor.grid(row=4,column=1,sticky=W)

    Label(frame1, text="Gender").grid(row=5, column=0, sticky=W)
    GenderVar=StringVar()
    duration= Entry(frame1, textvariable=GenderVar)
    duration.grid(row=5,column=1,sticky=W)

    frame2 = Frame(win)
    frame2.pack()

    # build my buttons in the other frame then pack them side by side
    b1= Button(frame2, text=" Save ", command=saveCustomer)
    b2= Button(frame2, text=" Search ", command=searchCustomer)
    b1.pack(side=LEFT); b2.pack(side=LEFT)

    return win

#main program!
win = makeWindow()
win.mainloop()

The complete error message I received was:

Exception in Tkinter callback
Traceback (most recent call last):

if ClientID in recordVar[0:50] and not ClientID=="" :
TypeError: 'in <string>' requires string as left operand, not method

Body:
Quoting from question:

TypeError: 'in' requires string as left operand, not method.

So somewhere you are using the in operator with a method on the left, not a string as expected. Had you posted the entire error/stack trace (as you should have done) we might have seen which line is causing the error. With a quick scan of your code I'd guess the error is here:

ClientID = ClientIDVar.get

Presumably you wanted to return the value of the ClientIDVar, not its get method (which is what you got). So it's a simple fix -- call the function properly:

ClientID = ClientIDVar.get()


问:
Why can't I specify the storage class for formal parameters of a function?
When I do as below the code works fine :

```<code>#include <stdio.h>
void test( int a)
{
 printf("a=%d\n",a);
}

int main()
{
    test(10);
    return 1;
}
</code>```

But when I do

```<code>#include <stdio.h>
void test( auto int a) // Or static int a Or extern int a
{
 printf("a=%d\n",a);
}

int main()
{
    test(10);
    return 1;
}
</code>```

It generates an error,

error: storage class specified for parameter 'a'

Why is that error? What happens internally(memory management)?

But it works fine without any error when I do:

```<code>void test( register int a)
{
 printf("a=%d\n",a);
}
</code>```

Why is that?

答:
First,quoting C11, chapter 6.7.6.3

The only storage-class specifier that shall occur in a parameter declaration is register.

So, this is explicitly specified in the standard.

That said, this restriction exists because with an explicit storage class like static/ extern, there will be problems in memory management, as function parameters are in the block scope for the function and their lifetimes are limited to the execution of the function body.

A parameter variable cannot outlive the call to the function; otherwise, what would be the effect of the argument in the next call to the same function? So static storage is not meaningful, and auto is redundant.

Since the function parameters has no linkage, extern also makes no sense.

Additionally, as mentioned in C11, for a hosted environment, the conforming signature for main() is int main(void), at least.

Body:
When I do as below the code works fine :

#include <stdio.h>
void test( int a)
{
 printf("a=%d\n",a);
}

int main()
{
    test(10);
    return 1;
}

But when I do

#include <stdio.h>
void test( auto int a) // Or static int a Or extern int a
{
 printf("a=%d\n",a);
}

int main()
{
    test(10);
    return 1;
}

It generates an error,

error: storage class specified for parameter 'a'

Why is that error? What happens internally(memory management)?

But it works fine without any error when I do:

void test( register int a)
{
 printf("a=%d\n",a);
}

Why is that?


问:
String startswith a particular text
I'm trying to read a csv file and I've to do column operations based on some condition.
Its completely ignoring my if condition and executes else statement.
Its a pain after lot of troubleshooting, i'm unable to rectify it.

Here is the code:

Tweet is my column name for tweets...

```<code>inf = pd.read_csv('string.csv')
for r in inf :
    if "RT @" in inf.Tweet :
        inf["Engagements"] = 0
    else :
        inf["Engagements"] = inf["Favorite_Count"] + inf["Retweet_Count"]

inf.to_csv('string2.csv', index=False)
</code>```

答:
In addition to the above concise answers, if you want to use a similar if else structure, you can use set_value to set the value of a specific row and column.

```<code>import pandas as pd
inf = pd.read_csv('string.csv')
for index,row in inf.iterrows():
    if "RT @" in row["Tweet"]:
        inf.set_value(index, "Engagements", 0)
    else:
        inf.set_value(index, "Engagements", row["Favorite_Count"] + row["Retweet_Count"])
inf.to_csv('string2.csv', index=False)
</code>```

Title: String startswith a particular text

Body:
I'm trying to read a csv file and I've to do column operations based on some condition.
Its completely ignoring my if condition and executes else statement.
Its a pain after lot of troubleshooting, i'm unable to rectify it.

Here is the code:

Tweet is my column name for tweets...

inf = pd.read_csv('string.csv')
for r in inf :
    if "RT @" in inf.Tweet :
        inf["Engagements"] = 0
    else :
        inf["Engagements"] = inf["Favorite_Count"] + inf["Retweet_Count"]

inf.to_csv('string2.csv', index=False)

Body:
In addition to the above concise answers, if you want to use a similar if else structure, you can use set_value to set the value of a specific row and column.

import pandas as pd
inf = pd.read_csv('string.csv')
for index,row in inf.iterrows():
    if "RT @" in row["Tweet"]:
        inf.set_value(index, "Engagements", 0)
    else:
        inf.set_value(index, "Engagements", row["Favorite_Count"] + row["Retweet_Count"])
inf.to_csv('string2.csv', index=False)


问:
c# override ToString() method in variable
Using this example code:

```<code>public class Product
{
    private Boolean _active;

    public Boolean active
    {
        get
        {
            return _active;
        }
        set
        {
            _active = value;
        }
    }
}

Product p = new Product();
p.active = true;
</code>```

How can I override the ToString() method so I can use this:

```<code>MessageBox.Show(p.active.ToString());
</code>```

答:
Why overriding the ToString of a variable instead of the ToString of the object? Can you explain more your scenario? Rather than create an extension method that will treat all the "bool" as "Yes" or "No" when you invoke the ToString on the variable, I suggest you to use the ToString of the object or use attributes to display your information

```<code>class Program
{
    static void Main(string[] args)
    {
        Product p = new Product();
        Console.WriteLine(p);
        Console.ReadLine();
    }
}

public class Product
{
    private Boolean _active;

    public Boolean active
    {
        get
        {
            return _active;
        }
        set
        {
            _active = value;
        }
    }

    public override string ToString()
    {
        return active ? "Yes" : "No";
    }
}
</code>```

If you want to use attributes, you can create an extension method with the approach described here https://stackoverflow.com/a/672212/819153

```<code>class Program
{
    static void Main(string[] args)
    {
        Product p = new Product();
        var attValue = Helper.ToStringProperty(p, prod => prod.active);
        Console.WriteLine(attValue);
        Console.ReadLine();
    }
}

public class Product
{
    private Boolean _active;

    [Display(Name = "Super Active")]
    public Boolean active
    {
        get
        {
            return _active;
        }
        set
        {
            _active = value;
        }
    }
}

public class Helper
{
    public static string ToStringProperty<TSource, TProperty>(TSource source,
        Expression<Func<TSource, TProperty>> propertyLambda)
    {
        Type type = typeof(TSource);

        MemberExpression member = propertyLambda.Body as MemberExpression;
        if (member == null)
            throw new ArgumentException(string.Format(
                "Expression '{0}' refers to a method, not a property.",
                propertyLambda.ToString()));

        PropertyInfo propInfo = member.Member as PropertyInfo;
        if (propInfo == null)
            throw new ArgumentException(string.Format(
                "Expression '{0}' refers to a field, not a property.",
                propertyLambda.ToString()));

        if (type != propInfo.ReflectedType &&
            !type.IsSubclassOf(propInfo.ReflectedType))
            throw new ArgumentException(string.Format(
                "Expresion '{0}' refers to a property that is not from type {1}.",
                propertyLambda.ToString(),
                type));

        var output = source.ToString();
        var attribute = propInfo.GetCustomAttributes(typeof(DisplayAttribute), false).Cast<DisplayAttribute>().FirstOrDefault();

        return attribute != null ? attribute.Name : output;
    }
}
</code>```

Body:
Using this example code:

public class Product
{
    private Boolean _active;

    public Boolean active
    {
        get
        {
            return _active;
        }
        set
        {
            _active = value;
        }
    }
}

Product p = new Product();
p.active = true;

How can I override the ToString() method so I can use this:

MessageBox.Show(p.active.ToString());

Body:
Why overriding the ToString of a variable instead of the ToString of the object? Can you explain more your scenario? Rather than create an extension method that will treat all the "bool" as "Yes" or "No" when you invoke the ToString on the variable, I suggest you to use the ToString of the object or use attributes to display your information

class Program
{
    static void Main(string[] args)
    {
        Product p = new Product();
        Console.WriteLine(p);
        Console.ReadLine();
    }
}

public class Product
{
    private Boolean _active;

    public Boolean active
    {
        get
        {
            return _active;
        }
        set
        {
            _active = value;
        }
    }

    public override string ToString()
    {
        return active ? "Yes" : "No";
    }
}

If you want to use attributes, you can create an extension method with the approach described here https://stackoverflow.com/a/672212/819153

class Program
{
    static void Main(string[] args)
    {
        Product p = new Product();
        var attValue = Helper.ToStringProperty(p, prod => prod.active);
        Console.WriteLine(attValue);
        Console.ReadLine();
    }
}

public class Product
{
    private Boolean _active;

    [Display(Name = "Super Active")]
    public Boolean active
    {
        get
        {
            return _active;
        }
        set
        {
            _active = value;
        }
    }
}

public class Helper
{
    public static string ToStringProperty<TSource, TProperty>(TSource source,
        Expression<Func<TSource, TProperty>> propertyLambda)
    {
        Type type = typeof(TSource);

        MemberExpression member = propertyLambda.Body as MemberExpression;
        if (member == null)
            throw new ArgumentException(string.Format(
                "Expression '{0}' refers to a method, not a property.",
                propertyLambda.ToString()));

        PropertyInfo propInfo = member.Member as PropertyInfo;
        if (propInfo == null)
            throw new ArgumentException(string.Format(
                "Expression '{0}' refers to a field, not a property.",
                propertyLambda.ToString()));

        if (type != propInfo.ReflectedType &&
            !type.IsSubclassOf(propInfo.ReflectedType))
            throw new ArgumentException(string.Format(
                "Expresion '{0}' refers to a property that is not from type {1}.",
                propertyLambda.ToString(),
                type));

        var output = source.ToString();
        var attribute = propInfo.GetCustomAttributes(typeof(DisplayAttribute), false).Cast<DisplayAttribute>().FirstOrDefault();

        return attribute != null ? attribute.Name : output;
    }
}


问:
Get button click inside UITableViewCell
I have a view controller with a table view and a separate nib for the table cell template. The cell template has some buttons. I want to access the button click along with the index of the cell clicked inside the view controller where I have defined the Table view.

So I have ViewController.h and ViewController.m where I have the UITableView and TableTemplate.h, TableTemplate.m and TableTemplate.xib where I have the nib defined. I want the button click event with cell index in ViewController.m.

Any help on how can I do that?

答:
```<code>cell.show.tag=indexPath.row;
     [cell.show addTarget:self action:@selector(showdata:) forControlEvents:UIControlEventTouchUpInside];

-(IBAction)showdata:(id)sender
{
    UIButton *button = (UIButton *)sender;

    UIStoryboard *storyBoard;
    storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    SecondViewController *detailView = [storyBoard instantiateViewControllerWithIdentifier:@"SecondViewController"];

    detailView.string=[NSString stringWithFormat:@"%@",[_array objectAtIndex:button.tag]];

    [self presentViewController:detailView animated:YES completion:nil];

}
</code>```

Title: Get button click inside UITableViewCell


问:
How get values from a select/option field in redux-form?
I am trying to get the values from my second form. It renders some select options and when I hit the delete button it just returns an empty object. How do I get the value from the options. With the normal input fields it would pass values with the name.

For example if I had an input type="text" name="email", when I would submit this it would give my an object like:

```<code>{email: "some string"}
</code>```

Here is the code:

```<code>import React , { Component } from 'react';
// import * as actions from '../actions';
import { reduxForm, Field } from 'redux-form';
import {connect} from 'react-redux';
import {postBooks, deleteBook} from '../../actions/booksActions';

class BooksForm extends Component {
  renderField(field) {
    const { meta: {touched, error} } = field;
    const className = `form-group ${touched && error ? 'has-danger' : ''}`;

    return (
      <div className={className}>
        <label className="control-label"><strong>{field.label}:</strong></label>
        <input
          className="form-control"
          type={field.type}
          {...field.input}
        />
        <div className="text-help">
          { touched ? error : ''}
        </div>
      </div>
    );
  }

  renderSelectField(field) {
    const bookList = _.map(field.options, (book) => {
      return (
        <option key={book._id}>{book.title}</option>
      )
    });

    return(
      <div className="form-group">
        <label htmlFor="sel1" className="control-label">{field.label}</label>
        <select className="form-control" id="sel1">
          {bookList}
        </select>
      </div>
    );
  }

  onSubmit(values) {
    this.props.postBooks(values);
  }

  onDelete(values) {
    console.log(values);
  }

  render() {
    const {handleSubmit} = this.props;

    return (
      <div>
      <div className="well">
      <form className="panel" onSubmit={handleSubmit(this.onSubmit.bind(this))}>
        <div className="panel-body">
        <Field
          label="Title"
          name="title"
          type="text"
          component={this.renderField}
        />
        <Field
          label="Description"
          name="description"
          type="text"
          component={this.renderField}
        />
        <Field
          label="Price"
          name="price"
          type="text"
          component={this.renderField}
        />
        <button className="btn btn-primary">Save Book</button>
        </div>
      </form>
      </div>
      <form className="Panel" onSubmit={handleSubmit(this.onDelete.bind(this))}>
        <div className="panel-body">
          <Field
            label="Select Book"
            name="selectedBook"
            options={this.props.books}
            component={this.renderSelectField}
          />
          <button className="btn btn-danger">Delete</button>
        </div>
      </form>
      </div>
    );
  }
}

function validate(values) {
  const errors = {};

  return errors;
}

function mapStateToProps(state) {
  return {
    books: state.books
  }
}

export default reduxForm({
  validate,
  form: 'bookForm'
})(connect(mapStateToProps, {postBooks, deleteBook})(BooksForm));
</code>```

答:
In renderSelectField I needed to add {...field.input} into the select to allow redux-form to monitor it.</p>

```<code><select className="form-control" id="sel1" {...field.input}>
</code>```

Body:
I am trying to get the values from my second form. It renders some select options and when I hit the delete button it just returns an empty object. How do I get the value from the options. With the normal input fields it would pass values with the name.

For example if I had an input type="text" name="email", when I would submit this it would give my an object like:

{email: "some string"}

Here is the code:

import React , { Component } from 'react';
// import * as actions from '../actions';
import { reduxForm, Field } from 'redux-form';
import {connect} from 'react-redux';
import {postBooks, deleteBook} from '../../actions/booksActions';

class BooksForm extends Component {
  renderField(field) {
    const { meta: {touched, error} } = field;
    const className = `form-group ${touched && error ? 'has-danger' : ''}`;

    return (

        {field.label}:
        <input
          className="form-control"
          type={field.type}
          {...field.input}
        />

          { touched ? error : ''}

    );
  }

  renderSelectField(field) {
    const bookList = _.map(field.options, (book) => {
      return (
        <option key={book._id}>{book.title}</option>
      )
    });

    return(

        {field.label}
        <select className="form-control" id="sel1">
          {bookList}
        </select>

    );
  }

  onSubmit(values) {
    this.props.postBooks(values);
  }

  onDelete(values) {
    console.log(values);
  }

  render() {
    const {handleSubmit} = this.props;

    return (

      <form className="panel" onSubmit={handleSubmit(this.onSubmit.bind(this))}>

        <Field
          label="Title"
          name="title"
          type="text"
          component={this.renderField}
        />
        <Field
          label="Description"
          name="description"
          type="text"
          component={this.renderField}
        />
        <Field
          label="Price"
          name="price"
          type="text"
          component={this.renderField}
        />
        <button className="btn btn-primary">Save Book</button>

      </form>

      <form className="Panel" onSubmit={handleSubmit(this.onDelete.bind(this))}>

          <Field
            label="Select Book"
            name="selectedBook"
            options={this.props.books}
            component={this.renderSelectField}
          />
          <button className="btn btn-danger">Delete</button>

      </form>

    );
  }
}

function validate(values) {
  const errors = {};

  return errors;
}

function mapStateToProps(state) {
  return {
    books: state.books
  }
}

export default reduxForm({
  validate,
  form: 'bookForm'
})(connect(mapStateToProps, {postBooks, deleteBook})(BooksForm));

Body:
In renderSelectField I needed to add {...field.input} into the select to allow redux-form to monitor it.

<select className="form-control" id="sel1" {...field.input}>


问:
Matlab rectangle property - 'Position' description confusion while ploting
I'm running Matlab R2014b and working at drawing a rectangle on an image given specific coordinates.

To be clear, say draw a rectangle[100, 100, 200, 50] is drawing a rectangle whose left corner is 100 pixels offset from the top left corner of the image in both horizontal and vertical directions, and the width is 200, height is 50.
The following code works:

```<code>figure;
imshow(im);
rectangle('Position',[100, 100, 200, 50],'edgeColor','r');
</code>```

But before I get the above correct method, I run doc rectangle and the command gives usage like rectangle('Position',[x,y,w,h]), then I checked the Rectangle Properties page, it says

The x and y elements define the coordinate for the lower-left corner of the rectangle. The width and height elements define the dimensions of the rectangle.

However, the above description is mismatch with the above correct code in y-directions, i.e. whether lower-left or upper-left corner to be (0,0) point.  I guess they are applyed in different scenarios. Explanation needed.

--** Edit: add a piece of code for anyone encountering this flip-up-down question to test**--

```<code>im = imread('e:/_Photos/2.jpg'); %load your local image file

%Original version, correct to draw rectangles
figure;
subplot(1,3,1);
imshow(im);
rectangle('Position',[100, 100, 200, 50],'edgeColor','g');

%flip once using `axis xy`, need to set y_new = height-y
subplot(1,3,2);
imshow(im);
axis xy;
rectangle('Position',[100, size(im,1)-100, 200, 50],'edgeColor','r');
rectangle('Position',[100, 100, 200, 50],'edgeColor','g');

%flip twice using `flipud` and `axis xy`,
%note we still need to recalculate the new y
subplot(1,3,3);
im = flipud(im);
imshow(im);
axis xy;
rectangle('Position',[100, size(im,1)-100, 200, 50],'edgeColor','g');
rectangle('Position',[100, 100, 200, 50],'edgeColor','r');
</code>```

答:
The full description of Rectangle Properties is:

Size and location of the rectangle, specified as a four-element vector of the form [x y width height]. Specify the values in data units. The x and y elements define the coordinate for the lower-left corner of the rectangle. The width and height elements define the dimensions of the rectangle.

The bold sentence means that you should pay attention to the axis direction. You first use imshow which flips the y-axis direction of the axes from top to bottom.

To see the same behavior as you expected, you can type axis xy to flip the axes back after you call imshow (so (0,0) point will be at the lower left corner). However, this will also flip the image, so you probably just need to calculate the position from the top:

```<code>rectangle('Position',[100 size(im,1)-100 200 50]);
</code>```

Body:
I'm running Matlab R2014b and working at drawing a rectangle on an image given specific coordinates.

To be clear, say draw a rectangle[100, 100, 200, 50] is drawing a rectangle whose left corner is 100 pixels offset from the top left corner of the image in both horizontal and vertical directions, and the width is 200, height is 50.
The following code works:

figure;
imshow(im);
rectangle('Position',[100, 100, 200, 50],'edgeColor','r');

But before I get the above correct method, I run doc rectangle and the command gives usage like rectangle('Position',[x,y,w,h]), then I checked the Rectangle Properties page, it says

The x and y elements define the coordinate for the lower-left corner of the rectangle. The width and height elements define the dimensions of the rectangle.

However, the above description is mismatch with the above correct code in y-directions, i.e. whether lower-left or upper-left corner to be (0,0) point.  I guess they are applyed in different scenarios. Explanation needed.

--** Edit: add a piece of code for anyone encountering this flip-up-down question to test**--

im = imread('e:/_Photos/2.jpg'); %load your local image file

%Original version, correct to draw rectangles
figure;
subplot(1,3,1);
imshow(im);
rectangle('Position',[100, 100, 200, 50],'edgeColor','g');

%flip once using `axis xy`, need to set y_new = height-y
subplot(1,3,2);
imshow(im);
axis xy;
rectangle('Position',[100, size(im,1)-100, 200, 50],'edgeColor','r');
rectangle('Position',[100, 100, 200, 50],'edgeColor','g');

%flip twice using `flipud` and `axis xy`,
%note we still need to recalculate the new y
subplot(1,3,3);
im = flipud(im);
imshow(im);
axis xy;
rectangle('Position',[100, size(im,1)-100, 200, 50],'edgeColor','g');
rectangle('Position',[100, 100, 200, 50],'edgeColor','r');

Body:
The full description of Rectangle Properties is:

Size and location of the rectangle, specified as a four-element vector of the form [x y width height]. Specify the values in data units. The x and y elements define the coordinate for the lower-left corner of the rectangle. The width and height elements define the dimensions of the rectangle.

The bold sentence means that you should pay attention to the axis direction. You first use imshow which flips the y-axis direction of the axes from top to bottom.

To see the same behavior as you expected, you can type axis xy to flip the axes back after you call imshow (so (0,0) point will be at the lower left corner). However, this will also flip the image, so you probably just need to calculate the position from the top:

rectangle('Position',[100 size(im,1)-100 200 50]);


问:
Export only subset of methods implemented by embedded struct
Is it possible to export only a subset of methods implemented by an embedded struct?
Is this a very go-unlike way to reduce copy - and - pasting of code and there is a more idiomatic way to do this?</p>

```<code>type A struct {
}

func (a *A) Hello() {
    fmt.Println("Hello!")
}

func (a *A) World() {
    fmt.Println("World!")
}

type B struct {
    A
}

type C struct {
    A
}

func main() {
    b := B{}
    c := C{}

    // B should only export the Hello - function
    b.Hello()

    // C should export both Hello - and World - function
    c.Hello()
    c.World()
}
</code>```

答:
This is how embedding works, there's nothing you can do about it. (Actually there is, see dirty trick at the end.)

What you want may be achieved with interfaces though. Make your structs unexported, (B => b and C => c), and create "constructor" like functions, which return interface types, containing only the methods you wish to publish:

```<code>type b struct {
    A
}

type c struct {
    A
}

type Helloer interface {
    Hello()
}

type HelloWorlder interface {
    Helloer
    World()
}

func NewB() Helloer {
    return &b{}
}

func NewC() HelloWorlder {
    return &c{}
}
</code>```

You might want to call the interfaces and functions different, this is just for demonstration.

Also note that while the returned Helloer interface does not include the World() method, it is still possible to "reach" it using type assertion, e.g.:

```<code>h := NewB() // h is of type Helloer
if hw, ok := h.(HelloWorlder); ok {
    hw.World() // This will succeed with the above implementations
}
</code>```

Try this on the Go Playground.

Dirty trick

If a type embeds the type A, (fields and) methods of A that get promoted will become part of the method set of the embedder type (and thus become methods of type A). This is detailed in Spec: Struct types:

A field or method f of an anonymous field in a struct x is called promoted if x.f is a legal selector that denotes that field or method f.

The focus is on the promotion, for which the selector must be legal. Spec: Selectors describes how x.f is resolved:

The following rules apply to selectors:

For a value x of type T or *T where T is not a pointer or interface type, x.f denotes the field or method at the shallowest depth in T where there is such an f. If there is not exactly one f with shallowest depth, the selector expression is illegal.

[...]

What does this mean? Simply by embedding, B.World will denote the B.A.World method as that is at the shallowest depth. But if we can achieve so that B.A.World won't be the shallowest, the type B won't have this World() method, because B.A.World won't get promoted.

How can we achieve that? We may add a field with name World:

```<code>type B struct {
    A
    World int
}
</code>```

This B type (or rather *B) will not have a World() method, as B.World denotes the field and not B.A.World as the former is at the shallowest depth. Try this on the Go Playground.

Again, this does not prevent anyone to explicitly refer to B.A.World(), so that method can be "reached" and called, all we achieved is that the type B or *B does not have a World() method.

Another variant of this "dirty trick" is to exploit the end of the first rule: "If there is not exactly one f with shallowest depth". This can be achieved to also embed another type, another struct which also has a World field or method, e.g.:

```<code>type hideWorld struct{ World int }

type B struct {
    A
    hideWorld
}
</code>```

Try this variant on the Go Playground.

Body:
Is it possible to export only a subset of methods implemented by an embedded struct?
Is this a very go-unlike way to reduce copy - and - pasting of code and there is a more idiomatic way to do this?

type A struct {
}

func (a *A) Hello() {
    fmt.Println("Hello!")
}

func (a *A) World() {
    fmt.Println("World!")
}

type B struct {
    A
}

type C struct {
    A
}

func main() {
    b := B{}
    c := C{}

    // B should only export the Hello - function
    b.Hello()

    // C should export both Hello - and World - function
    c.Hello()
    c.World()
}

Body:
This is how embedding works, there's nothing you can do about it. (Actually there is, see dirty trick at the end.)

What you want may be achieved with interfaces though. Make your structs unexported, (B => b and C => c), and create "constructor" like functions, which return interface types, containing only the methods you wish to publish:

type b struct {
    A
}

type c struct {
    A
}

type Helloer interface {
    Hello()
}

type HelloWorlder interface {
    Helloer
    World()
}

func NewB() Helloer {
    return &b{}
}

func NewC() HelloWorlder {
    return &c{}
}

You might want to call the interfaces and functions different, this is just for demonstration.

Also note that while the returned Helloer interface does not include the World() method, it is still possible to "reach" it using type assertion, e.g.:

h := NewB() // h is of type Helloer
if hw, ok := h.(HelloWorlder); ok {
    hw.World() // This will succeed with the above implementations
}

Try this on the Go Playground.

Dirty trick

If a type embeds the type A, (fields and) methods of A that get promoted will become part of the method set of the embedder type (and thus become methods of type A). This is detailed in Spec: Struct types:

A field or method f of an anonymous field in a struct x is called promoted if x.f is a legal selector that denotes that field or method f.

The focus is on the promotion, for which the selector must be legal. Spec: Selectors describes how x.f is resolved:

The following rules apply to selectors:

For a value x of type T or *T where T is not a pointer or interface type, x.f denotes the field or method at the shallowest depth in T where there is such an f. If there is not exactly one f with shallowest depth, the selector expression is illegal.

[...]

What does this mean? Simply by embedding, B.World will denote the B.A.World method as that is at the shallowest depth. But if we can achieve so that B.A.World won't be the shallowest, the type B won't have this World() method, because B.A.World won't get promoted.

How can we achieve that? We may add a field with name World:

type B struct {
    A
    World int
}

This B type (or rather *B) will not have a World() method, as B.World denotes the field and not B.A.World as the former is at the shallowest depth. Try this on the Go Playground.

Again, this does not prevent anyone to explicitly refer to B.A.World(), so that method can be "reached" and called, all we achieved is that the type B or *B does not have a World() method.

Another variant of this "dirty trick" is to exploit the end of the first rule: "If there is not exactly one f with shallowest depth". This can be achieved to also embed another type, another struct which also has a World field or method, e.g.:

type hideWorld struct{ World int }

type B struct {
    A
    hideWorld
}

Try this variant on the Go Playground.


问:
Load testing logged in routes in phoenix
I'm trying to do load testing for routes that require logging in.

I was previously using https://artillery.io/docs/index.html for logged out routes which worked fine. For logged in routes, I tried calling beforeRequest with a function to set the request headers & body.

config:
  target: "https://www.mywebsite.com/"
  phases:
    - duration: 60
      arrivalRate: 50
  processor: "test.js"
scenarios:
  - flow:
    - post:
        url: "/login"
        beforeRequest: "setReqBody"

and my beforeRequest looked like this:

function setReqBody(requestParams, context, ee, next) {
   requestParams.body = {'email': 'user@mail.com', 'password': 'password', '_csrf_token': window.csrfToken}
   return next();
}

I am getting an error that window is undefined.

I had a look around to see if there was anything else I could use for load testing phoenix, but didn't have much luck. Is there any other way I can log in & test those routes? Or other dependencies/libraries I can use in order to do this?

答:
Consider using Apache JMeter, it has:

HTTP Request sampler to mimic HTTP Requests

HTTP Header Manager to set required HTTP Request headers, i.e. Content-Type

a number of Post Processors for extracting "interesting" fields from response message, code, data, headers, etc.

HTML Reporting Dashboard to visualize load test results

See REST API Testing - How to Do it Right for details.


问:
How do I find out the path of the currently executing script?
Duplicate of: In Python, how do I get the path and name of the file that is currently executing?

I would like to find out the path to the currently executing script.
I have tried os.getcwd() but that only returns the directory I ran the script from not the actual directory the script is stored.

答:
How about using sys.path[0]

You can do something like

'print os.path.join(sys.path[0], sys.argv[0])'

https://docs.python.org/library/sys.html

OwnerDisplayName: Ashy

LastEditorDisplayName: Kev

OwnerDisplayName: Pat


问:
React: get redux state in router onEnter
I have googled this to death and it's very clear that this is a common problem however all of the solutions I found don't seem to fit my case.

I am a react novice and have adopted the following code:

```<code>const App = {
    path: 'app',
    onEnter: function (nextState, replace) {
        console.log("onEnter", nextState);
        /* somehow listen for redux state
        if (!state.auth.user) {
            replace('/login')
        }
        */
    },
    getChildRoutes(partialNextState, cb) {
        require.ensure([], (require) => {
            cb(null, [
                require('./routes/dostuff'),
                require('./routes/domorestuff'),
            ])
        })
    },
    getComponent(nextState, cb) {
        require.ensure([], (require) => {
            cb(null, require('./components/AppLayout'))
        })
    }
};

module.exports = App;
</code>```

As per the comment in the onEnter I need to authenticate before entering this route but I am unsure how to do this.

I tried the following:

```<code>const mapStateToProps = (state) => {
    return {
        user: state.auth.user
    }
};

module.exports = connect(
    mapStateToProps
)(App);
</code>```

but this produces "Uncaught Error: You must pass a component to the function returned by connect. Instead received {"path":"app"}"

The following code is used to create bootstrap the app and store:

```<code>import React from 'react';
import {render} from 'react-dom';
import {createStore, applyMiddleware} from 'redux';
import {Provider} from 'react-redux';
import {applyRouterMiddleware, Router, Route, hashHistory, IndexRedirect, Redirect} from 'react-router';
import {syncHistoryWithStore, routerMiddleware} from 'react-router-redux';
import reducers from './reducers';

const middleware = routerMiddleware(hashHistory);
const store = createStore(
    reducers,
    applyMiddleware(middleware)
);

const history = syncHistoryWithStore(hashHistory, store);

function scrollToTop() {
    window.scrollTo(0, 0);
}

const rootRoute = {
    childRoutes: [{
        path: '/',
        component: require('./containers/App'),
        indexRoute: {onEnter: (nextState, replace) => replace('/login')},
        childRoutes: [
            require('./routes/forgotPassword'),
            require('./routes/login'),
            {
                path: '*',
                indexRoute: {onEnter: (nextState, replace) => replace('/404')},
            }
        ]
    }]
};

render(
    <Provider store={store}>
        <Router
            onUpdate={scrollToTop}
            history={history}
            routes={rootRoute}
        />
    </Provider>,
    document.getElementById('app-container')
);
</code>```

I am using the following versions:

```<code>"react": "^15.5.4",
"react-dom": "^15.5.4",
"react-hot-loader": "^3.0.0-beta.6",
"react-redux": "^5.0.5",
"react-router": "^3.0.2",
"react-router-redux": "^4.0.8",
"redux": "~3.6.0",
</code>```

Any help would be greatly appreciated.

答:
It's possible to do what you want.  You need to somehow expose the store to your app file and it is currently out of scope.  The basic idea would be to create a function that accepts the store and expose it:

```<code>function App(store) {
    return {
      path: 'app',
      onEnter: function (nextState, replace) {
          // here you can do stuff with your store, something like store.getState()
          if (!state.auth.user) {
              replace('/login')
          }
          */
      },
      getChildRoutes(partialNextState, cb) {
          require.ensure([], (require) => {
              cb(null, [
                  require('./routes/dostuff'),
                  require('./routes/domorestuff'),
              ])
          })
      },
      getComponent(nextState, cb) {
          require.ensure([], (require) => {
              cb(null, require('./components/AppLayout'))
          })
      }
    }
};

module.exports = App;
</code>```

and

```<code>const rootRoute = {
    childRoutes: [{
        path: '/',
        component: require('./containers/App')(store),
        indexRoute: {onEnter: (nextState, replace) => replace('/login')},
        childRoutes: [
            require('./routes/forgotPassword'),
            require('./routes/login'),
            {
                path: '*',
                indexRoute: {onEnter: (nextState, replace) => replace('/404')},
            }
        ]
    }]
};
</code>```

Let me know how it goes!

Body:
I have googled this to death and it's very clear that this is a common problem however all of the solutions I found don't seem to fit my case.

I am a react novice and have adopted the following code:

const App = {
    path: 'app',
    onEnter: function (nextState, replace) {
        console.log("onEnter", nextState);
        /* somehow listen for redux state
        if (!state.auth.user) {
            replace('/login')
        }
        */
    },
    getChildRoutes(partialNextState, cb) {
        require.ensure([], (require) => {
            cb(null, [
                require('./routes/dostuff'),
                require('./routes/domorestuff'),
            ])
        })
    },
    getComponent(nextState, cb) {
        require.ensure([], (require) => {
            cb(null, require('./components/AppLayout'))
        })
    }
};

module.exports = App;

As per the comment in the onEnter I need to authenticate before entering this route but I am unsure how to do this.

I tried the following:

const mapStateToProps = (state) => {
    return {
        user: state.auth.user
    }
};

module.exports = connect(
    mapStateToProps
)(App);

but this produces "Uncaught Error: You must pass a component to the function returned by connect. Instead received {"path":"app"}"

The following code is used to create bootstrap the app and store:

import React from 'react';
import {render} from 'react-dom';
import {createStore, applyMiddleware} from 'redux';
import {Provider} from 'react-redux';
import {applyRouterMiddleware, Router, Route, hashHistory, IndexRedirect, Redirect} from 'react-router';
import {syncHistoryWithStore, routerMiddleware} from 'react-router-redux';
import reducers from './reducers';

const middleware = routerMiddleware(hashHistory);
const store = createStore(
    reducers,
    applyMiddleware(middleware)
);

const history = syncHistoryWithStore(hashHistory, store);

function scrollToTop() {
    window.scrollTo(0, 0);
}

const rootRoute = {
    childRoutes: [{
        path: '/',
        component: require('./containers/App'),
        indexRoute: {onEnter: (nextState, replace) => replace('/login')},
        childRoutes: [
            require('./routes/forgotPassword'),
            require('./routes/login'),
            {
                path: '*',
                indexRoute: {onEnter: (nextState, replace) => replace('/404')},
            }
        ]
    }]
};

render(
    <Provider store={store}>
        <Router
            onUpdate={scrollToTop}
            history={history}
            routes={rootRoute}
        />
    </Provider>,
    document.getElementById('app-container')
);

I am using the following versions:

"react": "^15.5.4",
"react-dom": "^15.5.4",
"react-hot-loader": "^3.0.0-beta.6",
"react-redux": "^5.0.5",
"react-router": "^3.0.2",
"react-router-redux": "^4.0.8",
"redux": "~3.6.0",

Any help would be greatly appreciated.

Body:
It's possible to do what you want.  You need to somehow expose the store to your app file and it is currently out of scope.  The basic idea would be to create a function that accepts the store and expose it:

function App(store) {
    return {
      path: 'app',
      onEnter: function (nextState, replace) {
          // here you can do stuff with your store, something like store.getState()
          if (!state.auth.user) {
              replace('/login')
          }
          */
      },
      getChildRoutes(partialNextState, cb) {
          require.ensure([], (require) => {
              cb(null, [
                  require('./routes/dostuff'),
                  require('./routes/domorestuff'),
              ])
          })
      },
      getComponent(nextState, cb) {
          require.ensure([], (require) => {
              cb(null, require('./components/AppLayout'))
          })
      }
    }
};

module.exports = App;

and

const rootRoute = {
    childRoutes: [{
        path: '/',
        component: require('./containers/App')(store),
        indexRoute: {onEnter: (nextState, replace) => replace('/login')},
        childRoutes: [
            require('./routes/forgotPassword'),
            require('./routes/login'),
            {
                path: '*',
                indexRoute: {onEnter: (nextState, replace) => replace('/404')},
            }
        ]
    }]
};

Let me know how it goes!


问:
VS 2010: unable to unit test
I posted this on MSDN as well but this community usually is much more helpful:

http://social.msdn.microsoft.com/Forums/en-US/vsunittest/thread/9a2717c7-4d24-4940-b5be-2bc3df6d7c7d

In a nutshell, VS refuses to start the testing agent. The machine is restarted to make sure nothing is in its memory. In other words, VSPerfMon is NOT running and hasn't been run prior.

Any help is welcome.

答: look in your list of running processes. If you have something running called (if memory serves) VSPerfMon ... kill it and try to run your tests again.</p>

Title: VS 2010: unable to unit test