002BIO中的基本使用

本文深入探讨了Java中文件的读写操作,包括不同方式的文件复制和读取,以及对GB2312和GBK编码兼容ASCII的解析。通过具体代码示例,展示了如何使用FileInputStream、FileOutputStream、BufferedInputStream、BufferedOutputStream和自定义的MyBufferStream进行文件处理。

需注意gb2312和GBK都是兼容ascii编码的。也就是说gbk包含了ascii中的字符映射。
 
我觉得这个应该是1

package stream;


import java.io.*;

public class MyStream {
    public static void main(String[] args) throws Exception {
        writer001();
//        read001();
//        read002();
//            read003();
//            copy001();
        long sta = System.currentTimeMillis();

//        copy002();
        copy003();
        long end = System.currentTimeMillis();
        System.out.println(end-sta+"毫秒");

    }

    private static void copy003() throws Exception {
        MyBufferStream myBufferStream = new MyBufferStream(new FileInputStream("d:/清弄-叙世.mp3"));
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("d:/2.mp3"));
        int res = 0;
        while ((res=myBufferStream.myread())!=-1){
            out.write(res);
        }
        myBufferStream.close();
        out.close();

    }

    private static void copy002() throws Exception {
        BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream("d:/清弄-叙世.mp3"));
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("d:/1.mp3"));
        int res = 0;
        while ((res=inputStream.read())!=-1){
                out.write(res);
        }
        inputStream.close();
        out.close();

    }

    private static void copy001() throws Exception {
        FileInputStream in = new FileInputStream("d:/1.jpg");
        FileOutputStream out = new FileOutputStream("d:/jingse.jpg");
        byte[] arr = new byte[1234];
        int res = 0;
        while ((res = in.read(arr)) != -1) {
            out.write(arr);
        }
        in.close();
        out.close();
    }

    private static void read003() throws Exception {
        FileInputStream in = new FileInputStream("st.txt");
        byte[] arr = new byte[in.available()];
        in.read(arr);
        System.out.println(new String(arr));




    }

    private static void read002() throws Exception {
        FileInputStream in = new FileInputStream("st.txt");
        byte[] arr = new byte[1234];
        int res =0;

        while ((res = in.read(arr)) != -1) {
            System.out.println(new String(arr,0,res));
        }

    }

    private static void writer001() throws Exception {

        FileOutputStream out = new FileOutputStream("st.txt",true);
        out.write("alsdkjflksdjlffsldkfj".getBytes());
        out.close();

    }

    private static void read001() throws Exception {
        FileInputStream inputStream = new FileInputStream("st.txt");
        int res = 0;
        while ((res = inputStream.read()) != -1) {
            System.out.println((char)res);
        }
        inputStream.close();

    }
}

字节的缓冲区 返回int

package stream;

import java.io.IOException;
import java.io.InputStream;

public class MyBufferStream {
    private InputStream inputStream;
    private byte[] arr = new byte[1234];
    int position = 0;
    int count = 0;
    public MyBufferStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public int myread() throws IOException {
        if (count == 0) {


           count =  inputStream.read(arr);
            if (count < 0) {
                return -1;
            }
            position = 0;
        }
        count--;
        byte b = arr[position];

        position++;
        return b&255;//-1相关的问题


    }

    public void close() throws IOException {
        inputStream.close();
    }


}

# main.py import logging import time import random import json from collections import deque from conscious_system import MemorySystem, UnconsciousLayer, PreconsciousLayer, ConsciousLayer, Stimulus, ConsciousState # 配置日志 logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) logger = logging.getLogger('MainSimulation') class BiologicalStateSimulator: """模拟生物状态随时间变化""" def __init__(self): self.state = { "sensor_acuity": 0.9, # 感官敏锐度 (0.0-1.0) "arousal_level": 0.7, # 觉醒水平 (0.0-1.0) "fatigue": 0.3, # 疲劳度 (0.0-1.0) "stress": 0.2, # 压力水平 (0.0-1.0) "nutrition": 0.8, # 营养水平 (0.0-1.0) "hydration": 0.9 # 水分水平 (0.0-1.0) } self.history = deque(maxlen=100) self.last_update = time.time() def update(self): """更新生物状态""" current_time = time.time() time_diff = current_time - self.last_update # 随时间自然变化 self.state["fatigue"] = min(1.0, self.state["fatigue"] + 0.01 * (time_diff / 10)) self.state["sensor_acuity"] = max(0.5, self.state["sensor_acuity"] - 0.005 * (time_diff / 10)) self.state["arousal_level"] = max(0.3, self.state["arousal_level"] - 0.003 * (time_diff / 10)) # 营养和水分随时间减少 self.state["nutrition"] = max(0.3, self.state["nutrition"] - 0.002 * (time_diff / 10)) self.state["hydration"] = max(0.4, self.state["hydration"] - 0.003 * (time_diff / 10)) # 如果疲劳度高,压力也会增加 if self.state["fatigue"] > 0.6: self.state["stress"] = min(1.0, self.state["stress"] + 0.01 * (time_diff / 10)) # 记录历史 self.history.append({ "timestamp": current_time, "state": self.state.copy() }) self.last_update = current_time return self.state def apply_event(self, event_type: str, intensity: float): """应用外部事件影响生物状态""" if event_type == "rest": self.state["fatigue"] = max(0.0, self.state["fatigue"] - 0.2 * intensity) self.state["arousal_level"] = min(1.0, self.state["arousal_level"] + 0.1 * intensity) elif event_type == "meal": self.state["nutrition"] = min(1.0, self.state["nutrition"] + 0.3 * intensity) self.state["hydration"] = min(1.0, self.state["hydration"] + 0.2 * intensity) elif event_type == "exercise": self.state["fatigue"] = min(1.0, self.state["fatigue"] + 0.3 * intensity) self.state["stress"] = max(0.0, self.state["stress"] - 0.2 * intensity) elif event_type == "stressful_event": self.state["stress"] = min(1.0, self.state["stress"] + 0.4 * intensity) self.state["arousal_level"] = min(1.0, self.state["arousal_level"] + 0.2 * intensity) logger.info(f"生物状态事件: {event_type}(强度:{intensity})") return self.state def generate_stimulus_sequence(sequence_length: int = 20) -> list: """生成多样化的刺激序列""" stimuli = [] stimulus_types = [ ("视觉", "外部", "场景"), ("听觉", "外部", "声音"), ("触觉", "外部", "感觉"), ("内部", "内部", "想法"), ("情感", "内部", "情绪"), ("记忆", "内部", "回忆"), ("威胁", "外部", "危险"), ("机会", "外部", "奖励") ] emotional_valences = [-0.9, -0.7, -0.5, -0.3, 0.0, 0.3, 0.5, 0.7, 0.9] intensities = [0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] for i in range(sequence_length): # 随机选择刺激类型 stype = random.choice(stimulus_types) content = f"{stype[2]}刺激 #{i + 1}" # 创建刺激 stimulus = Stimulus( content=content, intensity=random.choice(intensities), emotional_valence=random.choice(emotional_valences), source=stype[1], category=stype[0] ) # 添加额外属性 stimulus.associations = [f"关联{i}", f"标签{random.randint(1, 5)}"] stimulus.priority = random.uniform(0.3, 0.95) stimuli.append(stimulus) return stimuli # 更新后的刺激处理循环 for i in range(len(stimuli)): bio_state = bio_simulator.update() stimulus = stimuli[i] # 通过协调器处理刺激 processing_result = coordinator.process_stimulus( stimulus=stimulus, biological_state=bio_state ) if processing_result["reached_consciousness"]: conscious_output = processing_result["conscious_output"] # 记录到报告... # 主动回忆通过协调器 if i % 4 == 0: recalled = coordinator.deliberate_recall(keyword, max_results=4) # 获取完整报告 if i % 5 == 0: full_report = coordinator.get_system_report() # 添加意识流数据 stream_report = coordinator.get_consciousness_stream( last_n=5, summary=True ) full_report["consciousness_stream"] = stream_report def simulate_consciousness(): """模拟意识系统运行""" # 更新后的初始化部分 logger.info("初始化意识系统...") # 初始化记忆系统 from .memory.memory_system import MemorySystem memory_system = MemorySystem() # 初始化各层次 from .layers.unconscious import UnconsciousLayer from .layers.preconscious import PreconsciousLayer from .layers.conscious import ConsciousLayer unconscious_layer = UnconsciousLayer(memory_system) preconscious_layer = PreconsciousLayer(memory_system) conscious_layer = ConsciousLayer(memory_system) # 初始化协调器 from .conscious_layer import ConsciousSystemCoordinator coordinator = ConsciousSystemCoordinator( unconscious_layer=unconscious_layer, preconscious_layer=preconscious_layer, conscious_layer=conscious_layer, memory_system=memory_system ) # 初始化生物状态模拟器 bio_simulator = BiologicalStateSimulator() logger.info("意识系统初始化完成") # 生成刺激序列 stimuli = generate_stimulus_sequence(30) # 添加一些预定义的刺激 predefined_stimuli = [ Stimulus("A beautiful sunset over the mountains", 0.7, 0.8, "external", "visual"), Stimulus("Loud crash from the kitchen", 0.9, -0.6, "external", "auditory"), Stimulus("Remember mom's birthday tomorrow", 0.6, 0.5, "internal", "reminder"), Stimulus("Danger! Snake in the garden!", 1.0, -0.9, "external", "threat"), Stimulus("I should learn a new programming language", 0.5, 0.4, "internal", "thought"), Stimulus("Dream about flying over the city", 0.3, 0.2, "internal", "dream") ] stimuli.extend(predefined_stimuli) # 模拟生命事件序列 life_events = deque([ (5, "rest", 0.8), # 休息 (10, "meal", 0.9), # 进餐 (15, "stressful_event", 0.7), # 压力事件 (20, "exercise", 0.6), # 锻炼 (25, "rest", 0.7) # 休息 ]) # 报告收集 simulation_reports = [] # 处理刺激序列 for i in range(len(stimuli)): logger.info(f"\n===== 处理周期 {i + 1} =====") # 更新生物状态 bio_state = bio_simulator.update() logger.info(f"当前生物状态: {json.dumps(bio_state, indent=2)}") # 检查是否应用生命事件 if life_events and life_events[0][0] == i: _, event_type, intensity = life_events.popleft() bio_simulator.apply_event(event_type, intensity) # 选择刺激 stimulus = stimuli[i] logger.info(f"接收刺激: {stimulus}") # 前意识层处理 elevated = preconscious.receive_stimulus(stimulus) if elevated: logger.info(f"刺激提升到意识层 (优先级: {elevated.get('priority', 0.5):.2f})") # 意识层处理,传入生物状态 result = conscious.process_input(elevated, bio_state) # 提取关键信息 state = result.get("state", "UNKNOWN") attention = result.get("attention", [])[:3] workload = result.get("workload", {}).get("cognitive_load", 0.0) logger.info(f"意识层处理结果: 状态={state}, 注意力={attention}, 认知负荷={workload:.2f}") # 详细记录 report = { "cycle": i + 1, "stimulus": str(stimulus), "state": state, "attention": attention, "cognitive_load": workload, "biological_state": bio_state.copy(), "timestamp": time.time() } simulation_reports.append(report) else: logger.info("刺激未达到意识阈值") # 模拟主动回忆 if i % 4 == 0: keywords = ["danger", "learn", "beautiful", "memory", "dream", "threat"] keyword = random.choice(keywords) recalled = conscious.deliberate_recall(keyword, max_results=4) logger.info(f"主动回忆 '{keyword}': {recalled}") # 添加回忆任务报告 recall_report = { "cycle": i + 1, "type": "recall", "keyword": keyword, "results": recalled, "timestamp": time.time() } simulation_reports.append(recall_report) # 每5个周期获取一次详细报告 if i % 5 == 0: conscious_report = conscious.get_consciousness_report() logger.info(f"意识层状态报告:\n{json.dumps(conscious_report, indent=2)}") # 添加报告到模拟记录 report_entry = { "cycle": i + 1, "type": "full_report", "report": conscious_report, "timestamp": time.time() } simulation_reports.append(report_entry) # 记忆衰减 memory_system.decay_memories() # 随机睡眠模拟时间流逝 sleep_time = random.uniform(0.5, 1.5) time.sleep(sleep_time) # 关闭系统 unconscious.shutdown() shutdown_data = conscious.shutdown() logger.info(f"意识系统已安全关闭: {json.dumps(shutdown_data, indent=2)}") # 保存模拟报告 with open("simulation_report.json", "w") as f: json.dump(simulation_reports, f, indent=2) logger.info("模拟报告已保存到 simulation_report.json") return simulation_reports def analyze_simulation_report(report: list): """分析模拟报告""" if not report: logger.warning("没有可分析的报告数据") return # 收集关键指标 states = [] cognitive_loads = [] attention_changes = 0 high_load_cycles = [] for entry in report: if entry.get("type") == "full_report": # 分析完整报告 r = entry["report"] states.append(r["state"]) # 分析工作负载 workload = r["workload"]["cognitive_load"] cognitive_loads.append(workload) if workload > 0.8: high_load_cycles.append(entry["cycle"]) # 分析注意力变化 attention_history = r["attention"]["history"] if len(attention_history) > 1: attention_changes += len(attention_history) # 输出分析结果 logger.info("\n===== 模拟分析结果 =====") logger.info(f"总周期数: {len(report)}") logger.info(f"最常见的意识状态: {max(set(states), key=states.count)}") logger.info(f"平均认知负荷: {sum(cognitive_loads) / len(cognitive_loads):.2f}") logger.info(f"高认知负荷周期: {high_load_cycles}") logger.info(f"注意力变化次数: {attention_changes}") # 状态分布 state_dist = {} for state in states: state_dist[state] = state_dist.get(state, 0) + 1 logger.info(f"状态分布: {state_dist}") if __name__ == "__main__": simulation_report = simulate_consciousness() analyze_simulation_report(simulation_report) 这样改对吗
08-11
下载前可以先看下教程 https://pan.quark.cn/s/a4b39357ea24 在网页构建过程中,表单(Form)扮演着用户与网站之间沟通的关键角色,其主要功能在于汇集用户的各类输入信息。 JavaScript作为网页开发的核心技术,提供了多样化的API和函数来操作表单组件,诸如input和select等元素。 本专题将详细研究如何借助原生JavaScript对form表单进行视觉优化,并对input输入框与select下拉框进行功能增强。 一、表单基础1. 表单组件:在HTML语言中,<form>标签用于构建一个表单,该标签内部可以容纳多种表单组件,包括<input>(输入框)、<select>(下拉框)、<textarea>(多行文本输入区域)等。 2. 表单参数:诸如action(表单提交的地址)、method(表单提交的协议,为GET或POST)等属性,它们决定了表单的行为特性。 3. 表单行为:诸如onsubmit(表单提交时触发的动作)、onchange(表单元素值变更时触发的动作)等事件,能够通过JavaScript进行响应式处理。 二、input元素视觉优化1. CSS定制:通过设定input元素的CSS属性,例如border(边框)、background-color(背景色)、padding(内边距)、font-size(字体大小)等,能够调整其视觉表现。 2. placeholder特性:提供预填的提示文字,以帮助用户明确输入框的预期用途。 3. 图标集成:借助:before和:after伪元素或者额外的HTML组件结合CSS定位技术,可以在输入框中嵌入图标,从而增强视觉吸引力。 三、select下拉框视觉优化1. 复选功能:通过设置multiple属性...
【EI复现】基于深度强化学习的微能源网能量管理与优化策略研究(Python代码实现)内容概要:本文围绕“基于深度强化学习的微能源网能量管理与优化策略”展开研究,重点探讨了如何利用深度强化学习技术对微能源系统进行高效的能量管理与优化调度。文中结合Python代码实现,复现了EI级别研究成果,涵盖了微电网中分布式能源、储能系统及负荷的协调优化问题,通过构建合理的奖励函数与状态空间模型,实现对复杂能源系统的智能决策支持。研究体现了深度强化学习在应对不确定性可再生能源出力、负荷波动等挑战中的优势,提升了系统运行的经济性与稳定性。; 适合人群:具备一定Python编程基础和机器学习背景,从事能源系统优化、智能电网、强化学习应用等相关领域的研究生、科研人员及工程技术人员。; 使用场景及目标:①应用于微能源网的能量调度与优化控制,提升系统能效与经济效益;②为深度强化学习在能源管理领域的落地提供可复现的技术路径与代码参考;③服务于学术研究与论文复现,特别是EI/SCI级别高水平论文的仿真实验部分。; 阅读建议:建议读者结合提供的Python代码进行实践操作,深入理解深度强化学习算法在能源系统建模中的具体应用,重点关注状态设计、动作空间定义与奖励函数构造等关键环节,并可进一步扩展至多智能体强化学习或与其他优化算法的融合研究。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值