”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 使用 EventBridge 和 Lambda 进行自动故障排除和 ITSM 系统

使用 EventBridge 和 Lambda 进行自动故障排除和 ITSM 系统

发布于2024-08-23
浏览:984

Introduction :

Folks, In IT Operations, it's a very generic task to monitor server metrices like utilization of cpu/memory and disk or filesystems, but in case any of the metrics gets triggered to be critical, then dedicated persons need to perform some basic troubleshooting by logging into server and find out the initial cause of utilization which person has to perform multiple times if he gets multiple same alert that creates boredom and not productive at all. So as a workaround, there can be a system developed which will react once alarm gets triggered and act on those instances by executing few basic troubleshooting commands. Just to summarize the problem statement and expectation -

Problem Statement :

Develop a system which will fulfill below expectations -

  • Each EC2 instances should be monitored by CloudWatch.
  • Once alarm gets triggered, something has to be there which will login to that affected EC2 instance and perform some basic troubleshooting commands.
  • Then, create a JIRA issue to document that incident and add the output of commands in comment section.
  • Then, send an automatic email with providing all alarm details and JIRA issue details.

Architecture Diagram :

Automatic Troubleshooting & ITSM System using EventBridge and Lambda

Prerequisites :

  1. EC2 Instances
  2. CloudWatch Alarms
  3. EventBridge Rule
  4. Lambda Function
  5. JIRA Account
  6. Simple Notification Service

Implementation Steps :

  • A. CloudWatch Agent Installation and Configuration Setup :
    Open Systems Manager console and click on "Documents"
    Search for "AWS-ConfigureAWSPackage" document and execute by providing required details.
    Package Name = AmazonCloudwatchAgent
    Post installation, CloudWatch agent needs to be configured as per configuration file . For this, execute AmazonCloudWatch-ManageAgent document. Also, make sure JSON CloudWatch config file is stored in SSM Parameter.
    Once you see that metrices are reporting to CloudWatch console, then create an alarm for CPU and Memory utilizations etc.

  • B. Setup EventBridge Rule :
    To track the alarm state changes, here, we have customized pattern a little to track alarm state changes from OK to ALARM only, not reverse one. Then, add this rule to a lambda function as a trigger.

{
  "source": ["aws.cloudwatch"],
  "detail-type": ["CloudWatch Alarm State Change"],
  "detail": {
    "state": {
      "value": ["ALARM"]
    },
    "previousState": {
      "value": ["OK"]
    }
  }
}
  • C. Create a Lambda Function for Sending Email and Logging an Incident in JIRA : This lambda function is created for multiple activities which is triggered by EventBridge rule and as a destination SNS topic is added by using AWS SDK(Boto3). Once EventBridge rule is triggered then sends JSON event content to lambda by which function captures multiple details to process in different way. Here, as of now we have worked on two type of alarms - i. CPU Utilization and ii. Memory Utilization. Once any of these two alarms are triggered and alarm state is changed from OK to ALARM, then EventBridge gets triggered which also triggered Lambda function to perform those tasks mentioned in the form code.

Lambda Prerequisites :
We need below modules to import for make the codes work -

  • >> os
  • >> sys
  • >> json
  • >> boto3
  • >> time
  • >> requests

Note: From above modules, except 'requests' module rest all are downloaded within a lambda underlying infrastructure by default. Importing 'requests' module directly will not be supported in Lambda. Hence, first, install request module in a folder in your local machine(laptop) by executing below command -

pip3 install requests -t  --no-user

_After that, this will be downloaded in the folder from where you are executing above command or where you want to store the module source codes, here I hope lambda code is being prepared in your local machine. If yes, then create a zip file of that entire lambda source codes with module. After that, upload the zip file to lambda function.

So, here we are performing below two scenarios -

1. CPU Utilization - If CPU utilization alarm gets triggered, then lambda function need to fetch the instance and login to that instance and perform top 5 high consuming processes. Then, it will create a JIRA issue and add the process details in the comment section. Simultaneously, it will send an email with alarm details and jira issue details with process output.

2. Memory Utilization - Same approach as above

Now, let me reframe the task details which lambda is supposed to perform -

  1. Login to Instance
  2. Perform Basic Troubleshooting Steps.
  3. Create a JIRA Issue
  4. Send Email to Recipient with all Details

Scenario 1: When alarm state has been changed from OK to ALARM

First Set (Define the cpu and memory function) :

################# Importing Required Modules ################
############################################################
import json
import boto3
import time
import os
import sys
sys.path.append('./python')   ## This will add requests module along with all dependencies into this script
import requests
from requests.auth import HTTPBasicAuth

################## Calling AWS Services ###################
###########################################################
ssm = boto3.client('ssm')
sns_client = boto3.client('sns')
ec2 = boto3.client('ec2')

################## Defining Blank Variable ################
###########################################################
cpu_process_op = ''
mem_process_op = ''
issueid = ''
issuekey = ''
issuelink = ''

################# Function for CPU Utilization ################
###############################################################
def cpu_utilization(instanceid, metric_name, previous_state, current_state):
    global cpu_process_op
    if previous_state == 'OK' and current_state == 'ALARM':
        command = 'ps -eo user,pid,ppid,cmd,%mem,%cpu --sort=-%cpu | head -5'
        print(f'Impacted Instance ID is : {instanceid}, Metric Name: {metric_name}')
        # Start a session
        print(f'Starting session to {instanceid}')
        response = ssm.send_command(InstanceIds = [instanceid], DocumentName="AWS-RunShellScript", Parameters={'commands': [command]})
        command_id = response['Command']['CommandId']
        print(f'Command ID: {command_id}')
        # Retrieve the command output
        time.sleep(4)
        output = ssm.get_command_invocation(CommandId=command_id, InstanceId=instanceid)
        print('Please find below output -\n', output['StandardOutputContent'])
        cpu_process_op = output['StandardOutputContent']
    else:
        print('None')

################# Function for Memory Utilization ################
############################################################### 
def mem_utilization(instanceid, metric_name, previous_state, current_state):
    global mem_process_op
    if previous_state == 'OK' and current_state == 'ALARM':
        command = 'ps -eo user,pid,ppid,cmd,%mem,%cpu --sort=-%mem | head -5'
        print(f'Impacted Instance ID is : {instanceid}, Metric Name: {metric_name}')
        # Start a session
        print(f'Starting session to {instanceid}')
        response = ssm.send_command(InstanceIds = [instanceid], DocumentName="AWS-RunShellScript", Parameters={'commands': [command]})
        command_id = response['Command']['CommandId']
        print(f'Command ID: {command_id}')
        # Retrieve the command output
        time.sleep(4)
        output = ssm.get_command_invocation(CommandId=command_id, InstanceId=instanceid)
        print('Please find below output -\n', output['StandardOutputContent'])
        mem_process_op = output['StandardOutputContent']
    else:
        print('None')

Second Set (Create JIRA Issue) :

################## Create JIRA Issue ################
#####################################################
def create_issues(instanceid, metric_name, account, timestamp, region, current_state, previous_state, cpu_process_op, mem_process_op, metric_val):
    ## Create Issue ##
    url ='https://.atlassian.net//rest/api/2/issue'
    username = os.environ['username']
    api_token = os.environ['token']
    project = 'AnirbanSpace'
    issue_type = 'Incident'
    assignee = os.environ['username']
    summ_metric  = '%CPU Utilization' if 'CPU' in metric_name else '%Memory Utilization' if 'mem' in metric_name else '%Filesystem Utilization' if metric_name == 'disk_used_percent' else None
    metric_val = metric_val
    summary = f'Client | {account} | {instanceid} | {summ_metric} | Metric Value: {metric_val}'
    description = f'Client: Company\nAccount: {account}\nRegion: {region}\nInstanceID = {instanceid}\nTimestamp = {timestamp}\nCurrent State: {current_state}\nPrevious State = {previous_state}\nMetric Value = {metric_val}'

    issue_data = {
        "fields": {
            "project": {
                "key": "SCRUM"
            },
            "summary": summary,
            "description": description,
            "issuetype": {
                "name": issue_type
            },
            "assignee": {
                "name": assignee
            }
        }
    }
    data = json.dumps(issue_data)
    headers = {
        "Accept": "application/json",
        "Content-Type": "application/json"
    }
    auth = HTTPBasicAuth(username, api_token)
    response = requests.post(url, headers=headers, auth=auth, data=data)
    global issueid
    global issuekey
    global issuelink
    issueid = response.json().get('id')
    issuekey = response.json().get('key')
    issuelink = response.json().get('self')

    ################ Add Comment To Above Created JIRA Issue ###################
    output = cpu_process_op if metric_name == 'CPUUtilization' else mem_process_op if metric_name == 'mem_used_percent' else None
    comment_api_url = f"{url}/{issuekey}/comment"
    add_comment = requests.post(comment_api_url, headers=headers, auth=auth, data=json.dumps({"body": output}))

    ## Check the response
    if response.status_code == 201:
        print("Issue created successfully. Issue key:", response.json().get('key'))
    else:
        print(f"Failed to create issue. Status code: {response.status_code}, Response: {response.text}")

Third Set (Send an Email) :

################## Send An Email ################
#################################################
def send_email(instanceid, metric_name, account, region, timestamp, current_state, current_reason, previous_state, previous_reason, cpu_process_op, mem_process_op, metric_val, issueid, issuekey, issuelink):
    ### Define a dictionary of custom input ###
    metric_list = {'mem_used_percent': 'Memory', 'disk_used_percent': 'Disk', 'CPUUtilization': 'CPU'}

    ### Conditions ###
    if previous_state == 'OK' and current_state == 'ALARM' and metric_name in list(metric_list.keys()):
        metric_msg = metric_list[metric_name]
        output = cpu_process_op if metric_name == 'CPUUtilization' else mem_process_op if metric_name == 'mem_used_percent' else None
        print('This is output', output)
        email_body = f"Hi Team, \n\nPlease be informed that {metric_msg} utilization is high for the instanceid {instanceid}. Please find below more information \n\nAlarm Details:\nMetricName = {metric_name}, \nAccount = {account}, \nTimestamp = {timestamp}, \nRegion = {region}, \nInstanceID = {instanceid}, \nCurrentState = {current_state}, \nReason = {current_reason}, \nMetricValue = {metric_val}, \nThreshold = 80.00 \n\nProcessOutput: \n{output}\nIncident Deatils:\nIssueID = {issueid}, \nIssueKey = {issuekey}, \nLink = {issuelink}\n\nRegards,\nAnirban Das,\nGlobal Cloud Operations Team"
        res = sns_client.publish(
            TopicArn = os.environ['snsarn'],
            Subject = f'High {metric_msg} Utilization Alert : {instanceid}',
            Message = str(email_body)
            )
        print('Mail has been sent') if res else print('Email not sent')
    else:
        email_body = str(0)

Fourth Set (Calling Lambda Handler Function) :

################## Lambda Handler Function ################
###########################################################
def lambda_handler(event, context):
    instanceid = event['detail']['configuration']['metrics'][0]['metricStat']['metric']['dimensions']['InstanceId']
    metric_name = event['detail']['configuration']['metrics'][0]['metricStat']['metric']['name']
    account = event['account']
    timestamp = event['time']
    region = event['region']
    current_state = event['detail']['state']['value']
    current_reason = event['detail']['state']['reason']
    previous_state = event['detail']['previousState']['value']
    previous_reason = event['detail']['previousState']['reason']
    metric_val = json.loads(event['detail']['state']['reasonData'])['evaluatedDatapoints'][0]['value']
    ##### function calling #####
    if metric_name == 'CPUUtilization':
        cpu_utilization(instanceid, metric_name, previous_state, current_state)
        create_issues(instanceid, metric_name, account, timestamp, region, current_state, previous_state, cpu_process_op, mem_process_op, metric_val)
        send_email(instanceid, metric_name, account, region, timestamp, current_state, current_reason, previous_state, previous_reason, cpu_process_op, mem_process_op, metric_val, issueid, issuekey, issuelink)
    elif metric_name == 'mem_used_percent':
        mem_utilization(instanceid, metric_name, previous_state, current_state)
        create_issues(instanceid, metric_name, account, timestamp, region, current_state, previous_state, cpu_process_op, mem_process_op, metric_val)
        send_email(instanceid, metric_name, account, region, timestamp, current_state, current_reason, previous_state, previous_reason, cpu_process_op, mem_process_op, metric_val, issueid, issuekey, issuelink)
    else:
        None

Alarm Email Screenshot :

Automatic Troubleshooting & ITSM System using EventBridge and Lambda

Note: In ideal scenario, threshold is 80%, but for testing I changed it to 10%. Please see the Reason.

Alarm JIRA Issue :

Automatic Troubleshooting & ITSM System using EventBridge and Lambda

Scenario 2: When alarm state has been changed from OK to Insufficient data

In this scenario, if any server cpu or memory utilization metrics data are not captured, then alarm state gets changed from OK to INSUFFICIENT_DATA. This state can be achieved in two ways - a.) If server is in stopped state b.) If CloudWatch agent is not running or went in dead state.
So, as per below script, you'll be able to see that when cpu or memory utilization alarm status gets insufficient data, then lambda will first check if instance is in running status or not. If instance is in running state, then it will login and check CloudWatch agent status. Post that, it will create a JIRA issue and post the agent status in comment section of JIRA issue. After that, it will send an email with alarm details and agent status.

Full Code :

################# Importing Required Modules ################
############################################################
import json
import boto3
import time
import os
import sys
sys.path.append('./python')   ## This will add requests module along with all dependencies into this script
import requests
from requests.auth import HTTPBasicAuth

################## Calling AWS Services ###################
###########################################################
ssm = boto3.client('ssm')
sns_client = boto3.client('sns')
ec2 = boto3.client('ec2')

################## Defining Blank Variable ################
###########################################################
cpu_process_op = ''
mem_process_op = ''
issueid = ''
issuekey = ''
issuelink = ''

################# Function for CPU Utilization ################
###############################################################
def cpu_utilization(instanceid, metric_name, previous_state, current_state):
    global cpu_process_op
    if previous_state == 'OK' and current_state == 'INSUFFICIENT_DATA':
        ec2_status = ec2.describe_instance_status(InstanceIds=[instanceid,])['InstanceStatuses'][0]['InstanceState']['Name']
        if ec2_status == 'running':
            command = 'systemctl status amazon-cloudwatch-agent;sleep 3;systemctl restart amazon-cloudwatch-agent'
            print(f'Impacted Instance ID is : {instanceid}, Metric Name: {metric_name}')
            # Start a session
            print(f'Starting session to {instanceid}')
            response = ssm.send_command(InstanceIds = [instanceid], DocumentName="AWS-RunShellScript", Parameters={'commands': [command]})
            command_id = response['Command']['CommandId']
            print(f'Command ID: {command_id}')
            # Retrieve the command output
            time.sleep(4)
            output = ssm.get_command_invocation(CommandId=command_id, InstanceId=instanceid)
            print('Please find below output -\n', output['StandardOutputContent'])
            cpu_process_op = output['StandardOutputContent']
        else:
            cpu_process_op = f'Instance current status is {ec2_status}. Not able to reach out!!'
            print(f'Instance current status is {ec2_status}. Not able to reach out!!')
    else:
        print('None')

################# Function for Memory Utilization ################
############################################################### 
def mem_utilization(instanceid, metric_name, previous_state, current_state):
    global mem_process_op
    if previous_state == 'OK' and current_state == 'INSUFFICIENT_DATA':
        ec2_status = ec2.describe_instance_status(InstanceIds=[instanceid,])['InstanceStatuses'][0]['InstanceState']['Name']
        if ec2_status == 'running':
            command = 'systemctl status amazon-cloudwatch-agent'
            print(f'Impacted Instance ID is : {instanceid}, Metric Name: {metric_name}')
            # Start a session
            print(f'Starting session to {instanceid}')
            response = ssm.send_command(InstanceIds = [instanceid], DocumentName="AWS-RunShellScript", Parameters={'commands': [command]})
            command_id = response['Command']['CommandId']
            print(f'Command ID: {command_id}')
            # Retrieve the command output
            time.sleep(4)
            output = ssm.get_command_invocation(CommandId=command_id, InstanceId=instanceid)
            print('Please find below output -\n', output['StandardOutputContent'])
            mem_process_op = output['StandardOutputContent']
            print(mem_process_op)
        else:
            mem_process_op = f'Instance current status is {ec2_status}. Not able to reach out!!'
            print(f'Instance current status is {ec2_status}. Not able to reach out!!')     
    else:
        print('None')

################## Create JIRA Issue ################
#####################################################
def create_issues(instanceid, metric_name, account, timestamp, region, current_state, previous_state, cpu_process_op, mem_process_op, metric_val):
    ## Create Issue ##
    url ='https://.atlassian.net//rest/api/2/issue'
    username = os.environ['username']
    api_token = os.environ['token']
    project = 'AnirbanSpace'
    issue_type = 'Incident'
    assignee = os.environ['username']
    summ_metric  = '%CPU Utilization' if 'CPU' in metric_name else '%Memory Utilization' if 'mem' in metric_name else '%Filesystem Utilization' if metric_name == 'disk_used_percent' else None
    metric_val = metric_val
    summary = f'Client | {account} | {instanceid} | {summ_metric} | Metric Value: {metric_val}'
    description = f'Client: Company\nAccount: {account}\nRegion: {region}\nInstanceID = {instanceid}\nTimestamp = {timestamp}\nCurrent State: {current_state}\nPrevious State = {previous_state}\nMetric Value = {metric_val}'

    issue_data = {
        "fields": {
            "project": {
                "key": "SCRUM"
            },
            "summary": summary,
            "description": description,
            "issuetype": {
                "name": issue_type
            },
            "assignee": {
                "name": assignee
            }
        }
    }
    data = json.dumps(issue_data)
    headers = {
        "Accept": "application/json",
        "Content-Type": "application/json"
    }
    auth = HTTPBasicAuth(username, api_token)
    response = requests.post(url, headers=headers, auth=auth, data=data)
    global issueid
    global issuekey
    global issuelink
    issueid = response.json().get('id')
    issuekey = response.json().get('key')
    issuelink = response.json().get('self')

    ################ Add Comment To Above Created JIRA Issue ###################
    output = cpu_process_op if metric_name == 'CPUUtilization' else mem_process_op if metric_name == 'mem_used_percent' else None
    comment_api_url = f"{url}/{issuekey}/comment"
    add_comment = requests.post(comment_api_url, headers=headers, auth=auth, data=json.dumps({"body": output}))

    ## Check the response
    if response.status_code == 201:
        print("Issue created successfully. Issue key:", response.json().get('key'))
    else:
        print(f"Failed to create issue. Status code: {response.status_code}, Response: {response.text}")

################## Send An Email ################
#################################################
def send_email(instanceid, metric_name, account, region, timestamp, current_state, current_reason, previous_state, previous_reason, cpu_process_op, mem_process_op, metric_val, issueid, issuekey, issuelink):
    ### Define a dictionary of custom input ###
    metric_list = {'mem_used_percent': 'Memory', 'disk_used_percent': 'Disk', 'CPUUtilization': 'CPU'}

    ### Conditions ###
    if previous_state == 'OK' and current_state == 'INSUFFICIENT_DATA' and metric_name in list(metric_list.keys()):
        metric_msg = metric_list[metric_name]
        output = cpu_process_op if metric_name == 'CPUUtilization' else mem_process_op if metric_name == 'mem_used_percent' else None
        email_body = f"Hi Team, \n\nPlease be informed that {metric_msg} utilization alarm state has been changed to {current_state} for the instanceid {instanceid}. Please find below more information \n\nAlarm Details:\nMetricName = {metric_name}, \n Account = {account}, \nTimestamp = {timestamp}, \nRegion = {region},  \nInstanceID = {instanceid}, \nCurrentState = {current_state}, \nReason = {current_reason}, \nMetricValue = {metric_val}, \nThreshold = 80.00  \n\nProcessOutput = \n{output}\nIncident Deatils:\nIssueID = {issueid}, \nIssueKey = {issuekey}, \nLink = {issuelink}\n\nRegards,\nAnirban Das,\nGlobal Cloud Operations Team"
        res = sns_client.publish(
            TopicArn = os.environ['snsarn'],
            Subject = f'Insufficient {metric_msg} Utilization Alarm : {instanceid}',
            Message = str(email_body)
        )
        print('Mail has been sent') if res else print('Email not sent')
    else:
        email_body = str(0)

################## Lambda Handler Function ################
###########################################################
def lambda_handler(event, context):
    instanceid = event['detail']['configuration']['metrics'][0]['metricStat']['metric']['dimensions']['InstanceId']
    metric_name = event['detail']['configuration']['metrics'][0]['metricStat']['metric']['name']
    account = event['account']
    timestamp = event['time']
    region = event['region']
    current_state = event['detail']['state']['value']
    current_reason = event['detail']['state']['reason']
    previous_state = event['detail']['previousState']['value']
    previous_reason = event['detail']['previousState']['reason']
    metric_val = 'NA'
    ##### function calling #####
    if metric_name == 'CPUUtilization':
        cpu_utilization(instanceid, metric_name, previous_state, current_state)
        create_issues(instanceid, metric_name, account, timestamp, region, current_state, previous_state, cpu_process_op, mem_process_op, metric_val)
        send_email(instanceid, metric_name, account, region, timestamp, current_state, current_reason, previous_state, previous_reason, cpu_process_op, mem_process_op, metric_val, issueid, issuekey, issuelink)
    elif metric_name == 'mem_used_percent':
        mem_utilization(instanceid, metric_name, previous_state, current_state)
        create_issues(instanceid, metric_name, account, timestamp, region, current_state, previous_state, cpu_process_op, mem_process_op, metric_val)
        send_email(instanceid, metric_name, account, region, timestamp, current_state, current_reason, previous_state, previous_reason, cpu_process_op, mem_process_op, metric_val, issueid, issuekey, issuelink)
    else:
        None

Insufficient Data Email Screenshot :

Automatic Troubleshooting & ITSM System using EventBridge and Lambda

Insufficient data JIRA Issue :

Automatic Troubleshooting & ITSM System using EventBridge and Lambda

Conclusion :

In this article, we have tested scenarios on both cpu and memory utilization, but there can be lots of metrics on which we can configure auto-incident and auto-email functionality which will reduce significant efforts in terms of monitoring and creating incidents and all. This solution has given a initial approach how we can proceed further, but for sure there can be other possibilities to achieve this goal. I believe you all will understand the way we tried to make this relatable. Please like and comment if you love this article or have any other suggestions, so that we can populate in coming articles. ??

Thanks!!
Anirban Das

版本声明 本文转载于:https://dev.to/aws-builders/automatic-troubleshooting-itsm-system-using-eventbridge-and-lambda-nd?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 如何为 DOM 元素生成精确的 CSS 路径?
    如何为 DOM 元素生成精确的 CSS 路径?
    以增强的精度从 DOM 元素检索 CSS 路径提供的函数尝试为给定 DOM 元素生成 CSS 路径。然而,它的输出缺乏特异性,无法捕获元素在其兄弟元素中的位置。为了解决这个问题,我们需要一种更复杂的方法。改进的 CSS 路径函数下面介绍的增强函数解决了原来的限制:var cssPath = func...
    编程 发布于2024-11-03
  • 如何将单个 Python 字典写入具有精确标题和值行的 CSV 文件?
    如何将单个 Python 字典写入具有精确标题和值行的 CSV 文件?
    探索将 Python 字典写入 CSV 文件的细微差别您对将 Python 字典无缝写入 CSV 文件的追求给您带来了意想不到的挑战。虽然您设想在作为标题的字典键和作为第二行的值之间进行清晰的划分,但您当前的方法似乎还不够。让我们深入细节,解锁解决方案。问题在于方法的选择。 DictWriter.w...
    编程 发布于2024-11-03
  • 如何处理 Go 中延迟函数的错误返回值?
    如何处理 Go 中延迟函数的错误返回值?
    处理 Go 中返回值错误的延迟函数当返回变量的函数在没有延迟的情况下被延迟时,gometalinter 和 errcheck 正确地发出警告检查其返回的错误。这可能会导致未处理的错误和潜在的运行时问题。处理这种情况的习惯用法不是推迟函数本身,而是将其包装在另一个检查返回值的函数中。这是一个例子:de...
    编程 发布于2024-11-03
  • 为什么程序员不能总是记住代码:背后的科学
    为什么程序员不能总是记住代码:背后的科学
    如果您曾经想知道为什么程序员很难回忆起他们编写的确切代码,那么您并不孤单。尽管花费了数小时编码,许多开发人员经常忘记细节。这并不是因为缺乏知识或经验,而是因为工作本身的性质。我们来探究一下这种现象背后的原因。 编程的本质 通过记忆解决问题 这比仅仅记忆语法更能解决问题...
    编程 发布于2024-11-03
  • 你并不孤单:在社区的支持下掌握 Python
    你并不孤单:在社区的支持下掌握 Python
    加入 Python 社区可获得:社区论坛:向经验丰富的开发者获取支持和建议(如 Stack Overflow)。Discord 服务器:实时聊天室,提供即时支持和指导(如 Python Discord)。在线课程和研讨会:来自专家的指导,涵盖各种主题(如 Udemy 上的 Python NumPy ...
    编程 发布于2024-11-03
  • 学习伙伴
    学习伙伴
    聊天机器人界面,允许用户输入消息并接收来自 GPT-3.5 语言模型的对话响应。 特征 用于处理 HTTP 请求的基于 Flask 的 Web 服务器。 呈现用作用户界面的基本 HTML 模板 (chat.html)。 通过 POST 请求接受用户输入并将其发送到 OpenAI 的 GPT-3.5 ...
    编程 发布于2024-11-03
  • 前端开发 + 数据结构和算法:DSA 如何为您的 React 应用程序提供动力 ⚡
    前端开发 + 数据结构和算法:DSA 如何为您的 React 应用程序提供动力 ⚡
    专注于前端的面试通常根本不关心 DSA。 对于我们这些记得在学校/大学学习过 DSA 的人来说,所有的例子都感觉纯粹是算法(有充分的理由),但几乎没有任何例子或指导来说明我们每天使用的产品如何利用这个概念。 “我需要这个吗?” 你已经问过很多次这个问题了,不是吗? ? 以下是您今天可以在 React...
    编程 发布于2024-11-03
  • 为什么表行上的框阴影在不同浏览器中表现不同?
    为什么表行上的框阴影在不同浏览器中表现不同?
    跨浏览器表行上的框阴影外观不一致应用于表行 () 的 CSS 框阴影可能表现出不一致的行为跨各种浏览器。尽管 CSS 相同,但某些浏览器可能会按预期显示阴影,而其他浏览器则可能不会。要解决此问题,建议将 Transform 属性与 box-shadow 属性结合使用。将scale(1,1)添加到tr...
    编程 发布于2024-11-03
  • 探索 PHP 中的并发性和并行性:实践教程和技巧
    探索 PHP 中的并发性和并行性:实践教程和技巧
    理解并发性和并行性对于编写高效的 PHP 应用程序至关重要,特别是在处理需要同时处理的多个任务或操作时。这是理解和实现 PHP 并发性和并行性的分步指南,包含实践示例和说明。 1.并发与并行 并发:指系统通过交错执行同时处理多个任务的能力。这并不一定意味着任务是同时执行的,只是对它们...
    编程 发布于2024-11-03
  • ReactJs 与 Angular
    ReactJs 与 Angular
    React 和 Angular 是用于构建 Web 应用程序的两个最流行的框架/库,但它们在关键方面有所不同。以下是 React 和 Angular 之间主要区别的细分: 1. 类型:库与框架 React:一个用于构建用户界面的库,主要关注视图层。它允许开发人员将其与其他库集成以处理...
    编程 发布于2024-11-03
  • 如何使用变量中存储的类名动态实例化 JavaScript 对象?
    如何使用变量中存储的类名动态实例化 JavaScript 对象?
    使用动态类名实例化 JavaScript 对象假设您需要使用存储在变量中的类名实例化 JavaScript 对象。下面是一个说明性示例:// Define the class MyClass = Class.extend({}); // Store the class name in a strin...
    编程 发布于2024-11-03
  • Spring Boot 中的 OAuth 身份验证:Google 和 GitHub 登录集成指南
    Spring Boot 中的 OAuth 身份验证:Google 和 GitHub 登录集成指南
    使用 OAuth 2.0 增强安全性:在 Spring Boot 中实现社交登录 在现代 Web 开发的世界中,保护您的应用程序并使用户的身份验证尽可能顺利是首要任务。这就是 OAuth 2.0 的用武之地——它是一个强大的工具,不仅可以帮助保护您的 API,还可以让用户使用现有帐户从 Google...
    编程 发布于2024-11-03
  • 热点图——巴西 vs 意大利世界杯决赛)
    热点图——巴西 vs 意大利世界杯决赛)
    在这篇文章中,我开始尝试使用 Python 和 Seaborn 和 Matplotlib 创建 1970 年世界杯决赛中巴西运动的热图 。这个想法是根据那场比赛的比赛风格特征来代表巴西队在场上占据的空间。 1. 绘制场地 场地设计为比例坐标(130x90),包括边线、球门区和中心圈,...
    编程 发布于2024-11-03
  • 如何在 C++ 中连接字符串文字和字符文字?
    如何在 C++ 中连接字符串文字和字符文字?
    C 中的字符串文字和字符文字 尝试在 C 中连接字符串文字与字符文字时,可能会出现意外行为。例如:string str = "ab" 'c'; cout << str << endl;此代码会产生不可预测的输出,因为没有定义“”运算符来组合字符串文字和...
    编程 发布于2024-11-03
  • 通过“Go 练习挑战”课程释放您的算法潜力
    通过“Go 练习挑战”课程释放您的算法潜力
    通过 LabEx 的“Go Practice Challenges”课程踏上激动人心的旅程,提高您的编程技能。这门综合课程旨在帮助您掌握解决问题的艺术和提高编码效率,为您提供应对各种算法挑战的工具和技术。 深入算法世界 “围棋实践挑战”课程提供了一系列实际挑战,将突破您的算法思维界限...
    编程 发布于2024-11-03

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3