text
string
label_name
string
labels
int64
import rclpy from rclpy.action import ActionClient from rclpy.time import Duration from rclpy.node import Node from control_msgs.action import FollowJointTrajectory from trajectory_msgs.msg import JointTrajectoryPoint class ControlActionClient(Node): def __init__(self): super().__init__('joint_trajector...
Python
1
import ctypes import numpy as np import cv2 from pyueye import ueye def main(): hCam = ueye.HIDS(0) ret = ueye.is_InitCamera(hCam, None) if ret != ueye.IS_SUCCESS: print(f"Camera initialization failed with error code: {ret}") return pcImageMemory = None MemID = ueye.int() try:...
Python
1
let metadata = Metadata::try_from(*metadata_block)?; // get typed name let node_typed_name = metadata.name.as_ref().ok_or(Error::NoNameInMetadata)?; // map index in the list of vertices to this typed name vertex_idx_mapping.insert(idx as u64, node_typed_name.clone()); //...
Rust
0
agePrediction(prefix="timm_image", checkpoint_name="swin_tiny_patch4_window7_224") image_processor = ImageProcessor( model=model, train_transforms=augmentations["model.timm_image.train_transforms"], val_transforms=augmentations["model.timm_image.val_transforms"], size=224, no...
Python
1
import uuid from datetime import datetime, timedelta from sqlalchemy import func, or_ from app import db from app.dao.dao_utils import autocommit, version_class from app.models import ApiKey @autocommit @version_class(ApiKey) def save_model_api_key(api_key): api_key.secret = uuid.uuid4() db.session.add(api_...
Python
1
attrs.push(("label_side", label_side)); } write_tag_with_attrs(writer, "aux", "", &attrs) } } impl From<Aux> for datamodel::view_element::Aux { fn from(v: Aux) -> Self { datamodel::view_element::Aux { name: v.name, uid: ...
Rust
0
, labels=df["symbol"], autopct="%1.1f%%", colors=colors, startangle=90, ) ax.set_title("資產配置分布", fontsize=16, fontweight="bold") plt.tight_layout() return fig except...
Python
1
pt) else: return self.generate_vanilla(image_path, prompt) def use_custom_prompt(self, dataset): assert dataset is not None if listinstr(['MMfin', 'MMfin_CN'], dataset): return False if DATASET_TYPE(dataset) == 'MCQ' or DATASET_TYPE(dataset) == 'VQA':...
Python
1
10 assert stats.sent == 8 assert stats.failed == 2 assert stats.success_rate == 80.0 assert stats.duration is not None assert len(progress_calls) > 0 @pytest.mark.asyncio async def test_broadcast_cancellation(self): """Test broadcast cancellation functionality""...
Python
1
image(file: &str) -> bool { file.ends_with(".svg") || file.ends_with(".png") || file.ends_with(".jpg") || file.ends_with(".jpeg") } #[instrument] #[inline] pub fn clean_rfd_html_links(content: &str, num: &str) -> String { let mut cleaned = content .replace(r#"href="\#"#, &format!(r#"href="/rfd/{}#"#, n...
Rust
0
i1, image_op_or); } void image_mask_and(image* i0, image* i1) { image_mask_binary(i0, i1, image_op_and); } void image_mask_xor(image* i0, image* i1) { image_mask_binary(i0, i1, image_op_xor); } void image_mask_nor(image* i0, image* i1) { image_mask_binary(i0, i1, image_op_nor); } void image_mask_nand(image* i0, ima...
Rust
0
yst::{ ecs::{World, WriteStorage}, shred::{ResourceId, SystemData}, }; use derivative::Derivative; use ui_model_spi::{config::WidgetStatus, play::Siblings}; /// `UiRectifySystemData`. #[derive(Derivative, SystemData)] #[derivative(Debug)] pub struct UiRectifySystemData<'s> { /// `WidgetStatus` components. ...
Rust
0
dwValueType: DWORD, pValue: PCERT_RDN_VALUE_BLOB, psz: LPSTR, csz: DWORD, ) -> DWORD; pub fn CertRDNValueToStrW( dwValueType: DWORD, pValue: PCERT_RDN_VALUE_BLOB, psz: LPWSTR, csz: DWORD, ) -> DWORD; pub fn CertNameToStrA( dwCertEncodingTyp...
Rust
0
pect("during test"); assert_eq!(doc["foo"]["a"].as_i64().expect("during test"), 42); assert_eq!(doc["foo"]["b"].as_i64().expect("during test"), 43); } #[test] fn parse_change_type_to_object() { let s = r#"{ "foo" : [0, 1, 2], "foo" : { "b" : 43 } }"#; let doc: Hocon = d...
Rust
0
"""Utilities module for Azure DevOps MCP Server."""
Python
1
""" Split, Join, Enumerate em Python Split - dividir uma string #str join - juntar uma lista #str enumarate enumerar elementos da lista #list iteráveis """ string = 'O brasil é o pais do futebol, o brasil é penta.' lista_1 = string.split(' ') lista_2 = string.split(',') #for valor in lista_1: # print( f' A palavra...
Python
1
inct(); variable.set(&result).leave() }) .KV::<VersionFeature, QueryId>() .map(|(version_feature, query_id)| (version_feature.version_id, query_id)); query_results = addend_transitive_releases .join_...
Rust
0
ncher) { wigner_9j_bench(b, 6, 8); } // this one just uses a plain FnvHashMap, which requires storing both keys and // values #[bench] fn bench_regge3jm_map_25(b: &mut Bencher) { let tj_max = 25; let mut table = wigner_3jm_arg_table(0, tj_max); rand::thread_rng().shuffle(&mut table); let mut map =...
Rust
0
=delete_user_not_found_screen).pack() # Deleting popups def delete_login_success(): login_success_screen.destroy() def delete_password_not_recognised(): password_not_recog_screen.destroy() def delete_user_not_found_screen(): user_not_found_screen.destroy() # Designing Main(first) window def main_a...
Python
1
// Builder methods are broken up into modules, depending on what kind // of thing is being translated. Note that they use the `unpack` macro // above extensively. mod block; mod cfg; mod expr; mod into; mod matches; mod misc; mod scope; mod stmt; // Copyright 2022 <NAME> // See LICENSE.txt and LICENSE-Apache-2.0.txt f...
Rust
0
, SCANDATASRCR::CH7 => 7, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> SCANDATASRCR { match value { 0 => SCANDATASRCR::CH0, 1 => SCANDATASRCR::CH1, 2 => SCANDATASRCR::CH2, 3 => SCANDATASRCR:...
Rust
0
}); } let result = match self.table.name_map.entry(field.name.clone()) { Entry::Occupied(mut e) => { let ref_index = e.insert(index); self.track_ref(ref_index); DynamicInsertionResult::InsertedWithNameRef { po...
Rust
0
", "Do you?", "You want the money for the big salad, George?", "Ok thanks so much.", "(the Barney's sales associate turns and walks away.", "Elaine turns to Kramer as he admires himself in the mirror) What are you all dressed up for?", "A hundred and fifty dollars?", "A hundred and fifty dollars for what?...
Rust
0
:Workgroup as WorkgroupDims>::Idx) -> Self::Elem; } pub trait DimTranspose { fn transpose(self) -> Self; } #[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)] #[derive(GeobacterDeps)] pub struct Dim1D<T> { pub x: T, } #[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Ord, PartialOr...
Rust
0
# - read from kafka topic # - publish to redis pub from kafka import KafkaConsumer import argparse import atexit import logging import redis # - default kafka topic to write to topic_name = 'stock-analyzer' # - default kafka broker location kafka_broker = '127.0.0.1:9092' logger_format = '%(asctime)-15s %(message...
Python
1
from enum import Enum from telescope.rbac import permissions class GlobalRole(Enum): ADMIN = "admin" class SourceRole(Enum): OWNER = "owner" EDITOR = "editor" VIEWER = "viewer" USER = "user" RAW_QUERY_USER = "raw_query_user" ROLES = { "global": { GlobalRole.ADMIN.value: [ ...
Python
1
import os import sys import numpy as np import torch import random import tempfile import soundfile as sf import time from pathlib import Path # 确保当前目录在导入路径中 current_dir = os.path.dirname(os.path.abspath(__file__)) if current_dir not in sys.path: sys.path.append(current_dir) # 导入TTS模型 from .tts_models import Inde...
Python
1
""" 2019.06.25新增。 当前车次时刻表停靠面板,只读的时刻表,设计原则为尽可能简洁明了,直接继承TableWidget。 """ from PyQt5 import QtWidgets,QtGui,QtCore from PyQt5.QtCore import Qt from .data.train import Train from .data.graph import Graph class TrainTimetable(QtWidgets.QWidget): def __init__(self,graph:Graph,parent=None): super(TrainTimetable...
Python
1
import dbus class Notification: """ Displays a notification. Args: summary (str): Summary text. message (str): The message body (optional). timeout (int): Notification length in milliseconds (optional). app_name (str): Caller app name. Defaults to 'notify-send'. kw...
Python
1
""" pip install aiogram """ import asyncio import logging import os from collections import deque from pprint import pprint from aiogram import Bot, Dispatcher, types from aiogram.enums import ChatAction from aiogram.exceptions import TelegramRetryAfter import microcore as mc from microcore import Msg mc.use_logging...
Python
1
_len = N_max_character self.f0_embedding = nn.Embedding(N_max_character, n_dim) self.w0 = nn.Linear(N_max_character, n_position) self.wv = nn.Linear(n_dim, n_dim) # first linear(512,25) self.we = nn.Linear(n_dim, N_max_character) self.active = nn.Tanh() ...
Python
1
_str() .map(|s| s.starts_with(".")) .unwrap_or(false) } fn is_file(entry: &DirEntry) -> bool { entry .metadata() .map(|metadata| metadata.is_file()) .unwrap_or(false) } fn get_md5_of_file(file_path: &Path) -> Result<String, Error> { let file = std::fs::File::open(file_p...
Rust
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
Python
1
import json import hashlib import pytest from aries_askar import ( KeyAlg, Key, SeedMethod, ) from aries_askar.types import KeyBackend def test_get_supported_backends(): backends = Key.get_supported_backends() assert backends == [str(KeyBackend.Software)] @pytest.mark.parametrize( "key_al...
Python
1
(missing_docs)] pub trait HashImplInterface: HashImpl {} /// Basic trait for all hash types pub trait Hash { /// Computes image hash fn compute(&self, mat: &Mat) -> Mat; /// Compares two image hashes fn compare(&self, lhs: &Mat, rhs: &Mat) -> f64; } impl<T: HashImplInterface> Hash for T { /// Com...
Rust
0
in range(len(n)): x_center = (bins[i] + bins[i + 1]) / 2 y_height = n[i] if y_height != 0: plt.text( x_center, y_height + 50, f'{x_center:.5f}', ha='center', va='bottom...
Python
1
) => receive_other!{ Start that will be classified as either one of the successes or failures }, MaintainerResponse::Stop(mut successes, mut failures) => receive_other!{ Stop that will be classified as either one of the successes or failures }, MaintainerResponse::Kill(mut successes, mut failures) =...
Rust
0
"""This module contains constants related to MAVEN and IUVS.""" import datetime import numpy as np slit_start_pixel: int = 80 """The starting spatial pixel number of the slit.""" slit_end_pixel: int = 929 """The ending slit pixel number.""" orbit_insertion_date: datetime.datetime = datetime.datetime(2014, 9, 22, 2...
Python
1
from typing import Any, Dict, List, Type, TypeVar from attrs import define as _attrs_define from attrs import field as _attrs_field from ..models.channel_view_state import ChannelViewState T = TypeVar("T", bound="MyChannelViewState") @_attrs_define class MyChannelViewState: """自身のチャンネル閲覧状態 Attributes: ...
Python
1
// // SPDX-License-Identifier: Apache-2.0 OR MIT // // Copyright (C) 2021 <NAME> // //! An example of listing entries in an archive. use std::path::PathBuf; use clap::Parser; /// List entries in an archive. #[derive(Debug, Parser)] #[clap(version)] struct Opt { /// An archive to list entries. pub archive: P...
Rust
0
frect().height) max_width = max(max_width, surf.get_frect().width) total_height = sum(line_heights) + (len(line_surfaces) - 1) * line_spacing text_surface = pygame.Surface((max_width, total_height), pygame.SRCALPHA) # Blit each line with spacing y = 0 for i, surf in...
Python
1
= state.move_speed - move_speed_cond # 3. Update spawn_speed spawn_speed_cond = jnp.logical_and( jnp.logical_and(ramp_cond, 1 - timer_cond), state.spawn_speed > 1 ) spawn_speed = state.spawn_speed - spawn_speed_cond # 4. Update ramp_index ramp_index = state.ramp_index + jnp.logical_and(...
Python
1
2bHash, include_forks: bool) -> bool { match self.chain_store.get_chain_info(hash, false, None) { Some(chain_info) => include_forks || chain_info.on_main_chain, None => false } } pub fn get_block(&self, hash: &Blake2bHash, include_forks: bool, include_body: bool) -> Opti...
Rust
0
return Ok(()) } let url = format!("{}/{}/{}/{}", SYMBOL_SERVER, name, &hash, name); let mut resp = reqwest::blocking::get(&url)?; let status = resp.status(); if !status.is_success() { let msg = format!("{} for {}", status, url); return Err(Sto...
Rust
0
# Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. # Configuration file for the Sphinx documentation builder. # # For the full list of built-in configuration values, see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Project in...
Python
1
""" ============================= Plot and Use Subsurface Tools ============================= Subsurfaces can be used for efficient operations on subsets of cortical surface """ import tempfile import matplotlib.pyplot as plt import numpy as np import cortex.polyutils subject = 'S1' left, right = cortex.db.get_...
Python
1
ch::style::Dimension::Percent(1.0); self } pub(crate) fn align_items(mut self, align: Align) -> Self { self.0.align_items = align.into(); self } pub(crate) fn justify_content(mut self, justify: Justify) -> Self { self.0.justify_content = justify.into(); self ...
Rust
0
esult is placed in z[0 : 2*n]. unsafe fn karatsuba(z: *mut u32, x: *const u32, y: *const u32, xlen: usize, ylen: usize, zlen: usize) { let n = ylen; // Switch to basic multiplication if numbers are odd or small. // (n is always even if karatsubaThreshold is even, but be // conservat...
Rust
0
import os import subprocess # Generate the LEF file using magic PDK_ROOT = os.getenv('PDK_ROOT', '~/.ciel') PDK = os.getenv('PDK', 'sky130A') os.environ['PDK_ROOT'] = PDK_ROOT os.environ['PDK'] = PDK top_module = 'res_div' gds_in = f'gds/{top_module}.gds.gz' lef_out = f'lef/{top_module}.lef' rcfile = os.path.join(...
Python
1
()); let attr1 = Attr::from((0..1024).map(|i| i as i64)); let block = Block::new(1024, vec![attr1]); let res = plan.eval(&block).unwrap(); assert_eq!(1, res.len()); assert_eq!(9, res[0].n_records()); let array = res[0].codec.as_array().unwrap(); assert_eq!(&[1i64,...
Rust
0
"Dates are expected to be provided in ISO 8601 date format " "(YYYY-MM-DD)." ) return {"date": item, "type": "date"} def string(self, item: Any) -> str: # Remove escaped quotes return str(item).strip("\"'") def get_parser( allowed_comparators: Optio...
Python
1
�数应该返回新的长度 2, 并且 nums 中的前两个元素均为 2。你不需要考虑数组中超出新长度后面的元素。例如,函数返回的新长度为 2 ,而 nums = [2,2,3,3] 或 nums = [2,2,0,0],也会被视作正确答案。 示例 2: 输入:nums = [0,1,2,2,3,0,4,2], val = 2 输出:5, nums = [0,1,4,0,3] 解释:函数应该返回新的长度 5, 并且 nums 中的前五个元素为 0, 1, 3, 0, 4。注意这五个元素可为任意顺序。你不需要考虑数组中超出新长度后面的元素。   提示: 0 <= nums.length <= 100 0 <= nums[i] <= 50 ...
Rust
0
s").short('R').about("Print recursively all submounts for the selected filesystems."), Arg::new("raw").long("raw").short('r').about("Use raw output format."), Arg::new("real").long("real").about("Print only real filesystems."), Arg::new("source").long("source").short('S')...
Rust
0
0 && w > 0 { std::mem::swap(&mut label_areas[dst_idx], &mut split[*src_idx]); } } else if self.label_area_size[dst_idx] != 0 { let size = self.label_area_size[dst_idx] as i32; let (dw, dh) = drawing_area.dim_in_pixel(); let...
Rust
0
r\x1elf\x1cW\xc6n}\xf6\xae\x10\xd8\ s*\x5c\x12\xd4\x9a\xe7\xc5C\x0d\xc1Gr\xb3s\x85\ \x059O\xa5?\xd0\xa6M\xca\x93\xb2\xa7(\x08N\xa1\ |\xfc2\x91R:JQ]p\x8cj\xa9A\x93\xdf\ \xc8\xcc\x0a\xe1z\xf6\xd2\x93\xf0\xcc\x85\xa7\xd0x\x07Y\ r\xe9\x8a\xd3\xef\x85kYG\x9b\xe1\xe30\x0c\xf0\xce\ \xad\xeb\xf8\xfa\x957t\x1c\xe7\xce\x9c\xa3O\...
Python
1
# Expected to run this module as __main__ # Cloudpickle will think this is a dynamic class when this module is __main__ class Klass: classvar = None
Python
1
column2 = inv_rotation_matrix.column(2) / scale[2]; inv_rotation_matrix.set_column(0, &column0); inv_rotation_matrix.set_column(1, &column1); inv_rotation_matrix.set_column(2, &column2); inv_rotation_matrix = inv_rotation_matrix.transpose().into(); let homogeneous_pos = Vector4::new(-translation[0...
Rust
0
estyle='--', label=f'Exp decay k={config["k_main"]}') ax2.plot(combined_x_daily[:-len(future_dates)], combined_daily[:-len(future_dates)], color='lightblue', label='Daily Signatures') ax2.plot(future_x_transformed[:len(latest_entries)][:len(latest_entries)],np.insert(np.diff(latest_entries), 0, combined_daily[-len(futu...
Python
1
#!/usr/bin/env python # # MIT License # # Copyright The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to us...
Python
1
net = slim.dropout(net, dropout_keep_prob, is_training=is_training, scope='dropout7') net = slim.conv2d(net, num_classes, [1, 1], activation_fn=None, normalizer_fn=None, biases_initializer=tf.zeros_...
Python
1
from fastapi import APIRouter, Depends from app.schemas.user import User from sqlalchemy.orm import Session from app.db.session import SessionLocal from app.services.user import create_user, get_users from typing import List router = APIRouter() def get_db(): session = SessionLocal() try: yield ses...
Python
1
from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn import linear_model # Load data and train the model try: # Assuming the data file has no header and columns are separated by whitespace cars = pd.read_csv('./Data/cars.data', header=None,...
Python
1
profit += money - lastMoney else: loss += money - lastMoney print("空头平仓") lastMoney = money numOfHand = math.floor(money / now_close) money -= now_close * numOfHand money -= now_close * 0.00002...
Python
1
__all__ = 'run', from . import coroutines from . import events from . import tasks def run(main, *, debug=None): """Execute the coroutine and return the result. This function runs the passed coroutine, taking care of managing the asyncio event loop and finalizing asynchronous generators. This f...
Python
1
f.pixmap_formats, &mut bytes[index..]); index += block_len; index += buffer_pad(block_len, ::core::mem::align_of::<Format>()); let block_len: usize = vector_as_bytes(&self.roots, &mut bytes[index..]); index += block_len; index += buffer_pad(block_len, ::core::mem::align_of::<Scre...
Rust
0
&& self.offset() == other.offset() && self.size() == other.size() } } impl Eq for Region {} impl Region { /// The core function of initialization. /// /// # Arguments /// /// * `size` - Size of `Region`. /// * `region_type` - Type of `Region`. /// * `mem_mappin...
Rust
0
Once(*const cl_event, cl_uint) -> T { let mut vec: Vec<cl_event> = Vec::with_capacity(self.len()); for item in self.iter() { vec.push(item.event); } f(vec.as_ptr(), vec.len() as cl_uint) } } // this seems VERY hackey impl EventList for () { fn as_event_list<T, F...
Rust
0
) = gs.search_google( subquery, gs.QUICK_SEARCH, "", ut.INFORMATION_QUERY, keyword_set, meta_chat_history, ) if len(google_text) > 0: # digest google response into an answer for this subquery if debug: ...
Python
1
=> "invalid row letter", Errors::InvalidNorthingChar(..) => "MGRS point given invalid northing", Errors::InvalidEastingChar(..) => "MGRS point given invalid easting", Errors::InvalidLatitude(..) => "latitude outside UTM limits", Errors::InvalidLatitudeBand(..) => "invalid...
Rust
0
from pymtl import * from lizard.util.rtl.interface import Interface, UseInterface from lizard.util.rtl.method import MethodSpec from lizard.util.rtl.types import canonicalize_type from lizard.util.rtl.case_mux import CaseMuxInterface, CaseMux class LookupTableInterface(Interface): def __init__(s, in_type, out_type...
Python
1
'id': user_doc['_id'], # 'username': user_doc['username'], # 'hashed_password': user_doc['hashed_password'], # 'is_active': user_doc['is_active'], # 'is_admin': user_doc['is_admin'] # } # return UserInDB(**user_doc) # ...
Python
1
[inline] fn process(&mut self, input: Ports<Self::Input>) -> Ports<Self::Output> { let trigger = input[0]; let mut r = <Ports<Self::Output>>::default(); for (i, r) in r[0].iter_mut().enumerate() { if trigger[i] > 0.5 { if !self.triggered { self...
Rust
0
frequency: *freq, }); } for _ in 1..alphabet.len() { let left = queue.pop().unwrap(); let right = queue.pop().unwrap(); let sm_freq = left.frequency + right.frequency; queue.push(HuffmanNode { left: Some(Box::new(left)), ...
Rust
0
pub fn LLVMGetInsertBlock<'a>(Builder: &Builder<'a>) -> &'a BasicBlock; pub fn LLVMDisposeBuilder<'a>(Builder: &'a mut Builder<'a>); // Metadata pub fn LLVMSetCurrentDebugLocation<'a>(Builder: &Builder<'a>, L: &'a Value); // Terminators pub fn LLVMBuildRetVoid<'a>(B: &Builder<'a>) -> &'a Valu...
Rust
0
import libreria_funciones as paq paq.menu()
Python
1
# Copyright(C) 2017 Vincent A # # This file is part of a woob module. # # This woob module is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any...
Python
1
.6): x_vsize = voxel_size[0] y_vsize = voxel_size[1] max_x = points[:, 0].max() max_y = points[:, 1].max() min_x = points[:, 0].min() min_y = points[:, 1].min() max_x = np.floor(max_x / (x_vsize * downsample) + 1) * (x_vsize * downsample) max_y = np.floor(max_y / (y_vsize * downsample) +...
Python
1
elif word == '<end>': labels += [get_location_id(curr_loc, all_loc)] * len(curr_loc) if_loc = False else: if if_loc: curr_loc.append(word) else: labels.append(None) samples.append(labels) ...
Python
1
match $address >> (16 - 3) { 0b000 => { $on_ram }, 0b001 => { $on_ioreg_ppu }, 0b010 => { if $address <= 0x401F { $on_ioreg_other } else { $on_expansion_...
Rust
0
/// Provides the ideal harvest date based on planting date and time to maturity fn planned_harvest_date(&self, conn: &Connection) -> NaiveDate { let plant = Plant::get_plant_by_id(&conn, self.plant_id).unwrap(); self.date_planted + Duration::days(plant.days_to_maturity) } } // Licensed to...
Rust
0
# 📦 Import Library import pandas as pd import matplotlib.pyplot as plt import yfinance as yf # ⏱️ Ambil Data AAPL data = yf.download("AAPL", start="2024-04-01", end="2024-07-01") # 📊 Plot Harga Penutupan plt.figure(figsize=(10, 4)) plt.plot(data['Close'], label='Close Price') plt.title('Apple Stock Price (AAPL)') p...
Python
1
// Returns either a buffertoken and the corresponding index of the /// virtqueue it is coming from. (Index in the TxQueues.vqs vector) /// /// OR returns None, if no Buffertoken could be generated fn get_tkn(&mut self, len: usize) -> Option<(BufferToken, usize)> { // Check all ready token, for correct size. // ...
Rust
0
# cours/urls.py from django.urls import path from . import views urlpatterns = [ path('matieres/', views.liste_matieres, name='liste_matieres'), path('matieres/ajouter/', views.ajouter_matiere, name='ajouter_matiere'), path('matieres/modifier/<int:matiere_id>/', views.modifier_matiere, name='modifier_matie...
Python
1
img_byte_array, format="PNG") img_byte_array = img_byte_array.getvalue() image_base64 = base64.b64encode(img_byte_array).decode('utf-8') ego_pose = cur_data['param']['metas']['ego_pos'] accel = cur_data['param']['metas']['accel'] rotation_rate = cur_data['param']['metas']['rota...
Python
1
_command_max_exit_latency_too_large_capability, "Configure Endpoint Command Max Exit Latency Too Large Capability" ); ro_bit!( 2, force_save_context_capability, "Force Save Context Capability" ); ro_bit!( 3, compliance_transition_capability, "Compl...
Rust
0
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
Python
1
import torch LLAMA2_CONFIG_7B = { "vocab_size": 50257, # Vocabulary size "context_length": 4096, # Context length "emb_dim": 4096, # Embedding dimension "n_heads": 1, # Number of attention heads "n_layers": 6, # Number of layers "hidden_dim": 118, # NEW: Size...
Python
1
def max_frequency(lst: str) -> None: max_freq = 0 max_freq_element = None my_dict = {} for num in lst: my_dict[num] = my_dict.get(num, 0) + 1 for ele, freq in my_dict.items(): if freq > max_freq: max_freq = freq max_freq_element = ele print(f"{max_freq_e...
Python
1
def filtrar_diccionario(diccionario, lista_claves): diccionario_filtrado = {} for clave in lista_claves: if clave in diccionario: diccionario_filtrado[clave] = diccionario[clave] return diccionario_filtrado # Ejemplo de uso mi_diccionario = {'a': 1, 'b': 2, 'c': 3, 'd': 4} claves_a_filt...
Python
1
#! /usr/bin/env python # concatenates all DNA sequences from a single strain # into one long genome with NNNNNNNNNNNNNNNNN between # sequences # # uses taxonomy file to determine strain ID of each fasta # sequence # # requires fasta in order by strain # # usage (NNNNNNNNN is what to separate strains with): # *.py input...
Python
1
import cv2 import mediapipe as mp import socket # Initialize MediaPipe Hands mp_hands = mp.solutions.hands hands = mp_hands.Hands() mp_drawing = mp.solutions.drawing_utils # Define a function to send commands to the RoboDK server def send_command(x, y, z): client_socket = socket.socket(socket.AF_INET, socket.SOCK...
Python
1
op, raw, imm12hi: (raw >> 25) & 0x7f, imm12lo: (raw >> 7) & 0x1f, rs1: (raw >> 15) & 0x1f, rs2: (raw >> 20) & 0x1f, }) } /// Parse an instruction with the `Imm20Rd` format. pub fn parse_imm20_rd(op: OpcodeImm20Rd, raw: u32) -> Format { Format::Imm20Rd(FormatImm20...
Rust
0
<gh_stars>1-10 #[macro_use] extern crate ioctl_sys; pub use ioctl_sys::ioctl; #[doc(hidden)] pub extern crate libc; #[cfg(target_os = "linux")] #[path = "platform/linux.rs"] #[macro_use] mod platform; pub use platform::*; #[cfg(not(target_os = "linux"))] use platform_not_supported; <gh_stars>1-10 //! A module conta...
Rust
0
*value, ir_machine.get_ident_value(ident), ); } } #[test] fn multiply_huge() { tester(100, r#"x=asin999 c=1*x if c==0then:output="ok"else:output=":("end goto1"#); } #[test] fn acid_acos() { tester(100, r#"x=acos(0) u/=x!=9...
Rust
0
add fw to and del from fwg_with_rules['add-port-ids'] = list( set(new_firewall_group['ports']) - set(old_firewall_group['ports']) ) fwg_with_rules['del-port-ids'] = list( set(old_firewall_group['ports']) - set(new_firewall_group['ports']) ) # last-port dr...
Python
1
An iterator which loops over the steps of the proof in tree order /// (with repetition for duplicate subtrees). #[derive(Debug)] pub struct NormalIter<'a> { arr: &'a ProofTreeArray, explicit: bool, stack: Vec<(usize, usize)>, } impl<'a> Iterator for NormalIter<'a> { type Item = RPNStep; fn next(&...
Rust
0
.index); } let transition = Transition::with( -TransitionType::Transfer, metadata.into(), ancestors, assignments, vec![], ); Ok(transition) } } use funcmap::{FuncMap, TryFuncMap}; struct Test<S, T>(S, T, i32); #[allow(abso...
Rust
0
.0.0.1:8333").expect("bad address format"); let sockets = vec![addr]; let mut channel = TestChannel::new(sockets.clone()); let config = ConfigBuilder::new().with_network(Network::Regtest).build(); let blockchain_state = BlockchainState::new(&config); let genesis = blockchain_stat...
Rust
0
i i%i%i%i%i$%ia%ib%iV%iU%ic%iQ%iW%i]%i\%i[%i%i%i4%i,%i%i%i<%i^%i_%iZ%iT%ii%if%i`%iP%il%ig%ih%id%i...
Python
1
_spacing, ) # Execute a single forward run before the start of each epoch and # manually set the initial epigraph variable to slightly larger than # the largest value of the objective function over the six wavelengths # and the lengthscale constraint (final epoch only). ...
Python
1