问:
Pandas.DataFrame filtering by column of strings
I have a DataFrame like this:

```<code>import pandas as pd
df = pd.DataFrame()
df['trans'] = ['none', 'taxi', 'bus_101', 'bus_105', 'bus_106', 'car', 'horse']
df['cost']  = [1, 2, 3, 4, 5, 6, 7]
</code>```

And I want to filter all the buses out ('bus_101', 'bus_105', 'bus_106')

I tried two ways:

```<code>df['bus' not in df.trans].trans
</code>```

and tried to get a str out of Series, to compare its first 3 chars:

```<code>df[df.trans[:3] != 'bus'].trans
</code>```

and

```<code>df[df.trans.astype(str)[:3] != 'bus'].trans
</code>```

It didn't work out. I'd expect result to be:

```<code>0       none
1       taxi
5        car
6      horse
</code>```

But all I actually get are errors.

答:
You can use str.contains

```<code>df[~df.trans.str.contains('bus')]

   trans  cost
0   none     1
1   taxi     2
5    car     6
6  horse     7
</code>```

Brief explanation:

```<code>df.trans.str.contains('bus')
</code>```

will check whether 'bus' is contained in the values of trans:

```<code>0    False
1    False
2     True
3     True
4     True
5    False
6    False
Name: trans, dtype: bool
</code>```

The negation of it can be done by ~

```<code>~df.trans.str.contains('bus')

0     True
1     True
2    False
3    False
4    False
5     True
6     True
Name: trans, dtype: bool
</code>```

This Boolean series can be passed to df to select the desired entries.

Body:
I have a DataFrame like this:

import pandas as pd
df = pd.DataFrame()
df['trans'] = ['none', 'taxi', 'bus_101', 'bus_105', 'bus_106', 'car', 'horse']
df['cost']  = [1, 2, 3, 4, 5, 6, 7]

And I want to filter all the buses out ('bus_101', 'bus_105', 'bus_106')

I tried two ways:

df['bus' not in df.trans].trans

and tried to get a str out of Series, to compare its first 3 chars:

df[df.trans[:3] != 'bus'].trans

and

df[df.trans.astype(str)[:3] != 'bus'].trans

It didn't work out. I'd expect result to be:

0       none
1       taxi
5        car
6      horse

But all I actually get are errors.

Body:
You can use str.contains

df[~df.trans.str.contains('bus')]

   trans  cost
0   none     1
1   taxi     2
5    car     6
6  horse     7

Brief explanation:

df.trans.str.contains('bus')

will check whether 'bus' is contained in the values of trans:

0    False
1    False
2     True
3     True
4     True
5    False
6    False
Name: trans, dtype: bool

The negation of it can be done by ~

~df.trans.str.contains('bus')

0     True
1     True
2    False
3    False
4    False
5     True
6     True
Name: trans, dtype: bool

This Boolean series can be passed to df to select the desired entries.


来源: stackexchange

问:
Alexa Flash Briefing Error Parsing Feed
I wrote a Alexa flash briefing and it has been running smoothly for the last few days. All of the sudden yesterday, my endpoint stopped being recognized. When I try to test the endpoint anywhere else, everything looks good.

Just to make clear. This endpoint has been working for weeks without any issue up until yesterday.

I wrote the endpoint in AWS lambda. Here is my response code in lamba.

```<code>callback(null, {
    statusCode: '200',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify(
        {
            "uid": uuidv4(),
            "updateDate": new Date(),
            "titleText": "FILLER",
            "mainText": mainText})
        });
</code>```

I understand the statusCode is not necessary for a flash briefing response, and I have tested with it removed and it does not change anything. I have also tried remove JSON.stringify and nothing changes. Has anything changed in what they expect in the response and simply did not update the information on the documentation? Did I remove something in IAM that is required? Any help would be great!

答: So I seemed to have fixed the issue. I created a new Lambda function, pasted my code in, and now it seems to be working. I believe the issue may have been with the API Gateway. I may have edited something which changed my gateway settings.</p>

ContentLicense: CC BY-SA 3.0

Title: Alexa Flash Briefing Error Parsing Feed

Body:
I wrote a Alexa flash briefing and it has been running smoothly for the last few days. All of the sudden yesterday, my endpoint stopped being recognized. When I try to test the endpoint anywhere else, everything looks good.

Just to make clear. This endpoint has been working for weeks without any issue up until yesterday.

I wrote the endpoint in AWS lambda. Here is my response code in lamba.

callback(null, {
    statusCode: '200',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify(
        {
            "uid": uuidv4(),
            "updateDate": new Date(),
            "titleText": "FILLER",
            "mainText": mainText})
        });

I understand the statusCode is not necessary for a flash briefing response, and I have tested with it removed and it does not change anything. I have also tried remove JSON.stringify and nothing changes. Has anything changed in what they expect in the response and simply did not update the information on the documentation? Did I remove something in IAM that is required? Any help would be great!


问:
Sampling rows from dataframe and saving unselected ones
I'm triying to randomly choose rows from a dataframe; however, I also need unselected ones. I proceeded as follows

```<code>#grades is data with size 100
half-grades = grades[sample(nrow(grades), 50), ]
</code>```

How do I save unselected ones?

答:
Assuming you're looking for an even 50% split, the code is as follows.</p>

```<code>library(caTools)
split = sample.split(grades,SplitRatio=0.5)
half-grades1 = subset(grades, split == TRUE)
half-grades2 = subset(grades, split == FALSE)
</code>```

Body:
I'm triying to randomly choose rows from a dataframe; however, I also need unselected ones. I proceeded as follows

#grades is data with size 100
half-grades = grades[sample(nrow(grades), 50), ]

How do I save unselected ones?

Body:
Assuming you're looking for an even 50% split, the code is as follows.

library(caTools)
split = sample.split(grades,SplitRatio=0.5)
half-grades1 = subset(grades, split == TRUE)
half-grades2 = subset(grades, split == FALSE)


问:
Scraping JSON from an endpoint with REQUESTS
1) I want to use python for scraping a JSON file from an endpoint - (example: http://stats.nba.com/stats/boxscoreplayertrackv2/?GameID=0021700300). I've installed REQUESTS for Python and tried to download the page to a variable like that:

```<code>import requests
r = requests.get('http://stats.nba.com/stats/boxscoreplayertrackv2/?
GameID=0021700300')
</code>```

I have tried this on some regular web pages and it worked but for this endpoint, it is not working. When I send the request, the Python shell basically stops working and I have to restart it. I believe this has to have a very primitive solution.

Please, how can I download it?

2) After this, I would like to take the html/JSON and remove some of the code in the beginning and some in the ending so that it will remain only piece of json which will be possible transfer to a table (Excel or db table). My ultimate objective would be to automatize this process so every day would the script downloaded some new JSONs(need only to increase number in parameter in URL), modified them and transfered them to existing table/excel incrementally.

Could you please give me a direction how to do these steps? I just want to play with some data and this looks like the best way how to get them.
I'm new to Python and I have only some basics in programming so please excuse my primitive questions. I would appreciate any little advice.

ContentLicense: CC BY-SA 4.0

Body:
1) I want to use python for scraping a JSON file from an endpoint - (example: http://stats.nba.com/stats/boxscoreplayertrackv2/?GameID=0021700300). I've installed REQUESTS for Python and tried to download the page to a variable like that:

import requests
r = requests.get('http://stats.nba.com/stats/boxscoreplayertrackv2/?
GameID=0021700300')

I have tried this on some regular web pages and it worked but for this endpoint, it is not working. When I send the request, the Python shell basically stops working and I have to restart it. I believe this has to have a very primitive solution.

Please, how can I download it?

2) After this, I would like to take the html/JSON and remove some of the code in the beginning and some in the ending so that it will remain only piece of json which will be possible transfer to a table (Excel or db table). My ultimate objective would be to automatize this process so every day would the script downloaded some new JSONs(need only to increase number in parameter in URL), modified them and transfered them to existing table/excel incrementally.

Could you please give me a direction how to do these steps? I just want to play with some data and this looks like the best way how to get them.
I'm new to Python and I have only some basics in programming so please excuse my primitive questions. I would appreciate any little advice.

Body:
It looks like you need to add a couple of headers, you can then access the json as you would normally e.g.

import requests
import json

headers={'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0', 'Accept': 'application/json; charset=utf-8'}
r = requests.get('https://stats.nba.com/stats/boxscoreplayertrackv2/?GameID=0021700300', headers=headers)

j =r.json()

for row in j['resultSets']:
    print (row['name'])
    for rowSet in row['rowSet']:
        print (rowSet)

Outputs:

PlayerStats
['0021700300', 1610612764, 'WAS', 'Washington', 203490, 'Otto Porter Jr.', 'F', '', '32:05', 4.22, 2.25, 5, 11, 16, 48, 0, 0, 28, 0, 2, 4, 0.5, 6, 14, 0.428, 0.444, 0, 0, 0.0]
['0021700300', 1610612764, 'WAS', 'Washington', 202693, 'Markieff Morris', 'F', '', '20:39', 3.81, 1.31, 3, 4, 7, 30, 0, 0, 19, 1, 1, 2, 0.5, 0, 4, 0.0, 0.167, 2, 4, 0.5]
...
['0021700300', 1610612750, 'MIN', 'Minnesota', 201952, 'Jeff Teague', '', 'DNP - Injury/Illness                    ', '0:00', 0.0, 0.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0, 0, 0, 0.0, 0.0, 0, 0, 0.0]
TeamStats
['0021700300', 1610612764, 'Wizards', 'WAS', 'Washington', '240:00', 16.74, 29, 60, 89, 399, 4, 0, 287, 23, 14, 31, 0.452, 22, 52, 0.422, 0.434, 12, 21, 0.57]
['0021700300', 1610612750, 'Timberwolves', 'MIN', 'Minnesota', '240:00', 16.58, 30, 53, 83, 407, 1, 1, 296, 27, 18, 37, 0.485, 17, 48, 0.353, 0.412, 12, 18, 0.667]

Or to write to csv (for Excel):

import requests
import json
import csv

headers={'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0', 'Accept': 'application/json; charset=utf-8'}
r = requests.get('https://stats.nba.com/stats/boxscoreplayertrackv2/?GameID=0021700300', headers=headers)

j =r.json()

with open( "test.csv", 'w' ) as out_file:
    csv_w = csv.writer( out_file )
    for row in j['resultSets']:
        csv_w.writerow ([row['name']])
        for rowSet in row['rowSet']:
            csv_w.writerow (rowSet)


问:
What is the best way to 'soft launch' a new React Native app built using Expo?
We're working on an app with React Native using the Expo framework. The app is being developed for iOS and Android. We would like to release the app local to a certain region (Los Angeles) before releasing more broadly in the US. Based on my read of iOS and Android docs, we can only limit the app by country, not specific regions or localities such as Los Angeles. Does anyone have any recommendations on how we could launch the app to stores, but limit their download only to folks in a certain US region?</p>

答:
I don't believe this is possible, both iOS and Google App Stores can make your app discoverable by country only. if you're only wanting to "soft launch" the app for demonstration purposes only, an alternative solution would be to publish using the Expo XDE and provide users with the but this would require the end-user to then install Expo on their device.

https://blog.expo.io/publishing-on-exponent-790493660d24


问:
Why do I need a service to read the google Firebase token?
I use this code in MainActivity which is not extending FirebaseInstanceIdService to read the token generated by google firebase:

```<code>String token= FirebaseInstanceId.getInstance().getToken();
</code>```

However according to Firebase documentation I have to create a service which extends FirebaseInstanceIdService and retrieves the token on token refresh:

```<code>public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
    @Override
    public void onTokenRefresh() {
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    }
    }
}
</code>```

Why do I need to run  a service to read the token and What are the limitations of reading token from a simple activity?

答:
There's two things to keep in mind.

1) The token could change at any time, at which point the old token becomes invalid.  You don't want to be using an invalid token, or your app features that depend on it might not work.

2) The token could be refreshed when you don't have an activity started.  In order to respond to a token refresh that could happen at any time, you'll need a Service to handle that event in the background as soon as it occurs.

Body:
I use this code in MainActivity which is not extending FirebaseInstanceIdService to read the token generated by google firebase:

String token= FirebaseInstanceId.getInstance().getToken();

However according to Firebase documentation I have to create a service which extends FirebaseInstanceIdService and retrieves the token on token refresh:

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
    @Override
    public void onTokenRefresh() {
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    }
    }
}

Why do I need to run  a service to read the token and What are the limitations of reading token from a simple activity?


问:
How to detect AVPlayer actually started to play in swift
Hello I have set my UISliderminimum value to 0.00. Then I set it's max value in this way.

```<code>self.viewPlayer.layer.addSublayer(playerLayer)
    let duration : CMTime = avPlayer.avPlayer.currentItem!.asset.duration
    let seconds : Float64 = CMTimeGetSeconds(duration)

    sliderBar.maximumValue=Float(seconds)
    sliderBar!.isContinuous = false
    sliderBar!.tintColor = UIColor.green
</code>```

But I am  getting this exception

```<code>*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Attempting to set a slider's minimumValue (0.000000) to be larger than the maximumValue (nan)'
enter code here
</code>```

I know after prepareForPlay() to actual playing it takes some time to really play the video. So how can I detect when the player really started to play the video?
Please help me.
Thanks

答:
From Apple's docs:

You can observe an AVPlayerLayer object’s readyForDisplay property to be notified when the layer has user-visible content. In particular, you might insert the player layer into the layer tree only when there is something for the user to look at and then perform a transition from

Body:
Hello I have set my UISliderminimum value to 0.00. Then I set it's max value in this way.

self.viewPlayer.layer.addSublayer(playerLayer)
    let duration : CMTime = avPlayer.avPlayer.currentItem!.asset.duration
    let seconds : Float64 = CMTimeGetSeconds(duration)

    sliderBar.maximumValue=Float(seconds)
    sliderBar!.isContinuous = false
    sliderBar!.tintColor = UIColor.green

But I am  getting this exception

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Attempting to set a slider's minimumValue (0.000000) to be larger than the maximumValue (nan)'
enter code here

I know after prepareForPlay() to actual playing it takes some time to really play the video. So how can I detect when the player really started to play the video?
Please help me.
Thanks


答:
This is easily accomplished with caret::createDataPartition().

```<code>library(caret)
theIndex <- createDataPartition(grades, p = .50,list=FALSE)
sampled <- grades[theIndex,]
notSampled <- grades[-theIndex,]
</code>```

Title: Sampling rows from dataframe and saving unselected ones

Body:
This is easily accomplished with caret::createDataPartition().

library(caret)
theIndex <- createDataPartition(grades, p = .50,list=FALSE)
sampled <- grades[theIndex,]
notSampled <- grades[-theIndex,]


问:
RAII and factory design pattern?
Let's say I have Foo class:

```<code>struct Resource {
  void block();
  void unblock();
};
struct Foo {
   static Foo create() {
      Resource resource;
      resource.block();
      return Foo{resource};
    }
   ~Foo() { resource.unblock(); }
   void f() {}
private:
   Resource resource;
   Foo(Resource resource): resource(resource) {}
};
</code>```

Am I right and there is no guarantee that ~Foo will be called only once in such block?

```<code>{
   Foo foo = Foo::create();
   foo.f();
}
</code>```

If there is no guarantee, is it possible to fix somehow if using c++11 and move semantic? For example not call unblock_resource in moved foo, but I am not sure is there guarantee to use move constructor/operator= in return from Foo::create?

答:
You are looking for copy-elision.

In short, your code is guaranteed to work in C++17, as described at http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0135r0.html

In C++14 and before there is no such guarantee.

Copy elision is an optimization that existed before C++11 and allowed compiler to omit copy constructor call in some cases.

C++11 has added move semantics and copy elision was expanded to allow compiler to avoid moving or copying (if moving is not available) an object.

Regardless of what compiler actually does, your class must still provide copy or move constructor, even if one will not be used by the compiler.

C++17 introduces "guaranteed copy-elision", which allows you to return objects of non-movable classes, just like in your case. Note that proposal explicitly mentions "factory functions". Quote:

it is impossible or very difficult to write factory functions

Example from proposal has this example:

```<code>struct NonMoveable {
  NonMoveable(int);
  NonMoveable(NonMoveable&) = delete;
  void NonMoveable(NonMoveable&) = delete;
  std::array<int, 1024> arr;
};
NonMoveable make() {
  return NonMoveable(42); // ok, directly constructs returned object
}
</code>```

As of today, both Clang and GCC are able to compile that code with -std=c++17 flag, but not with -std=c++14.

I see two ways for you to solve this problem:

Use C++17: I recommend deleting both copy and move constructor (and operator=) to make sure your code will not compile under earlier standard with buggy effects.

Rely only on things that are available in C++14 to make your code work everywhere. You might want add additional state to your object, delete copy constructor and implement move constructor.

This is an example of how it can be done in C++14.

```<code>class Foo {
public:
    Foo() = default;
    Foo(const Foo &) = delete;
    Foo(Foo &&rvalue) noexcept { std::swap(blocked, rvalue.blocked); }
    ~Foo() { if (blocked) unblock();
    void block() { blocked = true; }
    void unblock() { blocked = false; }
private:
    bool blocked{false};
};
</code>```

Title: RAII and factory design pattern?

Body:
Let's say I have Foo class:

struct Resource {
  void block();
  void unblock();
};
struct Foo {
   static Foo create() {
      Resource resource;
      resource.block();
      return Foo{resource};
    }
   ~Foo() { resource.unblock(); }
   void f() {}
private:
   Resource resource;
   Foo(Resource resource): resource(resource) {}
};

Am I right and there is no guarantee that ~Foo will be called only once in such block?

{
   Foo foo = Foo::create();
   foo.f();
}

If there is no guarantee, is it possible to fix somehow if using c++11 and move semantic? For example not call unblock_resource in moved foo, but I am not sure is there guarantee to use move constructor/operator= in return from Foo::create?

Body:
You are looking for copy-elision.

In short, your code is guaranteed to work in C++17, as described at http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0135r0.html

In C++14 and before there is no such guarantee.

Copy elision is an optimization that existed before C++11 and allowed compiler to omit copy constructor call in some cases.

C++11 has added move semantics and copy elision was expanded to allow compiler to avoid moving or copying (if moving is not available) an object.

Regardless of what compiler actually does, your class must still provide copy or move constructor, even if one will not be used by the compiler.

C++17 introduces "guaranteed copy-elision", which allows you to return objects of non-movable classes, just like in your case. Note that proposal explicitly mentions "factory functions". Quote:

it is impossible or very difficult to write factory functions

Example from proposal has this example:

struct NonMoveable {
  NonMoveable(int);
  NonMoveable(NonMoveable&) = delete;
  void NonMoveable(NonMoveable&) = delete;
  std::array<int, 1024> arr;
};
NonMoveable make() {
  return NonMoveable(42); // ok, directly constructs returned object
}

As of today, both Clang and GCC are able to compile that code with -std=c++17 flag, but not with -std=c++14.

I see two ways for you to solve this problem:

Use C++17: I recommend deleting both copy and move constructor (and operator=) to make sure your code will not compile under earlier standard with buggy effects.

Rely only on things that are available in C++14 to make your code work everywhere. You might want add additional state to your object, delete copy constructor and implement move constructor.

This is an example of how it can be done in C++14.

class Foo {
public:
    Foo() = default;
    Foo(const Foo &) = delete;
    Foo(Foo &&rvalue) noexcept { std::swap(blocked, rvalue.blocked); }
    ~Foo() { if (blocked) unblock();
    void block() { blocked = true; }
    void unblock() { blocked = false; }
private:
    bool blocked{false};
};


问:
Change scale's tick mark labels on sliderInput in R Shiny
This is what my web application looks like:

However, I don't want visible tick lines at random intervals (45,001, 90,001, etc). Quite simply, it looks pretty ugly. How can I change my code so that it is labeled at 1, 50k, 100k, 150k...400k, 428,036?

Here is my current code:

```<code>  sliderInput(inputId = "CR_num",
              label = "Please choose how many case reports you would like our tool to analyze.",
              value = "20000",
              step = 5000,
              min = 1,
              max = 428036)
</code>```

I think the step parameter only allows the user to choose values from the scale at that interval...it doesn't change the labels.

Thanks.

答:
I was able to do it by using the shinyWidgets library.  Basically, create a list of your desired step values and call the sliderTextInput() function.

```<code>numlist <- prettyNum(c(1, seq(5000, (floor(428036/5000)*5000), 5000), 428036), big.mark = ",")

slider <- sliderTextInput(
  inputId = "CR_num",
  label = "Please choose how many case reports you would like our tool to analyze.",
  choices = numlist,
  selected ="20,000",
  grid = FALSE, dragRange = FALSE)
</code>```

Now the only options are the ones you chose:

The only hiccup is now the values are strings, so there are a LOT of tick marks.
 So, I removed them.

Body:
This is what my web application looks like:

However, I don't want visible tick lines at random intervals (45,001, 90,001, etc). Quite simply, it looks pretty ugly. How can I change my code so that it is labeled at 1, 50k, 100k, 150k...400k, 428,036?

Here is my current code:

  sliderInput(inputId = "CR_num",
              label = "Please choose how many case reports you would like our tool to analyze.",
              value = "20000",
              step = 5000,
              min = 1,
              max = 428036)

I think the step parameter only allows the user to choose values from the scale at that interval...it doesn't change the labels.

Thanks.

Body:
I was able to do it by using the shinyWidgets library.  Basically, create a list of your desired step values and call the sliderTextInput() function.

numlist <- prettyNum(c(1, seq(5000, (floor(428036/5000)*5000), 5000), 428036), big.mark = ",")

slider <- sliderTextInput(
  inputId = "CR_num",
  label = "Please choose how many case reports you would like our tool to analyze.",
  choices = numlist,
  selected ="20,000",
  grid = FALSE, dragRange = FALSE)

Now the only options are the ones you chose:

The only hiccup is now the values are strings, so there are a LOT of tick marks.
 So, I removed them.


答:
This should work:</p>

```<code>import pandas as pd
df= pd.DataFrame()
df['trans'] = ['none', 'taxi', 'bus_101', 'bus_105', 'bus_106', 'car', 'horse']
df['cost']  = [1, 2, 3, 4, 5, 6, 7]
df[df['trans'].str.contains("bus") == False]

    trans   cost
0   none    1
1   taxi    2
5   car     6
6   horse   7
</code>```

Title: Pandas.DataFrame filtering by column of strings

Body:
This should work:

import pandas as pd
df= pd.DataFrame()
df['trans'] = ['none', 'taxi', 'bus_101', 'bus_105', 'bus_106', 'car', 'horse']
df['cost']  = [1, 2, 3, 4, 5, 6, 7]
df[df['trans'].str.contains("bus") == False]

    trans   cost
0   none    1
1   taxi    2
5   car     6
6   horse   7


问:
How to use multiple input parameters in ASP.NET Web API and getting data from database by stored procedure
I am using multiple input parameters in my ASP.NET Web API application but I am not getting the output.

My code is here:

```<code>[HttpGet]
[Route("api/tblProducts/{Price1}/{Price2}/{CategoryId}/{Color}/{Size}")]
[ResponseType(typeof(IEnumerable<GetSimilarProducts_Result>))]
public IHttpActionResult GetSimlarProduct(Decimal Price1,Decimal Price2,string CategoryId, string Color, string Size)
{
    IEnumerable<GetSimilarProducts_Result> tblSmlrProduct = db.GetSimilarProducts(Price1, Price2,CategoryId, Color, Size ).AsEnumerable();

    if (tblSmlrProduct == null)
    {
        return NotFound();
    }

    return Ok(tblSmlrProduct);
}
</code>```

and I using given URI for accessing it

```<code>   http://localhost:54393/api/tblProducts/GetsimlarProduct?Price1=1000&Price2=10000&CategoryId=Cat102&Color=Black&Size=M
</code>```

Please help me how I can get data from database and my other stored procedure working well
My method code made by visual studio

```<code>public virtual ObjectResult<GetSimilarProducts_Result> GetSimilarProducts(Nullable<decimal> price1, Nullable<decimal> price2, string size, string categoryId, string color)
        {
            var price1Parameter = price1.HasValue ?
                new ObjectParameter("Price1", price1) :
                new ObjectParameter("Price1", typeof(decimal));

            var price2Parameter = price2.HasValue ?
                new ObjectParameter("Price2", price2) :
                new ObjectParameter("Price2", typeof(decimal));

            var sizeParameter = size != null ?
                new ObjectParameter("Size", size) :
                new ObjectParameter("Size", typeof(string));

            var categoryIdParameter = categoryId != null ?
                new ObjectParameter("CategoryId", categoryId) :
                new ObjectParameter("CategoryId", typeof(string));

            var colorParameter = color != null ?
                new ObjectParameter("Color", color) :
                new ObjectParameter("Color", typeof(string));

            return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<GetSimilarProducts_Result>("GetSimilarProducts", price1Parameter, price2Parameter, sizeParameter, categoryIdParameter, colorParameter);
        }
</code>```

and this is my stored procedure code

```<code>USE [MakaAnOrderDB]
GO

/****** Object:  StoredProcedure [dbo].[GetSimilarProducts]    Script Date: 12/14/2017 12:44:09 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[GetSimilarProducts]
(@Price1 decimal(18,0),@Price2 decimal(18,0),@Size nvarchar(max),@CategoryId nvarchar(255),@Color nvarchar(20))

As
Begin
Select top(20)* from tblProduct where PrdPrice Between @Price1 And @Price2 And PrdSize=@Size And PrdColor=@Color
End

GO
</code>```

Update : my stored procedure which is working well

```<code>USE [MakaAnOrderDB]
GO

/****** Object:  StoredProcedure [dbo].[SingleProductDetails]    Script Date: 12/14/2017 12:44:24 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[SingleProductDetails]
@ProductId nvarchar(255)=''
As
Begin
Select* from tblProduct where ProductId=@ProductId

End

GO
</code>```

Update: this is c# code of fetching information from SingleProductDetails Procedure

```<code>[HttpGet]
        [Route("api/tblProducts/{productId}")]
        [ResponseType(typeof(IEnumerable<SingleProductDetails_Result>))]
        public IHttpActionResult Get(string productId)
        {
            IEnumerable<SingleProductDetails_Result> tblProduct = db.SingleProductDetails(productId).AsEnumerable();
            if (tblProduct == null)
            {
                return NotFound();
            }

            return Ok(tblProduct);
        }
</code>```

update:Code made by visual studio for procedure sigleProductDetails

```<code>public virtual ObjectResult<SingleProductDetails_Result> SingleProductDetails(string productId)
        {
            var productIdParameter = productId != null ?
                new ObjectParameter("ProductId", productId) :
                new ObjectParameter("ProductId", typeof(string));

            return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<SingleProductDetails_Result>("SingleProductDetails", productIdParameter);
        }
</code>```

答:
Another way, in case you want to get rid of that long query string:

Create a class from your parameters and pass it as a complex object.

Change HttpGet to HttpPost.

Body:
I am using multiple input parameters in my ASP.NET Web API application but I am not getting the output.

My code is here:

[HttpGet]
[Route("api/tblProducts/{Price1}/{Price2}/{CategoryId}/{Color}/{Size}")]
[ResponseType(typeof(IEnumerable<GetSimilarProducts_Result>))]
public IHttpActionResult GetSimlarProduct(Decimal Price1,Decimal Price2,string CategoryId, string Color, string Size)
{
    IEnumerable<GetSimilarProducts_Result> tblSmlrProduct = db.GetSimilarProducts(Price1, Price2,CategoryId, Color, Size ).AsEnumerable();

    if (tblSmlrProduct == null)
    {
        return NotFound();
    }

    return Ok(tblSmlrProduct);
}

and I using given URI for accessing it

   http://localhost:54393/api/tblProducts/GetsimlarProduct?Price1=1000&Price2=10000&CategoryId=Cat102&Color=Black&Size=M

Please help me how I can get data from database and my other stored procedure working well
My method code made by visual studio

public virtual ObjectResult<GetSimilarProducts_Result> GetSimilarProducts(Nullable<decimal> price1, Nullable<decimal> price2, string size, string categoryId, string color)
        {
            var price1Parameter = price1.HasValue ?
                new ObjectParameter("Price1", price1) :
                new ObjectParameter("Price1", typeof(decimal));

            var price2Parameter = price2.HasValue ?
                new ObjectParameter("Price2", price2) :
                new ObjectParameter("Price2", typeof(decimal));

            var sizeParameter = size != null ?
                new ObjectParameter("Size", size) :
                new ObjectParameter("Size", typeof(string));

            var categoryIdParameter = categoryId != null ?
                new ObjectParameter("CategoryId", categoryId) :
                new ObjectParameter("CategoryId", typeof(string));

            var colorParameter = color != null ?
                new ObjectParameter("Color", color) :
                new ObjectParameter("Color", typeof(string));

            return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<GetSimilarProducts_Result>("GetSimilarProducts", price1Parameter, price2Parameter, sizeParameter, categoryIdParameter, colorParameter);
        }

and this is my stored procedure code

USE [MakaAnOrderDB]
GO

/****** Object:  StoredProcedure [dbo].[GetSimilarProducts]    Script Date: 12/14/2017 12:44:09 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[GetSimilarProducts]
(@Price1 decimal(18,0),@Price2 decimal(18,0),@Size nvarchar(max),@CategoryId nvarchar(255),@Color nvarchar(20))

As
Begin
Select top(20)* from tblProduct where PrdPrice Between @Price1 And @Price2 And PrdSize=@Size And PrdColor=@Color
End

GO

Update : my stored procedure which is working well

USE [MakaAnOrderDB]
GO

/****** Object:  StoredProcedure [dbo].[SingleProductDetails]    Script Date: 12/14/2017 12:44:24 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[SingleProductDetails]
@ProductId nvarchar(255)=''
As
Begin
Select* from tblProduct where ProductId=@ProductId

End

GO

Update: this is c# code of fetching information from SingleProductDetails Procedure

[HttpGet]
        [Route("api/tblProducts/{productId}")]
        [ResponseType(typeof(IEnumerable<SingleProductDetails_Result>))]
        public IHttpActionResult Get(string productId)
        {
            IEnumerable<SingleProductDetails_Result> tblProduct = db.SingleProductDetails(productId).AsEnumerable();
            if (tblProduct == null)
            {
                return NotFound();
            }

            return Ok(tblProduct);
        }

update:Code made by visual studio for procedure sigleProductDetails

public virtual ObjectResult<SingleProductDetails_Result> SingleProductDetails(string productId)
        {
            var productIdParameter = productId != null ?
                new ObjectParameter("ProductId", productId) :
                new ObjectParameter("ProductId", typeof(string));

            return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<SingleProductDetails_Result>("SingleProductDetails", productIdParameter);
        }


问:
Extending the Jenkins Groovy DSL
How can I add/edit new code to my Jenkins instance that would be accesible in a DSL script?  Context follows

I've inherited a Jenkins instance.  Part of this inheritance includes spending the night in a haunted house writing some new automation in groovy via the Jobs DSL plugin.  Since I'm fearful of ruining our jenkins instance, my first step is setting up a local development instance.

I'm having trouble running one of our existing DSL Scripts on my local development instance -- my builds on the local server fail with the following in the Jenkins error console.

```<code>Processing DSL script jobs.groovy
ERROR: startup failed:
jobs.groovy: 1: unable to resolve class thecompanysname.jenkins.extensions
</code>```

The script in question starts off like this.

```<code>import thecompanysname.jenkins.extensions

use(extensions) {
  def org = 'project-name'
  def project = 'test-jenkins-repo'
  def _email = 'foo@example.com'
</code>```

So, as near I can tell, it seems like a predecesor has written some custom Groovy code that they're importing

```<code>import thecompanysname.jenkins.extensions
</code>```

What's not clear to me is

Where this code lives

How I can find it in our real Jenkins instance

How I can add to to my local instance

Specific answers are welcome, as our here's how you can learn to fish answers.

答:
While there may be other ways to accomplish this, after a bit of poking around I discovered

The Jenkins instance I've installed has an older version of the Jobs DSL plugin installed.

This version of the Jobs DSL plugin allowed you to set an additional classpath in your Process DSL Builds job section that pointed to additional jar files.

These jar files can give you access to additional classes in your groovy scripts (i.e. thecompanysname.jenkins.extensions)

Unfortunately, more recent versions of the Jobs DSL plugin have removed this option, and it's not clear if it's possible to add it back.  That, however, is another question.

Title: Extending the Jenkins Groovy DSL

Body:
How can I add/edit new code to my Jenkins instance that would be accesible in a DSL script?  Context follows

I've inherited a Jenkins instance.  Part of this inheritance includes spending the night in a haunted house writing some new automation in groovy via the Jobs DSL plugin.  Since I'm fearful of ruining our jenkins instance, my first step is setting up a local development instance.

I'm having trouble running one of our existing DSL Scripts on my local development instance -- my builds on the local server fail with the following in the Jenkins error console.

Processing DSL script jobs.groovy
ERROR: startup failed:
jobs.groovy: 1: unable to resolve class thecompanysname.jenkins.extensions

The script in question starts off like this.

import thecompanysname.jenkins.extensions

use(extensions) {
  def org = 'project-name'
  def project = 'test-jenkins-repo'
  def _email = 'foo@example.com'

So, as near I can tell, it seems like a predecesor has written some custom Groovy code that they're importing

import thecompanysname.jenkins.extensions

What's not clear to me is

Where this code lives

How I can find it in our real Jenkins instance

How I can add to to my local instance

Specific answers are welcome, as our here's how you can learn to fish answers.


问:
How do I get a wordpress container to work behind an NGINX reverse proxy
Wondering if anybody else has similar issues with Docker wordpress containers. I'm not confident in my apache/wordpress abilities. Maybe somebody here can help.

Trying to setup the standard wordpress docker container behind an nginx reverse proxy using ssl.

All my other apps work fine, it's only worpress/apache with the issue.

My NGINX default.conf:

```<code>server {
        listen 80;
        server_name example.com;
        return 301 https://example.com$request_uri;
}
########## ADDED
upstream app-a {
    server example.com:2368;
}

upstream app-b {
    server example.com:8080;
}

##########
server {
        listen 443 ssl;
        server_name example.com;
        root /usr/share/nginx/html;
        index index.html index.htm;
        client_max_body_size 10G;
        location / {
                 proxy_pass         http://app-a;
            proxy_redirect     off;
            proxy_set_header   Host $host;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header   X-Forwarded-Host $server_name;
        }

location = /press {
                return 301 https://example.com:8443;
        }

        ssl on;
        ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
        ssl_prefer_server_ciphers On;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS;
}

server {
        listen 8443 ssl;

        server_name example.com;

        #root /usr/share/nginx/html;
        root /var/www/html/press;
        index index.php index.html index.htm;
        client_max_body_size 10G;

        location / {
                proxy_pass         http://app-b;
            proxy_redirect     off;
            proxy_set_header   Host $host;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header   X-Forwarded-Host $server_name;
        }

        ssl on;
        ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

        ssl_prefer_server_ciphers On;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS;

}
</code>```

How I'm starting my wordpress container:

```<code>docker run -d --name mywordpress --link mytestsql:mysql -v mypressvol:/var/www/html -e WORDPRESS_DB_USER=root -e WORDPRESS_DB_PASSWORD=secret -p 8080:80 wordpress
</code>```

When I run the WP setup I get language selection but no graphics and shows not secure in the address bar. However If I go to 8080 in my browser the app works just fine, but no ssl.  Like I said all my other apps work fine with this.  It's only WordPress giving me fits. Any ideas?  Thanks.

答:
This configurations work fine:

1) Nginx proxy

```<code>server {
    listen                          80;
    server_name                     example.ru www.example.ru;
    return 301                      https://$server_name$request_uri;
}

 server {
    listen 443;
    server_name example.ru www.example.ru;

    ssl_certificate           /etc/nginx/certs/example.ru.crt;
    ssl_certificate_key       /etc/nginx/certs/example.ru.key;

    ssl on;
    ssl_session_cache  builtin:1000  shared:SSL:10m;
    ssl_protocols  TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!DES:!MD5:!PSK:!RC4;
    ssl_prefer_server_ciphers on;

    location / {
        proxy_pass http://wp_web;
    }
}
</code>```

Don't forget to put them both in one network in docker-compose.yml in order to access the container by service name.

2) Wordpress container. Your host. Apache2 conf

```<code><VirtualHost *:80>
    # The ServerName directive sets the request scheme, hostname and port that
    # the server uses to identify itself. This is used when creating
    # redirection URLs. In the context of virtual hosts, the ServerName
    # specifies what hostname must appear in the request's Host: header to
    # match this virtual host. For the default virtual host (this file) this
    # value is not decisive as it is used as a last resort host regardless.
    # However, you must set it for any further virtual host explicitly.

    ServerName example.ru
    ServerAlias www.example.ru

    SetEnvIf X-Forwarded-Proto https HTTPS=on

    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/example

    <Directory /var/www/example>
        Allowoverride All
    </Directory>

    # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
    # error, crit, alert, emerg.
    # It is also possible to configure the loglevel for particular
    # modules, e.g.
    #LogLevel info ssl:warn

    ErrorLog /var/www/example/logs/apache.error.log
    CustomLog /var/www/example/logs/apache.access.log combined_with_x_real_ip

    # For most configuration files from conf-available/, which are
    # enabled or disabled at a global level, it is possible to
    # include a line for only one particular virtual host. For example the
    # following line enables the CGI configuration for this host only
    # after it has been globally disabled with "a2disconf".
    #Include conf-available/serve-cgi-bin.conf
</VirtualHost>
</code>```

Body:
Wondering if anybody else has similar issues with Docker wordpress containers. I'm not confident in my apache/wordpress abilities. Maybe somebody here can help.

Trying to setup the standard wordpress docker container behind an nginx reverse proxy using ssl.

All my other apps work fine, it's only worpress/apache with the issue.

My NGINX default.conf:

server {
        listen 80;
        server_name example.com;
        return 301 https://example.com$request_uri;
}
########## ADDED
upstream app-a {
    server example.com:2368;
}

upstream app-b {
    server example.com:8080;
}

##########
server {
        listen 443 ssl;
        server_name example.com;
        root /usr/share/nginx/html;
        index index.html index.htm;
        client_max_body_size 10G;
        location / {
                 proxy_pass         http://app-a;
            proxy_redirect     off;
            proxy_set_header   Host $host;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header   X-Forwarded-Host $server_name;
        }

location = /press {
                return 301 https://example.com:8443;
        }

        ssl on;
        ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
        ssl_prefer_server_ciphers On;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS;
}

server {
        listen 8443 ssl;

        server_name example.com;

        #root /usr/share/nginx/html;
        root /var/www/html/press;
        index index.php index.html index.htm;
        client_max_body_size 10G;

        location / {
                proxy_pass         http://app-b;
            proxy_redirect     off;
            proxy_set_header   Host $host;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header   X-Forwarded-Host $server_name;
        }

        ssl on;
        ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

        ssl_prefer_server_ciphers On;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS;

}

How I'm starting my wordpress container:

docker run -d --name mywordpress --link mytestsql:mysql -v mypressvol:/var/www/html -e WORDPRESS_DB_USER=root -e WORDPRESS_DB_PASSWORD=secret -p 8080:80 wordpress

When I run the WP setup I get language selection but no graphics and shows not secure in the address bar. However If I go to 8080 in my browser the app works just fine, but no ssl.  Like I said all my other apps work fine with this.  It's only WordPress giving me fits. Any ideas?  Thanks.

Body:
This configurations work fine:

1) Nginx proxy

server {
    listen                          80;
    server_name                     example.ru www.example.ru;
    return 301                      https://$server_name$request_uri;
}

 server {
    listen 443;
    server_name example.ru www.example.ru;

    ssl_certificate           /etc/nginx/certs/example.ru.crt;
    ssl_certificate_key       /etc/nginx/certs/example.ru.key;

    ssl on;
    ssl_session_cache  builtin:1000  shared:SSL:10m;
    ssl_protocols  TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!DES:!MD5:!PSK:!RC4;
    ssl_prefer_server_ciphers on;

    location / {
        proxy_pass http://wp_web;
    }
}

Don't forget to put them both in one network in docker-compose.yml in order to access the container by service name.

2) Wordpress container. Your host. Apache2 conf

<VirtualHost *:80>
    # The ServerName directive sets the request scheme, hostname and port that
    # the server uses to identify itself. This is used when creating
    # redirection URLs. In the context of virtual hosts, the ServerName
    # specifies what hostname must appear in the request's Host: header to
    # match this virtual host. For the default virtual host (this file) this
    # value is not decisive as it is used as a last resort host regardless.
    # However, you must set it for any further virtual host explicitly.

    ServerName example.ru
    ServerAlias www.example.ru

    SetEnvIf X-Forwarded-Proto https HTTPS=on

    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/example

    <Directory /var/www/example>
        Allowoverride All
    </Directory>

    # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
    # error, crit, alert, emerg.
    # It is also possible to configure the loglevel for particular
    # modules, e.g.
    #LogLevel info ssl:warn

    ErrorLog /var/www/example/logs/apache.error.log
    CustomLog /var/www/example/logs/apache.access.log combined_with_x_real_ip

    # For most configuration files from conf-available/, which are
    # enabled or disabled at a global level, it is possible to
    # include a line for only one particular virtual host. For example the
    # following line enables the CGI configuration for this host only
    # after it has been globally disabled with "a2disconf".
    #Include conf-available/serve-cgi-bin.conf
</VirtualHost>


问:
How to color table rows according to a specific input dynamically?
I am just starting to learn about javascript, jquery , and ajax.

I really need help knowing the logic or how I should approach this problem:

I have a table of " expenses" that could be monthly :

```<code>      Type     Cost     Monthly/yearly
      Laundry    2000$     Monthly
      Groceries    300$    Monthly
      Clothes    100$    Monthly
</code>```

I have an input budget . What I need is that say the user inputted 200$ , the rows whose cost is greater than the budget AND that are monthly should be coloured in red:

```<code> Type     Cost     Monthly/yearly
  Laundry    2000$     Monthly (colored in red)
  Groceries    300$    Monthly (colored in red)
  Clothes    100$    Monthly
</code>```

But then the user can input another budget , and then the colors in the table should update automatically. Now he inputs 1000$ :

```<code>Type     Cost     Monthly/yearly
      Laundry    2000$     Monthly ( only one colored in red)
      Groceries    300$    Monthly
      Clothes    100$    Monthly
</code>```

How can I achieve that? I just need to know how to approach this logic wise. I'm using Node.Js

答:
man if you post us onyl your ideas, without any piece of actual code, we can't really help you. I only give you and advice: you could check with javascript the value of your input box and if it's greater/lesser than X, colour it (with "style" attribute) via Javascript. Example

```<code><input type="text" id="boo" onfocusout="colourbox()">
</code>```

in your head tag, just write some js code

```<code><script>
function colourbox(){
var boo = document.getElementById("boo");
if(boo.value > 200)
    boo.style="background-color:red";
}
</script>
</code>```

this code colours red your input box in case of it contains a value greater than 200. Hope it helps

Body:
I am just starting to learn about javascript, jquery , and ajax.

I really need help knowing the logic or how I should approach this problem:

I have a table of " expenses" that could be monthly :

      Type     Cost     Monthly/yearly
      Laundry    2000$     Monthly
      Groceries    300$    Monthly
      Clothes    100$    Monthly

I have an input budget . What I need is that say the user inputted 200$ , the rows whose cost is greater than the budget AND that are monthly should be coloured in red:

 Type     Cost     Monthly/yearly
  Laundry    2000$     Monthly (colored in red)
  Groceries    300$    Monthly (colored in red)
  Clothes    100$    Monthly

But then the user can input another budget , and then the colors in the table should update automatically. Now he inputs 1000$ :

Type     Cost     Monthly/yearly
      Laundry    2000$     Monthly ( only one colored in red)
      Groceries    300$    Monthly
      Clothes    100$    Monthly

How can I achieve that? I just need to know how to approach this logic wise. I'm using Node.Js

Body:
man if you post us onyl your ideas, without any piece of actual code, we can't really help you. I only give you and advice: you could check with javascript the value of your input box and if it's greater/lesser than X, colour it (with "style" attribute) via Javascript. Example

<input type="text" id="boo" onfocusout="colourbox()">

in your head tag, just write some js code

<script>
function colourbox(){
var boo = document.getElementById("boo");
if(boo.value > 200)
    boo.style="background-color:red";
}
</script>

this code colours red your input box in case of it contains a value greater than 200. Hope it helps


问:
Can I call fields from associated model in react components?
Is there a way to get fields from associated model in react components in rails?

I have listing model that I am maping through in react component and getting all the fields within each record including the ID of the model that is associated to listing model that I am getting.

What I specifically want to achieve is to get another field through the associated ID that I have in listing model but, I am not getting it just like we do in rails, for example

```<code>listing.modelNameThatIsAssociated.fieldName
</code>```

How to achieve this?

here a snippet of my code

controller

```<code>def all
 begin
   @listings = Listing.all
 rescue => e
   @listings = []
 end
end

def filter
 @listings = Listing.where(nil)

 filtering_params(params).each do |key, value|
   @listings = @listings.public_send(key, value) if value.present?
 end
 render json: { listings: @listings }, status: 200
end

private
def filtering_params(params)
  params[:filters].slice(:bedrooms, :bathrooms, :price, :parking)
end
</code>```

all.html.erb

```<code><%= react_component('ListingsPage', listings: @listings) %>
</code>```

And here My react component(listings.js.jsx)

```<code>class ListingsList extends React.Component {
    constructor(props) {
      super(props);
}

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

    return (
      <div className='ListingList_container'>
        <table>
          <thead>
           <tr>
            <td>#</td>
            <td>Name</td>
            <td>Address</td>
            <td>Lat</td>
            <td>Lng</td>
            <td>Bedrooms</td>
            <td>Bathrooms</td>
            <td>Price</td>
            <td>Parking</td>
            <td>Building ID</td>
          </tr>
        </thead>
          <tbody>
          {
            listings.map((listing, index) => (
              <tr key={listing.id}>
                <td>{index + 1}</td>
                <td>{listing.name}</td>
                <td>{listing.address}</td>
                <td>{listing.lat}</td>
                <td>{listing.lng}</td>
                <td>{listing.bedrooms}</td>
                <td>{listing.bathrooms}</td>
                <td>{this.formatNumber(listing.price)}</td>
                <td>{listing.parking ? 'Available' : 'None'}</td>

                // below I want to get building name just like we do in rails
                // through association 'listing.building.name' but, that
                // doesn't work
                <td>{listing.building_id}</td> // this works, I am getting building ID
               <td>{listing.building.name}</td> // this doesn't work
              </tr>
            ))
          }
        </tbody>
      </table>
    </div>
  );
 }
}
</code>```

I appreciate every single view and help thanks in advance. Please let me know if my question is not clear.

答:
You'll have to load the associations first, then use the include option in as_json to add them to the JSON output

For example, if your Listing model has_many :offers and has_many :views, then you would write this:

```<code># In the controller
@listings = Listing.preload(:offers, :views)

# In your view
<%= react_component(
  'ListingsPage',
  listings: @listings.as_json(include: [:offers, :views])
) %>
</code>```

Body:
Is there a way to get fields from associated model in react components in rails?

I have listing model that I am maping through in react component and getting all the fields within each record including the ID of the model that is associated to listing model that I am getting.

What I specifically want to achieve is to get another field through the associated ID that I have in listing model but, I am not getting it just like we do in rails, for example

listing.modelNameThatIsAssociated.fieldName

How to achieve this?

here a snippet of my code

controller

def all
 begin
   @listings = Listing.all
 rescue => e
   @listings = []
 end
end

def filter
 @listings = Listing.where(nil)

 filtering_params(params).each do |key, value|
   @listings = @listings.public_send(key, value) if value.present?
 end
 render json: { listings: @listings }, status: 200
end

private
def filtering_params(params)
  params[:filters].slice(:bedrooms, :bathrooms, :price, :parking)
end

all.html.erb

<%= react_component('ListingsPage', listings: @listings) %>

And here My react component(listings.js.jsx)

class ListingsList extends React.Component {
    constructor(props) {
      super(props);
}

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

    return (

            #
            Name
            Address
            Lat
            Lng
            Bedrooms
            Bathrooms
            Price
            Parking
            Building ID

          {
            listings.map((listing, index) => (

                {index + 1}
                {listing.name}
                {listing.address}
                {listing.lat}
                {listing.lng}
                {listing.bedrooms}
                {listing.bathrooms}
                {this.formatNumber(listing.price)}
                {listing.parking ? 'Available' : 'None'}

                // below I want to get building name just like we do in rails
                // through association 'listing.building.name' but, that
                // doesn't work
                {listing.building_id}	 // this works, I am getting building ID
               {listing.building.name}	 // this doesn't work

            ))
          }

  );
 }
}

I appreciate every single view and help thanks in advance. Please let me know if my question is not clear.

Body:
You'll have to load the associations first, then use the include option in as_json to add them to the JSON output

For example, if your Listing model has_many :offers and has_many :views, then you would write this:

# In the controller
@listings = Listing.preload(:offers, :views)

# In your view
<%= react_component(
  'ListingsPage',
  listings: @listings.as_json(include: [:offers, :views])
) %>


问:
How to backpropagate with complex valued weights
We are currently trying to replicate the results of the following paper: https://openreview.net/forum?id=H1S8UE-Rb

To do so, we need to run backpropagation on a neural network which contains complex valued weights.

When we try to do so (with code [0]), we get an error (at [1]). We cannot find the source code for any project that trains a neural network containing complex valued weights.

We were wondering if we would need to implement the paper's backpropagation adjustments ourselves or if this is already part of some neural network libraries. If it needs to be implemented in Tensorflow, what would be the proper steps to achieve that?

[0]:

```<code>def define_neuron(x):
    """
    x is input tensor
    """

    x = tf.cast(x, tf.complex64)

    mnist_x = mnist_y = 28
    n = mnist_x * mnist_y
    c = 10
    m = 10  # m needs to be calculated

    with tf.name_scope("linear_combination"):
        complex_weight = weight_complex_variable([n,m])
        complex_bias = bias_complex_variable([m])
        h_1 = x @ complex_weight + complex_bias

    return h_1

def main(_):
    mnist = input_data.read_data_sets(
        FLAGS.data_dir,
        one_hot=True,
    )

    # `None` for the first dimension in this shape means that it is variable.
    x_shape = [None, 784]
    x = tf.placeholder(tf.float32, x_shape)
    y_ = tf.placeholder(tf.float32, [None, 10])

    yz = h_1 = define_neuron(x)

    y = tf.nn.softmax(tf.abs(yz))

    with tf.name_scope('loss'):
        cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
            labels=y_,
            logits=y,
        )

    cross_entropy = tf.reduce_mean(cross_entropy)

    with tf.name_scope('adam_optimizer'):
        optimizer = tf.train.AdamOptimizer(1e-4)
        optimizer = tf.train.GradientDescentOptimizer(1e-4)
        train_step = optimizer.minimize(cross_entropy)
</code>```

[1]:

```<code>Extracting /tmp/tensorflow/mnist/input_data/train-images-idx3-ubyte.gz
Extracting /tmp/tensorflow/mnist/input_data/train-labels-idx1-ubyte.gz
Extracting /tmp/tensorflow/mnist/input_data/t10k-images-idx3-ubyte.gz
Extracting /tmp/tensorflow/mnist/input_data/t10k-labels-idx1-ubyte.gz
Traceback (most recent call last):
  File "complex.py", line 156, in <module>
    tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
  File "/Users/kevin/wdev/learn_tensor/env/lib/python3.6/site-packages/tensorflow/python/platform/app.py", line 48, in run
    _sys.exit(main(_sys.argv[:1] + flags_passthrough))
  File "complex.py", line 58, in main
    train_step = optimizer.minimize(cross_entropy)
  File "/Users/kevin/wdev/learn_tensor/env/lib/python3.6/site-packages/tensorflow/python/training/optimizer.py", line 343, in minimize
    grad_loss=grad_loss)
  File "/Users/kevin/wdev/learn_tensor/env/lib/python3.6/site-packages/tensorflow/python/training/optimizer.py", line 419, in compute_gradients
    [v for g, v in grads_and_vars
  File "/Users/kevin/wdev/learn_tensor/env/lib/python3.6/site-packages/tensorflow/python/training/optimizer.py", line 547, in _assert_valid_dtypes
    dtype, t.name, [v for v in valid_dtypes]))
ValueError: Invalid type tf.complex64 for linear_combination/Variable:0, expected: [tf.float32, tf.float64, tf.float16].
</code>```

答: I have also tried to implement a similar network in tensorflow and saw that the optimizer cannot do backpropagation using complex valued tensors. The work around is to have separate real tensors for the real and imaginary parts. You will have to do write a function that will get the amplitude of the "complex" output of the network which is simply Re^2 - Im^2. This output value is what you will use to compute the loss. </p>

Body:
We are currently trying to replicate the results of the following paper: https://openreview.net/forum?id=H1S8UE-Rb

To do so, we need to run backpropagation on a neural network which contains complex valued weights.

When we try to do so (with code [0]), we get an error (at [1]). We cannot find the source code for any project that trains a neural network containing complex valued weights.

We were wondering if we would need to implement the paper's backpropagation adjustments ourselves or if this is already part of some neural network libraries. If it needs to be implemented in Tensorflow, what would be the proper steps to achieve that?

[0]:

def define_neuron(x):
    """
    x is input tensor
    """

    x = tf.cast(x, tf.complex64)

    mnist_x = mnist_y = 28
    n = mnist_x * mnist_y
    c = 10
    m = 10  # m needs to be calculated

    with tf.name_scope("linear_combination"):
        complex_weight = weight_complex_variable([n,m])
        complex_bias = bias_complex_variable([m])
        h_1 = x @ complex_weight + complex_bias

    return h_1

def main(_):
    mnist = input_data.read_data_sets(
        FLAGS.data_dir,
        one_hot=True,
    )

    # `None` for the first dimension in this shape means that it is variable.
    x_shape = [None, 784]
    x = tf.placeholder(tf.float32, x_shape)
    y_ = tf.placeholder(tf.float32, [None, 10])

    yz = h_1 = define_neuron(x)

    y = tf.nn.softmax(tf.abs(yz))

    with tf.name_scope('loss'):
        cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
            labels=y_,
            logits=y,
        )

    cross_entropy = tf.reduce_mean(cross_entropy)

    with tf.name_scope('adam_optimizer'):
        optimizer = tf.train.AdamOptimizer(1e-4)
        optimizer = tf.train.GradientDescentOptimizer(1e-4)
        train_step = optimizer.minimize(cross_entropy)

[1]:

Extracting /tmp/tensorflow/mnist/input_data/train-images-idx3-ubyte.gz
Extracting /tmp/tensorflow/mnist/input_data/train-labels-idx1-ubyte.gz
Extracting /tmp/tensorflow/mnist/input_data/t10k-images-idx3-ubyte.gz
Extracting /tmp/tensorflow/mnist/input_data/t10k-labels-idx1-ubyte.gz
Traceback (most recent call last):
  File "complex.py", line 156, in <module>
    tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
  File "/Users/kevin/wdev/learn_tensor/env/lib/python3.6/site-packages/tensorflow/python/platform/app.py", line 48, in run
    _sys.exit(main(_sys.argv[:1] + flags_passthrough))
  File "complex.py", line 58, in main
    train_step = optimizer.minimize(cross_entropy)
  File "/Users/kevin/wdev/learn_tensor/env/lib/python3.6/site-packages/tensorflow/python/training/optimizer.py", line 343, in minimize
    grad_loss=grad_loss)
  File "/Users/kevin/wdev/learn_tensor/env/lib/python3.6/site-packages/tensorflow/python/training/optimizer.py", line 419, in compute_gradients
    [v for g, v in grads_and_vars
  File "/Users/kevin/wdev/learn_tensor/env/lib/python3.6/site-packages/tensorflow/python/training/optimizer.py", line 547, in _assert_valid_dtypes
    dtype, t.name, [v for v in valid_dtypes]))
ValueError: Invalid type tf.complex64 for linear_combination/Variable:0, expected: [tf.float32, tf.float64, tf.float16].


问:
Parsing IMDB with BeautifulSoup
I've stripped the following code from IMDB's mobile site using BeautifulSoup, with Python 2.7.

I want to create a separate object for the episode number '1', title 'Winter is Coming', and IMDB score '8.9'. Can't seem to figure out how to split apart the episode number and the title.

```<code>   <a class="btn-full" href="/title/tt1480055?ref_=m_ttep_ep_ep1">
     <span class="text-large">
      1.
      <strong>
       Winter Is Coming
      </strong>
     </span>
     <br/>
     <span class="mobile-sprite tiny-star">
     </span>
     <strong>
      8.9
     </strong>
     17 Apr. 2011
    </a>
</code>```

答:
Using url html scraping with reguest and regular expression search.

```<code>import os, sys, requests

frame = ('http://www.imdb.com/title/tt1480055?ref_=m_ttep_ep_ep1')
f = requests.get(frame)
helpme = f.text
import re
result = re.findall('itemprop="name" class="">(.*?) ', helpme)
result2 = re.findall('"ratingCount">(.*?)</span>', helpme)
result3 = re.findall('"ratingValue">(.*?)</span>', helpme)
print result[0].encode('utf-8')
print result2[0]
print result3[0]
</code>```

output:

```<code>Winter Is Coming
24,474
9.0
</code>```

Title: Parsing IMDB with BeautifulSoup

Body:
I've stripped the following code from IMDB's mobile site using BeautifulSoup, with Python 2.7.

I want to create a separate object for the episode number '1', title 'Winter is Coming', and IMDB score '8.9'. Can't seem to figure out how to split apart the episode number and the title.

      1.

       Winter Is Coming

      8.9

     17 Apr. 2011

Body:
Using url html scraping with reguest and regular expression search.

import os, sys, requests

frame = ('http://www.imdb.com/title/tt1480055?ref_=m_ttep_ep_ep1')
f = requests.get(frame)
helpme = f.text
import re
result = re.findall('itemprop="name" class="">(.*?)&nbsp;', helpme)
result2 = re.findall('"ratingCount">(.*?)</span>', helpme)
result3 = re.findall('"ratingValue">(.*?)</span>', helpme)
print result[0].encode('utf-8')
print result2[0]
print result3[0]

output:

Winter Is Coming
24,474
9.0


问:
Removing \r from lines read from file
I am having a weird problem. I read a text file then I split it using \n as a delimiter. I noticed that the split lines contain '\r' at the end. So I am trying to remove it, I tried doing so using String.Replace but without luck. Here is my code:

```<code>    string fileOutput = File.ReadAllText(location);
    SettingsManager.proxies.Clear();
    foreach (string line in fileOutput.Split('\n'))
    {
        string cleanLine = line;
        if (cleanLine.Contains("\r")) cleanLine.Replace("\r", "");
        SettingsManager.proxies.Add(cleanLine);
    }
</code>```

EDIT: After staring at the code for 1 min, I found that I didn't assign the replaced value to the original string.

```<code>cleanLine.Replace("\r",""); //assigns a value to nothing
</code>```

I should have assigned cleanLine to cleanLine.Replace();

```<code>cleanLine = cleanLine.Replace("\r","");
</code>```

答:
As others have suggested, use File.ReadAllLines() instead. It will split on \n as well as \r\n. Your sample can be rewritten as:

```<code>SettingsManager.proxies.Clear();
foreach (string line in File.ReadAllLines(location))
    SettingsManager.proxies.Add(line);
</code>```

ContentLicense: CC BY-SA 2.5

Title: Removing \r from lines read from file

Body:
I am having a weird problem. I read a text file then I split it using \n as a delimiter. I noticed that the split lines contain '\r' at the end. So I am trying to remove it, I tried doing so using String.Replace but without luck. Here is my code:

    string fileOutput = File.ReadAllText(location);
    SettingsManager.proxies.Clear();
    foreach (string line in fileOutput.Split('\n'))
    {
        string cleanLine = line;
        if (cleanLine.Contains("\r")) cleanLine.Replace("\r", "");
        SettingsManager.proxies.Add(cleanLine);
    }

EDIT: After staring at the code for 1 min, I found that I didn't assign the replaced value to the original string.

cleanLine.Replace("\r",""); //assigns a value to nothing

I should have assigned cleanLine to cleanLine.Replace();

cleanLine = cleanLine.Replace("\r","");

Body:
As others have suggested, use File.ReadAllLines() instead. It will split on \n as well as \r\n. Your sample can be rewritten as:

SettingsManager.proxies.Clear();
foreach (string line in File.ReadAllLines(location))
    SettingsManager.proxies.Add(line);


问:
How is the index of label determined in MXNet
I am trying to understand the Handwritten Digit recognition for MXNet in python here

The code which creates the training data and label data is shown below:

```<code>def read_data(label_url, image_url):
    with gzip.open(download_data(label_url)) as flbl:
        magic, num = struct.unpack(">II", flbl.read(8))
        label = np.fromstring(flbl.read(), dtype=np.int8)
    with gzip.open(download_data(image_url), 'rb') as fimg:
        magic, num, rows, cols = struct.unpack(">IIII", fimg.read(16))
        image = np.fromstring(fimg.read(), dtype=np.uint8).reshape(len(label), rows, cols)
    return (label, image)
</code>```

Then the numbers are predicted using the code below:

```<code>prob = model.predict(val_img[0:1].astype(np.float32)/255)[0]
assert max(prob) > 0.99, "Low prediction accuracy."
print 'Classified as %d with probability %f' % (prob.argmax(), max(prob))
</code>```

The output is - Classified as 7 with probability 0.999391.
My question is how MXNet was able to determine that the index returned by argmax function corresponds to label -7

答:
The value 7 is coming from prob.argmax(). That method returns the index of the top scoring value.

https://mxnet.incubator.apache.org/api/python/ndarray.html#mxnet.ndarray.argmax

Body:
I am trying to understand the Handwritten Digit recognition for MXNet in python here

The code which creates the training data and label data is shown below:

def read_data(label_url, image_url):
    with gzip.open(download_data(label_url)) as flbl:
        magic, num = struct.unpack(">II", flbl.read(8))
        label = np.fromstring(flbl.read(), dtype=np.int8)
    with gzip.open(download_data(image_url), 'rb') as fimg:
        magic, num, rows, cols = struct.unpack(">IIII", fimg.read(16))
        image = np.fromstring(fimg.read(), dtype=np.uint8).reshape(len(label), rows, cols)
    return (label, image)

Then the numbers are predicted using the code below:

prob = model.predict(val_img[0:1].astype(np.float32)/255)[0]
assert max(prob) > 0.99, "Low prediction accuracy."
print 'Classified as %d with probability %f' % (prob.argmax(), max(prob))

The output is - Classified as 7 with probability 0.999391.
My question is how MXNet was able to determine that the index returned by argmax function corresponds to label -7


问:
Close Angular Material Dialog On Browser Back
I am using Angular Material (5.0.0) to create a Single Page Web Application for mobile devices.  I have a scenario when I need to display a dialog.  I would like to allow the user to hit back to close the dialog, as it's a very common behavior on mobile (especially on Android).

When this happens currently, the page goes to the previous page.  I instead need the button to simply dismiss the dialog.

Any ideas on how this might be accomplished??

答:
You can inject the MatDialog service and call closeAll method to close all the opened dialogs as below,

```<code>constructor(public dialog: MatDialog) {
         this.dialog.closeAll();
}
</code>```

LIVE DEMO

Body:
You can inject the MatDialog service and call closeAll method to close all the opened dialogs as below,

constructor(public dialog: MatDialog) {
         this.dialog.closeAll();
}

LIVE DEMO


问:
Another approach for simple MySQL query

I'm looking for another approach to write this query (should run on MySQL), The approach can be worse then what I already have as long as its different and still gives the correct answer, there aren't restrictions on the approach.

My query:

The query finds the average of student in each subject and also finds the average of averages per subject per student:

```<code>SELECT t1.*,t2.totalAvg
FROM (SELECT StudentFirstName,StudentLastName,ClassName,AVG(Grade) AS `average for this subject`
      FROM tests
      INNER JOIN students ON tests.StudentID=students.StudentID
      GROUP BY StudentFirstName,StudentLastName,ClassName
     ) t1
JOIN (SELECT StudentFirstName,StudentLastName,AVG(`average for this subject`) as totalAvg
      FROM (SELECT StudentFirstName,StudentLastName,ClassName,AVG(Grade) AS `average for this subject`
            FROM tests
            INNER JOIN students ON tests.StudentID=students.StudentID
            GROUP BY StudentFirstName,StudentLastName,ClassName
           ) t
      GROUP BY StudentFirstName,StudentLastName
     ) t2
ON t1.StudentFirstName=t2.StudentFirstName and t1.StudentLastName=t2.StudentLastName;
</code>```

Students table:

```<code>  pk-INT           VARCHAR             VARCHAR
+-----------+------------------+-----------------+
| StudentID | StudentFirstName | StudentLastName |
+-----------+------------------+-----------------+
|         1 | agam             | rafaeli         |
|         2 | amir             | aizinger        |
|         3 | avi              | caspi           |
|         4 | avia             | wolf            |
+-----------+------------------+-----------------+
</code>```

Tests table:

```<code>  PK-VARCHR    PK-VARCHR     PK&FK-INT   INT
+------------+------------+-----------+-------+
| TestDate   | ClassName  | StudentID | Grade |
+------------+------------+-----------+-------+
| 2017-07-01 | Algebra    |         1 |    88 |
| 2017-08-02 | Algo       |         1 |    97 |
| 2017-09-01 | Algebra    |         1 |    80 |
| 2017-09-01 | Algebra    |         1 |    97 |
| 2017-09-01 | Set-theory |         1 |    85 |
| 2017-09-04 | Calcules   |         1 |    86 |
| 2016-05-03 | Set-theory |         2 |    84 |
| 2016-07-02 | Calcules   |         2 |    89 |
| 2016-07-04 | Algo       |         2 |    83 |
| 2016-07-05 | Algebra    |         2 |    79 |
| 2016-06-03 | Algebra    |         3 |    99 |
| 2016-07-02 | Algo       |         3 |    97 |
| 2016-07-03 | Calcules   |         3 |    96 |
| 2016-09-03 | Set-theory |         3 |    95 |
| 2016-06-03 | Algebra    |         4 |    78 |
+------------+------------+-----------+-------+
</code>```

SAMPLE DATA:

```<code>DROP DATABASE IF EXISTS error404;
CREATE DATABASE error404;
USE error404
CREATE TABLE students
(
    StudentID        INT NOT NULL AUTO_INCREMENT,
    StudentFirstName VARCHAR(25),
    StudentLastName  VARCHAR(25),
    PRIMARY KEY (StudentID)
);
INSERT INTO students (StudentFirstName,StudentLastName) VALUES
('agam'  , 'rafaeli'), ('amir'  , 'aizinger'), ('avi'   , 'caspi'),
('avia'  , 'wolf ');
CREATE TABLE tests
(
    testid    INT NOT NULL AUTO_INCREMENT,
    TestDate  DATE,
    ClassName VARCHAR(25),
    StudentID INT NOT NULL,
    Grade     INT NOT NULL,
    PRIMARY KEY (testid),
    KEY (StudentID)
);
INSERT INTO tests (TestDate,ClassName,StudentID,Grade) VALUES
('2017-07-01', 'Algebra'    , 1 , 88 ), ('2017-08-02', 'Algo'       , 1 , 97 ),
('2017-09-01', 'Algebra'    , 1 , 80 ), ('2017-09-01', 'Algebra'    , 1 , 97 ),
('2017-09-01', 'Set-theory' , 1 , 85 ), ('2017-09-04', 'Calcules'   , 1 , 86 ),
('2016-05-03', 'Set-theory' , 2 , 84 ), ('2016-07-02', 'Calcules'   , 2 , 89 ),
('2016-07-04', 'Algo'       , 2 , 83 ), ('2016-07-05', 'Algebra'    , 2 , 79 ),
('2016-06-03', 'Algebra'    , 3 , 99 ), ('2016-07-02', 'Algo'       , 3 , 97 ),
('2016-07-03', 'Calcules'   , 3 , 96 ), ('2016-09-03', 'Set-theory' , 3 , 95 ),
('2016-06-03', 'Algebra'    , 4 , 78 );
</code>```

答:
Delay use of the students table, most of the calculations do not require student names.</p>

```<code>SELECT
      s.StudentFirstName
    , s.StudentLastName
    , t1.ClassName
    , t1.student_class_avg AS `average for this subject`
    , t2.student_avg_avg   AS totalAvg
FROM students s
INNER JOIN (SELECT StudentID,ClassName,AVG(Grade) AS student_class_avg
      FROM tests
      GROUP BY StudentID,ClassName
     ) t1 ON s.StudentID = t1.StudentID
INNER JOIN (
      SELECT StudentID,AVG(student_class_avg) AS student_avg_avg
      FROM (
            SELECT StudentID,ClassName,AVG(Grade) AS student_class_avg
            FROM tests
            GROUP BY StudentID,ClassName
           ) t
      GROUP BY StudentID
     ) t2 ON s.StudentID = t2.StudentID
ORDER BY
      s.StudentFirstName
    , s.StudentLastName
    , t1.ClassName
;
</code>```

Title: Another approach for simple MySQL query

Body:
I'm looking for another approach to write this query (should run on MySQL), The approach can be worse then what I already have as long as its different and still gives the correct answer, there aren't restrictions on the approach.

My query:

The query finds the average of student in each subject and also finds the average of averages per subject per student:

SELECT t1.*,t2.totalAvg
FROM (SELECT StudentFirstName,StudentLastName,ClassName,AVG(Grade) AS `average for this subject`
      FROM tests
      INNER JOIN students ON tests.StudentID=students.StudentID
      GROUP BY StudentFirstName,StudentLastName,ClassName
     ) t1
JOIN (SELECT StudentFirstName,StudentLastName,AVG(`average for this subject`) as totalAvg
      FROM (SELECT StudentFirstName,StudentLastName,ClassName,AVG(Grade) AS `average for this subject`
            FROM tests
            INNER JOIN students ON tests.StudentID=students.StudentID
            GROUP BY StudentFirstName,StudentLastName,ClassName
           ) t
      GROUP BY StudentFirstName,StudentLastName
     ) t2
ON t1.StudentFirstName=t2.StudentFirstName and t1.StudentLastName=t2.StudentLastName;

Students table:

  pk-INT           VARCHAR             VARCHAR
+-----------+------------------+-----------------+
| StudentID | StudentFirstName | StudentLastName |
+-----------+------------------+-----------------+
|         1 | agam             | rafaeli         |
|         2 | amir             | aizinger        |
|         3 | avi              | caspi           |
|         4 | avia             | wolf            |
+-----------+------------------+-----------------+

Tests table:

  PK-VARCHR    PK-VARCHR     PK&FK-INT   INT
+------------+------------+-----------+-------+
| TestDate   | ClassName  | StudentID | Grade |
+------------+------------+-----------+-------+
| 2017-07-01 | Algebra    |         1 |    88 |
| 2017-08-02 | Algo       |         1 |    97 |
| 2017-09-01 | Algebra    |         1 |    80 |
| 2017-09-01 | Algebra    |         1 |    97 |
| 2017-09-01 | Set-theory |         1 |    85 |
| 2017-09-04 | Calcules   |         1 |    86 |
| 2016-05-03 | Set-theory |         2 |    84 |
| 2016-07-02 | Calcules   |         2 |    89 |
| 2016-07-04 | Algo       |         2 |    83 |
| 2016-07-05 | Algebra    |         2 |    79 |
| 2016-06-03 | Algebra    |         3 |    99 |
| 2016-07-02 | Algo       |         3 |    97 |
| 2016-07-03 | Calcules   |         3 |    96 |
| 2016-09-03 | Set-theory |         3 |    95 |
| 2016-06-03 | Algebra    |         4 |    78 |
+------------+------------+-----------+-------+

SAMPLE DATA:

DROP DATABASE IF EXISTS error404;
CREATE DATABASE error404;
USE error404
CREATE TABLE students
(
    StudentID        INT NOT NULL AUTO_INCREMENT,
    StudentFirstName VARCHAR(25),
    StudentLastName  VARCHAR(25),
    PRIMARY KEY (StudentID)
);
INSERT INTO students (StudentFirstName,StudentLastName) VALUES
('agam'  , 'rafaeli'), ('amir'  , 'aizinger'), ('avi'   , 'caspi'),
('avia'  , 'wolf ');
CREATE TABLE tests
(
    testid    INT NOT NULL AUTO_INCREMENT,
    TestDate  DATE,
    ClassName VARCHAR(25),
    StudentID INT NOT NULL,
    Grade     INT NOT NULL,
    PRIMARY KEY (testid),
    KEY (StudentID)
);
INSERT INTO tests (TestDate,ClassName,StudentID,Grade) VALUES
('2017-07-01', 'Algebra'    , 1 , 88 ), ('2017-08-02', 'Algo'       , 1 , 97 ),
('2017-09-01', 'Algebra'    , 1 , 80 ), ('2017-09-01', 'Algebra'    , 1 , 97 ),
('2017-09-01', 'Set-theory' , 1 , 85 ), ('2017-09-04', 'Calcules'   , 1 , 86 ),
('2016-05-03', 'Set-theory' , 2 , 84 ), ('2016-07-02', 'Calcules'   , 2 , 89 ),
('2016-07-04', 'Algo'       , 2 , 83 ), ('2016-07-05', 'Algebra'    , 2 , 79 ),
('2016-06-03', 'Algebra'    , 3 , 99 ), ('2016-07-02', 'Algo'       , 3 , 97 ),
('2016-07-03', 'Calcules'   , 3 , 96 ), ('2016-09-03', 'Set-theory' , 3 , 95 ),
('2016-06-03', 'Algebra'    , 4 , 78 );

Body:
Delay use of the students table, most of the calculations do not require student names.

SELECT
      s.StudentFirstName
    , s.StudentLastName
    , t1.ClassName
    , t1.student_class_avg AS `average for this subject`
    , t2.student_avg_avg   AS totalAvg
FROM students s
INNER JOIN (SELECT StudentID,ClassName,AVG(Grade) AS student_class_avg
      FROM tests
      GROUP BY StudentID,ClassName
     ) t1 ON s.StudentID = t1.StudentID
INNER JOIN (
      SELECT StudentID,AVG(student_class_avg) AS student_avg_avg
      FROM (
            SELECT StudentID,ClassName,AVG(Grade) AS student_class_avg
            FROM tests
            GROUP BY StudentID,ClassName
           ) t
      GROUP BY StudentID
     ) t2 ON s.StudentID = t2.StudentID
ORDER BY
      s.StudentFirstName
    , s.StudentLastName
    , t1.ClassName
;


问:
How to swap @JsonBackReference and @JsonManagedReference based on which Entity is reference
I'm trying to find a way to swap the @JsonBackRefence and the @JsonManagedReference based on what entity I reference from the associated repository.

Site.java

```<code>@Entity
@Table(name = "Site")
public class Site {

    @Id
    private String id;

    @OneToMany(mappedBy="site")
    @JsonManagedReference
    private List<Building> buildings;
}
</code>```

Building.java

```<code>@Entity
@Table(name = "building")
public class Building{

    @Id
    private String id;

    @ManyToOne
    @JoinColumn(name = "SITE_ID")
    @JsonBackReference
    private Site site;
}
</code>```

SiteRepository.java

```<code>public List<Site> findAll(); //Works as intended
</code>```

BuildingRepository.java

```<code>public Building findById(buildingId); //Works if references are swapped
</code>```

However when calling  findById(buildingId), I want to have the @JsonBackReference swapped. Therefore, the @JsonBackReference is in Site.java and the @JsonManagedReference is in the Building.java entity.

Note: @JsonIdentityInfo almosts handles it, but it gives me too much information ie: when I call findById(buildingId) from the BuildingRepository it gives me all the buildings for the site joined to the building found.

答:
If I understand you correctly the @JsonIgnoreProperties annotation should help you:

@JsonIgnoreProperties("site")
@OneToMany(mappedBy="site")
private List<Building> buildings;

@JsonIgnoreProperties("buildings")
@ManyToOne
private Site site;
```

Body:
I'm trying to find a way to swap the @JsonBackRefence and the @JsonManagedReference based on what entity I reference from the associated repository.

Site.java

@Entity
@Table(name = "Site")
public class Site {

    @Id
    private String id;

    @OneToMany(mappedBy="site")
    @JsonManagedReference
    private List<Building> buildings;
}

Building.java

@Entity
@Table(name = "building")
public class Building{

    @Id
    private String id;

    @ManyToOne
    @JoinColumn(name = "SITE_ID")
    @JsonBackReference
    private Site site;
}

SiteRepository.java

public List<Site> findAll(); //Works as intended

BuildingRepository.java

public Building findById(buildingId); //Works if references are swapped

However when calling  findById(buildingId), I want to have the @JsonBackReference swapped. Therefore, the @JsonBackReference is in Site.java and the @JsonManagedReference is in the Building.java entity.

Note: @JsonIdentityInfo almosts handles it, but it gives me too much information ie: when I call findById(buildingId) from the BuildingRepository it gives me all the buildings for the site joined to the building found.


问:
Find the position of a specific number that appear first in the list [python]
So I want to find a number that appears more than once in the list. I want the position of the first one.

Example: Say I want 3

```<code>     s = [1,2,3,4,5,3,9,8]  => s[2] appears first
</code>```

答:
```<code>s.index(3)
</code>```

will return 2, as you desire.

index will raise ValueError if the specified item is not in the list.

Body:
So I want to find a number that appears more than once in the list. I want the position of the first one.

Example: Say I want 3

     s = [1,2,3,4,5,3,9,8]  => s[2] appears first

Body:
s.index(3)

will return 2, as you desire.

index will raise ValueError if the specified item is not in the list.


问:
How to use dism.exe in WiX ExePackage for IIS feature activation?
I have made a bootstrapper project with WiX 3.9.
In this project i install IIS Express and then i activate the IIS features.
Until now i added the Dism.exe from my computer as a resource and activated the features like that:

```<code><ExePackage Id='IIS_WebserverRole'
            DisplayName='Installing IIS: IIS-WebServerRole'
            PerMachine='yes'
            SourceFile='.\Resources\Dism.exe'
            InstallCondition='SetupType="1" OR SetupType="3"'
            InstallCommand='/Online /Enable-Feature /FeatureName:IIS-WebServerRole'>
</ExePackage>
</code>```

This works fine, but i think it would be better to use the Dism.exe which we can find in C:\Windows\System32\ on the computer to be installed and not a resource file from my own computer.
So i tried this:

```<code><ExePackage Id='IIS_WebserverRole'
            DisplayName='Installing IIS: IIS-WebServerRole'
            PerMachine='yes'
            SourceFile='[SystemFolder]Dism.exe'
            InstallCondition='SetupType="1" OR SetupType="3"'
            InstallCommand='/Online /Enable-Feature /FeatureName:IIS-WebServerRole'>
</ExePackage>
</code>```

[SystemFolder] is a Burn standard variable which returns per example "C:\Windows\System32\".
But this doesn't work.
So i tried the following one.
You can find it in the first answer of this article:

Install IIS if not installed yet

```<code><ExePackage Id='IIS_WebserverRole'
            DisplayName='Installing IIS: IIS-WebServerRole'
            PerMachine='yes'
            SourceFile='.\Resources\run.bat'
            InstallCondition='SetupType="1" OR SetupType="3"'
            InstallCommand='Dism.exe /Online /Enable-Feature /FeatureName:IIS-WebServerRole'>
</ExePackage>
</code>```

But even this doesn't work.
I always get an error in the log file, that the executable file cannot be executed ;)

What's going wrong?
Can anybody give me a hint, what to do?
Thanks in advance!

答:
Use [System64Folder]dism.exe instead

--- EDIT ---

https://github.com/wixtoolset/issues/issues/5307

As mentioned above, the directory that WiX points to with property [SystemFolder] has been updated.

Unless [System64Folder] is being used, in 64 bit operating system, [SystemFolder] will point to C:\Windows\SysWow64 not C:\Window\System32 where 64 bit version of dism.exe resides.

This question was asked before the change, but it was confusing to me when I arrived to this page, so thought it would be worth mentioning.

Body:
I have made a bootstrapper project with WiX 3.9.
In this project i install IIS Express and then i activate the IIS features.
Until now i added the Dism.exe from my computer as a resource and activated the features like that:

<ExePackage Id='IIS_WebserverRole'
            DisplayName='Installing IIS: IIS-WebServerRole'
            PerMachine='yes'
            SourceFile='.\Resources\Dism.exe'
            InstallCondition='SetupType="1" OR SetupType="3"'
            InstallCommand='/Online /Enable-Feature /FeatureName:IIS-WebServerRole'>
</ExePackage>

This works fine, but i think it would be better to use the Dism.exe which we can find in C:\Windows\System32\ on the computer to be installed and not a resource file from my own computer.
So i tried this:

<ExePackage Id='IIS_WebserverRole'
            DisplayName='Installing IIS: IIS-WebServerRole'
            PerMachine='yes'
            SourceFile='[SystemFolder]Dism.exe'
            InstallCondition='SetupType="1" OR SetupType="3"'
            InstallCommand='/Online /Enable-Feature /FeatureName:IIS-WebServerRole'>
</ExePackage>

[SystemFolder] is a Burn standard variable which returns per example "C:\Windows\System32\".
But this doesn't work.
So i tried the following one.
You can find it in the first answer of this article:

Install IIS if not installed yet

<ExePackage Id='IIS_WebserverRole'
            DisplayName='Installing IIS: IIS-WebServerRole'
            PerMachine='yes'
            SourceFile='.\Resources\run.bat'
            InstallCondition='SetupType="1" OR SetupType="3"'
            InstallCommand='Dism.exe /Online /Enable-Feature /FeatureName:IIS-WebServerRole'>
</ExePackage>

But even this doesn't work.
I always get an error in the log file, that the executable file cannot be executed ;)

What's going wrong?
Can anybody give me a hint, what to do?
Thanks in advance!


问:
VTK : how to read grid cells' lenth, width and height?
I have a huge grid in *.pvd format. I would like to ensure some cells size specification have been respected when building said grid. To do so, I should get a cell data array with (dx,dy,dz)

I first tried to check this in Paraview with very little success. Then I resolved to export the mesh in various format (vtk, vtu, ex2) and import things into python using the vtk module, as in the code below. Unfortunately, the size of the mesh forbids it and I get various error messages stating "Unable to allocate n cells of size x".

```<code>import vtk
reader = vtk.vtkXMLUnstructuredGridReader()
reader.SetFileName("my_mesh.vtu")
reader.Update()
</code>```

Finally, in Paraview there is a python-shell that allows me to open the grid file in either pvd or vtk format:

```<code>>>> from paraview.simple import *
>>> my_vtk = OpenDataFile("my_mesh.vtk")
>>> print dir(my_vtk)
</code>```

Despite my browsing the methods and attribute of this reader object, I remain clueless about where to fetch any geometry information on the grid. I also browsed through the simple module documentation and I can't really wrap my head around it.

So how can one retrieve information regarding the geometry of cells from a paraview.servermanager.LegacyVTKReader object?

Any clue about how to achieve this with through the paraview GUI, or any kludge to load the vtk object into python vtk despite the memory issue is also very welcome. Sorry for such a hazy question, but I don't really know where to get started...

答:
You can use GetClientSideObject() (see here) to get a VTK object in the Paraview Python shell. After that you can use all the regular VTK Python functions. For example, you can write the following in the Paraview Python shell

```<code>>>> from paraview.simple import *
>>> currentSelection = GetActiveSource()
>>> readerObj = currentSelection.GetClientSideObject()
>>> unstructgrid = readerObj.GetOutput()
>>> firstCell = unstructgrid.GetCell(0)
>>> cellPoints = firstCell.GetPoints()
</code>```

Alternatively, you can use Programmable Filter in ParaView. This allows access to full VTK python module and even NumPy or other modules. You can enter following script in the script window of the programmable filter:

```<code>import vtk as v
import numpy as np

inp = self.GetUnstructuredGridInput()
cells = inp.GetCells()
cells.InitTraversal()
cellPtIds = v.vtkIdList()
lenArr = v.vtkDoubleArray()
lenArr.SetNumberOfComponents(3)
lenArr.SetName('CellSize')
while cells.GetNextCell( cellPtIds ):
    pts = []
    for i in range( cellPtIds.GetNumberOfIds() ):
        ptCoords = inp.GetPoint( cellPtIds.GetId(i) )
        pts.append( ptCoords )
    pts = np.array( pts )
    dx = np.max(pts[:,0]) - np.min(pts[:,0])
    dy = np.max(pts[:,1]) - np.min(pts[:,1])
    dz = np.max(pts[:,2]) - np.min(pts[:,2])
    lenArr.InsertNextTuple3(dx, dy, dz)
out = self.GetUnstructuredGridOutput()
out.ShallowCopy( inp )
out.GetCellData().AddArray( lenArr )
</code>```

In Paraview when you select the 'ProgrammableFilter1' icon in your pipeline, a new cell data array will be available to you from the drop-down as shown in the screenshot below. You can modify the script above to save the data to file to analyze externally.

Body:
I have a huge grid in *.pvd format. I would like to ensure some cells size specification have been respected when building said grid. To do so, I should get a cell data array with (dx,dy,dz)

I first tried to check this in Paraview with very little success. Then I resolved to export the mesh in various format (vtk, vtu, ex2) and import things into python using the vtk module, as in the code below. Unfortunately, the size of the mesh forbids it and I get various error messages stating "Unable to allocate n cells of size x".

import vtk
reader = vtk.vtkXMLUnstructuredGridReader()
reader.SetFileName("my_mesh.vtu")
reader.Update()

Finally, in Paraview there is a python-shell that allows me to open the grid file in either pvd or vtk format:

>>> from paraview.simple import *
>>> my_vtk = OpenDataFile("my_mesh.vtk")
>>> print dir(my_vtk)

Despite my browsing the methods and attribute of this reader object, I remain clueless about where to fetch any geometry information on the grid. I also browsed through the simple module documentation and I can't really wrap my head around it.

So how can one retrieve information regarding the geometry of cells from a paraview.servermanager.LegacyVTKReader object?

Any clue about how to achieve this with through the paraview GUI, or any kludge to load the vtk object into python vtk despite the memory issue is also very welcome. Sorry for such a hazy question, but I don't really know where to get started...

Body:
You can use GetClientSideObject() (see here) to get a VTK object in the Paraview Python shell. After that you can use all the regular VTK Python functions. For example, you can write the following in the Paraview Python shell

>>> from paraview.simple import *
>>> currentSelection = GetActiveSource()
>>> readerObj = currentSelection.GetClientSideObject()
>>> unstructgrid = readerObj.GetOutput()
>>> firstCell = unstructgrid.GetCell(0)
>>> cellPoints = firstCell.GetPoints()

Alternatively, you can use Programmable Filter in ParaView. This allows access to full VTK python module and even NumPy or other modules. You can enter following script in the script window of the programmable filter:

import vtk as v
import numpy as np

inp = self.GetUnstructuredGridInput()
cells = inp.GetCells()
cells.InitTraversal()
cellPtIds = v.vtkIdList()
lenArr = v.vtkDoubleArray()
lenArr.SetNumberOfComponents(3)
lenArr.SetName('CellSize')
while cells.GetNextCell( cellPtIds ):
    pts = []
    for i in range( cellPtIds.GetNumberOfIds() ):
        ptCoords = inp.GetPoint( cellPtIds.GetId(i) )
        pts.append( ptCoords )
    pts = np.array( pts )
    dx = np.max(pts[:,0]) - np.min(pts[:,0])
    dy = np.max(pts[:,1]) - np.min(pts[:,1])
    dz = np.max(pts[:,2]) - np.min(pts[:,2])
    lenArr.InsertNextTuple3(dx, dy, dz)
out = self.GetUnstructuredGridOutput()
out.ShallowCopy( inp )
out.GetCellData().AddArray( lenArr )

In Paraview when you select the 'ProgrammableFilter1' icon in your pipeline, a new cell data array will be available to you from the drop-down as shown in the screenshot below. You can modify the script above to save the data to file to analyze externally.


问:
How to set up pdftk or iText to work with Rails 3 on Heroku?
I'm trying to find a way to inject FDF file content into a fillable PDF file (provided by customer and not supposed to be 're-drawn' using Prawn or PDFKit), and I think I have to use either iText(with JRuby) or pdftk.

Both of these libs work with no problem on my Ubuntu local machine, but I am wondering how I would get either them to work on Heroku. Has anyone tried to get iText(JRuby) or PDFTK to work on Heroku ?

Thanks for your help!

答:
You can use pdftk on Heroku – it's pre-installed. You use it by shelling out to it as a command-line program from within your Ruby app.

For most pdftk commands, you will use Tempfiles. Interpolate the Tempfile#paths in the arguments to pdftk.

```<code>`pdftk #{subcommand}`
raise Exception unless $?.success?
</code>```

In some cases, you will be able to pipe data in and out using stdin and stdout rather than Tempfiles.

```<code>input = ...
output = IO.popen "pdftk #{subcommand}", 'w+b' do |io|
  io.write input
  io.flush
  io.close_write
  io.read
end
</code>```

Body:
You can use pdftk on Heroku – it's pre-installed. You use it by shelling out to it as a command-line program from within your Ruby app.

For most pdftk commands, you will use Tempfiles. Interpolate the Tempfile#paths in the arguments to pdftk.

`pdftk #{subcommand}`
raise Exception unless $?.success?

In some cases, you will be able to pipe data in and out using stdin and stdout rather than Tempfiles.

input = ...
output = IO.popen "pdftk #{subcommand}", 'w+b' do |io|
  io.write input
  io.flush
  io.close_write
  io.read
end


问:
Sampling rows from dataframe and saving unselected ones
I'm triying to randomly choose rows from a dataframe; however, I also need unselected ones. I proceeded as follows

```<code>#grades is data with size 100
half-grades = grades[sample(nrow(grades), 50), ]
</code>```

How do I save unselected ones?

答:
```<code>set.seed(1234)
half-grades=grades[-(sample(nrow(grades), 50)), ]
</code>```

Body:
I'm triying to randomly choose rows from a dataframe; however, I also need unselected ones. I proceeded as follows

#grades is data with size 100
half-grades = grades[sample(nrow(grades), 50), ]

How do I save unselected ones?