问:
CSS not applying to html code within {% block bodycontent %}
I'm currently building a website and am having trouble getting the css to apply to parts of my html code. I have a base.html which I want displayed on every page, and I'm using {% block bodycontent %} in different documents to give the different pages specific features. However, I'm finding that the css stylesheet doesn't seem to apply to the code within the block, and is only applying to base.html. I'm using the flask framework, and am not sure if this may be the problem - when I run the html file locally without flask, the styling seems to be working, but of course the page is incomplete, because it is not interacting with the base.

This is my base:

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Welcome</title>
</head>
<body>

  <div class="header">
    <nav>
      <a href="/">Welcome</a>
        <ul class="nav_links">
          <li> <a href="about_us">About us</a></li>
          <li> <a href="mission_statement">mission statement</a></li>
          <li> <a href="login">Login</a></li>
          <li> <a href="contact"><img src="../static/imag/contact.png" alt="Contact" class="contact"></a></li>
        </ul>
      </nav>
  </div>

{% block bodycontent %}
{% endblock bodycontent %}

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

This is my about_us.html:

```<code>{% extends "base.html" %}
{% block bodycontent %}
<link rel="stylesheet" href="../static/css/about_us.css">

  <div>
    <h1>Welcome!</h1>
    <h2>About us</h2>
    <p>insert paragraph about us</p>
  </div>

{% endblock bodycontent %}
</code>```

and finally, this is an excerpt of the css which is aplying only to the base.html - in this case, the .header and nav are applying, but the div etc. aren't.:

```<code>.header{
  overflow: visible;
  background-color: White;
  position: sticky;
  padding: 0;
  margin-top: -20px;
  margin-left: -20px;
  margin-right: -20px;
}

nav{
  display: flex;
  align-items: center;
  justify-content: space-between;
}

div{
  color: DimGray;
  font-family: Helvetica;
}

div h1{
  position: absolute;
  top: 17%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 600px;
  max-width: 100%;
  padding: 10px;
  text-align: center;
}

div h2{
  position: absolute;
  top: 35%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 600px;
  max-width: 100%;
  padding: 10px;
  text-align: center;
}

div p{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 600px;
  max-width: 100%;
  padding: 10px;
  font-size: 20px;
  text-align: center;
  line-height: 2em;
}
</code>```

I hope this contains all the information needed to answer the question. Sorry this is so long, I'm new to stack overflow and hope someone can help. Thank you in advance!

答:
Try adding {% load static %}.

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <link rel="stylesheet" href="{% static 'file.css' %}"> <!-- Here -->
   {% load static %}
  <title>Welcome</title>
</head>
<body>
  {% block content %}

  <div class="header">
    <nav>
      <a href="/">Welcome</a>
        <ul class="nav_links">
          <li> <a href="about_us">About us</a></li>
          <li> <a href="mission_statement">mission statement</a></li>
          <li> <a href="login">Login</a></li>
          <li> <a href="contact"><img src="../static/imag/contact.png" alt="Contact" class="contact"></a></li>
        </ul>
      </nav>
  </div>

 {% endblock content %}

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

Body:
I'm currently building a website and am having trouble getting the css to apply to parts of my html code. I have a base.html which I want displayed on every page, and I'm using {% block bodycontent %} in different documents to give the different pages specific features. However, I'm finding that the css stylesheet doesn't seem to apply to the code within the block, and is only applying to base.html. I'm using the flask framework, and am not sure if this may be the problem - when I run the html file locally without flask, the styling seems to be working, but of course the page is incomplete, because it is not interacting with the base.

This is my base:

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Welcome</title>

      Welcome

 About us

 mission statement

 Login

{% block bodycontent %}
{% endblock bodycontent %}

This is my about_us.html:

{% extends "base.html" %}
{% block bodycontent %}
<link rel="stylesheet" href="../static/css/about_us.css">

Welcome!

About us

insert paragraph about us

{% endblock bodycontent %}

and finally, this is an excerpt of the css which is aplying only to the base.html - in this case, the .header and nav are applying, but the div etc. aren't.:

.header{
  overflow: visible;
  background-color: White;
  position: sticky;
  padding: 0;
  margin-top: -20px;
  margin-left: -20px;
  margin-right: -20px;
}

nav{
  display: flex;
  align-items: center;
  justify-content: space-between;
}

div{
  color: DimGray;
  font-family: Helvetica;
}

div h1{
  position: absolute;
  top: 17%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 600px;
  max-width: 100%;
  padding: 10px;
  text-align: center;
}

div h2{
  position: absolute;
  top: 35%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 600px;
  max-width: 100%;
  padding: 10px;
  text-align: center;
}

div p{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 600px;
  max-width: 100%;
  padding: 10px;
  font-size: 20px;
  text-align: center;
  line-height: 2em;
}

I hope this contains all the information needed to answer the question. Sorry this is so long, I'm new to stack overflow and hope someone can help. Thank you in advance!

Body:
Try adding {% load static %}.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <link rel="stylesheet" href="{% static 'file.css' %}"> <!-- Here -->
   {% load static %}
  <title>Welcome</title>
</head>
<body>
  {% block content %}

  <div class="header">
    <nav>
      <a href="/">Welcome</a>
        <ul class="nav_links">
          <li> <a href="about_us">About us</a></li>
          <li> <a href="mission_statement">mission statement</a></li>
          <li> <a href="login">Login</a></li>
          <li> <a href="contact"><img src="../static/imag/contact.png" alt="Contact" class="contact"></a></li>
        </ul>
      </nav>
  </div>

 {% endblock content %}

</body>
</html>


来源: stackexchange

问:
Create SOAP request using KSOAP Android
I need to generate a soap request like this one.

SOAP-REQUEST

```<code>POST /TennisMasters/TennisMasters.Listener.asmx HTTP/1.1
Host: playinkstudio.com
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://playinktennismasters.com/authenticateUser"

    <?xml version="1.0" encoding="utf-8"?>
    <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
      <soap:Body>
        <authenticateUser xmlns="http://playinktennismasters.com/">
          <user>string</user>
        </authenticateUser>
      </soap:Body>
    </soap:Envelope>
</code>```

I am using KSOAP2, to build this request.

```<code>private static String SOAP_ACTION = "http://playinktennismasters.com/authenticateUser";
private static String NAMESPACE = "http://playinktennismasters.com/";
private static String METHOD_NAME = "authenticateUser";
private static String URL = "http://playinkstudio.com/TennisMasters/TennisMasters.Listener.asmx";

    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
    request.addProperty("user", "A Json String will be here");

    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
            SoapEnvelope.VER12);
    envelope.dotNet = true;
    envelope.setOutputSoapObject(request);
    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
    androidHttpTransport.debug = true;
    try {
        androidHttpTransport.call(SOAP_ACTION, envelope);
    } catch (Exception e) {
        e.printStackTrace();
    }
</code>```

This is the request which I got from debugging.

```<code><v:Envelope xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:d="http://www.w3.org/2001/XMLSchema" xmlns:c="http://www.w3.org/2003/05/soap-encoding" xmlns:v="http://www.w3.org/2003/05/soap-envelope">
<v:Header />
<v:Body>
<authenticateUser xmlns="http://playinktennismasters.com/" **id="o0" c:root="1"**>
<user **i:type="d:string"**>{"email":"asad.mahmood@gmail.com","UserDate":"Feb 22, 2012 7:01:24 PM","GearId":0,"GearValue":0,"Income":0,"Level":0,"MatchResult":0,"MatchType":0,"OfferId":0,"OpponentId":0,"Partners":0,"ExhibitionCount":0,"PowerRuns":0,"PowerServes":0,"PowerShots":0,"Seeds":0,"Energy":0,"Cash":0,"Stamina":0,"Strength":0,"SubLevel":0,"TotalEnergy":0,"TotalStamina":0,"TrainingId":0,"Agility":0,"UserId":0,"Age":0,"ActivityId":0,"gearIsGift":0}</user>
</authenticateUser>
</v:Body>
</v:Envelope>
</code>```

I don't know why extra attributes like "id" and "c:root" are being added in authenticateUser.
and extra attribute in  i:type="d:String".
Please can come someone give me a good example or tutorial which can guide me to create a request like above,Really Need help thanks.

答:
This generic sample is a working example. The soap web request sends: 90 and gets back "ninety".

function interface:

```<code>package com.mindef.idttpda.soap;

// function interface for two parameters
@FunctionalInterface
public interface Function2<One, Two> {
    public void apply(One one, Two two);
}
</code>```

soap request class (with multiple parameters :-):

```<code>package com.mindef.idttpda.soap;

// dependencies
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import java.util.Map;

/**
 * class for executing soap web service call.
 */
public class SoapRequest implements Runnable {

    // soap response comes in here
    SoapResponse soapResponse;

    // webservice variables
    String url, namespace, method, action;

    // list of parameters for web service method
    Map<String, Object> parameters;

    /**
     * soap call to webservice
     * @param parameters - list with parameters for method of web service call.
     * @param soapResponse - response of web service call is put in here
     */
    public SoapRequest(Map<String, Object> parameters, SoapResponse soapResponse) {
        this.parameters = parameters;
        this.soapResponse = soapResponse;
    }

    /**
     * set url of web service
     * example: https://www.dataaccess.com/webservicesserver/NumberConversion.wso
     * @param url - url of web service
     * @return this - for method chaining
     */
    public SoapRequest url(String url) {

        this.url = url;
        return this;
    }

    /**
     * set namespace of web service
     * example: http://www.dataaccess.com/webservicesserver/
     * @param namespace - namespace of webservice
     * @return this - for method chaining
     */
    public SoapRequest namespace(String namespace){
        this.namespace = namespace;
        return this;
    }

    /**
     * set method of web service
     * example: NumberToWords
     * @param method - method to call on web service
     * @return this - for method chaining
     */
    public SoapRequest method(String method){
        this.method = method;
        return this;
    }

    /**
     * set soap action of web service call
     * example: https://www.dataaccess.com/webservicesserver/NumberConversion.wso/NumberToWords
     * @param action - full name of action to call on webservice
     * @return this - for method chaining
     */
    public SoapRequest action(String action){
        this.action = action;
        return this;
    }

    /**
     * execute soap web service call
     */
    @Override
    public void run() {

        // soap object.
        SoapObject soapObject = new SoapObject(this.namespace, this.method);

        // create parameters
        for(Map.Entry<String, Object> parameter : parameters.entrySet()) {
            PropertyInfo propertyInfo = new PropertyInfo();
            propertyInfo.setName(parameter.getKey());
            propertyInfo.setValue(parameter.getValue());
            propertyInfo.setType(String.class);
            soapObject.addProperty(propertyInfo);
        }

        // make soap envelope
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.setOutputSoapObject(soapObject);

        // execute web request
        HttpTransportSE httpTransportSE = new HttpTransportSE(url);
        try {
            httpTransportSE.call(action, envelope);
            SoapPrimitive soapPrimitive = (SoapPrimitive) envelope.getResponse();
            soapResponse.complete(soapPrimitive.toString());
        }

        // exception handling
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * call soap web service
     */
    public void call() {
        new Thread(this).start();
    }
};
</code>```

soap response:

```<code>package com.mindef.idttpda.soap;

// dependencies
import android.view.View;

/**
 * class for executing function with response.
 */
public class SoapResponse {

    // operation executed when response is received from web service
    Function2<View, String> completeFunction;

    // view where operation is executed on.
    View view;

    /**
     * soap response from soap web request.
     * @param view - view where function is executed on
     * @param completeFunction - function to execute when response is received
     */
    public SoapResponse(View view, Function2<View, String> completeFunction) {
        this.view = view;
        this.completeFunction = completeFunction;
    }

    /**
     * execute function with response
     * @param response - response from soap web request
     */
    public void complete(String response) {
        completeFunction.apply(view, response);
    }
}
</code>```

how to call soap web service method:

```<code>    /**
     * load userlist from database and put in spinner
     */
    private void loadWhatever(View loginView) {

        // execute soap web request.
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("ubiNum","90");
        SoapResponse soapResponse = new SoapResponse(loginView, (view, string) -> this.loginOperation(view, string));
        new SoapRequest(parameters, soapResponse)
            .url("https://www.dataaccess.com/webservicesserver/NumberConversion.wso")
            .namespace("http://www.dataaccess.com/webservicesserver/")
            .action("https://www.dataaccess.com/webservicesserver/NumberConversion.wso/NumberToWords")
            .method("NumberToWords")
            .call();
</code>```

Replace the lambda expression with your own function. The lambda function is there so it can be replaced with whatever function you want to use the soap web service response for. You must keep the lambda signature.

```<code>(view, string) -> this.loginOperation(view, string)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Create SOAP request using KSOAP Android

Body:
I need to generate a soap request like this one.

SOAP-REQUEST

POST /TennisMasters/TennisMasters.Listener.asmx HTTP/1.1
Host: playinkstudio.com
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://playinktennismasters.com/authenticateUser"

    <?xml version="1.0" encoding="utf-8"?>
    <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
      <soap:Body>
        <authenticateUser xmlns="http://playinktennismasters.com/">
          <user>string</user>
        </authenticateUser>
      </soap:Body>
    </soap:Envelope>

I am using KSOAP2, to build this request.

private static String SOAP_ACTION = "http://playinktennismasters.com/authenticateUser";
private static String NAMESPACE = "http://playinktennismasters.com/";
private static String METHOD_NAME = "authenticateUser";
private static String URL = "http://playinkstudio.com/TennisMasters/TennisMasters.Listener.asmx";

    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
    request.addProperty("user", "A Json String will be here");

    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
            SoapEnvelope.VER12);
    envelope.dotNet = true;
    envelope.setOutputSoapObject(request);
    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
    androidHttpTransport.debug = true;
    try {
        androidHttpTransport.call(SOAP_ACTION, envelope);
    } catch (Exception e) {
        e.printStackTrace();
    }

This is the request which I got from debugging.

<v:Envelope xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:d="http://www.w3.org/2001/XMLSchema" xmlns:c="http://www.w3.org/2003/05/soap-encoding" xmlns:v="http://www.w3.org/2003/05/soap-envelope">
<v:Header />
<v:Body>
<authenticateUser xmlns="http://playinktennismasters.com/" **id="o0" c:root="1"**>
<user **i:type="d:string"**>{"email":"asad.mahmood@gmail.com","UserDate":"Feb 22, 2012 7:01:24 PM","GearId":0,"GearValue":0,"Income":0,"Level":0,"MatchResult":0,"MatchType":0,"OfferId":0,"OpponentId":0,"Partners":0,"ExhibitionCount":0,"PowerRuns":0,"PowerServes":0,"PowerShots":0,"Seeds":0,"Energy":0,"Cash":0,"Stamina":0,"Strength":0,"SubLevel":0,"TotalEnergy":0,"TotalStamina":0,"TrainingId":0,"Agility":0,"UserId":0,"Age":0,"ActivityId":0,"gearIsGift":0}</user>
</authenticateUser>
</v:Body>
</v:Envelope>

I don't know why extra attributes like "id" and "c:root" are being added in authenticateUser.
and extra attribute in  i:type="d:String".
Please can come someone give me a good example or tutorial which can guide me to create a request like above,Really Need help thanks.

Body:
This generic sample is a working example. The soap web request sends: 90 and gets back "ninety".

function interface:

package com.mindef.idttpda.soap;

// function interface for two parameters
@FunctionalInterface
public interface Function2<One, Two> {
    public void apply(One one, Two two);
}

soap request class (with multiple parameters :-):

package com.mindef.idttpda.soap;

// dependencies
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import java.util.Map;

/**
 * class for executing soap web service call.
 */
public class SoapRequest implements Runnable {

    // soap response comes in here
    SoapResponse soapResponse;

    // webservice variables
    String url, namespace, method, action;

    // list of parameters for web service method
    Map<String, Object> parameters;

    /**
     * soap call to webservice
     * @param parameters - list with parameters for method of web service call.
     * @param soapResponse - response of web service call is put in here
     */
    public SoapRequest(Map<String, Object> parameters, SoapResponse soapResponse) {
        this.parameters = parameters;
        this.soapResponse = soapResponse;
    }

    /**
     * set url of web service
     * example: https://www.dataaccess.com/webservicesserver/NumberConversion.wso
     * @param url - url of web service
     * @return this - for method chaining
     */
    public SoapRequest url(String url) {

        this.url = url;
        return this;
    }

    /**
     * set namespace of web service
     * example: http://www.dataaccess.com/webservicesserver/
     * @param namespace - namespace of webservice
     * @return this - for method chaining
     */
    public SoapRequest namespace(String namespace){
        this.namespace = namespace;
        return this;
    }

    /**
     * set method of web service
     * example: NumberToWords
     * @param method - method to call on web service
     * @return this - for method chaining
     */
    public SoapRequest method(String method){
        this.method = method;
        return this;
    }

    /**
     * set soap action of web service call
     * example: https://www.dataaccess.com/webservicesserver/NumberConversion.wso/NumberToWords
     * @param action - full name of action to call on webservice
     * @return this - for method chaining
     */
    public SoapRequest action(String action){
        this.action = action;
        return this;
    }

    /**
     * execute soap web service call
     */
    @Override
    public void run() {

        // soap object.
        SoapObject soapObject = new SoapObject(this.namespace, this.method);

        // create parameters
        for(Map.Entry<String, Object> parameter : parameters.entrySet()) {
            PropertyInfo propertyInfo = new PropertyInfo();
            propertyInfo.setName(parameter.getKey());
            propertyInfo.setValue(parameter.getValue());
            propertyInfo.setType(String.class);
            soapObject.addProperty(propertyInfo);
        }

        // make soap envelope
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.setOutputSoapObject(soapObject);

        // execute web request
        HttpTransportSE httpTransportSE = new HttpTransportSE(url);
        try {
            httpTransportSE.call(action, envelope);
            SoapPrimitive soapPrimitive = (SoapPrimitive) envelope.getResponse();
            soapResponse.complete(soapPrimitive.toString());
        }

        // exception handling
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * call soap web service
     */
    public void call() {
        new Thread(this).start();
    }
};

soap response:

package com.mindef.idttpda.soap;

// dependencies
import android.view.View;

/**
 * class for executing function with response.
 */
public class SoapResponse {

    // operation executed when response is received from web service
    Function2<View, String> completeFunction;

    // view where operation is executed on.
    View view;

    /**
     * soap response from soap web request.
     * @param view - view where function is executed on
     * @param completeFunction - function to execute when response is received
     */
    public SoapResponse(View view, Function2<View, String> completeFunction) {
        this.view = view;
        this.completeFunction = completeFunction;
    }

    /**
     * execute function with response
     * @param response - response from soap web request
     */
    public void complete(String response) {
        completeFunction.apply(view, response);
    }
}

how to call soap web service method:

    /**
     * load userlist from database and put in spinner
     */
    private void loadWhatever(View loginView) {

        // execute soap web request.
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("ubiNum","90");
        SoapResponse soapResponse = new SoapResponse(loginView, (view, string) -> this.loginOperation(view, string));
        new SoapRequest(parameters, soapResponse)
            .url("https://www.dataaccess.com/webservicesserver/NumberConversion.wso")
            .namespace("http://www.dataaccess.com/webservicesserver/")
            .action("https://www.dataaccess.com/webservicesserver/NumberConversion.wso/NumberToWords")
            .method("NumberToWords")
            .call();

Replace the lambda expression with your own function. The lambda function is there so it can be replaced with whatever function you want to use the soap web service response for. You must keep the lambda signature.

(view, string) -> this.loginOperation(view, string)

ContentLicense: CC BY-SA 4.0


问:
'List<dynamic>' is not a subtype of type 'List<String>' when decoding data
When I try to get data from my Firebase database I encounter this error when decoding List. This is the error. Unhandled Exception: type 'List' is not a subtype of type 'List'. I attach the method, which triggers the error.</p>
```<code>Future<void> fetchProducts() async {
    final url = Uri.parse(
        'https://recipier-e1139-default-rtdb.europe-west1.firebasedatabase.app/recipes.json');
    final response = await http.get(url);
    final extractedData = json.decode(response.body) as Map<String, dynamic>;
    if (extractedData.isEmpty || extractedData['error'] != null) {
      return;
    }
    List<Recipe> loadedRecipes = [];
    extractedData.forEach(
      (id, data) {
        loadedRecipes.add(
          Recipe(
            title: data['title'],
            description: data['description'],
            id: id,
            ingredients: data['ingredients'],
            steps: data['steps'],
            kcal: data['kcal'],
            p: data['p'],
            c: data['c'],
            f: data['f'],
          ),
        );
      },
    );
    _recipes = loadedRecipes;
    notifyListeners();
  }
</code>```

答:
Attach your Recipe model, for what I can see there is an attribute that is of type List<String> but firebase cast it to List<dynamic>, maybe try to do something like this if you're sure they're all of type String:

```<code>Future<void> fetchProducts() async {
    final url = Uri.parse(
        'https://recipier-e1139-default-rtdb.europe-west1.firebasedatabase.app/recipes.json');
    final response = await http.get(url);
    final extractedData = json.decode(response.body) as Map<String, dynamic>;
    if (extractedData.isEmpty || extractedData['error'] != null) {
      return;
    }
    List<Recipe> loadedRecipes = [];
    extractedData.forEach(
      (id, data) {
        loadedRecipes.add(
          Recipe(
            title: data['title'],
            description: data['description'],
            id: id,
            ingredients: data['ingredients'].cast<String>(), /// if this is of type list
            steps: data['steps'].cast<String>(), /// if this is of type list
            kcal: data['kcal'],
            p: data['p'],
            c: data['c'],
            f: data['f'],
          ),
        );
      },
    );
    _recipes = loadedRecipes;
    notifyListeners();
  }
</code>```

Body:
When I try to get data from my Firebase database I encounter this error when decoding List. This is the error. Unhandled Exception: type 'List' is not a subtype of type 'List'. I attach the method, which triggers the error.

Future<void> fetchProducts() async {
    final url = Uri.parse(
        'https://recipier-e1139-default-rtdb.europe-west1.firebasedatabase.app/recipes.json');
    final response = await http.get(url);
    final extractedData = json.decode(response.body) as Map<String, dynamic>;
    if (extractedData.isEmpty || extractedData['error'] != null) {
      return;
    }
    List<Recipe> loadedRecipes = [];
    extractedData.forEach(
      (id, data) {
        loadedRecipes.add(
          Recipe(
            title: data['title'],
            description: data['description'],
            id: id,
            ingredients: data['ingredients'],
            steps: data['steps'],
            kcal: data['kcal'],
            p: data['p'],
            c: data['c'],
            f: data['f'],
          ),
        );
      },
    );
    _recipes = loadedRecipes;
    notifyListeners();
  }

Body:
Attach your Recipe model, for what I can see there is an attribute that is of type List<String> but firebase cast it to List<dynamic>, maybe try to do something like this if you're sure they're all of type String:

Future<void> fetchProducts() async {
    final url = Uri.parse(
        'https://recipier-e1139-default-rtdb.europe-west1.firebasedatabase.app/recipes.json');
    final response = await http.get(url);
    final extractedData = json.decode(response.body) as Map<String, dynamic>;
    if (extractedData.isEmpty || extractedData['error'] != null) {
      return;
    }
    List<Recipe> loadedRecipes = [];
    extractedData.forEach(
      (id, data) {
        loadedRecipes.add(
          Recipe(
            title: data['title'],
            description: data['description'],
            id: id,
            ingredients: data['ingredients'].cast<String>(), /// if this is of type list
            steps: data['steps'].cast<String>(), /// if this is of type list
            kcal: data['kcal'],
            p: data['p'],
            c: data['c'],
            f: data['f'],
          ),
        );
      },
    );
    _recipes = loadedRecipes;
    notifyListeners();
  }


问:
SQL Query question (count dates for each month)
Hope you can help me with the following, i have the following view availble:
DD/MM/YYYY

```<code>ENTITY | StartDate  | EndDate    | CodeA | CodeB | Revenue | Currency
AZERT  | 01/01/2011 | 02/01/2011 | SU    | BOLD  | 100     | EUR
AZERT  | 28/01/2011 | 02/02/2011 | SU    | BOLD  | 500     | EUR
</code>```

Can someone help with a query to pull the data so that I get the following summed?

```<code>ENTITY | YYYY.MM | CodeA | CodeB | DAYS | TIMES | Revenue | Currency
AZERT  | 2011.01 | SU    | BOD   | 5    | 2     | 500     | EUR
AZERT  | 2011.02 | SU    | BOD   | 1    | 0     | 100     | EUR
</code>```

Where YYYY.MM is created depending on the difference between Sdate and EDate.
And DAYS is the variance between the start and end day in the right month
And TIMES is the number of times that the StartDate occurs in that month
Revenue splitted depening how many days there are.

答:
Assuming you are using SQL Server 2005 or later, would this work?</p>

```<code>SELECT
    DATEADD(dd, -DAY(EndDate + 1,EndDate))  -- Get first day of month for EndDate
    ,CodeA
    ,CodeB
    ,SUM(DATEDIFF(dd,StartDate, EndDate)) AS 'DAYS'
FROM
    TABLE1
GROUP BY
    DATEADD(dd, -DAY(EndDate + 1,EndDate))
    ,CodeA
    ,CodeB
</code>```

Body:
Hope you can help me with the following, i have the following view availble:
DD/MM/YYYY

ENTITY | StartDate  | EndDate    | CodeA | CodeB | Revenue | Currency
AZERT  | 01/01/2011 | 02/01/2011 | SU    | BOLD  | 100     | EUR
AZERT  | 28/01/2011 | 02/02/2011 | SU    | BOLD  | 500     | EUR

Can someone help with a query to pull the data so that I get the following summed?

ENTITY | YYYY.MM | CodeA | CodeB | DAYS | TIMES | Revenue | Currency
AZERT  | 2011.01 | SU    | BOD   | 5    | 2     | 500     | EUR
AZERT  | 2011.02 | SU    | BOD   | 1    | 0     | 100     | EUR

Where YYYY.MM is created depending on the difference between Sdate and EDate.
And DAYS is the variance between the start and end day in the right month
And TIMES is the number of times that the StartDate occurs in that month
Revenue splitted depening how many days there are.

Body:
Assuming you are using SQL Server 2005 or later, would this work?

SELECT
    DATEADD(dd, -DAY(EndDate + 1,EndDate))  -- Get first day of month for EndDate
    ,CodeA
    ,CodeB
    ,SUM(DATEDIFF(dd,StartDate, EndDate)) AS 'DAYS'
FROM
    TABLE1
GROUP BY
    DATEADD(dd, -DAY(EndDate + 1,EndDate))
    ,CodeA
    ,CodeB


问:
Pandas - Conditional Probability of a given specific b
I have DataFrame with two columns of "a" and "b".  How can I find the conditional probability of "a" given specific "b"?

```<code>df.groupby('a').groupby('b')
</code>```

does not work.  Lets assume I have 3 categories in column a, for each specific on I have 5 categories of b. What I need to do is to find total number of on class of b for each class of a. I tried apply command, but I think I do not know how to use it properly.

```<code>df.groupby('a').apply(lambda x: x[x['b']] == '...').count()
</code>```

答:
The question is a little odd, in that it suggests that column B has categorical values. Typically, we compute (conditional) expectations on real-valued variables. In this case, it's actually much simpler

df.groupby('A')['B'].mean()

For example, in the dataframe

df = pd.DataFrame({'A':['foo', 'bar', 'foo', 'bar','foo', 'bar', 'foo', 'foo'], 'B':[1, 1, 2, 3,2, 2, 1, 3], 'C':np.random.randn(8), 'D':np.random.randn(8)})

we get

A

bar    2.0

foo    1.8

Name: B, dtype: float64

Body:
I have DataFrame with two columns of "a" and "b".  How can I find the conditional probability of "a" given specific "b"?

df.groupby('a').groupby('b')

does not work.  Lets assume I have 3 categories in column a, for each specific on I have 5 categories of b. What I need to do is to find total number of on class of b for each class of a. I tried apply command, but I think I do not know how to use it properly.

df.groupby('a').apply(lambda x: x[x['b']] == '...').count()


问:
Embed Google Form in Gmail using Apps Script
I'm trying to use Apps script to embed a prefilled Form in an email.  The emails will only be sent to Gmail users.  I want something that works the same as pressing the 'include form in email' option when manually emailing a form.

I've successfully created the prefilledUrl and used UrlFetchApp and HtmlService to get the Html from the form and send email.

But when it arrives it looks like the screenshot below and user can not submit.

A stripped down version of the  code I am using is the following:

```<code>var prefilledForm = 'prefilledForm link here');
Logger.log(prefilledForm);

var subject = 'Message from Office';
var response = UrlFetchApp.fetch(prefilledForm);
var htmlBody = HtmlService.createHtmlOutput(response).getContent();

var body = 'Dear '+mName+',\n\n'+mMessage+'\nPlease acknowledge by submitting the form below.\nRegards,\nSchool Office';

GmailApp.sendEmail(eEmail,subject,body,{
  noReply:true,
  htmlBody: htmlBody
});
</code>```

Is there anyway to embed the form in an email just like it does when you select 'include form in email' like the screenshot below?

答:
I found workaround to allow to do it without need of manual attention. After point 3rd in Ashton Fei's response replace all instances of Title, description and link url with desired values using getCode() and replace():

```<code>  var formUrl = form.getPublishedUrl()
  var template = HtmlService.createTemplateFromFile("form.html").getCode(); // HTML code to string
  template = template.replaceAll("FORM__URL", formUrl).replace("TITLE", title).replace("Descpition_text", desctiptionText); //Swapping bits that need change
  var htmlBody = eval(template).getContent() //"Go back to HTML"
</code>```

Now you can use this HTML as you email htmlBody

Body:
I'm trying to use Apps script to embed a prefilled Form in an email.  The emails will only be sent to Gmail users.  I want something that works the same as pressing the 'include form in email' option when manually emailing a form.

I've successfully created the prefilledUrl and used UrlFetchApp and HtmlService to get the Html from the form and send email.

But when it arrives it looks like the screenshot below and user can not submit.

A stripped down version of the  code I am using is the following:

var prefilledForm = 'prefilledForm link here');
Logger.log(prefilledForm);

var subject = 'Message from Office';
var response = UrlFetchApp.fetch(prefilledForm);
var htmlBody = HtmlService.createHtmlOutput(response).getContent();

var body = 'Dear '+mName+',\n\n'+mMessage+'\nPlease acknowledge by submitting the form below.\nRegards,\nSchool Office';

GmailApp.sendEmail(eEmail,subject,body,{
  noReply:true,
  htmlBody: htmlBody
});

Is there anyway to embed the form in an email just like it does when you select 'include form in email' like the screenshot below?

Body:
I found workaround to allow to do it without need of manual attention. After point 3rd in Ashton Fei's response replace all instances of Title, description and link url with desired values using getCode() and replace():

  var formUrl = form.getPublishedUrl()
  var template = HtmlService.createTemplateFromFile("form.html").getCode(); // HTML code to string
  template = template.replaceAll("FORM__URL", formUrl).replace("TITLE", title).replace("Descpition_text", desctiptionText); //Swapping bits that need change
  var htmlBody = eval(template).getContent() //"Go back to HTML"

Now you can use this HTML as you email htmlBody


问:
Extract data of specific dates from NETCDF dataset
I have netcdf data which contains daily for the year 2020 with specific humidity as the variable, and an excel file that contains the date of all the cyclones that formed over the North Indian Ocean. Mostly, when we want to extract data within a particular time range we use to do slice using xarray, but in this particular situation, I am facing the problem that I need to extract data only for those specific cyclone days which are in the excel file and create a composite. If anyone can help me by showing how it can be done it will be much appreciated.
I am attaching a link to the netcdf dataset and the excel file containing the cyclone days.netcdf cyclonedays</p>

答:
This is fairly straightforward. You can convert the string dates to pandas datetime objects, and then select data from the DataArray directly using that.

```<code>import xarray as xr
import pandas as pd

ds = xr.load_dataset('data.nc')
times = pd.read_excel('time.xlsx')

times['Date(DD/MM/YYYY)'] = pd.to_datetime(times['Date(DD/MM/YYYY)'], infer_datetime_format=True)

ds['shum'][ds.time.isin(times.values)]
</code>```

In this case, the output has no data because your dates in 2020 while the netcdf file only has dates from 2019.

Body:
This is fairly straightforward. You can convert the string dates to pandas datetime objects, and then select data from the DataArray directly using that.

import xarray as xr
import pandas as pd

ds = xr.load_dataset('data.nc')
times = pd.read_excel('time.xlsx')

times['Date(DD/MM/YYYY)'] = pd.to_datetime(times['Date(DD/MM/YYYY)'], infer_datetime_format=True)

ds['shum'][ds.time.isin(times.values)]

In this case, the output has no data because your dates in 2020 while the netcdf file only has dates from 2019.


问:
django.db.utils.IntegrityError: The row in table 'main_page_projects' with primary key '1' has an invalid foreign key
Created first project model and populated it with some data, then tried to add profile model to it (no data there) through foreign key and while trying to do a migration for linking profile model with projects model getting an error:

django.db.utils.IntegrityError: The row in table 'main_page_projects' with primary key '1' has an invalid foreign key: main_page_projects.profile_id contains a value '1' that does not have a corresponding value in main_page_profile.id.

Value nr 1 was picked during the makemigration:

It is impossible to add a non-nullable field 'profile' to projects without specifying a default. This is because the database needs something to populate existing rows.
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit and manually define a default value in models.py.

I googled around and looked also stackoverflow, probably if I delete migration files and sqlite3 database then migrations should work, but I would like to know how to make it to work without deleting migration files and database. If populate profile then migration also works, but why it won't create a link with default values?

What should I do differently or where I go wrong?

Using Django 4.0.2 and Python 3.9.5

models.py

```<code>from django.db import models

class Profile(models.Model):
    full_name = models.CharField(max_length=50, verbose_name='Name')
    email = models.EmailField(unique=True, verbose_name='Email')
    bio = models.TextField(max_length=500, verbose_name='Description')
    profile_picture = models.ImageField(upload_to='profile_picture')

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = 'Profile'
        verbose_name_plural = 'Profiles'

class Projects(models.Model):
    name = models.CharField(max_length=50, unique=True, verbose_name='Name')
    slug = models.SlugField(unique=True)
    tech = models.CharField(max_length=50)
    description = models.TextField(max_length=500, verbose_name='Description')
    image = models.ImageField(upload_to='portfolio/')
    profile = models.ForeignKey(Profile, on_delete=models.CASCADE)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = 'Project'
        verbose_name_plural = 'Projects'

</code>```

Projects migration and Profile migration code

Projects migration

```<code>from django.db import migrations, models

class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Projects',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=50, unique=True, verbose_name='Name')),
                ('slug', models.SlugField(unique=True)),
                ('tech', models.CharField(max_length=50)),
                ('description', models.TextField(max_length=150, verbose_name='Description')),
                ('image', models.ImageField(upload_to='portfolio/')),
            ],
        ),
    ]

</code>```

Profile migration

```<code>
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('main_page', '0003_projects_image'),
    ]

    operations = [
        migrations.CreateModel(
            name='Profile',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('full_name', models.CharField(max_length=50, verbose_name='Name')),
                ('email', models.EmailField(max_length=254, unique=True, verbose_name='Email')),
                ('bio', models.TextField(max_length=500, verbose_name='Description')),
                ('profile_picture', models.ImageField(upload_to='profile_picture')),
            ],
            options={
                'verbose_name': 'Profile',
                'verbose_name_plural': 'Profiles',
            },
        ),
    ]

</code>```

Foreign key relation migration

```<code># Generated by Django 4.0.2 on 2022-02-11 08:05

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('main_page', '0004_profile'),
    ]

    operations = [
        migrations.AddField(
            model_name='projects',
            name='profile',
            field=models.ForeignKey(default='1', on_delete=django.db.models.deletion.CASCADE, to='main_page.profile'),
            preserve_default=False,
        ),
    ]

</code>```

答:
You can not create an entry in a database table (or modify one by adding a field via migrations) with a ForeignKey that points to a non existing entry on the target table ("Profile" in your case). It does not make sense - so you get the integrity error.
Leave away the default=1 and make it "blank=True, null=True" so you can leave it empty upon creation or during migration.</p>

Body:
Created first project model and populated it with some data, then tried to add profile model to it (no data there) through foreign key and while trying to do a migration for linking profile model with projects model getting an error:

django.db.utils.IntegrityError: The row in table 'main_page_projects' with primary key '1' has an invalid foreign key: main_page_projects.profile_id contains a value '1' that does not have a corresponding value in main_page_profile.id.

Value nr 1 was picked during the makemigration:

It is impossible to add a non-nullable field 'profile' to projects without specifying a default. This is because the database needs something to populate existing rows.
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit and manually define a default value in models.py.

I googled around and looked also stackoverflow, probably if I delete migration files and sqlite3 database then migrations should work, but I would like to know how to make it to work without deleting migration files and database. If populate profile then migration also works, but why it won't create a link with default values?

What should I do differently or where I go wrong?

Using Django 4.0.2 and Python 3.9.5

models.py

from django.db import models

class Profile(models.Model):
    full_name = models.CharField(max_length=50, verbose_name='Name')
    email = models.EmailField(unique=True, verbose_name='Email')
    bio = models.TextField(max_length=500, verbose_name='Description')
    profile_picture = models.ImageField(upload_to='profile_picture')

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = 'Profile'
        verbose_name_plural = 'Profiles'

class Projects(models.Model):
    name = models.CharField(max_length=50, unique=True, verbose_name='Name')
    slug = models.SlugField(unique=True)
    tech = models.CharField(max_length=50)
    description = models.TextField(max_length=500, verbose_name='Description')
    image = models.ImageField(upload_to='portfolio/')
    profile = models.ForeignKey(Profile, on_delete=models.CASCADE)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = 'Project'
        verbose_name_plural = 'Projects'

Projects migration and Profile migration code

Projects migration

from django.db import migrations, models

class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Projects',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=50, unique=True, verbose_name='Name')),
                ('slug', models.SlugField(unique=True)),
                ('tech', models.CharField(max_length=50)),
                ('description', models.TextField(max_length=150, verbose_name='Description')),
                ('image', models.ImageField(upload_to='portfolio/')),
            ],
        ),
    ]

Profile migration

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('main_page', '0003_projects_image'),
    ]

    operations = [
        migrations.CreateModel(
            name='Profile',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('full_name', models.CharField(max_length=50, verbose_name='Name')),
                ('email', models.EmailField(max_length=254, unique=True, verbose_name='Email')),
                ('bio', models.TextField(max_length=500, verbose_name='Description')),
                ('profile_picture', models.ImageField(upload_to='profile_picture')),
            ],
            options={
                'verbose_name': 'Profile',
                'verbose_name_plural': 'Profiles',
            },
        ),
    ]

Foreign key relation migration

# Generated by Django 4.0.2 on 2022-02-11 08:05

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('main_page', '0004_profile'),
    ]

    operations = [
        migrations.AddField(
            model_name='projects',
            name='profile',
            field=models.ForeignKey(default='1', on_delete=django.db.models.deletion.CASCADE, to='main_page.profile'),
            preserve_default=False,
        ),
    ]


问:
Lenses, the State monad, and Maps with known keys
here is a puzzle that I keep on bumping into and that, I believe, no previous SO question has been addressing: How can I best use the lens library to set or get values within a State monad managing a nested data structure that involves Maps when I know for a fact that certain keys are present in the maps involved?

Here is the puzzle

{-# LANGUAGE TemplateHaskell, DerivingVia #-}

import Control.Monad.State
import Control.Monad.Except
import Control.Lens
import Data.Maybe
import Control.Monad
import Data.Map

type M = StateT World (ExceptT String Identity)

data World = World
  { _users      :: Map UserId User
  , _otherStuff :: Int
  }

type UserId = Int

data User = User
  { _balance     :: Balance
  , _moreStuff   :: Int
  }

newtype Balance = Balance Int
  deriving (Eq, Ord, Num) via Int

makeLenses 'World
makeLenses 'User

deleteUser :: UserId -> M ()
deleteUser uid = do
   user <- use $ users . at uid
   unless (isJust user) (throwError "unknown user")

   -- from here on we know the users exists.

   -- Question: how should the following lens look like?
   balance <- use $ users . ix uid . balance
   when (balance < 0) (throwError "you first have to settle your debt")
   when (balance > 0) (throwError "you first have to withdraw the remaining balance")

   users . at uid .= Nothing
```
<h1>Attempt 1: using <code>ix</code></h1>
<p>The snippet above is using <code>ix</code>.</p>
<pre class="lang-hs prettyprint-override"><code>   balance <- use $ users . ix uid . balance
</code>```

This yields a Traversal, so it may focus on multiple elements or none at all. In the context of use this means we need a Monoid and a Semigroup instance. In fact, this is what GHC has to say:

```<code>    • No instance for (Monoid Balance) arising from a use of ‘ix’
    • In the first argument of ‘(.)’, namely ‘ix uid’
      In the second argument of ‘(.)’, namely ‘ix uid . balance’
      In the second argument of ‘($)’, namely ‘users . ix uid . balance’
   |
45 |    balance <- use $ users . ix uid . balance
</code>```

There is no good way to implement <> for Balance. I could just implement addition, or use error, because, in fact, this function will never be called. But is this the cleanest way to do this?

Attempt 2: using at

Another option seems to be using at.

   balance <- use $ users . at uid . balance
```
<p>This yields a <code>Lens</code> that focuses on a <code>Maybe User</code>. This means, the follow-up lens <code>balance</code> has the wrong type.</p>
```    • Couldn't match type ‘User’
                     with ‘Maybe (IxValue (Map UserId User))’
      Expected type: (User -> Const Balance User)
                     -> Map UserId User -> Const Balance (Map UserId User)
        Actual type: (Maybe (IxValue (Map UserId User))
                      -> Const Balance (Maybe (IxValue (Map UserId User))))
                     -> Map UserId User -> Const Balance (Map UserId User)
    • In the first argument of ‘(.)’, namely ‘at uid’
      In the second argument of ‘(.)’, namely ‘at uid . balance’
      In the second argument of ‘($)’, namely ‘users . at uid . balance’
```
<h1>Attempt 3: working with <code>at</code>'s <code>Maybe</code></h1>
<p>Let's try to work with that <code>Maybe</code></p>
<pre class="lang-hs prettyprint-override"><code>   balance <- use $ users . at uid . _Just . balance
</code>```

This time, we have a Prism, which needs to deal with the situation when it has to work with Nothing. So we are back at requiring a Monoid.

```<code>    • No instance for (Monoid Balance) arising from a use of ‘_Just’
    • In the first argument of ‘(.)’, namely ‘_Just’
      In the second argument of ‘(.)’, namely ‘_Just . balance’
      In the second argument of ‘(.)’, namely ‘at uid . _Just . balance’
</code>```

Attempt 3b: working with at's Maybe

Let's try another way to work with that Maybe

   balance <- use $ users . at uid . non undefined . balance
```
<p>From the documentation:</p>
<blockquote>
<p>If v is an element of a type a, and a' is a sans the element v, then non v is an isomorphism from Maybe a' to a.</p>
</blockquote>
<p>We can use <code>undefined</code>, <code>error</code> or any "empty" <code>User</code> we want, it does not matter, since this case is never triggered, given the user id is present in the map.</p>
<p>For this to work we need <code>Eq</code> for <code>User</code>, which is fair enough. And it compiles and seems to work; that is, for reading. For writing, there is an, initially, unexpected twist:</p>
<pre class="lang-hs prettyprint-override"><code>topUp :: UserId -> Balance -> M ()
topUp uid b = do
   user <- use $ users . at uid
   unless (isJust user) (throwError "unknown user")

   users . at uid . non undefined . balance += b
</code>```

Running this blows up

```<code>experiment-exe: Prelude.undefined
CallStack (from HasCallStack):
  error, called at libraries/base/GHC/Err.hs:79:14 in base:GHC.Err
  undefined, called at app/Main.hs:55:25 in main:Main
</code>```

The explanation is that when writing, we use the optics "right-to-left", and in this direction non is injecting the User we provide as its parameter. Replacing undefined with a "empty" User obscures this mistake. It always replaces the existing user with the empty user, effectively loosing the user's initial balance when trying to top-up.

Conclusion

So, I have found options to make this work for reading, but none seems to be convincing. And I could not figure this out for writing.

What is your recommendation? How should that lens be constructed?

Edit: moved solution to self answer.

答:
There is:

balance <- use $ users . at uid . to fromJust . balance for reading (see this answer)

users . at uid . traversed . balance += b for writing (see this comment)

And this lens works for reading and writing:

users . unsafeSingular (ix uid) . balance (see this answer)

Body:
here is a puzzle that I keep on bumping into and that, I believe, no previous SO question has been addressing: How can I best use the lens library to set or get values within a State monad managing a nested data structure that involves Maps when I know for a fact that certain keys are present in the maps involved?

Here is the puzzle

{-# LANGUAGE TemplateHaskell, DerivingVia #-}

import Control.Monad.State
import Control.Monad.Except
import Control.Lens
import Data.Maybe
import Control.Monad
import Data.Map

type M = StateT World (ExceptT String Identity)

data World = World
  { _users      :: Map UserId User
  , _otherStuff :: Int
  }

type UserId = Int

data User = User
  { _balance     :: Balance
  , _moreStuff   :: Int
  }

newtype Balance = Balance Int
  deriving (Eq, Ord, Num) via Int

makeLenses 'World
makeLenses 'User

deleteUser :: UserId -> M ()
deleteUser uid = do
   user <- use $ users . at uid
   unless (isJust user) (throwError "unknown user")

   -- from here on we know the users exists.

   -- Question: how should the following lens look like?
   balance <- use $ users . ix uid . balance
   when (balance < 0) (throwError "you first have to settle your debt")
   when (balance > 0) (throwError "you first have to withdraw the remaining balance")

   users . at uid .= Nothing

Attempt 1: using ix

The snippet above is using ix.

   balance <- use $ users . ix uid . balance

This yields a Traversal, so it may focus on multiple elements or none at all. In the context of use this means we need a Monoid and a Semigroup instance. In fact, this is what GHC has to say:

    • No instance for (Monoid Balance) arising from a use of ‘ix’
    • In the first argument of ‘(.)’, namely ‘ix uid’
      In the second argument of ‘(.)’, namely ‘ix uid . balance’
      In the second argument of ‘($)’, namely ‘users . ix uid . balance’
   |
45 |    balance <- use $ users . ix uid . balance

There is no good way to implement <> for Balance. I could just implement addition, or use error, because, in fact, this function will never be called. But is this the cleanest way to do this?

Attempt 2: using at

Another option seems to be using at.

   balance <- use $ users . at uid . balance

This yields a Lens that focuses on a Maybe User. This means, the follow-up lens balance has the wrong type.

    • Couldn't match type ‘User’
                     with ‘Maybe (IxValue (Map UserId User))’
      Expected type: (User -> Const Balance User)
                     -> Map UserId User -> Const Balance (Map UserId User)
        Actual type: (Maybe (IxValue (Map UserId User))
                      -> Const Balance (Maybe (IxValue (Map UserId User))))
                     -> Map UserId User -> Const Balance (Map UserId User)
    • In the first argument of ‘(.)’, namely ‘at uid’
      In the second argument of ‘(.)’, namely ‘at uid . balance’
      In the second argument of ‘($)’, namely ‘users . at uid . balance’

Attempt 3: working with at's Maybe

Let's try to work with that Maybe

   balance <- use $ users . at uid . _Just . balance

This time, we have a Prism, which needs to deal with the situation when it has to work with Nothing. So we are back at requiring a Monoid.

    • No instance for (Monoid Balance) arising from a use of ‘_Just’
    • In the first argument of ‘(.)’, namely ‘_Just’
      In the second argument of ‘(.)’, namely ‘_Just . balance’
      In the second argument of ‘(.)’, namely ‘at uid . _Just . balance’

Attempt 3b: working with at's Maybe

Let's try another way to work with that Maybe

   balance <- use $ users . at uid . non undefined . balance

From the documentation:

If v is an element of a type a, and a' is a sans the element v, then non v is an isomorphism from Maybe a' to a.

We can use undefined, error or any "empty" User we want, it does not matter, since this case is never triggered, given the user id is present in the map.

For this to work we need Eq for User, which is fair enough. And it compiles and seems to work; that is, for reading. For writing, there is an, initially, unexpected twist:

topUp :: UserId -> Balance -> M ()
topUp uid b = do
   user <- use $ users . at uid
   unless (isJust user) (throwError "unknown user")

   users . at uid . non undefined . balance += b

Running this blows up

experiment-exe: Prelude.undefined
CallStack (from HasCallStack):
  error, called at libraries/base/GHC/Err.hs:79:14 in base:GHC.Err
  undefined, called at app/Main.hs:55:25 in main:Main

The explanation is that when writing, we use the optics "right-to-left", and in this direction non is injecting the User we provide as its parameter. Replacing undefined with a "empty" User obscures this mistake. It always replaces the existing user with the empty user, effectively loosing the user's initial balance when trying to top-up.

Conclusion

So, I have found options to make this work for reading, but none seems to be convincing. And I could not figure this out for writing.

What is your recommendation? How should that lens be constructed?

Edit: moved solution to self answer.


问:
How does Azure App Service decide whether my app active or idle?
I'm trying to find information what are the criteria for that? I know that "Always On" option exists and calls periodically the service to keep it alive.

So my question:
Is it only REST calls to an endpoint shows that service in active? If I have a Kafka consumer that receive the messages, is it considered as the app is not idle?

答:
A web app can time out after 20 minutes of inactivity, and only requests to the actual web app can reset the timer. Viewing the app's configuration in the Azure portal or making requests to the advanced tools site (https://<app_name>.scm.azurewebsites.net) doesn't reset the timer. If you set the web app that hosts your job to run continuously, run on a schedule, or use event-driven triggers, enable the Always on setting on your web app's Azure Configuration page.

WebJobs is designed for background processing. You can do as much background processing as you want in a WebJob. For more information about WebJobs, see Run background tasks with WebJobs.


问:
Cakephp custom query pagination
I'm trying to use custom query in Cake then paginate the results with the code below:

```<code>$query = $this->Petition->query($sql);
</code>```

I tried:

```<code>$petitions = $this->paginate($query);
</code>```

and it doesn't work. Is there a way we can do this?

OK I wasn't clear enough: I need to use variable array fetched from custom query on pagination so I can use this for pagination in the view. Is there an easy way of doing this?
Below is my code:

```<code>function index() {
        if ($this->Session->read('Auth.User.group_id') != 1) {
            $commune_id = $this->Session->read('Auth.User.commune_id');
            $commune_id = $this->Petition->Commune->findbyId($commune_id);
            $commune_id = $this->Petition->Commune->find('all',array('conditions' => array('group' => $commune_id['Commune']['group'])));
            $count = count($commune_id);
            $i=1;
            $sql = "SELECT * FROM `petitions` WHERE `commune_id` = ";
            foreach($commune_id as $commune_ids){
                if($i==1){
                $sql .= $commune_ids['Commune']['id'];
                }else{
                $sql .= " OR `commune_id` = ".$commune_ids['Commune']['id'];
                }
            /*if($i != $count){
            $this->paginate = array(
                'or' => array(
                    array('Petition.commune_id LIKE' => $commune_ids['Commune']['id'] . ","),
                    //array('Petition.commune_id LIKE' => "," . $commune_ids['Commune']['id'] . ",")
                    ),
                'limit' => 10
            );
            }*/
            $i++;
            }
            $query = $this->Petition->query($sql);
        }
        $this->Petition->recursive = 0;
        $petitions = $this->paginate();
        $this->set('petitions', $petitions);
    }
</code>```

答:
this is not how pagination works
you need to fill $this->validate with your conditions etc
and then use $this->paginate() plainly

see
http://book.cakephp.org/view/1232/Controller-Setup

also note the chapter about the custom query part if it is really(!) necessary.

Title: Cakephp custom query pagination

Body:
I'm trying to use custom query in Cake then paginate the results with the code below:

$query = $this->Petition->query($sql);

I tried:

$petitions = $this->paginate($query);

and it doesn't work. Is there a way we can do this?

OK I wasn't clear enough: I need to use variable array fetched from custom query on pagination so I can use this for pagination in the view. Is there an easy way of doing this?
Below is my code:

function index() {
        if ($this->Session->read('Auth.User.group_id') != 1) {
            $commune_id = $this->Session->read('Auth.User.commune_id');
            $commune_id = $this->Petition->Commune->findbyId($commune_id);
            $commune_id = $this->Petition->Commune->find('all',array('conditions' => array('group' => $commune_id['Commune']['group'])));
            $count = count($commune_id);
            $i=1;
            $sql = "SELECT * FROM `petitions` WHERE `commune_id` = ";
            foreach($commune_id as $commune_ids){
                if($i==1){
                $sql .= $commune_ids['Commune']['id'];
                }else{
                $sql .= " OR `commune_id` = ".$commune_ids['Commune']['id'];
                }
            /*if($i != $count){
            $this->paginate = array(
                'or' => array(
                    array('Petition.commune_id LIKE' => $commune_ids['Commune']['id'] . ","),
                    //array('Petition.commune_id LIKE' => "," . $commune_ids['Commune']['id'] . ",")
                    ),
                'limit' => 10
            );
            }*/
            $i++;
            }
            $query = $this->Petition->query($sql);
        }
        $this->Petition->recursive = 0;
        $petitions = $this->paginate();
        $this->set('petitions', $petitions);
    }


问:
How to break out of a do-while style loop in Rust?
Rust allows a kind of do-while loop eg:

So the C style:

```<code>do {
    something();
} while (test());
</code>```

Can be written in Rust as:

```<code>while {
    something();
    test()
}{}
</code>```

However there is a problem using break in this case:

So this C style:

```<code>do {
    if (something()) {
        break;
    }
} while (test());
</code>```

Can't be written in Rust as:

```<code>while {
    if (something()) {
        break;
    }
    test()
}{}
</code>```

Fails to compile with cannot break outside of a loop.

Is there a way to break out of this form of while loop?

Note 1) the reason to use:
do {...} while test() flow control instead of
while test() {...} is in this case test() will be false when entering the loop initially.

Note 2) When using  while {...} flow control: calling continue in the body of the code will skip the break check at the end.

See related question: How to wrap a do-while style loop in a macro, maintaining 'continue' flow control?

答:
With rust you can label a loop when you declare it and use the label to break the loop later:

'mylabel: loop {
  something();
  if test() { break 'mylabel; }
}
```

Body:
Rust allows a kind of do-while loop eg:

So the C style:

do {
    something();
} while (test());

Can be written in Rust as:

while {
    something();
    test()
}{}

However there is a problem using break in this case:

So this C style:

do {
    if (something()) {
        break;
    }
} while (test());

Can't be written in Rust as:

while {
    if (something()) {
        break;
    }
    test()
}{}

Fails to compile with cannot break outside of a loop.

Is there a way to break out of this form of while loop?

Note 1) the reason to use:
do {...} while test() flow control instead of
while test() {...} is in this case test() will be false when entering the loop initially.

Note 2) When using  while {...} flow control: calling continue in the body of the code will skip the break check at the end.

See related question: How to wrap a do-while style loop in a macro, maintaining 'continue' flow control?


问:
How to find the subset of a dataframe, given a specific index and a specific value?
I have a huge dataframe to work with. I am having difficulties in figuring out how to get the subset of the dataframe given a specific index and only such columns should be selected having a specific value.

My objective can be illustrated as follows:

```<code>data = {'A': [5,6,9,8,3,2,4,1],
        'B': [1,5,3,4,2,1,1,1],
        'C': [1,0,0,1,3,4,5,3],
        'D': [5,6,9,8,7,1,1,1]
        }

df = pd.DataFrame(data)
df
</code>```

I would like to have a subset of DataFrame where index is 5 and the specific value is 1.

Desired Output:

```<code>  B D
------
5 1 1
</code>```

I used the following command to get the index=5 values.

```<code>df.loc[df.index==5, df.columns]
</code>```

I tried to refer to related questions, but could not come up with a solution. Please do help.

答:
```<code>pd.DataFrame(data.loc[5, data.iloc[5,:]==1]).T
Out[]:
   B  D
5  1  1
</code>```

Body:
I have a huge dataframe to work with. I am having difficulties in figuring out how to get the subset of the dataframe given a specific index and only such columns should be selected having a specific value.

My objective can be illustrated as follows:

data = {'A': [5,6,9,8,3,2,4,1],
        'B': [1,5,3,4,2,1,1,1],
        'C': [1,0,0,1,3,4,5,3],
        'D': [5,6,9,8,7,1,1,1]
        }

df = pd.DataFrame(data)
df

I would like to have a subset of DataFrame where index is 5 and the specific value is 1.

Desired Output:

  B D
------
5 1 1

I used the following command to get the index=5 values.

df.loc[df.index==5, df.columns]

I tried to refer to related questions, but could not come up with a solution. Please do help.


问:
TypeError: incompatible index of inserted column with frame index when grouping 2 columns
I have a dataset that looks like this (+ some other cols):

```<code>Value         Theme       Country
-1.975767     Weather     China
-0.540979     Fruits      China
-2.359127     Fruits      China
-2.815604     Corona      Brazil
-0.929755     Weather     UK
-0.929755     Weather     UK
</code>```

I want to find standard deviations for the values after grouping by Themes and Countries (as explained here calculate standard deviation by grouping two columns

```<code>df = pd.read_csv('./Brazil.csv')
df['std'] = df.groupby(['themes', 'country'])['value'].std()
</code>```

However, currently, I get this error:

```<code>File /usr/local/Cellar/ipython/8.0.1/libexec/lib/python3.10/site-packages/pandas/core/frame.py:3656, in DataFrame.__setitem__(self, key, value)
   3653     self._setitem_array([key], value)
   3654 else:
   3655     # set column
-> 3656     self._set_item(key, value)

File /usr/local/Cellar/ipython/8.0.1/libexec/lib/python3.10/site-packages/pandas/core/frame.py:3833, in DataFrame._set_item(self, key, value)
   3823 def _set_item(self, key, value) -> None:
   3824     """
   3825     Add series to DataFrame in specified column.
   3826
   (...)
   3831     ensure homogeneity.
   3832     """
-> 3833     value = self._sanitize_column(value)
   3835     if (
   3836         key in self.columns
   3837         and value.ndim == 1
   3838         and not is_extension_array_dtype(value)
   3839     ):
   3840         # broadcast across multiple columns if necessary
   3841         if not self.columns.is_unique or isinstance(self.columns, MultiIndex):

File /usr/local/Cellar/ipython/8.0.1/libexec/lib/python3.10/site-packages/pandas/core/frame.py:4534, in DataFrame._sanitize_column(self, value)
   4532 # We should never get here with DataFrame value
   4533 if isinstance(value, Series):
-> 4534     return _reindex_for_setitem(value, self.index)
   4536 if is_list_like(value):
   4537     com.require_length_match(value, self.index)

File /usr/local/Cellar/ipython/8.0.1/libexec/lib/python3.10/site-packages/pandas/core/frame.py:10985, in _reindex_for_setitem(value, index)
  10981     if not value.index.is_unique:
  10982         # duplicate axis
  10983         raise err
> 10985     raise TypeError(
  10986         "incompatible index of inserted column with frame index"
  10987     ) from err
  10988 return reindexed_value

TypeError: incompatible index of inserted column with frame index
</code>```

答:
You can use a rolling method to calculate cumulative standard deviations for each group.

Code

import pandas as pd

# Create a sample dataframe
import io
text_csv = '''Value,Theme,Country
-1.975767,Weather,China
-0.540979,Fruits,China
-2.359127,Fruits,China
-2.815604,Corona,Brazil
-0.929755,Weather,UK
-0.929755,Weather,UK'''
df = pd.read_csv(io.StringIO(text_csv))

# Calculate cumulative standard deviations
df_std = df.groupby(['Theme', 'Country'], as_index=False)['Value'].rolling(len(df), min_periods=1).std()

# Merge the original df with the cumulative std values
df_std = df.join(df_std.drop(['Theme', 'Country'], axis=1).rename(columns={'Value': 'CorrectedStd'}))
```

Output

Value
Theme
Country
CorrectedStd

0
-1.97577
Weather
China
nan

1
-0.540979
Fruits
China
nan

2
-2.35913
Fruits
China
1.28562

3
-2.8156
Corona
Brazil
nan

4
-0.929755
Weather
UK
nan

5
-0.929755
Weather
UK
0

Body:
I have a dataset that looks like this (+ some other cols):

Value         Theme       Country
-1.975767     Weather     China
-0.540979     Fruits      China
-2.359127     Fruits      China
-2.815604     Corona      Brazil
-0.929755     Weather     UK
-0.929755     Weather     UK

I want to find standard deviations for the values after grouping by Themes and Countries (as explained here calculate standard deviation by grouping two columns

df = pd.read_csv('./Brazil.csv')
df['std'] = df.groupby(['themes', 'country'])['value'].std()

However, currently, I get this error:

File /usr/local/Cellar/ipython/8.0.1/libexec/lib/python3.10/site-packages/pandas/core/frame.py:3656, in DataFrame.__setitem__(self, key, value)
   3653     self._setitem_array([key], value)
   3654 else:
   3655     # set column
-> 3656     self._set_item(key, value)

File /usr/local/Cellar/ipython/8.0.1/libexec/lib/python3.10/site-packages/pandas/core/frame.py:3833, in DataFrame._set_item(self, key, value)
   3823 def _set_item(self, key, value) -> None:
   3824     """
   3825     Add series to DataFrame in specified column.
   3826
   (...)
   3831     ensure homogeneity.
   3832     """
-> 3833     value = self._sanitize_column(value)
   3835     if (
   3836         key in self.columns
   3837         and value.ndim == 1
   3838         and not is_extension_array_dtype(value)
   3839     ):
   3840         # broadcast across multiple columns if necessary
   3841         if not self.columns.is_unique or isinstance(self.columns, MultiIndex):

File /usr/local/Cellar/ipython/8.0.1/libexec/lib/python3.10/site-packages/pandas/core/frame.py:4534, in DataFrame._sanitize_column(self, value)
   4532 # We should never get here with DataFrame value
   4533 if isinstance(value, Series):
-> 4534     return _reindex_for_setitem(value, self.index)
   4536 if is_list_like(value):
   4537     com.require_length_match(value, self.index)

File /usr/local/Cellar/ipython/8.0.1/libexec/lib/python3.10/site-packages/pandas/core/frame.py:10985, in _reindex_for_setitem(value, index)
  10981     if not value.index.is_unique:
  10982         # duplicate axis
  10983         raise err
> 10985     raise TypeError(
  10986         "incompatible index of inserted column with frame index"
  10987     ) from err
  10988 return reindexed_value

TypeError: incompatible index of inserted column with frame index

Body:
You can use a rolling method to calculate cumulative standard deviations for each group.

Code

import pandas as pd

# Create a sample dataframe
import io
text_csv = '''Value,Theme,Country
-1.975767,Weather,China
-0.540979,Fruits,China
-2.359127,Fruits,China
-2.815604,Corona,Brazil
-0.929755,Weather,UK
-0.929755,Weather,UK'''
df = pd.read_csv(io.StringIO(text_csv))

# Calculate cumulative standard deviations
df_std = df.groupby(['Theme', 'Country'], as_index=False)['Value'].rolling(len(df), min_periods=1).std()

# Merge the original df with the cumulative std values
df_std = df.join(df_std.drop(['Theme', 'Country'], axis=1).rename(columns={'Value': 'CorrectedStd'}))

Output

Value
Theme
Country
CorrectedStd

0
-1.97577
Weather
China
nan

1
-0.540979
Fruits
China
nan

2
-2.35913
Fruits
China
1.28562

3
-2.8156
Corona
Brazil
nan

4
-0.929755
Weather
UK
nan

5
-0.929755
Weather
UK
0


问:
Download FTP file to S3 through AWS Glue, S3 path is not recognized
on a AWS Glue Job, I'm using ftplib to download files and store them to S3, with the following code:

```<code>from ftplib import FTP
ftp = FTP()
ftp.connect("ftp.ser.ver", 21)
ftp.login("user", "password")
remotefile='filename.txt'
download='s3://bucket/folder/filename.txt'
with open(download,'wb') as file:
    ftp.retrbinary('RETR %s' % remotefile, file.write)
</code>```

And I got an error stated as follow:

FileNotFoundError: [Errno 2] No such file or directory

Ran the same code through local and changed the download path to local path and the code works. I'm fairly new to S3 and Glue and not sure where to look for right documentations. Any insight and suggestion is greatly appreciated.

答:
You can't download an FTP file and directly save it towards S3. You will have to use either a memory-based or file-based stream to save it in the glue environment before you could upload it to S3.

from boto3.session import Session
import boto3
from ftplib import FTP
ftp = FTP()
ftp.connect("ftp.ser.ver", 21)
ftp.login("user", "password")

with open("/tmp/filename.txt",'wb') as file:
    ftp.retrbinary("filename.txt", file.write)

s3 = boto3.client('s3')
with open("/tmp/filename.txt", "rb") as f:
    s3.upload_fileobj(f, "BUCKET_NAME", "OBJECT_NAME")
```

Body:
on a AWS Glue Job, I'm using ftplib to download files and store them to S3, with the following code:

from ftplib import FTP
ftp = FTP()
ftp.connect("ftp.ser.ver", 21)
ftp.login("user", "password")
remotefile='filename.txt'
download='s3://bucket/folder/filename.txt'
with open(download,'wb') as file:
    ftp.retrbinary('RETR %s' % remotefile, file.write)

And I got an error stated as follow:

FileNotFoundError: [Errno 2] No such file or directory

Ran the same code through local and changed the download path to local path and the code works. I'm fairly new to S3 and Glue and not sure where to look for right documentations. Any insight and suggestion is greatly appreciated.


问:
Month wise total and cummilative sum - Pandas
I want to have a month wise distribution of total revenue and month on month cumulative revenue sorted according to the months of the year. A sample of the source is table given below

```<code>Bill_Date     Sale_Net_Value
2021-01-01    220
2021-01-28    300
2021-02-03    250
</code>```

Expected Output:

```<code>Month  Total_Revnue cumilitive
Jan    520          520
Feb    250          770
</code>```

答:
Using your sample table as the df variable below, here is my attempt:

```<code>df.index = pd.to_datetime(df['Bill_Date'],format='%Y-%m-%d')
df = df.groupby(pd.Grouper(freq='M')).sum().reset_index()

df['Bill_Date'] = pd.to_datetime(df['Bill_Date'],format='%Y-%m-%d').dt.strftime('%b')

df['Cumulative'] = df['Sale_Net_Value'].cumsum()

df=df.rename(columns={"Bill_Date":"Month", "Sale_Net_Value":"Total_Revenue"})

print(df)
</code>```

Output:

```<code>  Month  Total_Revenue  Cumulative
0   Jan            520         520
1   Feb            250         770
</code>```

Body:
I want to have a month wise distribution of total revenue and month on month cumulative revenue sorted according to the months of the year. A sample of the source is table given below

Bill_Date     Sale_Net_Value
2021-01-01    220
2021-01-28    300
2021-02-03    250

Expected Output:

Month  Total_Revnue cumilitive
Jan    520          520
Feb    250          770

Body:
Using your sample table as the df variable below, here is my attempt:

df.index = pd.to_datetime(df['Bill_Date'],format='%Y-%m-%d')
df = df.groupby(pd.Grouper(freq='M')).sum().reset_index()

df['Bill_Date'] = pd.to_datetime(df['Bill_Date'],format='%Y-%m-%d').dt.strftime('%b')

df['Cumulative'] = df['Sale_Net_Value'].cumsum()

df=df.rename(columns={"Bill_Date":"Month", "Sale_Net_Value":"Total_Revenue"})

print(df)

Output:

  Month  Total_Revenue  Cumulative
0   Jan            520         520
1   Feb            250         770


问:
C# | Create a json string out of static class fields with values
I need a method that will be able to loop through every static property in a static class, and combine these to a string with json syntax, where key name would equal to Property name, and key value would be the value of the property.

So the result would be a string with value:

{ "StaticPropertyName_string": "string_value_of_this_property", "StaticPropertyName_int": 34 }
```
<p>I have a working method that successfully does the opposite - takes a json and maps data to static fields. But can't figure out how to do it in reverse</p>
<pre class="lang-cs prettyprint-override"><code>    public static void MapProfileToJson(JToken source) //// source = plain json string
    {
        var destinationProperties = typeof(Fields)
            .GetProperties(BindingFlags.Public | BindingFlags.Static);

        foreach (JProperty prop in source)
        {
            var destinationProp = destinationProperties
                .SingleOrDefault(p => p.Name.Equals(prop.Name, StringComparison.OrdinalIgnoreCase));
            var value = ((JValue)prop.Value).Value;

            if (typeof(Fields).GetProperty(prop.Name) != null)
                destinationProp.SetValue(null, Convert.ChangeType(value, destinationProp.PropertyType));
            else
                Console.WriteLine("(!) property \"" + prop.Name + "\" is not found in class... skip");
        }
    }
</code>```

Example static class:

    public static class Fields
    {
        public static bool BoolField { get; set; }
        public static string StringField { get; set; }
        public static int IntField { get; set; }
        public static double DoubleField { get; set; }
    }
```
<p>p.s.
<em>Key value pairs saved in string, could be wrapped at the end like</em></p>
<pre class="lang-cs prettyprint-override"><code>    ResultString = "{ " + resultString + " }";
</code>```

C# .NET 4.7.2 (console app)

答:
I think it would be nice to have some simple code to assign json properties to a static class properties too. I created this code using @RichardDeeming answer

```<code>public static void MapStaticClassFromJson(string json, Type staticClassToMap)
{
    var jsonObject = JObject.Parse(json);

    var properties = staticClassToMap.GetProperties(BindingFlags.Public | BindingFlags.Static);
    foreach (PropertyInfo prop in properties)
    prop.SetValue(null, Convert.ChangeType(jsonObject[prop.Name], prop.PropertyType, CultureInfo.CurrentCulture), null);
}
</code>```

test

```<code> MapStaticClassFromJson(json,typeof(Data));
 Console.WriteLine(Data.StaticPropertyName_int);
 Console.WriteLine(Data.StaticPropertyName_string);
</code>```

result

```<code>34
string_value_of_this_property
</code>```

Body:
I need a method that will be able to loop through every static property in a static class, and combine these to a string with json syntax, where key name would equal to Property name, and key value would be the value of the property.

So the result would be a string with value:

{ "StaticPropertyName_string": "string_value_of_this_property", "StaticPropertyName_int": 34 }

I have a working method that successfully does the opposite - takes a json and maps data to static fields. But can't figure out how to do it in reverse

    public static void MapProfileToJson(JToken source) //// source = plain json string
    {
        var destinationProperties = typeof(Fields)
            .GetProperties(BindingFlags.Public | BindingFlags.Static);

        foreach (JProperty prop in source)
        {
            var destinationProp = destinationProperties
                .SingleOrDefault(p => p.Name.Equals(prop.Name, StringComparison.OrdinalIgnoreCase));
            var value = ((JValue)prop.Value).Value;

            if (typeof(Fields).GetProperty(prop.Name) != null)
                destinationProp.SetValue(null, Convert.ChangeType(value, destinationProp.PropertyType));
            else
                Console.WriteLine("(!) property \"" + prop.Name + "\" is not found in class... skip");
        }
    }

Example static class:

    public static class Fields
    {
        public static bool BoolField { get; set; }
        public static string StringField { get; set; }
        public static int IntField { get; set; }
        public static double DoubleField { get; set; }
    }

p.s.
Key value pairs saved in string, could be wrapped at the end like

    ResultString = "{ " + resultString + " }";

C# .NET 4.7.2 (console app)

Body:
I think it would be nice to have some simple code to assign json properties to a static class properties too. I created this code using @RichardDeeming answer

public static void MapStaticClassFromJson(string json, Type staticClassToMap)
{
    var jsonObject = JObject.Parse(json);

    var properties = staticClassToMap.GetProperties(BindingFlags.Public | BindingFlags.Static);
    foreach (PropertyInfo prop in properties)
    prop.SetValue(null, Convert.ChangeType(jsonObject[prop.Name], prop.PropertyType, CultureInfo.CurrentCulture), null);
}

test

 MapStaticClassFromJson(json,typeof(Data));
 Console.WriteLine(Data.StaticPropertyName_int);
 Console.WriteLine(Data.StaticPropertyName_string);

result

34
string_value_of_this_property


问:
PySpark DataFrame - Append Random Permutation of a Single Column
I'm using PySpark (a new thing for me). Now, suppose I Have the following table:

+-------+-------+----------+
| Col1  | Col2  | Question |
+-------+-------+----------+
| val11 | val12 | q1       |
| val21 | val22 | q2       |
| val31 | val32 | q3       |
+-------+-------+----------+

and I would like to append to it a new column, random_qustion which is in fact a permutation of the values in the Question column, so the result might look like this:

+-------+-------+----------+-----------------+
| Col1  | Col2  | Question | random_question |
+-------+-------+----------+-----------------+
| val11 | val12 | q1       | q2              |
| val21 | val22 | q2       | q3              |
| val31 | val32 | q3       | q1              |
+-------+-------+----------+-----------------+

I'v tried to do that as follow:
python
df.withColumn(
    'random_question'
    ,df.orderBy(rand(seed=0))['question']
    ).createOrReplaceTempView('with_random_questions')

The problem is that the above code does append the required column but WITHOUT permuting the values in it.

What am I doing wrong and how can I fix this?

Thank you,

Gilad

答:
The above answer is wrong. You are not guaranteed to have the same set of ids in the two dataframes and you will lose rows.

```<code>df = spark.createDataFrame(pd.DataFrame({'a':[1,2,3,4],'b':[10,11,12,13],'c':[100,101,102,103]}))
questions = df.select(F.col('a').alias('random_question'))
random = questions.orderBy(F.rand())
df = df.withColumn('row_id', F.monotonically_increasing_id())
random = random.withColumn('row_id', F.monotonically_increasing_id())
df.show()
random.show()
</code>```

output on my system:

```<code>+---+---+---+-----------+
|  a|  b|  c|     row_id|
+---+---+---+-----------+
|  1| 10|100| 8589934592|
|  2| 11|101|25769803776|
|  3| 12|102|42949672960|
|  4| 13|103|60129542144|
+---+---+---+-----------+

+---------------+-----------+
|random_question|     row_id|
+---------------+-----------+
|              4|          0|
|              1| 8589934592|
|              2|17179869184|
|              3|25769803776|
+---------------+-----------+
</code>```

Use the following utility to add permuted columns in place of the original columns or as new columns

```<code>from pyspark.sql.types import StructType, StructField
from pyspark.sql.functions import rand, col
from pyspark.sql import Row
def permute_col_maintain_corr_join(df, colnames,  newnames=[], replace = False):
    '''
    colname: list of columns to be permuted
    newname: list of new names for the permuted columns
    replace: whether to add permuted columns as new columns or replace the original columne
    '''
    def flattener(rdd_1):
        r1 = rdd_1[0].asDict()
        idx = rdd_1[1]
        combined_dict = {**r1,**{'index':idx}}
        out_row = Row(**combined_dict)
        return out_row
    def compute_schema_wid(df):
        dfs = df.schema.fields
        ids = StructField('index', IntegerType(), False)
        return StructType(dfs+[ids])
    if not newnames:
        newnames = [f'{i}_sha' for i in colnames]
    assert len(colnames) == len(newnames)
    if not replace:
        assert not len(set(df.columns).intersection(set(newnames))), 'with replace False newnames cannot contain a column name from df'
    else:
        _rc = set(df.columns) - set(colnames)
        assert not len(_rc.intersection(set(newnames))), 'with replace True newnames cannot contain a column name from df other than one from colnames'
    df_ts = df.select(*colnames).toDF(*newnames)
    if replace:
        df = df.drop(*colnames)
    df_ts = df_ts.orderBy(rand())
    df_ts_s = compute_schema_wid(df_ts)
    df_s = compute_schema_wid(df)
    df_ts = df_ts.rdd.zipWithUniqueId().map(flattener).toDF(schema=df_ts_s)
    df = df.rdd.zipWithUniqueId().map(flattener).toDF(schema=df_s)
    df = df.join(df_ts,on='index').drop('index')
    return df
</code>```

Body:
The above answer is wrong. You are not guaranteed to have the same set of ids in the two dataframes and you will lose rows.

df = spark.createDataFrame(pd.DataFrame({'a':[1,2,3,4],'b':[10,11,12,13],'c':[100,101,102,103]}))
questions = df.select(F.col('a').alias('random_question'))
random = questions.orderBy(F.rand())
df = df.withColumn('row_id', F.monotonically_increasing_id())
random = random.withColumn('row_id', F.monotonically_increasing_id())
df.show()
random.show()

output on my system:

+---+---+---+-----------+
|  a|  b|  c|     row_id|
+---+---+---+-----------+
|  1| 10|100| 8589934592|
|  2| 11|101|25769803776|
|  3| 12|102|42949672960|
|  4| 13|103|60129542144|
+---+---+---+-----------+

+---------------+-----------+
|random_question|     row_id|
+---------------+-----------+
|              4|          0|
|              1| 8589934592|
|              2|17179869184|
|              3|25769803776|
+---------------+-----------+

Use the following utility to add permuted columns in place of the original columns or as new columns

from pyspark.sql.types import StructType, StructField
from pyspark.sql.functions import rand, col
from pyspark.sql import Row
def permute_col_maintain_corr_join(df, colnames,  newnames=[], replace = False):
    '''
    colname: list of columns to be permuted
    newname: list of new names for the permuted columns
    replace: whether to add permuted columns as new columns or replace the original columne
    '''
    def flattener(rdd_1):
        r1 = rdd_1[0].asDict()
        idx = rdd_1[1]
        combined_dict = {**r1,**{'index':idx}}
        out_row = Row(**combined_dict)
        return out_row
    def compute_schema_wid(df):
        dfs = df.schema.fields
        ids = StructField('index', IntegerType(), False)
        return StructType(dfs+[ids])
    if not newnames:
        newnames = [f'{i}_sha' for i in colnames]
    assert len(colnames) == len(newnames)
    if not replace:
        assert not len(set(df.columns).intersection(set(newnames))), 'with replace False newnames cannot contain a column name from df'
    else:
        _rc = set(df.columns) - set(colnames)
        assert not len(_rc.intersection(set(newnames))), 'with replace True newnames cannot contain a column name from df other than one from colnames'
    df_ts = df.select(*colnames).toDF(*newnames)
    if replace:
        df = df.drop(*colnames)
    df_ts = df_ts.orderBy(rand())
    df_ts_s = compute_schema_wid(df_ts)
    df_s = compute_schema_wid(df)
    df_ts = df_ts.rdd.zipWithUniqueId().map(flattener).toDF(schema=df_ts_s)
    df = df.rdd.zipWithUniqueId().map(flattener).toDF(schema=df_s)
    df = df.join(df_ts,on='index').drop('index')
    return df


问:
Skip parent if using PHP
Not sure if this is even possible, but the basic idea of the code is as follows:

```<code>if(isset($_POST['submit'])) {
    if($_POST['field'] == 0) {
        // do not process the code in the if statement
    }
    // code to process if the above validation criteria is not met
}
</code>```

I basically want to try and keep it as simple as possible without lots of if's everywhere, just the quick validation statements at the top, and if none of those if statements are triggered, it will process the code to update the database etc.

I have tried the continue statement function with no joy, I believe that only works with loops.

Thanks!

答:
You could put all of this in a function and then call 'return' from the inside 'if':</p>

```<code>if(isset($_POST['submit']) && validate_form())
{
    ...
}

function validate_form()
{
    if($_POST['field'] == 0) {
        return false;
    }
    if(another check that fails) {
        return false;
    }
    ...
    return true;
}
</code>```

Title: Skip parent if using PHP

Body:
Not sure if this is even possible, but the basic idea of the code is as follows:

if(isset($_POST['submit'])) {
    if($_POST['field'] == 0) {
        // do not process the code in the if statement
    }
    // code to process if the above validation criteria is not met
}

I basically want to try and keep it as simple as possible without lots of if's everywhere, just the quick validation statements at the top, and if none of those if statements are triggered, it will process the code to update the database etc.

I have tried the continue statement function with no joy, I believe that only works with loops.

Thanks!

Body:
You could put all of this in a function and then call 'return' from the inside 'if':

if(isset($_POST['submit']) && validate_form())
{
    ...
}

function validate_form()
{
    if($_POST['field'] == 0) {
        return false;
    }
    if(another check that fails) {
        return false;
    }
    ...
    return true;
}


答:
You could group on your months and sum your 'Sale_Net_Value' column, and then create a new column on that using assign and cumsum() :

```<code>df['Bill_Date'] = pd.to_datetime(df.Bill_Date)

df.groupby(df.Bill_Date.dt.month_name().str[:3]).agg(
    Total_revenue=('Sale_Net_Value','sum')
    ).assign(cumulative= lambda col: col['Total_revenue'].cumsum())
</code>```

prints:

```<code>           Total_revenue  cumulative
Bill_Date
Jan                  520         520
Mar                  250         770
</code>```

Title: Month wise total and cummilative sum - Pandas

Body:
You could group on your months and sum your 'Sale_Net_Value' column, and then create a new column on that using assign and cumsum() :

df['Bill_Date'] = pd.to_datetime(df.Bill_Date)

df.groupby(df.Bill_Date.dt.month_name().str[:3]).agg(
    Total_revenue=('Sale_Net_Value','sum')
    ).assign(cumulative= lambda col: col['Total_revenue'].cumsum())

prints:

           Total_revenue  cumulative
Bill_Date
Jan                  520         520
Mar                  250         770


问:
How to find parent form from element?
I am trying to find parent form from element using code below:

```<code><form id="f1" action="action1.html">
form1 <button id="btn1" onclick="testaction(this); return false;" >test form 1</button>
</form>

<script type="text/javascript" >
function testaction(element) {
    var e = $(element.id);
    var form = e.parent('form');

    alert(form.id); // undefined!!
    alert(form.action); // undefined!!
    alert(document.forms[0].action); //http://localhost/action1.html
}
</script>
</code>```

It should be something really simple.... Thanks in advance

答:
Button element has form property http://www.w3schools.com/jsref/dom_obj_pushbutton.asp</p>

```<code>buttonElement.form
</code>```

Title: How to find parent form from element?

Body:
I am trying to find parent form from element using code below:

<form id="f1" action="action1.html">
form1 <button id="btn1" onclick="testaction(this); return false;" >test form 1</button>
</form>

It should be something really simple.... Thanks in advance

Body:
Button element has form property http://www.w3schools.com/jsref/dom_obj_pushbutton.asp

buttonElement.form


问:
Get the 3rd part of the string in Postgres
I have data like,

```<code>ab-volt-ssn-dev
ab-volt-lnid-dev
ab-volt-ssn-hamp-dev
ab-volt-cf-apnt-test
</code>```

I need output to be like,

```<code>ssn
lnid
ssn
cf
</code>```

答:
You can use split_part()

```<code>select split_part('ab-volt-ssn-hamp-dev', '-', 3);
</code>```

If you need to access multiple parts, then converting it to an array might be easier:

```<code>select elements[1],
       elements[2],
       elements[3],
       elements[4]
from (
   select string_to_array(the_column, '-') as elements
   from the_table
) t;
</code>```

Body:
I have data like,

ab-volt-ssn-dev
ab-volt-lnid-dev
ab-volt-ssn-hamp-dev
ab-volt-cf-apnt-test

I need output to be like,

ssn
lnid
ssn
cf

Body:
You can use split_part()

select split_part('ab-volt-ssn-hamp-dev', '-', 3);

If you need to access multiple parts, then converting it to an array might be easier:

select elements[1],
       elements[2],
       elements[3],
       elements[4]
from (
   select string_to_array(the_column, '-') as elements
   from the_table
) t;


问:
Get ID of preceding image on click event
I have this HTML code

```<code><div> <img src="download1.jpeg" image-id="9a8ae555af5f"></div>
<div><h1><a href ="#">test</a></h1></div>

</code>```

When a user clicks on the "test" link, i would like to navigate through the tree and fetch the "image-id" attribute of the image preceding the link

I have tried this but imageID returns undefined

```<code>function trackClick(event)
{
  let imageId = this.$('a').prev('img').attr('image-id');

console.log("imageId", imageId);
}

document.addEventListener('click', trackClick, true);

</code>```

Any ideas on how i can make this work using js or css selectors?

thanks

答:
This is jquery solution with prev() and parent() function:

$('#test').on('click', function() {
    alert($(this).parent().parent().prev('div').find('img').attr('image-id'))
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <img src="download1.jpeg" image-id="9a8ae555af5f">
</div>
<div>
  <h1>
    test
  </h1>
</div></code>```

Body:
I have this HTML code

test

When a user clicks on the "test" link, i would like to navigate through the tree and fetch the "image-id" attribute of the image preceding the link

I have tried this but imageID returns undefined

function trackClick(event)
{
  let imageId = this.$('a').prev('img').attr('image-id');

console.log("imageId", imageId);
}

document.addEventListener('click', trackClick, true);

Any ideas on how i can make this work using js or css selectors?

thanks

Body:
This is jquery solution with prev() and parent() function:

$('#test').on('click', function() {
    alert($(this).parent().parent().prev('div').find('img').attr('image-id'))
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <img src="download1.jpeg" image-id="9a8ae555af5f">
</div>
<div>
  <h1>
    <a href ="#" id = 'test'>test</a>
  </h1>
</div>