问:
How to automatically parse out the fields(Protobuf) used in the code?
Given the following trade.proto file:

```<code>message Trade {
    message ProductInfo {
      optional uint64 product_id = 1;
      optional String product_name = 2;
      repeated int other_field = 3;
    }
    optional string id = 1;
    optional uint64 partition_time = 2;
    optional ProductInfo product_info= 3;
}
</code>```

Given the following code：

```<code>def getOtherFieldSize(trade: Trade): Int = {
  if (20221205 == trade.getPartitionTime) {
    trade.getProductInfo.getOtherFieldList.size
  } else {
    0
  }
}
</code>```

How to get the fields of trade.proto used in the code? For example:

```<code>partition_time
product_info.other_field
</code>```

Body:
Given the following trade.proto file:

message Trade {
    message ProductInfo {
      optional uint64 product_id = 1;
      optional String product_name = 2;
      repeated int other_field = 3;
    }
    optional string id = 1;
    optional uint64 partition_time = 2;
    optional ProductInfo product_info= 3;
}

Given the following code：

def getOtherFieldSize(trade: Trade): Int = {
  if (20221205 == trade.getPartitionTime) {
    trade.getProductInfo.getOtherFieldList.size
  } else {
    0
  }
}

How to get the fields of trade.proto used in the code? For example:

partition_time
product_info.other_field


来源: stackexchange

问:
WARNING of duplicate C++ declaration/object description (for namespace) when use "doxygenfile" objective for different source files
I want to use doxygen and sphinx to generate documents for source file, in the rst file, I use "doxygenfile" to introduce the source file, like

```<code>.. doxygenfile:: Headerfile1.hpp
   :project: MyProject

.. doxygenfile:: Headerfile2.hpp
   :project: MyProject
</code>```

As the classes in the two headerfile is defined in the same namespace, so they both have a same namespace delcare:

```<code>namespace Namespace_xxx
{
   ...
   definitions ...
   ...
}
</code>```

When build, a warning is reported like:

WARNING: Duplicate C++ declaration, also defined at XXX :17.
Declaration is '.. cpp:type:: Namespace_xxx'.

And the same situation for python file, a warning like：
WARNING: duplicate object description of <module_name>, when I import submodule from the same module in different .py and introduce them to the rst by "doxygen".

Why sphinx recognize reference of namespace or module as duplicated declaration? How to fix this problem?

I tried to use :noindex: true option, but it reported that "noindex" is not a valid option for "doxygenfile" when build

ContentLicense: CC BY-SA 4.0

Body:
I want to use doxygen and sphinx to generate documents for source file, in the rst file, I use "doxygenfile" to introduce the source file, like

.. doxygenfile:: Headerfile1.hpp
   :project: MyProject

.. doxygenfile:: Headerfile2.hpp
   :project: MyProject

As the classes in the two headerfile is defined in the same namespace, so they both have a same namespace delcare:

namespace Namespace_xxx
{
   ...
   definitions ...
   ...
}

When build, a warning is reported like:

WARNING: Duplicate C++ declaration, also defined at XXX :17.
Declaration is '.. cpp:type:: Namespace_xxx'.

And the same situation for python file, a warning like：
WARNING: duplicate object description of <module_name>, when I import submodule from the same module in different .py and introduce them to the rst by "doxygen".

Why sphinx recognize reference of namespace or module as duplicated declaration? How to fix this problem?

I tried to use :noindex: true option, but it reported that "noindex" is not a valid option for "doxygenfile" when build


问:
Extract values using np.where
I am trying to filter contents in a column using np.where function. The column has 4 values but i am trying to extract it as below

Classify

SEARCH

Website

App

Discover

If the classify column has search then it should populate Search in the column otherwise it should populate Content.

But the final table is only having search values. Is there anything wrong in the np.where function ?

```<code>I am trying below :

</code>```
```<code>df['Classify'] = np.where(df['Classify'] == 'SEARCH','Search','Content')
</code>```
```<code>
</code>```

Title: Extract values using np.where

Body:
I am trying to filter contents in a column using np.where function. The column has 4 values but i am trying to extract it as below

Classify

SEARCH

Website

App

Discover

If the classify column has search then it should populate Search in the column otherwise it should populate Content.

But the final table is only having search values. Is there anything wrong in the np.where function ?

I am trying below :

df['Classify'] = np.where(df['Classify'] == 'SEARCH','Search','Content')


问:
Errors when using event_calendar in Rails 2.3.8
I have developed a project using event_calendar in Rails 2.3.8. I have implemented it to show results on the calendar, but a problem arises when a user tries to navigate to the next or previous month's calendar. It shows all events, it doesn't show the search results regarding that month as it should.

app\controllers\calendar_controller.rb

```<code>class CalendarController < ApplicationController
  @@id = nil

  def index
    @var = params[:event]
    @month = (params[:month] || (Time.zone || Time).now.month).to_i
    @year = (params[:year] || (Time.zone || Time).now.year).to_i
    @shown_month = Date.civil(@year, @month)
    @first_day_of_week = 1

    if params[:my].nil?
      if (defined? (params[:event][:trainer_id]))
        params[:my] = (params[:event][:trainer_id])
        @@id = (params[:event][:trainer_id])
        @event_strips = Event.event_strips_for_month(@shown_month, @first_day_of_week, :conditions=>["trainer_id = ?",params[:my]])
      else
        @event_strips = Event.event_strips_for_month(@shown_month, @first_day_of_week)
      end
    else
      @event_strips = Event.event_strips_for_month(@shown_month, @first_day_of_week, :conditions=>["trainer_id = ?",params[:my]])
    end

  end
end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have developed a project using event_calendar in Rails 2.3.8. I have implemented it to show results on the calendar, but a problem arises when a user tries to navigate to the next or previous month's calendar. It shows all events, it doesn't show the search results regarding that month as it should.

app\controllers\calendar_controller.rb

class CalendarController < ApplicationController
  @@id = nil

  def index
    @var = params[:event]
    @month = (params[:month] || (Time.zone || Time).now.month).to_i
    @year = (params[:year] || (Time.zone || Time).now.year).to_i
    @shown_month = Date.civil(@year, @month)
    @first_day_of_week = 1

    if params[:my].nil?
      if (defined? (params[:event][:trainer_id]))
        params[:my] = (params[:event][:trainer_id])
        @@id = (params[:event][:trainer_id])
        @event_strips = Event.event_strips_for_month(@shown_month, @first_day_of_week, :conditions=>["trainer_id = ?",params[:my]])
      else
        @event_strips = Event.event_strips_for_month(@shown_month, @first_day_of_week)
      end
    else
      @event_strips = Event.event_strips_for_month(@shown_month, @first_day_of_week, :conditions=>["trainer_id = ?",params[:my]])
    end

  end
end


问:
Can I upload js files to Sonatype Nexus REPOSITORY MANAGER 3?
Currently I know that Sonatype Nexus REPOSITORY MANAGER 3 can upload the corresponding package of npm to the hosted repository of npm in tgz format, how should I upload the js file to Sonatype Nexus REPOSITORY if I want to upload it?</p>


问:
Pandas + pyodbc = Warnings - pandas only supports SQLAlchemy or sqlite3
```<code>import pandas as pd
import pyodbc
import requests as rq

conn = pyodbc.connect("Driver={SQL Server};"
                  "Server=Servername;"
                  "Database=AVR;"
                  "Trusted_Connection=yes;")

df_kontrola = pd.read_sql_query("select ........'",conn)

conn.close()
del conn
....
send email
....
</code>```

If I run the script in the Anaconda environment (Spyder 4, Python 3.8.8 (default, Apr 13 2021, 15:08:03) [MSC v.1916 64 bit (AMD64)]. IPython 7.22.0 -- An enhanced Interactive Python. ) so the script will run fine, without any warning.
(The station is not regularly updated and is offline (only intranet), administrators update Anaconda once every 3-4 months.)

But, if I run the script in due to user rights on the same station in the second python 3.9.5 as scheduled task "c:...\python.exe c:...\script.py".

I get this warning "UserWarning: pandas only supports SQLAlchemy connectable (engine/connection) or database string URI or sqlite3 DBAPI2 connection. Other DBAPI2 objects are not tested. Please consider using SQLAlchemy." and the task scheduler reports an error at startup.

And even if the script runs fine (an email with the result is sent at the end of the script).

How do I remove this warning so that the task scheduler doesn't report a startup error?

Body:
import pandas as pd
import pyodbc
import requests as rq

conn = pyodbc.connect("Driver={SQL Server};"
                  "Server=Servername;"
                  "Database=AVR;"
                  "Trusted_Connection=yes;")

df_kontrola = pd.read_sql_query("select ........'",conn)

conn.close()
del conn
....
send email
....

If I run the script in the Anaconda environment (Spyder 4, Python 3.8.8 (default, Apr 13 2021, 15:08:03) [MSC v.1916 64 bit (AMD64)]. IPython 7.22.0 -- An enhanced Interactive Python. ) so the script will run fine, without any warning.
(The station is not regularly updated and is offline (only intranet), administrators update Anaconda once every 3-4 months.)

But, if I run the script in due to user rights on the same station in the second python 3.9.5 as scheduled task "c:...\python.exe c:...\script.py".

I get this warning "UserWarning: pandas only supports SQLAlchemy connectable (engine/connection) or database string URI or sqlite3 DBAPI2 connection. Other DBAPI2 objects are not tested. Please consider using SQLAlchemy." and the task scheduler reports an error at startup.

And even if the script runs fine (an email with the result is sent at the end of the script).

How do I remove this warning so that the task scheduler doesn't report a startup error?


问:
Return List of Permutations of String Using Stack C++
I am working on a program that returns a list of all possible permutations of a given string. So far the code I have produces a list of substring of the given input. For example for a string abcd, I get the output a, ab, abc, abcd, abd, ac, acd, ad, b, bc, bcd, bd, c, cd, d. This is the wrong output as I am trying to get the list to produce abcd, abdc, acbd, acdb, adbc, adcb, bacd, badc, bcad, bcda, bdac, bdca, cabd, cadb, cbad, cbda, cdab, cdba, dabc, dacb, dbac, dbca, dcab, dcba. There is a logical error in my code and I am having trouble figuring out how to modify it.

Just for some clarification I have to do this without recursion and only using a stack implementation.

Here is my code:

```<code>class Node
{
    public:
        string word;
        int place;
        Node *next;
        Node(); //default constructor (never used)
        Node(string); // Constructor creates Node with word
};

class List
{
    public:
        Node *head;
        List();
        void insert(string);
};

Node :: Node()
{
    word = "";
    next = NULL;
}

// Constructor with string input sets word and freq to 1
Node :: Node(string s)
{
    word = s;
    next = NULL;
}

List :: List()
{
    head = NULL;
}
</code>```
```<code>void List :: insert(string s)
{
    Node *latest = new Node(s); // create new node that has string s and freq 1
    latest->next = head; // add latest node to start of the list
    head = latest;// make this the new head
    return;
}

string List :: print()
{
    Node *curr = head; // curr is ths current node as it progresses through the linked list. Initialized to head to start at the head of the list
    string output = ""; // output string
    while(curr!=NULL){ // loop over list
        output = output + " " + curr->word; //append current word onto output string
        curr = curr->next; // proceed to next node
    }
    return output;
}
</code>```
```<code>class Pair
{
    public:
        string in_str;
        string fixed_str;
};

List anagrams(string input_str)
{
    List final_output;
    stack<class Pair> recurStack;
    Pair init, stacktop;
    init.in_str = input_str;
    init.fixed_str = "";
    recurStack.push(init);

    while(!recurStack.empty())
    {
        stacktop = recurStack.top();
        recurStack.pop();
        if (stacktop.in_str.length() == 0)
        {
            final_output.insert(stacktop.fixed_str);
            continue;
        }
        char last = stacktop.in_str.back();
        stacktop.in_str.pop_back();
        Pair to_push;
        to_push.in_str = stacktop.in_str;
        to_push.fixed_str = stacktop.fixed_str;
        recurStack.push(to_push);
        to_push.fixed_str = last + stacktop.fixed_str;
        recurStack.push(to_push);
    }
    return final_output;
}
</code>```
```<code>int main(int argc, char** argv)
{
    List myList = anagrams("abcd");
    cout << myList.print() << endl;

</code>```

Body:
I am working on a program that returns a list of all possible permutations of a given string. So far the code I have produces a list of substring of the given input. For example for a string abcd, I get the output a, ab, abc, abcd, abd, ac, acd, ad, b, bc, bcd, bd, c, cd, d. This is the wrong output as I am trying to get the list to produce abcd, abdc, acbd, acdb, adbc, adcb, bacd, badc, bcad, bcda, bdac, bdca, cabd, cadb, cbad, cbda, cdab, cdba, dabc, dacb, dbac, dbca, dcab, dcba. There is a logical error in my code and I am having trouble figuring out how to modify it.

Just for some clarification I have to do this without recursion and only using a stack implementation.

Here is my code:

class Node
{
    public:
        string word;
        int place;
        Node *next;
        Node(); //default constructor (never used)
        Node(string); // Constructor creates Node with word
};

class List
{
    public:
        Node *head;
        List();
        void insert(string);
};

Node :: Node()
{
    word = "";
    next = NULL;
}

// Constructor with string input sets word and freq to 1
Node :: Node(string s)
{
    word = s;
    next = NULL;
}

List :: List()
{
    head = NULL;
}

void List :: insert(string s)
{
    Node *latest = new Node(s); // create new node that has string s and freq 1
    latest->next = head; // add latest node to start of the list
    head = latest;// make this the new head
    return;
}

string List :: print()
{
    Node *curr = head; // curr is ths current node as it progresses through the linked list. Initialized to head to start at the head of the list
    string output = ""; // output string
    while(curr!=NULL){ // loop over list
        output = output + " " + curr->word; //append current word onto output string
        curr = curr->next; // proceed to next node
    }
    return output;
}

class Pair
{
    public:
        string in_str;
        string fixed_str;
};

List anagrams(string input_str)
{
    List final_output;
    stack<class Pair> recurStack;
    Pair init, stacktop;
    init.in_str = input_str;
    init.fixed_str = "";
    recurStack.push(init);

    while(!recurStack.empty())
    {
        stacktop = recurStack.top();
        recurStack.pop();
        if (stacktop.in_str.length() == 0)
        {
            final_output.insert(stacktop.fixed_str);
            continue;
        }
        char last = stacktop.in_str.back();
        stacktop.in_str.pop_back();
        Pair to_push;
        to_push.in_str = stacktop.in_str;
        to_push.fixed_str = stacktop.fixed_str;
        recurStack.push(to_push);
        to_push.fixed_str = last + stacktop.fixed_str;
        recurStack.push(to_push);
    }
    return final_output;
}

int main(int argc, char** argv)
{
    List myList = anagrams("abcd");
    cout << myList.print() << endl;


问:
How to copy the text with its text view font on clipboard?
I'm developing a font style app in which there are multiple fonts shows correctly on the textview but I want to copy that text with font and paste it on another app like whatsapp or anywhere else !!
So on the app its shows correctly but when I copy it to the clipboard and paste it in other same plain text is copied not the font !!</p>
```<code>           case 0:
                Typeface typeface = ResourcesCompat.getFont(context,R.font.f1);
                holder.fontText.setTypeface(typeface);
               break;
            case 1:
                Typeface t1 = ResourcesCompat.getFont(context,R.font.f2);
                holder.fontText.setTypeface(t1);
                break;
            case 2:
                Typeface t2 = ResourcesCompat.getFont(context,R.font.f3);
                holder.fontText.setTypeface(t2);
                break;
</code>```
```<code>  String s1 = holder.fontText.getText().toString();

        holder.copy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ClipboardManager clipboardManager = (ClipboardManager)
                        context.getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clipData = ClipData.newPlainText("Copied text",s1 );
                clipboardManager.setPrimaryClip(clipData);

//        let user know data save on clipBoard Successfully.
                Toast.makeText(context, "Copied to clipBoard", Toast.LENGTH_SHORT).show();
            }
        });
</code>```

Body:
I'm developing a font style app in which there are multiple fonts shows correctly on the textview but I want to copy that text with font and paste it on another app like whatsapp or anywhere else !!
So on the app its shows correctly but when I copy it to the clipboard and paste it in other same plain text is copied not the font !!

           case 0:
                Typeface typeface = ResourcesCompat.getFont(context,R.font.f1);
                holder.fontText.setTypeface(typeface);
               break;
            case 1:
                Typeface t1 = ResourcesCompat.getFont(context,R.font.f2);
                holder.fontText.setTypeface(t1);
                break;
            case 2:
                Typeface t2 = ResourcesCompat.getFont(context,R.font.f3);
                holder.fontText.setTypeface(t2);
                break;

  String s1 = holder.fontText.getText().toString();

        holder.copy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ClipboardManager clipboardManager = (ClipboardManager)
                        context.getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clipData = ClipData.newPlainText("Copied text",s1 );
                clipboardManager.setPrimaryClip(clipData);

//        let user know data save on clipBoard Successfully.
                Toast.makeText(context, "Copied to clipBoard", Toast.LENGTH_SHORT).show();
            }
        });


问:
Prometheus and cloudwatch agent deployed to ECS cluster, but prometheus namesapce is not showing on AWS cloudwatch metrics
I have been working on deploying proemtheus and cloud watch agent to ECS cluster. The aim is to be able to see the application metrics that has been gathered by prometheus on AWS cloudwatch metrics. However, after several attempts, the metrics are still not displaying on cloudwatch. Clouwatch agent is also not running on the ECS instance. Here is my configuration file and the error log displayed on the cloudwatch logs.

Resources:
PrometheusConfigSSMParameter:

```<code>Type: AWS::SSM::Parameter
Properties:
  Name: !Sub 'AmazonCloudWatch-PrometheusConfigName-${ECSClusterName}-EC2-${ECSNetworkMode}'
  Type: String
  Tier: Standard
  Description: !Sub 'Prometheus Scraping SSM Parameter for ECS Cluster: ${ECSClusterName}'
  Value: |-
    global:
      scrape_interval: 1m
      scrape_timeout: 10s
    scrape_configs:
      - job_name: sportsbook-app
        static_configs:
          - targets: [ "localhost:xxxx" ]
            labels:
              group: "dev"
</code>```

CWAgentConfigSSMParameter:

```<code>Type: AWS::SSM::Parameter
Properties:
  Name: !Sub 'AmazonCloudWatch-CWAgentConfig-${ECSClusterName}-EC2-${ECSNetworkMode}'
  Type: String
  Tier: Intelligent-Tiering
  Description: !Sub 'CWAgent SSM Parameter with App Mesh and Java EMF Definition for ECS Cluster: ${ECSClusterName}'
  Value: |-
    {
       "agent": {
        "debug": true
      },
      "logs": {
        "metrics_collected": {
          "prometheus": {
            "prometheus_config_path": "env:PROMETHEUS_CONFIG_CONTENT",
            "ecs_service_discovery": {
              "sd_frequency": "1m",
              "sd_result_file": "/tmp/cwagent_ecs_auto_sd.yaml",
              "docker_label": {
                "sd_port_label": "ECS_PROMETHEUS_EXPORTER_PORT",
                "sd_job_name_label": "ECS_PROMETHEUS_JOB_NAME"
              },
              "task_definition_list": [
                {
                  "sd_job_name": "ecs-appmesh-colors",
                  "sd_metrics_ports": "9901",
                  "sd_task_definition_arn_pattern": ".*:task-definition/.*-ColorTeller-(white):[0-9]+",
                  "sd_metrics_path": "/stats/prometheus"
                },
                {
                  "sd_job_name": "ecs-appmesh-gateway",
                  "sd_metrics_ports": "9901",
                  "sd_task_definition_arn_pattern": ".*:task-definition/.*-ColorGateway:[0-9]+",
                  "sd_metrics_path": "/stats/prometheus"
                }
              ]
            },
            "emf_processor": {
              "metric_declaration_dedup": true,
              "metric_declaration": [
                {
                  "source_labels": ["container_name"],
                  "label_matcher": "^envoy$",
                  "dimensions": [["ClusterName","TaskDefinitionFamily"]],
                  "metric_selectors": [
                    "^envoy_http_downstream_rq_(total|xx)$",
                    "^envoy_cluster_upstream_cx_(r|t)x_bytes_total$",
                    "^envoy_cluster_membership_(healthy|total)$",
                    "^envoy_server_memory_(allocated|heap_size)$",
                    "^envoy_cluster_upstream_cx_(connect_timeout|destroy_local_with_active_rq)$",
                    "^envoy_cluster_upstream_rq_(pending_failure_eject|pending_overflow|timeout|per_try_timeout|rx_reset|maintenance_mode)$",
                    "^envoy_http_downstream_cx_destroy_remote_active_rq$",
                    "^envoy_cluster_upstream_flow_control_(paused_reading_total|resumed_reading_total|backed_up_total|drained_total)$",
                    "^envoy_cluster_upstream_rq_retry$",
                    "^envoy_cluster_upstream_rq_retry_(success|overflow)$",
                    "^envoy_server_(version|uptime|live)$"
                  ]
                },
                {
                  "source_labels": ["container_name"],
                  "label_matcher": "^envoy$",
                  "dimensions": [["ClusterName","TaskDefinitionFamily","envoy_http_conn_manager_prefix","envoy_response_code_class"]],
                  "metric_selectors": [
                    "^envoy_http_downstream_rq_xx$"
                  ]
                },
                {
                  "source_labels": ["Java_EMF_Metrics"],
                  "label_matcher": "^true$",
                  "dimensions": [["ClusterName","TaskDefinitionFamily"]],
                  "metric_selectors": [
                    "^jvm_threads_(current|daemon)$",
                    "^jvm_classes_loaded$",
                    "^java_lang_operatingsystem_(freephysicalmemorysize|totalphysicalmemorysize|freeswapspacesize|totalswapspacesize|systemcpuload|processcpuload|availableprocessors|openfiledescriptorcount)$",
                    "^catalina_manager_(rejectedsessions|activesessions)$",
                    "^jvm_gc_collection_seconds_(count|sum)$",
                    "^catalina_globalrequestprocessor_(bytesreceived|bytessent|requestcount|errorcount|processingtime)$"
                  ]
                },
                {
                  "source_labels": ["Java_EMF_Metrics"],
                  "label_matcher": "^true$",
                  "dimensions": [["ClusterName","TaskDefinitionFamily","area"]],
                  "metric_selectors": [
                    "^jvm_memory_bytes_used$"
                  ]
                },
                {
                  "source_labels": ["Java_EMF_Metrics"],
                  "label_matcher": "^true$",
                  "dimensions": [["ClusterName","TaskDefinitionFamily","pool"]],
                  "metric_selectors": [
                    "^jvm_memory_pool_bytes_used$"
                  ]
                }
              ]
            }
          }
        },
        "force_flush_interval": 5
      }
    }
</code>```

ECSCWAgentTaskDefinition:
Type: 'AWS::ECS::TaskDefinition'
DependsOn:
- PrometheusConfigSSMParameter
- CWAgentConfigSSMParameter
Properties:

```<code>  Family: !Sub 'cwagent-prometheus-${ECSClusterName}-EC2-${ECSNetworkMode}'
  TaskRoleArn: !If [CreateRoles, !Ref CWAgentECSTaskRole, !Sub 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/${TaskRoleName}']
  ExecutionRoleArn: !If [CreateRoles, !Ref CWAgentECSExecutionRole, !Sub 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/${ExecutionRoleName}']
  NetworkMode: !Ref ECSNetworkMode
  ContainerDefinitions:
    - Name: cloudwatch-agent-prometheus
      Image: amazon/cloudwatch-agent:1.247355.0b252062
      Essential: true
      MountPoints: []
      PortMappings: []
      Environment: []
      Secrets:
        - Name: PROMETHEUS_CONFIG_CONTENT
          ValueFrom: !Sub 'AmazonCloudWatch-PrometheusConfigName-${ECSClusterName}-EC2-${ECSNetworkMode}'
        - Name: CW_CONFIG_CONTENT
          ValueFrom: !Sub 'AmazonCloudWatch-CWAgentConfig-${ECSClusterName}-EC2-${ECSNetworkMode}'
      LogConfiguration:
        LogDriver: awslogs
        Options:
          awslogs-create-group: 'True'
          awslogs-group: "/ecs/ecs-cwagent-prometheus"
          awslogs-region: !Ref AWS::Region
          awslogs-stream-prefix: !Sub 'ecs-EC2-${ECSNetworkMode}'
  RequiresCompatibilities:
    - EC2
  Cpu: '512'
  Memory: '1024'
</code>```

Body:
I have been working on deploying proemtheus and cloud watch agent to ECS cluster. The aim is to be able to see the application metrics that has been gathered by prometheus on AWS cloudwatch metrics. However, after several attempts, the metrics are still not displaying on cloudwatch. Clouwatch agent is also not running on the ECS instance. Here is my configuration file and the error log displayed on the cloudwatch logs.

Resources:
PrometheusConfigSSMParameter:

Type: AWS::SSM::Parameter
Properties:
  Name: !Sub 'AmazonCloudWatch-PrometheusConfigName-${ECSClusterName}-EC2-${ECSNetworkMode}'
  Type: String
  Tier: Standard
  Description: !Sub 'Prometheus Scraping SSM Parameter for ECS Cluster: ${ECSClusterName}'
  Value: |-
    global:
      scrape_interval: 1m
      scrape_timeout: 10s
    scrape_configs:
      - job_name: sportsbook-app
        static_configs:
          - targets: [ "localhost:xxxx" ]
            labels:
              group: "dev"

CWAgentConfigSSMParameter:

Type: AWS::SSM::Parameter
Properties:
  Name: !Sub 'AmazonCloudWatch-CWAgentConfig-${ECSClusterName}-EC2-${ECSNetworkMode}'
  Type: String
  Tier: Intelligent-Tiering
  Description: !Sub 'CWAgent SSM Parameter with App Mesh and Java EMF Definition for ECS Cluster: ${ECSClusterName}'
  Value: |-
    {
       "agent": {
        "debug": true
      },
      "logs": {
        "metrics_collected": {
          "prometheus": {
            "prometheus_config_path": "env:PROMETHEUS_CONFIG_CONTENT",
            "ecs_service_discovery": {
              "sd_frequency": "1m",
              "sd_result_file": "/tmp/cwagent_ecs_auto_sd.yaml",
              "docker_label": {
                "sd_port_label": "ECS_PROMETHEUS_EXPORTER_PORT",
                "sd_job_name_label": "ECS_PROMETHEUS_JOB_NAME"
              },
              "task_definition_list": [
                {
                  "sd_job_name": "ecs-appmesh-colors",
                  "sd_metrics_ports": "9901",
                  "sd_task_definition_arn_pattern": ".*:task-definition/.*-ColorTeller-(white):[0-9]+",
                  "sd_metrics_path": "/stats/prometheus"
                },
                {
                  "sd_job_name": "ecs-appmesh-gateway",
                  "sd_metrics_ports": "9901",
                  "sd_task_definition_arn_pattern": ".*:task-definition/.*-ColorGateway:[0-9]+",
                  "sd_metrics_path": "/stats/prometheus"
                }
              ]
            },
            "emf_processor": {
              "metric_declaration_dedup": true,
              "metric_declaration": [
                {
                  "source_labels": ["container_name"],
                  "label_matcher": "^envoy$",
                  "dimensions": [["ClusterName","TaskDefinitionFamily"]],
                  "metric_selectors": [
                    "^envoy_http_downstream_rq_(total|xx)$",
                    "^envoy_cluster_upstream_cx_(r|t)x_bytes_total$",
                    "^envoy_cluster_membership_(healthy|total)$",
                    "^envoy_server_memory_(allocated|heap_size)$",
                    "^envoy_cluster_upstream_cx_(connect_timeout|destroy_local_with_active_rq)$",
                    "^envoy_cluster_upstream_rq_(pending_failure_eject|pending_overflow|timeout|per_try_timeout|rx_reset|maintenance_mode)$",
                    "^envoy_http_downstream_cx_destroy_remote_active_rq$",
                    "^envoy_cluster_upstream_flow_control_(paused_reading_total|resumed_reading_total|backed_up_total|drained_total)$",
                    "^envoy_cluster_upstream_rq_retry$",
                    "^envoy_cluster_upstream_rq_retry_(success|overflow)$",
                    "^envoy_server_(version|uptime|live)$"
                  ]
                },
                {
                  "source_labels": ["container_name"],
                  "label_matcher": "^envoy$",
                  "dimensions": [["ClusterName","TaskDefinitionFamily","envoy_http_conn_manager_prefix","envoy_response_code_class"]],
                  "metric_selectors": [
                    "^envoy_http_downstream_rq_xx$"
                  ]
                },
                {
                  "source_labels": ["Java_EMF_Metrics"],
                  "label_matcher": "^true$",
                  "dimensions": [["ClusterName","TaskDefinitionFamily"]],
                  "metric_selectors": [
                    "^jvm_threads_(current|daemon)$",
                    "^jvm_classes_loaded$",
                    "^java_lang_operatingsystem_(freephysicalmemorysize|totalphysicalmemorysize|freeswapspacesize|totalswapspacesize|systemcpuload|processcpuload|availableprocessors|openfiledescriptorcount)$",
                    "^catalina_manager_(rejectedsessions|activesessions)$",
                    "^jvm_gc_collection_seconds_(count|sum)$",
                    "^catalina_globalrequestprocessor_(bytesreceived|bytessent|requestcount|errorcount|processingtime)$"
                  ]
                },
                {
                  "source_labels": ["Java_EMF_Metrics"],
                  "label_matcher": "^true$",
                  "dimensions": [["ClusterName","TaskDefinitionFamily","area"]],
                  "metric_selectors": [
                    "^jvm_memory_bytes_used$"
                  ]
                },
                {
                  "source_labels": ["Java_EMF_Metrics"],
                  "label_matcher": "^true$",
                  "dimensions": [["ClusterName","TaskDefinitionFamily","pool"]],
                  "metric_selectors": [
                    "^jvm_memory_pool_bytes_used$"
                  ]
                }
              ]
            }
          }
        },
        "force_flush_interval": 5
      }
    }

ECSCWAgentTaskDefinition:
Type: 'AWS::ECS::TaskDefinition'
DependsOn:
- PrometheusConfigSSMParameter
- CWAgentConfigSSMParameter
Properties:

  Family: !Sub 'cwagent-prometheus-${ECSClusterName}-EC2-${ECSNetworkMode}'
  TaskRoleArn: !If [CreateRoles, !Ref CWAgentECSTaskRole, !Sub 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/${TaskRoleName}']
  ExecutionRoleArn: !If [CreateRoles, !Ref CWAgentECSExecutionRole, !Sub 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/${ExecutionRoleName}']
  NetworkMode: !Ref ECSNetworkMode
  ContainerDefinitions:
    - Name: cloudwatch-agent-prometheus
      Image: amazon/cloudwatch-agent:1.247355.0b252062
      Essential: true
      MountPoints: []
      PortMappings: []
      Environment: []
      Secrets:
        - Name: PROMETHEUS_CONFIG_CONTENT
          ValueFrom: !Sub 'AmazonCloudWatch-PrometheusConfigName-${ECSClusterName}-EC2-${ECSNetworkMode}'
        - Name: CW_CONFIG_CONTENT
          ValueFrom: !Sub 'AmazonCloudWatch-CWAgentConfig-${ECSClusterName}-EC2-${ECSNetworkMode}'
      LogConfiguration:
        LogDriver: awslogs
        Options:
          awslogs-create-group: 'True'
          awslogs-group: "/ecs/ecs-cwagent-prometheus"
          awslogs-region: !Ref AWS::Region
          awslogs-stream-prefix: !Sub 'ecs-EC2-${ECSNetworkMode}'
  RequiresCompatibilities:
    - EC2
  Cpu: '512'
  Memory: '1024'


问:
How to login to AWS CodeArtifact before npm installs
How can I trigger the login before the install script in node v18.12.1/npm 8.19.2?

I expect the npm preinstall script will run before the install script based on the documentation. When running node v14.21.1/npm 6.14.17 I was able to follow the instructions in this tutorial to trigger a CodeArtifact login with the preinstall script. All packages were installed from my CodeArtifact repository on running npm install as expected.

After updating to node v18.12.1/npm 8.19.2, npm install fails with error:

```<code>Unable to authenticate, your authentication token seems to be invalid
</code>```

What I have tested (each in a fresh environment with no npm cache):

npm run preinstall successfully logs on

∴ AWS credentials are configured and the preinstall script works when executed

npm install fails authentication

npm run preinstall; npm install successfully logs on and installs from CodeArtifact

∴ the preinstall script is not running. I get no results from filtering the debug logs suggesting the co:login step is not run:

```<code>$ cat /root/.npm/_logs/2022-12-06T07_12_47_353Z-debug-0.log | grep co:login

$ echo $?
1
</code>```

After reverting to node v14.21.1/npm 6.14.17, npm install behaves as expected, logging in and installing packages from CodeArtifact.
I have recreated the problem with a minimal package.json which can be tested in a docker container:

```<code>docker run --rm -it -v ~/.aws:/root/.aws:ro --name app node:18.12.1 /bin/bash
wget --quiet -O "awscliv2.zip" "https://awscli.amazonaws.com/awscli-exe-linux-$(uname -m).zip" && unzip -q awscliv2.zip
./aws/install
rm awscliv2.zip && rm -r ./aws
</code>```

Copy files in from a separate terminal

```<code>docker cp package.json app:/package.json
docker cp package-lock.json app:/package-lock.json
</code>```

And then install with npm install in the docker container.

package.json template would require you to substitute your own CodeArtifact repository, domain and owner

```<code>{
  "name": "app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "preinstall": "npm run co:login",
    "co:login": "aws codeartifact login --tool npm --repository my-repository --domain my-domain --domain-owner 123456789 --region ap-southeast-2"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "dayjs": "^1.11.6"
  }
}
</code>```

package-lock.json template would require you to substitute your own CodeArtifact url

```<code>{
  "name": "app",
  "version": "1.0.0",
  "lockfileVersion": 2,
  "requires": true,
  "packages": {
    "": {
      "name": "app",
      "version": "1.0.0",
      "hasInstallScript": true,
      "license": "ISC",
      "dependencies": {
        "dayjs": "^1.11.6"
      }
    },
    "node_modules/dayjs": {
      "version": "1.11.6",
      "resolved": "https://mydomain-123456789.d.codeartifact.ap-southeast-2.amazonaws.com:443/npm/my-repository/dayjs/-/dayjs-1.11.6.tgz",
      "integrity": "sha512-zZbY5giJAinCG+7AGaw0wIhNZ6J8AhWuSXKvuc1KAyMiRsvGQWqh4L+MomvhdAYjN+lqvVCMq1I41e3YHvXkyQ=="
    }
  },
  "dependencies": {
    "dayjs": {
      "version": "1.11.6",
      "resolved": "https://mydomain-123456789.d.codeartifact.ap-southeast-2.amazonaws.com:443/npm/my-repository/dayjs/-/dayjs-1.11.6.tgz",
      "integrity": "sha512-zZbY5giJAinCG+7AGaw0wIhNZ6J8AhWuSXKvuc1KAyMiRsvGQWqh4L+MomvhdAYjN+lqvVCMq1I41e3YHvXkyQ=="
    }
  }
}
</code>```

Body:
How can I trigger the login before the install script in node v18.12.1/npm 8.19.2?

I expect the npm preinstall script will run before the install script based on the documentation. When running node v14.21.1/npm 6.14.17 I was able to follow the instructions in this tutorial to trigger a CodeArtifact login with the preinstall script. All packages were installed from my CodeArtifact repository on running npm install as expected.

After updating to node v18.12.1/npm 8.19.2, npm install fails with error:

Unable to authenticate, your authentication token seems to be invalid

What I have tested (each in a fresh environment with no npm cache):

npm run preinstall successfully logs on

∴ AWS credentials are configured and the preinstall script works when executed

npm install fails authentication

npm run preinstall; npm install successfully logs on and installs from CodeArtifact

∴ the preinstall script is not running. I get no results from filtering the debug logs suggesting the co:login step is not run:

$ cat /root/.npm/_logs/2022-12-06T07_12_47_353Z-debug-0.log | grep co:login

$ echo $?
1

After reverting to node v14.21.1/npm 6.14.17, npm install behaves as expected, logging in and installing packages from CodeArtifact.
I have recreated the problem with a minimal package.json which can be tested in a docker container:

docker run --rm -it -v ~/.aws:/root/.aws:ro --name app node:18.12.1 /bin/bash
wget --quiet -O "awscliv2.zip" "https://awscli.amazonaws.com/awscli-exe-linux-$(uname -m).zip" && unzip -q awscliv2.zip
./aws/install
rm awscliv2.zip && rm -r ./aws

Copy files in from a separate terminal

docker cp package.json app:/package.json
docker cp package-lock.json app:/package-lock.json

And then install with npm install in the docker container.

package.json template would require you to substitute your own CodeArtifact repository, domain and owner

{
  "name": "app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "preinstall": "npm run co:login",
    "co:login": "aws codeartifact login --tool npm --repository my-repository --domain my-domain --domain-owner 123456789 --region ap-southeast-2"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "dayjs": "^1.11.6"
  }
}

package-lock.json template would require you to substitute your own CodeArtifact url

{
  "name": "app",
  "version": "1.0.0",
  "lockfileVersion": 2,
  "requires": true,
  "packages": {
    "": {
      "name": "app",
      "version": "1.0.0",
      "hasInstallScript": true,
      "license": "ISC",
      "dependencies": {
        "dayjs": "^1.11.6"
      }
    },
    "node_modules/dayjs": {
      "version": "1.11.6",
      "resolved": "https://mydomain-123456789.d.codeartifact.ap-southeast-2.amazonaws.com:443/npm/my-repository/dayjs/-/dayjs-1.11.6.tgz",
      "integrity": "sha512-zZbY5giJAinCG+7AGaw0wIhNZ6J8AhWuSXKvuc1KAyMiRsvGQWqh4L+MomvhdAYjN+lqvVCMq1I41e3YHvXkyQ=="
    }
  },
  "dependencies": {
    "dayjs": {
      "version": "1.11.6",
      "resolved": "https://mydomain-123456789.d.codeartifact.ap-southeast-2.amazonaws.com:443/npm/my-repository/dayjs/-/dayjs-1.11.6.tgz",
      "integrity": "sha512-zZbY5giJAinCG+7AGaw0wIhNZ6J8AhWuSXKvuc1KAyMiRsvGQWqh4L+MomvhdAYjN+lqvVCMq1I41e3YHvXkyQ=="
    }
  }
}


问:
How to install Intel SGX SDK on Windows 11
I'm trying to install Intel SGX SDK on Windows 11.

I followed Intel instruction, downloaded the executable: "Intel SGX SDK for Windows v2.17.100.2.exe", and tried to execute it.

The only thing that happens is that a zip program is opened and asks me where to unzip it. But no installation is initiated.

Somewhere in the installation guide by Intel (which has been written few years ago) it is been suggested to unzip it and install the files in "installs" directory. But from what I unzipped - there is no such a directory.

I installed the nuget package (SGX SDK) on Visual Studio - but I'm interested in the other programs that the SDK suppose to provide and specifically the code examples.

I probably missing something.

Thanks for any help!


问:
django rest ViewAPI parameters not displayed in OpenAPI dynamic schema
I want to make a swagger document of my project, so I tried to generate a dynamic schema for my APIs, using django rest automatic dynamic generated schema, as said in its document.

This is my urls.py:

```<code>from django.urls import path, include
from rest_framework.schemas import get_schema_view

schema_view = get_schema_view(title="Example API")

urlpatterns = [
    path("schema/", schema_view, name="schema"),
    ...
]
</code>```

And this is one of my view serializers:

```<code>class BookSerializer(serializers.ModelSerializer):
    summary_publisher_name = serializers.ReadOnlyField(source="published_by.name")
    authors = AuthorSerializer(many=True)
    chapters = ChapterSerializer(many=True, read_only=True)

    class Meta:
        model = Book
        fields = ["title", "summary_publisher_name", "authors", "chapters"]
    ...
</code>```

The problem is that in generated schema, there is none of these API parameters.
How can I add them to schema? Is there any automation way, or I need to add all fields for any of my views, by myself?

Body:
I want to make a swagger document of my project, so I tried to generate a dynamic schema for my APIs, using django rest automatic dynamic generated schema, as said in its document.

This is my urls.py:

from django.urls import path, include
from rest_framework.schemas import get_schema_view

schema_view = get_schema_view(title="Example API")

urlpatterns = [
    path("schema/", schema_view, name="schema"),
    ...
]

And this is one of my view serializers:

class BookSerializer(serializers.ModelSerializer):
    summary_publisher_name = serializers.ReadOnlyField(source="published_by.name")
    authors = AuthorSerializer(many=True)
    chapters = ChapterSerializer(many=True, read_only=True)

    class Meta:
        model = Book
        fields = ["title", "summary_publisher_name", "authors", "chapters"]
    ...

The problem is that in generated schema, there is none of these API parameters.
How can I add them to schema? Is there any automation way, or I need to add all fields for any of my views, by myself?


问:
Google Analytics Ad Cost Upload Mismatch
I have a problem with cost data uploaded to Google Analytics via the Management API.
The script itself works just fine. On a daily schedule it uploads a CSV from BigQuery to the management API. But in some cases the cost data shown in the UI is different from the data in the upload file.

For example:
In my BigQuery Table is see costs of 349.44 for a certain campaign on a certain date.
In the UI for the same campaign and date I see 92.31.
If I download the uploaded CSV again from the Data Upload section I see 257.13.
So three different numbers in three places that should not differ.
For the same campaign and other dates the data is correct.

All costs are in EUR so no currency conversion takes place and not just recent data is affected but also data from many month ago. I haven't found any resources that address this issue and would be greatful for any input.


问:
Why don't glibc malloc thread local arenas
glibc malloc assigns each thread only one arena. Why don't malloc simply thread local arena to avoid locking?

I have tried searching over Google and have found 0 answers related to this question.


问:
Sorting, Grouping and Skipping the first record of each group in mongoDB
Database: MongoDB
Consider a Entity: Item

```<code>{name: itemName,
itemId: itemIdValue,
category: categoryName,
manufactureDate: Date()}
</code>```

I want to find and remove the list of items such that

Consider/find only records having manufactureDate less than 'dateD1'

Grouped by category

In each group(result of step 2) records to be sorted by manufactureDate in descending order

After records are sorted in each group (result after step 3), the first record of each group to be skipped.

Remove them from the DB

I want to achieve the above from SpringBoot Application issuing the query to DB as a bulk deletion.
I've used org.springframework.data.mongodb.core.query,
Forming the query like:

```<code>Query query = new Query();
query.addCriteria(Criteria.where("manufactureDate").lt(dateD1)); //Step 1
query.with(
Sort.by(Direction.ASC, "category")
.and(Sort.by(Direction.DESC, "manufactureDate"))); //Step 2 and 3
mongoTemplate.findAllAndRemove(query, Item.class) ; //Step 5
</code>```

Question/ Problem: I am unable to fit the 4th step in this.

Body:
Database: MongoDB
Consider a Entity: Item

{name: itemName,
itemId: itemIdValue,
category: categoryName,
manufactureDate: Date()}

I want to find and remove the list of items such that

Consider/find only records having manufactureDate less than 'dateD1'

Grouped by category

In each group(result of step 2) records to be sorted by manufactureDate in descending order

After records are sorted in each group (result after step 3), the first record of each group to be skipped.

Remove them from the DB

I want to achieve the above from SpringBoot Application issuing the query to DB as a bulk deletion.
I've used org.springframework.data.mongodb.core.query,
Forming the query like:

Query query = new Query();
query.addCriteria(Criteria.where("manufactureDate").lt(dateD1)); //Step 1
query.with(
Sort.by(Direction.ASC, "category")
.and(Sort.by(Direction.DESC, "manufactureDate"))); //Step 2 and 3
mongoTemplate.findAllAndRemove(query, Item.class) ; //Step 5

Question/ Problem: I am unable to fit the 4th step in this.


问:
FlatMapFunction with spark java
I am trying to implement transformation logic using flatmap on 7gb input json file.
following code snippet throws
Cannot resolve method 'flatMap(anonymous org.apache.spark.api.java.function.FlatMapFunction<org.apache.spark.sql.Row,com.test.mapper.ProductType>)'

any suggestions please.

dataset is a Dataset<Row> of input json file.

```<code>            dataset.flatMap(new FlatMapFunction<Row, ProductType>() {
            private static final long serialVersionUID = -432662341173300339L;

            @Override
            public Iterator<ProductType> call(Row row) throws Exception {
                List<ProductType> productTypeList = new ArrayList<>();

                GenericRowWithSchema dep = row.getAs("dep");
                GenericRowWithSchema identity = Util.getRow(dep, "identity");

                String dt= Util.getValue(dep, "startDate");
                String flg = Util.getValue(dep, "withdrawalPenalty");
                return productTypeList.iterator();

            }
        });
</code>```
```<code>public class ProductType implements Serializable {
    String id;
    String domain;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getDomain() {
        return domain;
    }

    public void setDomain(String domain) {
        this.domain = domain;
    }
}
</code>```
```<code>class Util{

public static GenericRowWithSchema getRow(GenericRowWithSchema row, String fieldName) {
        try {
            return row.getAs(fieldName);
        } catch(Exception ex) {

            return null;
        }
    }

 public static String getValue(Row row, String fieldName) {
        try {
            return row.getAs(fieldName);
        } catch(Exception ex) {
            return "";
        }
    }

}

</code>```

Title: FlatMapFunction with spark java

Body:
I am trying to implement transformation logic using flatmap on 7gb input json file.
following code snippet throws
Cannot resolve method 'flatMap(anonymous org.apache.spark.api.java.function.FlatMapFunction<org.apache.spark.sql.Row,com.test.mapper.ProductType>)'

any suggestions please.

dataset is a Dataset<Row> of input json file.

            dataset.flatMap(new FlatMapFunction<Row, ProductType>() {
            private static final long serialVersionUID = -432662341173300339L;

            @Override
            public Iterator<ProductType> call(Row row) throws Exception {
                List<ProductType> productTypeList = new ArrayList<>();

                GenericRowWithSchema dep = row.getAs("dep");
                GenericRowWithSchema identity = Util.getRow(dep, "identity");

                String dt= Util.getValue(dep, "startDate");
                String flg = Util.getValue(dep, "withdrawalPenalty");
                return productTypeList.iterator();

            }
        });

public class ProductType implements Serializable {
    String id;
    String domain;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getDomain() {
        return domain;
    }

    public void setDomain(String domain) {
        this.domain = domain;
    }
}

class Util{

public static GenericRowWithSchema getRow(GenericRowWithSchema row, String fieldName) {
        try {
            return row.getAs(fieldName);
        } catch(Exception ex) {

            return null;
        }
    }

 public static String getValue(Row row, String fieldName) {
        try {
            return row.getAs(fieldName);
        } catch(Exception ex) {
            return "";
        }
    }

}


问:
Using reverse engeneering with Scaffold-DBContext, makes virtual collections read-only
Using EF Core 7, after scaffolding, the generated code looks like this:

```<code>public partial class Category
{
    public Guid CategoryId { get; set; }
    public Guid Title { get; set; }

    public virtual ICollection<Product> Products { get; } = new List<Product>(); // <= setter missing here
}
</code>```

As you can see, Products is read-only, which was not in previous versions of EF. The problem is that I can't fill it when creating a Category object:

```<code>Category cat = new Category()
{
    CategoryId = Guid.NewGuid(),
    Title = "",
    Products = new List<Products>() {/* ... */} // <= Error happens here
}
</code>```

it also happens when I'm going to customize the Products of a Category which are returned from database. The solution is to add setter in class model definition, but it will be deleted next time I scaffold and it's hard to manage. Is there any solution, or I need to turn back to EF5, or wait a while for fix?

Body:
Using EF Core 7, after scaffolding, the generated code looks like this:

public partial class Category
{
    public Guid CategoryId { get; set; }
    public Guid Title { get; set; }

    public virtual ICollection<Product> Products { get; } = new List<Product>(); // <= setter missing here
}

As you can see, Products is read-only, which was not in previous versions of EF. The problem is that I can't fill it when creating a Category object:

Category cat = new Category()
{
    CategoryId = Guid.NewGuid(),
    Title = "",
    Products = new List<Products>() {/* ... */} // <= Error happens here
}

it also happens when I'm going to customize the Products of a Category which are returned from database. The solution is to add setter in class model definition, but it will be deleted next time I scaffold and it's hard to manage. Is there any solution, or I need to turn back to EF5, or wait a while for fix?


问:
Kafka message pile up due to too many groups
My kafka application has multiple groups for multiple topics! (around 5-10 for each topic)
The kafka group sometimes become inactive but still exist in the system, and message keeps on piling up!

What is the right approach to fix this? One way is to reduce the retention time to 5-10 minutes, because the use for kafka in my application is to inform other services immediately!

```<code>@Bean
public NewTopic customTopic(){
    return TopicBuilder
            .name("customTopic")
            .config(TopicConfig.RETENTION_MS_CONFIG, "1680000")
            .config(TopicConfig.CLEANUP_POLICY_CONFIG , "delete")
            .build();
}
</code>```

Body:
My kafka application has multiple groups for multiple topics! (around 5-10 for each topic)
The kafka group sometimes become inactive but still exist in the system, and message keeps on piling up!

What is the right approach to fix this? One way is to reduce the retention time to 5-10 minutes, because the use for kafka in my application is to inform other services immediately!

@Bean
public NewTopic customTopic(){
    return TopicBuilder
            .name("customTopic")
            .config(TopicConfig.RETENTION_MS_CONFIG, "1680000")
            .config(TopicConfig.CLEANUP_POLICY_CONFIG , "delete")
            .build();
}


问:
how to increment price if number of days increase in Django
view.py

```<code>def booking(request):

    all_location = location.get_all_location()
    all_products = Product.get_all_products()
    data = {'amount': 5000}
    data['product'] = all_products
    data['location'] = all_location

    return render(request, 'booking.html', data)
</code>```

my html file

```<code>   <input type='number' placeholder='enter days' </div>
    <div class="mb-5">
      <div class="row">
        <div class="col-6 form-group">
          <input type="text" class="form-control p-4" placeholder="" required="required"> **{% comment %}Want to Get Value from days and save it variable {% endcomment %}**
        </div>
      </div> ** <p>Amount = RS {{amount}} </p> **{% comment %}Want to Save amount in variable if user increase days then amount variable get increment {% endcomment %}** ** <div class="form-group">
        <textarea class="form-control py-3 px-4" rows="3" placeholder="Special Request" required="required"></textarea>
      </div>
    </div>
    </div>
</code>```

I want to get and amount days value in variable then want to increment the amount if user increase days. I get the amount dynamically by view function and my other problem is that how to prevent user to change amount from source code.  *

Body:
view.py

def booking(request):

    all_location = location.get_all_location()
    all_products = Product.get_all_products()
    data = {'amount': 5000}
    data['product'] = all_products
    data['location'] = all_location

    return render(request, 'booking.html', data)

my html file

   <input type='number' placeholder='enter days'

          <input type="text" class="form-control p-4" placeholder="" required="required"> **{% comment %}Want to Get Value from days and save it variable {% endcomment %}**

 **
Amount = RS {{amount}}
 **{% comment %}Want to Save amount in variable if user increase days then amount variable get increment {% endcomment %}** **

        <textarea class="form-control py-3 px-4" rows="3" placeholder="Special Request" required="required"></textarea>

I want to get and amount days value in variable then want to increment the amount if user increase days. I get the amount dynamically by view function and my other problem is that how to prevent user to change amount from source code.  *


问:
How do I keep Material UI's bottom navigation at the very bottom of the screen?
I'm trying to figure out how to keep Material UI's bottom navigation at the very bottom of the page so that, rather than always being visible, it only appears below the body's main content.

Here's how my content is rendering in my app:

```<code>return (
        <div id='appContainer'>
            <Header />
            <Nav currentPage={currentPage} handlePageChange={handlePageChange} />
            {renderPage()}
            <Footer />
        </div>
    )
</code>```

This is the code I've got for my footer itself:

```<code>return (
        <React.Fragment>
            <CssBaseline />
            <AppBar position="fixed" id="footer" sx={{ top: 'auto', bottom: 0,  }}>
                <Toolbar disableGutters>
                    <Box sx={{ flexGrow: 1 }} style={{ display: "flex", justifyContent: "center", textAlign: "center", width: "100%" }} flexDirection="column">
                        <div id="upper-footer">
                            <img
                                src={Logo}
                                id="footer-logo"
                                style={{ width: "10%", marginTop: "10px", marginBottom: "10px" }}
                                alt="logo"
                                href="/"
                            />
                            <div id="social-icons">
                                <FacebookIcon sx={{ m:0.5 }}/>
                                <InstagramIcon sx={{ m:0.5 }}/>
                                <GoogleIcon sx={{ m:0.5 }}/>
                            </div>
                            <div id="footer-contact">
                                <Typography
                                    variant="h6"
                                    noWrap
                                    component="a"
                                    href="/"
                                    sx={{
                                        mr: 2,
                                        display: { xs: "none", md: "flex" },
                                        fontFamily: "montserrat, sans-serif",
                                        fontWeight: 700,
                                        color: "inherit",
                                        textDecoration: "none",
                                        // backgroundImage: "/assets/images/distressed-btn.svg",
                                    }}
                                >
                                    <a href='tel:0000000000' style={{ display: "flex", alignItems: "center", textDecoration: "none", color: "inherit" }}>
                                        <PhonelinkRingIcon sx={{ m:0.5 }}/> (000) 000-0000
                                    </a>
                                </Typography>
                                <Typography
                                    variant="h6"
                                    noWrap
                                    component="a"
                                    href="/"
                                    sx={{
                                        mr: 2,
                                        display: { xs: "none", md: "flex" },
                                        fontFamily: "montserrat, sans-serif",
                                        fontWeight: 700,
                                        color: "inherit",
                                        textDecoration: "none",
                                        // backgroundImage: "/assets/images/distressed-btn.svg",
                                        href: "#",
                                        alignItems: "center"
                                    }}
                                >
                                    <LocalActivityIcon sx={{ m:0.5 }}/> Tickets Available Soon
                                </Typography>
                            </div>
                        </div>
                        <div id="lower-footer">
                            <p>More Content Here</p>
                        </div>
                    </Box>
                </Toolbar>
            </AppBar>
        </React.Fragment>
    )
</code>```

Any help is greatly appreciated! :)

Body:
I'm trying to figure out how to keep Material UI's bottom navigation at the very bottom of the page so that, rather than always being visible, it only appears below the body's main content.

Here's how my content is rendering in my app:

return (

            {renderPage()}

    )

This is the code I've got for my footer itself:

return (
        <React.Fragment>
            <CssBaseline />
            <AppBar position="fixed" id="footer" sx={{ top: 'auto', bottom: 0,  }}>
                <Toolbar disableGutters>
                    <Box sx={{ flexGrow: 1 }} style={{ display: "flex", justifyContent: "center", textAlign: "center", width: "100%" }} flexDirection="column">

                                <FacebookIcon sx={{ m:0.5 }}/>
                                <InstagramIcon sx={{ m:0.5 }}/>
                                <GoogleIcon sx={{ m:0.5 }}/>

                                <Typography
                                    variant="h6"
                                    noWrap
                                    component="a"
                                    href="/"
                                    sx={{
                                        mr: 2,
                                        display: { xs: "none", md: "flex" },
                                        fontFamily: "montserrat, sans-serif",
                                        fontWeight: 700,
                                        color: "inherit",
                                        textDecoration: "none",
                                        // backgroundImage: "/assets/images/distressed-btn.svg",
                                    }}
                                >

                                        <PhonelinkRingIcon sx={{ m:0.5 }}/> (000) 000-0000

                                </Typography>
                                <Typography
                                    variant="h6"
                                    noWrap
                                    component="a"
                                    href="/"
                                    sx={{
                                        mr: 2,
                                        display: { xs: "none", md: "flex" },
                                        fontFamily: "montserrat, sans-serif",
                                        fontWeight: 700,
                                        color: "inherit",
                                        textDecoration: "none",
                                        // backgroundImage: "/assets/images/distressed-btn.svg",
                                        href: "#",
                                        alignItems: "center"
                                    }}
                                >
                                    <LocalActivityIcon sx={{ m:0.5 }}/> Tickets Available Soon
                                </Typography>

More Content Here

                    </Box>
                </Toolbar>
            </AppBar>
        </React.Fragment>
    )

Any help is greatly appreciated! :)


问:
I want to compute precision, recall and F1 after training with tflearn
I have trained a text classification model using tflearn and successfully performed model evaluation. I want to calculate the precision, recall and f1 using sklearn. But when i tried to perform prediction on test labels i receive an error.

```<code>#creating our training data
training = []
output = []
#create an empty array for our output
output_empty = [0] * len(classes)

#training set, bag of words for each sentence
for doc in documents:
  #initialize our bag of words
  bag = []
  #list of tokenized words for the pattern
  pattern_words = doc[0]
  # stem each word
  pattern_words = [stemmer.stem(word.lower()) for word in pattern_words]
  # create our bag of words array
  for w in words:
    bag.append(1) if w in pattern_words else bag.append(0)

    # output is a '0' for each tag and '1' for current tag
    output_row = list(output_empty)
    output_row[classes.index(doc[1])] = 1

    training.append([bag, output_row])

# shuffle our features and turn into np.array
random.shuffle(training)
training = np.array(training)

# create train and test lists
train_x = list(training[:,0])
train_y = list(training[:,1])
</code>```
```<code>from sklearn.model_selection import train_test_split
train_x, test_x, train_y, test_y = train_test_split(train_x, train_y, test_size=0.10, random_state=10, stratify=train_y)
</code>```
```<code>train_x = np.array(train_x)
train_y = np.array(train_y)
test_x=np.array(test_x)
test_y = np.array(test_y)
</code>```
```<code>net = tflearn.input_data(shape=[None, len(train_x[0])])
net = tflearn.fully_connected(net, 128)
net = tflearn.fully_connected(net, len(train_y[0]), activation='softmax')
net = tflearn.regression(net)
# Define model and setup tensorboard
model = tflearn.DNN(net, tensorboard_dir='tflearn_logs')
model.fit(train_x, train_y, n_epoch=10, batch_size=8, show_metric=True )

model.evaluate(test_x, test_y)
</code>```

I am able to perform prediction on test_x but i get the error below  when i perform prediction on test_y

```<code> predict_y = model.predict(test_y)
</code>```
```<code>---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-56-33f24cfe9a52> in <module>
----> 1 predicted_y = model.predict(test_y)
      2 #y_hatclass = model.predict_classes(test_x)

3 frames

/usr/local/lib/python3.8/dist-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1162           if (not is_tensor_handle_feed and
   1163               not subfeed_t.get_shape().is_compatible_with(np_val.shape)):
-> 1164             raise ValueError(
   1165                 f'Cannot feed value of shape {str(np_val.shape)} for Tensor '
   1166                 f'{subfeed_t.name}, which has shape '

ValueError: Cannot feed value of shape (143, 7) for Tensor InputData/X:0, which has shape (?, 55)
</code>```

Please anyone help me with the way to go about it.

Body:
I have trained a text classification model using tflearn and successfully performed model evaluation. I want to calculate the precision, recall and f1 using sklearn. But when i tried to perform prediction on test labels i receive an error.

#creating our training data
training = []
output = []
#create an empty array for our output
output_empty = [0] * len(classes)

#training set, bag of words for each sentence
for doc in documents:
  #initialize our bag of words
  bag = []
  #list of tokenized words for the pattern
  pattern_words = doc[0]
  # stem each word
  pattern_words = [stemmer.stem(word.lower()) for word in pattern_words]
  # create our bag of words array
  for w in words:
    bag.append(1) if w in pattern_words else bag.append(0)

    # output is a '0' for each tag and '1' for current tag
    output_row = list(output_empty)
    output_row[classes.index(doc[1])] = 1

    training.append([bag, output_row])

# shuffle our features and turn into np.array
random.shuffle(training)
training = np.array(training)

# create train and test lists
train_x = list(training[:,0])
train_y = list(training[:,1])

from sklearn.model_selection import train_test_split
train_x, test_x, train_y, test_y = train_test_split(train_x, train_y, test_size=0.10, random_state=10, stratify=train_y)

train_x = np.array(train_x)
train_y = np.array(train_y)
test_x=np.array(test_x)
test_y = np.array(test_y)

net = tflearn.input_data(shape=[None, len(train_x[0])])
net = tflearn.fully_connected(net, 128)
net = tflearn.fully_connected(net, len(train_y[0]), activation='softmax')
net = tflearn.regression(net)
# Define model and setup tensorboard
model = tflearn.DNN(net, tensorboard_dir='tflearn_logs')
model.fit(train_x, train_y, n_epoch=10, batch_size=8, show_metric=True )

model.evaluate(test_x, test_y)

I am able to perform prediction on test_x but i get the error below  when i perform prediction on test_y

 predict_y = model.predict(test_y)

---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-56-33f24cfe9a52> in <module>
----> 1 predicted_y = model.predict(test_y)
      2 #y_hatclass = model.predict_classes(test_x)

3 frames

/usr/local/lib/python3.8/dist-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1162           if (not is_tensor_handle_feed and
   1163               not subfeed_t.get_shape().is_compatible_with(np_val.shape)):
-> 1164             raise ValueError(
   1165                 f'Cannot feed value of shape {str(np_val.shape)} for Tensor '
   1166                 f'{subfeed_t.name}, which has shape '

ValueError: Cannot feed value of shape (143, 7) for Tensor InputData/X:0, which has shape (?, 55)

Please anyone help me with the way to go about it.


问:
when we click on button it updates the counter by 1 and a new circle also created each time with num printed on each new circle. Get deleted on click
In the react js app the initial value of the button is zero. Suppose we click on a button 10 times then 10 new circles will be created line by line. with a counter number printed on it. now if we click on any circle then the circle reduce by one and counter value is also reduced by one.

The answer should be in the react app with the help of hooks.


问:
Super tool tip is showing in different position in flutter web
My requirement is to show the tooltip when clicking on red color text. I used super_tooltip for this purpose but when I click on any text the tooltip position is not changing.It is always shown in the same position.
I need to show the tooltip in the exact position of the text not in different directions

It is displayed like below,

Below is the code to call my tooltip function

```<code>  WidgetSpan(
                alignment: spanAlignment,
                child:
                MouseRegion(
                  cursor: SystemMouseCursors.click,
                  child: GestureDetector(
                    onTap:(){
                      showToolTips();
                    },

                    child: Container(

                      child: Text(
                        w,
                        style: words[currentWord]!.textStyle ?? textStyle,
                      ),
                    ),
                  ),
                ),
              ),
</code>```

Tooltip code:

```<code>void showToolTips() {
    if (tooltip != null && tooltip!.isOpen) {
      tooltip!.close();
      return;
    }
    RenderBox renderBox = conText.findRenderObject() as RenderBox;
    final RenderBox overlay =
    Overlay.of(conText)!.context.findRenderObject() as RenderBox;
    var targetGlobalCenter = renderBox
        .localToGlobal(renderBox.size.center(Offset.zero), ancestor: overlay);

    tooltip = SuperTooltip(
      containsBackgroundOverlay: false,
      showCloseButton: ShowCloseButton.inside,
      dismissOnTapOutside: true,
      backgroundColor: Colors.white,
      minimumOutSidePadding: 0.0,
      snapsFarAwayVertically: false,
      popupDirection: TooltipDirection.down,
      borderColor: Colors.white,
      hasShadow: true,
      touchThrougArea: new Rect.fromCircle(center:targetGlobalCenter, radius: 10.0),
      content: Container(
        width: 190,
        color: Colors.white,  // height: 270,
        margin: const EdgeInsets.only(left: 12.0, right: 12.0, top: 12, bottom: 12),
        child: ClipRRect(
          child: Wrap(
              children: [
                Container(
                  padding: const EdgeInsets.all(0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                          Row(
                            children: const [
                               Padding(
                                padding: EdgeInsets.only(
                                    left: 15.0),
                                child: Text(
                                  'Add to read later',
                                ),
                              ),
                            ],
                          ),
                    ],
                  ),
                ),
              ]
          ),
        ),
      ),
    );
    tooltip!.show(conText);
  }
</code>```

Please help me to fix this.Thanks in advance

Body:
My requirement is to show the tooltip when clicking on red color text. I used super_tooltip for this purpose but when I click on any text the tooltip position is not changing.It is always shown in the same position.
I need to show the tooltip in the exact position of the text not in different directions

It is displayed like below,

Below is the code to call my tooltip function

  WidgetSpan(
                alignment: spanAlignment,
                child:
                MouseRegion(
                  cursor: SystemMouseCursors.click,
                  child: GestureDetector(
                    onTap:(){
                      showToolTips();
                    },

                    child: Container(

                      child: Text(
                        w,
                        style: words[currentWord]!.textStyle ?? textStyle,
                      ),
                    ),
                  ),
                ),
              ),

Tooltip code:

void showToolTips() {
    if (tooltip != null && tooltip!.isOpen) {
      tooltip!.close();
      return;
    }
    RenderBox renderBox = conText.findRenderObject() as RenderBox;
    final RenderBox overlay =
    Overlay.of(conText)!.context.findRenderObject() as RenderBox;
    var targetGlobalCenter = renderBox
        .localToGlobal(renderBox.size.center(Offset.zero), ancestor: overlay);

    tooltip = SuperTooltip(
      containsBackgroundOverlay: false,
      showCloseButton: ShowCloseButton.inside,
      dismissOnTapOutside: true,
      backgroundColor: Colors.white,
      minimumOutSidePadding: 0.0,
      snapsFarAwayVertically: false,
      popupDirection: TooltipDirection.down,
      borderColor: Colors.white,
      hasShadow: true,
      touchThrougArea: new Rect.fromCircle(center:targetGlobalCenter, radius: 10.0),
      content: Container(
        width: 190,
        color: Colors.white,  // height: 270,
        margin: const EdgeInsets.only(left: 12.0, right: 12.0, top: 12, bottom: 12),
        child: ClipRRect(
          child: Wrap(
              children: [
                Container(
                  padding: const EdgeInsets.all(0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                          Row(
                            children: const [
                               Padding(
                                padding: EdgeInsets.only(
                                    left: 15.0),
                                child: Text(
                                  'Add to read later',
                                ),
                              ),
                            ],
                          ),
                    ],
                  ),
                ),
              ]
          ),
        ),
      ),
    );
    tooltip!.show(conText);
  }

Please help me to fix this.Thanks in advance


问:
Initializiner element is not constant error (C)
When creating a struct and initializing it like so in file foo.h:
struct t_foo{int a, int b}foo{1, 2};
And then using it in another file foomap.h:
(addr is implemented as #define addrX VAL )

```<code>struct foomap_item
{
int addr
int read;
int write;
}

struct foomap_item foomap[]{
{addr1, foo.a, 0   },
{addr2, 0,     foo.b }
}
</code>```

I get an error "Initializiner element is not constant", because fields in my struct foo is not actually a constant. The point of this is to initialize "map" and have the ability to change fields in my foomap (read and write).

I believe that something like two or three additional hashmaps will work but I don't understand which variable and where put on right now.

Body:
When creating a struct and initializing it like so in file foo.h:
struct t_foo{int a, int b}foo{1, 2};
And then using it in another file foomap.h:
(addr is implemented as #define addrX VAL )

struct foomap_item
{
int addr
int read;
int write;
}

struct foomap_item foomap[]{
{addr1, foo.a, 0   },
{addr2, 0,     foo.b }
}

I get an error "Initializiner element is not constant", because fields in my struct foo is not actually a constant. The point of this is to initialize "map" and have the ability to change fields in my foomap (read and write).

I believe that something like two or three additional hashmaps will work but I don't understand which variable and where put on right now.


问:
Setting different height to every item according to video causing lag in recyclerview
I have a recycler view with a frame layout and I'm adding video player to it in onBindview holder.

MY NEED:

If the video height is smaller than 4:5 ratio then warp the height of frame layout according to the video height.

If the video height is larger than 4:5 then set the frame layout max-height 4:5 and then zoom fit the video in the frame layout.

MY MAIN CONTAINER IS CONSTRAINLAYOUT AND MY FRAME LAYOUT XML:

```<code>    <FrameLayout
        android:id="@+id/frame"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginStart="0.5dp"
        android:layout_marginEnd="0.5dp"
        app:layout_constraintDimensionRatio="H,4:5"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/caption"/>
</code>```

SETTING FRAME LAYOUT RATIO IN ONBINDVIEWHOLDER :

```<code>           height = mediaObjectItem.getHeight();
            width = mediaObjectItem.getWidth();
                params = (ConstraintLayout.LayoutParams) media_container.getLayoutParams();
                if ((float) height / (float) width > (float) 1.25) {
                    params.dimensionRatio = "4:5";

                } else {
                    params.dimensionRatio = width + ":" + height;
                }
                media_container.setLayoutParams(params);
</code>```

My friend suggested it is not a good idea to set height & width manually. So how can I achieve my needs?

Body:
I have a recycler view with a frame layout and I'm adding video player to it in onBindview holder.

MY NEED:

If the video height is smaller than 4:5 ratio then warp the height of frame layout according to the video height.

If the video height is larger than 4:5 then set the frame layout max-height 4:5 and then zoom fit the video in the frame layout.

MY MAIN CONTAINER IS CONSTRAINLAYOUT AND MY FRAME LAYOUT XML:

    <FrameLayout
        android:id="@+id/frame"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginStart="0.5dp"
        android:layout_marginEnd="0.5dp"
        app:layout_constraintDimensionRatio="H,4:5"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/caption"/>

SETTING FRAME LAYOUT RATIO IN ONBINDVIEWHOLDER :

           height = mediaObjectItem.getHeight();
            width = mediaObjectItem.getWidth();
                params = (ConstraintLayout.LayoutParams) media_container.getLayoutParams();
                if ((float) height / (float) width > (float) 1.25) {
                    params.dimensionRatio = "4:5";

                } else {
                    params.dimensionRatio = width + ":" + height;
                }
                media_container.setLayoutParams(params);

My friend suggested it is not a good idea to set height & width manually. So how can I achieve my needs?


问:
.net Logging assembling
I needed to write a custom logger for .net. Although I already did it I am not completely happy because I fail to understand how Filters are called into the ILoggingProvider or ILoggerFactory. I'm not refering to how filters work, but how my filter is feeded from appsettings without myself configuring that, like for example ConsoleLogger, writing the ext method AddConsole is enough.

I've done some researching but been unable to find useful info. Microsoft docs. I even looked into github at logging repo. Can anyone clarify this for me?

Title: .net Logging assembling


问:
No 'Access-Control-Allow-Origin' when downloading md files from firestore
I'm trying to display a little blog like system on a small webapp.

The Idea was to actually store the posts within a .md file which are stored on firestore. I'm now trying to grab the files from the firestore instead of the local react app folder.

Within the useEffect I have the following code:

```<code>useEffect(() => {

    const storageRef = projectStorage.ref()
    const fileRef = storageRef.child('/blog/' + file)

    fileRef.getDownloadURL().then((url) => {
      fetch(url)
        .then(res => res.text())
        .then(text => setContent(text))
    })

}, [file, slug, t])
</code>```

I assume I grab the file correctly from the storage itself because of the error printed to the console. The link points directly to the .md file

```<code>Access to fetch at 'https://firebasestorage.googleapis.com/v0/b/lechnerio.appspot.com/o/blog%2Ftest-blog-post.md?alt=media&token=768fafad-f4ba-4a00-babf-7b03a3aa26d2' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
</code>```

Body:
I'm trying to display a little blog like system on a small webapp.

The Idea was to actually store the posts within a .md file which are stored on firestore. I'm now trying to grab the files from the firestore instead of the local react app folder.

Within the useEffect I have the following code:

useEffect(() => {

    const storageRef = projectStorage.ref()
    const fileRef = storageRef.child('/blog/' + file)

    fileRef.getDownloadURL().then((url) => {
      fetch(url)
        .then(res => res.text())
        .then(text => setContent(text))
    })

}, [file, slug, t])

I assume I grab the file correctly from the storage itself because of the error printed to the console. The link points directly to the .md file

Access to fetch at 'https://firebasestorage.googleapis.com/v0/b/lechnerio.appspot.com/o/blog%2Ftest-blog-post.md?alt=media&token=768fafad-f4ba-4a00-babf-7b03a3aa26d2' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.


问:
how to check if JSON string has extra fields in Spark (not specified in the schema)
from_json Spark SQL function omits the fields that are not in schema but are present in the raw JSON string. How do I check if extra fields are present in JSON?

e.g

```<code>df.select(from_json(col("json_string"), schema)))
</code>```

where json_string is { "field0" : "go", "field1": "test" }

and schema is only aware of field0. How do I check if any extra fields (field1) are present in the json_string?  Spark just omits the field1 with no obvious way to retrieve the info about it's existence.

Body:
from_json Spark SQL function omits the fields that are not in schema but are present in the raw JSON string. How do I check if extra fields are present in JSON?

e.g

df.select(from_json(col("json_string"), schema)))

where json_string is { "field0" : "go", "field1": "test" }

and schema is only aware of field0. How do I check if any extra fields (field1) are present in the json_string?  Spark just omits the field1 with no obvious way to retrieve the info about it's existence.


问:
import {MatTableModule} from '@angular/material/table'; causing weird errors
I'm trying to implement a score board for my small project.
And when I try to use mat table, it causes me "Can't bind to 'dataSource' since it isn't a known property of 'table'." error.
My code :
score-screen.components.ts

```<code>import { Component, OnInit } from '@angular/core';
import { object } from '@angular/fire/database';
@Component({
  selector: 'app-scoreboard-screen',
  templateUrl: './scoreboard-screen.component.html',
  styleUrls: ['./scoreboard-screen.component.scss']
})
export class ScoreboardScreenComponent implements OnInit {

  lessons = [
    {
      id: 1,
      'description': 'Introduction to Angular Material',
      'duration': '4:17',
      'seqNo': 1,
      courseId: 12
    },
    {
      id: 2,
      'description': 'Introduction to Angular Material',
      'duration': '4:17',
      'seqNo': 2,
      courseId: 13
    }
  ]

  displayedColumns = ['seqNo',"description","duration"];

  constructor() {

  }

  ngOnInit(): void {
  }

}
</code>```

scoreboard-screen.component.html

```<code><table mat-table class="lessons-table table-hover" [dataSource]="lessons">
    <ng-container matColumnDef="seqNo" >
        <th mat-header-cell *matHeaderCellDef>#</th>
        <td mat-cell *matCellDef="let lesson"> {{lesson.seqNo}} </td>
    </ng-container>

    <ng-container matColumnDef="description" >
        <th mat-header-cell *matHeaderCellDef>Description</th>
        <td mat-cell *matCellDef="let lesson"> {{lesson.description}} </td>
    </ng-container>

    <ng-container matColumnDef="duration" >
        <th mat-header-cell *matHeaderCellDef>Duration</th>
        <td duration-cell *matCellDef="let lesson"> {{lesson.duration}} </td>
    </ng-container>

    <th mat-header-row *matHeaderRowDef="displayedColumns">#</th>
    <tr mat-row *matRowDef="let lesson; columns:displayedColumns"></tr>

</table>
</code>```

But when I tried to import MatTableModule in my app.module.ts, it gives me bunch of weird errors like the image that I have attached above.

This is my app.module.ts

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { initializeApp,provideFirebaseApp } from '@angular/fire/app';
import { environment } from '../environments/environment';
import { provideAuth,getAuth } from '@angular/fire/auth';
import { provideDatabase,getDatabase } from '@angular/fire/database';
import { provideFirestore,getFirestore } from '@angular/fire/firestore';
import { GameScreenComponent } from './game-screen/game-screen/game-screen.component';
import { HomeScreenComponent } from './home-screen/home-screen/home-screen.component';
import { ScoreboardScreenComponent } from './scoreboard-screen/scoreboard-screen/scoreboard-screen.component';
// import { MatTableModule } from '@angular/material/table'

@NgModule({
  declarations: [
    AppComponent,
    GameScreenComponent,
    HomeScreenComponent,
    ScoreboardScreenComponent,

  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    ReactiveFormsModule,
    // MatTableModule,
    provideFirebaseApp(() => initializeApp(environment.firebase)),
    provideAuth(() => getAuth()),
    provideDatabase(() => getDatabase()),
    provideFirestore(() => getFirestore()),
    // BrowserAnimationsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

</code>```

Can I please get some help on this? Below are parts of my errors when I import the MatTableModule in app.modules.ts (I got like 400 lines of errors like this, and most of them are related to cdk, but I don't think I used it in any of my project)

```<code>Error: node_modules/@angular/material/table/index.d.ts:178:18 - error TS2707: Generic type 'ɵɵComponentDeclaration' requires between 7 and 8 type arguments.

Error: node_modules/@angular/material/table/index.d.ts:188:18 - error TS2707: Generic type 'ɵɵDirectiveDeclaration' requires between 6 and 8 type arguments.

Error: node_modules/@angular/material/table/index.d.ts:198:18 - error TS2707: Generic type 'ɵɵComponentDeclaration' requires between 7 and 8 type arguments.

Error: node_modules/@angular/material/table/index.d.ts:382:18 - error TS2707: Generic type 'ɵɵComponentDeclaration' requires between 7 and 8 type arguments.

Error: src/app/scoreboard-screen/scoreboard-screen/scoreboard-screen.component.html:2:1 - error NG8001: 'mat-table' is not a known element:
1. If 'mat-table' is an Angular component, then verify that it is part of this module.
2. If 'mat-table' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

Error occurs in the template of component ScoreboardScreenComponent.

Error: src/app/scoreboard-screen/scoreboard-screen/scoreboard-screen.component.html:2:46 - error NG8002: Can't bind to 'dataSource' since it isn't a known property of 'mat-table'.
1. If 'mat-table' is an Angular component and it has 'dataSource' input, then verify that it is part of this module.
2. If 'mat-table' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.
</code>```

And this is the error when I don't import MatTableModule

```<code>Error: src/app/scoreboard-screen/scoreboard-screen/scoreboard-screen.component.html:2:52 - error NG8002: Can't bind to 'dataSource' since it isn't a known property of 'table'.
</code>```

Body:
I'm trying to implement a score board for my small project.
And when I try to use mat table, it causes me "Can't bind to 'dataSource' since it isn't a known property of 'table'." error.
My code :
score-screen.components.ts

import { Component, OnInit } from '@angular/core';
import { object } from '@angular/fire/database';
@Component({
  selector: 'app-scoreboard-screen',
  templateUrl: './scoreboard-screen.component.html',
  styleUrls: ['./scoreboard-screen.component.scss']
})
export class ScoreboardScreenComponent implements OnInit {

  lessons = [
    {
      id: 1,
      'description': 'Introduction to Angular Material',
      'duration': '4:17',
      'seqNo': 1,
      courseId: 12
    },
    {
      id: 2,
      'description': 'Introduction to Angular Material',
      'duration': '4:17',
      'seqNo': 2,
      courseId: 13
    }
  ]

  displayedColumns = ['seqNo',"description","duration"];

  constructor() {

  }

  ngOnInit(): void {
  }

}

scoreboard-screen.component.html

    <ng-container matColumnDef="seqNo" >
        #
         {{lesson.seqNo}}
    </ng-container>

    <ng-container matColumnDef="description" >
        Description
         {{lesson.description}}
    </ng-container>

    <ng-container matColumnDef="duration" >
        Duration
         {{lesson.duration}}
    </ng-container>

    #

But when I tried to import MatTableModule in my app.module.ts, it gives me bunch of weird errors like the image that I have attached above.

This is my app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { initializeApp,provideFirebaseApp } from '@angular/fire/app';
import { environment } from '../environments/environment';
import { provideAuth,getAuth } from '@angular/fire/auth';
import { provideDatabase,getDatabase } from '@angular/fire/database';
import { provideFirestore,getFirestore } from '@angular/fire/firestore';
import { GameScreenComponent } from './game-screen/game-screen/game-screen.component';
import { HomeScreenComponent } from './home-screen/home-screen/home-screen.component';
import { ScoreboardScreenComponent } from './scoreboard-screen/scoreboard-screen/scoreboard-screen.component';
// import { MatTableModule } from '@angular/material/table'

@NgModule({
  declarations: [
    AppComponent,
    GameScreenComponent,
    HomeScreenComponent,
    ScoreboardScreenComponent,

  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    ReactiveFormsModule,
    // MatTableModule,
    provideFirebaseApp(() => initializeApp(environment.firebase)),
    provideAuth(() => getAuth()),
    provideDatabase(() => getDatabase()),
    provideFirestore(() => getFirestore()),
    // BrowserAnimationsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Can I please get some help on this? Below are parts of my errors when I import the MatTableModule in app.modules.ts (I got like 400 lines of errors like this, and most of them are related to cdk, but I don't think I used it in any of my project)

Error: node_modules/@angular/material/table/index.d.ts:178:18 - error TS2707: Generic type 'ɵɵComponentDeclaration' requires between 7 and 8 type arguments.

Error: node_modules/@angular/material/table/index.d.ts:188:18 - error TS2707: Generic type 'ɵɵDirectiveDeclaration' requires between 6 and 8 type arguments.

Error: node_modules/@angular/material/table/index.d.ts:198:18 - error TS2707: Generic type 'ɵɵComponentDeclaration' requires between 7 and 8 type arguments.

Error: node_modules/@angular/material/table/index.d.ts:382:18 - error TS2707: Generic type 'ɵɵComponentDeclaration' requires between 7 and 8 type arguments.

Error: src/app/scoreboard-screen/scoreboard-screen/scoreboard-screen.component.html:2:1 - error NG8001: 'mat-table' is not a known element:
1. If 'mat-table' is an Angular component, then verify that it is part of this module.
2. If 'mat-table' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

Error occurs in the template of component ScoreboardScreenComponent.

Error: src/app/scoreboard-screen/scoreboard-screen/scoreboard-screen.component.html:2:46 - error NG8002: Can't bind to 'dataSource' since it isn't a known property of 'mat-table'.
1. If 'mat-table' is an Angular component and it has 'dataSource' input, then verify that it is part of this module.
2. If 'mat-table' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.

And this is the error when I don't import MatTableModule

Error: src/app/scoreboard-screen/scoreboard-screen/scoreboard-screen.component.html:2:52 - error NG8002: Can't bind to 'dataSource' since it isn't a known property of 'table'.


问:
pyomo iterate objective using for loop or anything
I want to create obj1 , obj2 for this instead of making 1 objective with multiple indexes , I suggest using for loop but don't know how</p>
```<code># Objective
def ObjRule(m, b):
    return 42*m.gen_o[b] + 32*m.gen_t[b]
m.obj = pyo.Objective(m.T,rule=ObjRule, sense=pyo.minimize)

</code>```
```<code>This is what i get with current code
1 Objective Declarations
    obj : Size=3, Index=T, Active=True
        Key : Active : Sense    : Expression
          1 :   True : minimize : 42*gen_o[1] + 32*gen_t[1]
          2 :   True : minimize : 42*gen_o[2] + 32*gen_t[2]
          3 :   True : minimize : 42*gen_o[3] + 32*gen_t[3]

</code>```

Body:
I want to create obj1 , obj2 for this instead of making 1 objective with multiple indexes , I suggest using for loop but don't know how

# Objective
def ObjRule(m, b):
    return 42*m.gen_o[b] + 32*m.gen_t[b]
m.obj = pyo.Objective(m.T,rule=ObjRule, sense=pyo.minimize)

This is what i get with current code
1 Objective Declarations
    obj : Size=3, Index=T, Active=True
        Key : Active : Sense    : Expression
          1 :   True : minimize : 42*gen_o[1] + 32*gen_t[1]
          2 :   True : minimize : 42*gen_o[2] + 32*gen_t[2]
          3 :   True : minimize : 42*gen_o[3] + 32*gen_t[3]


问:
When use Route Attribute on Action Method, OnActionExecuting is not triggering
In a Dotnet core 3 application when I use [Route] Attribute on Action Method then OnActionExecuting is not triggering.

Action Method with Rout Attribute:

```<code>[Route("Login/{id}")]
        public ActionResult Login(int id)
        {
            var vm = new AcccountLoginViewModel();
            vm.CityId= id;
            return View(vm);
        }
</code>```

OnActionExecuting:

```<code> public override void OnActionExecuting(ActionExecutingContext filterContext) {
            filterContext.ActionArguments.TryGetValue("id", out object? id);

            if(id == null) {
                filterContext.ActionArguments.TryGetValue("CityId", out id);
                ViewBag.CityId = id;
            }
            else
            {
                ViewBag.CityId = id;
            }

            base.OnActionExecuting(filterContext);
        }
</code>```

Startup.cs

```<code>app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(name: "areas", pattern: "{area:exists}/{controller=AdminHome}/{action=DashBoard}/{id?}");
                endpoints.MapAreaControllerRoute(name: "Admins", areaName: "Admins", pattern: "Admins/{controller=AdminHome}/{action=DashBoard}");
                endpoints.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Cities}/{id?}");
            });
</code>```

tried to add a route at startup.cs

endpoints.MapControllerRoute(name: "customRout", pattern: "{action=Cities}/{id?}");

Body:
In a Dotnet core 3 application when I use [Route] Attribute on Action Method then OnActionExecuting is not triggering.

Action Method with Rout Attribute:

[Route("Login/{id}")]
        public ActionResult Login(int id)
        {
            var vm = new AcccountLoginViewModel();
            vm.CityId= id;
            return View(vm);
        }

OnActionExecuting:

 public override void OnActionExecuting(ActionExecutingContext filterContext) {
            filterContext.ActionArguments.TryGetValue("id", out object? id);

            if(id == null) {
                filterContext.ActionArguments.TryGetValue("CityId", out id);
                ViewBag.CityId = id;
            }
            else
            {
                ViewBag.CityId = id;
            }

            base.OnActionExecuting(filterContext);
        }

Startup.cs

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(name: "areas", pattern: "{area:exists}/{controller=AdminHome}/{action=DashBoard}/{id?}");
                endpoints.MapAreaControllerRoute(name: "Admins", areaName: "Admins", pattern: "Admins/{controller=AdminHome}/{action=DashBoard}");
                endpoints.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Cities}/{id?}");
            });

tried to add a route at startup.cs

endpoints.MapControllerRoute(name: "customRout", pattern: "{action=Cities}/{id?}");