text string | label_name string | labels int64 |
|---|---|---|
#!/usr/bin/env python3
"""Update all model path references in the codebase to use new structure."""
import re
from pathlib import Path
# Path mappings
PATH_MAPPINGS = {
# Old pretrained paths → New pretrained paths
'model_weights/pat/pretrained/PAT-L_29k_weights.h5': 'model_weights/pretrained/PAT-L_29k_weight... | Python | 1 |
import pickle
import torch
import lzma
from pathlib import Path
from tops import logger
class BaseDetector:
def __init__(self, cache_directory: str) -> None:
if cache_directory is not None:
self.cache_directory = Path(cache_directory, str(self.__class__.__name__))
self.cache_direc... | Python | 1 |
];
CircleListPointer(cur_node.next_key)
}
pub fn prev_node(&self, cur_ptr: CircleListPointer) -> CircleListPointer {
let cur_node = &self.nodes[cur_ptr.0];
CircleListPointer(cur_node.prev_key)
}
pub fn remove(&mut self, cur_ptr: CircleListPointer) -> T {
let rem_node = ... | Rust | 0 |
nd=True)
modal = create_custom_modal_overlay(
page=page,
title="カスタムモーダルテスト",
content=test_content,
width=600,
height=500,
resizable=True,
draggable=True
)
page.overlay.append(modal)
pag... | Python | 1 |
ck_remaining,
}.unwrap_or(Duration::from_secs(60));
let time_heuristic = std::cmp::min(remaining / 10, Duration::from_millis(250));
let mut last_pv = None;
for depth in 1.. {
if !infinite && depth >= max_depth {
log::debug!("Stopping search because r... | Rust | 0 |
B, params: *mut [GLint; 4]);
/// glGetVertexAttribivARB
/// * `pname` group: VertexAttribPropertyARB
pub type glGetVertexAttribivARB_t = unsafe extern "system" fn(index: GLuint, pname: VertexAttribPropertyARB, params: *mut [GLint; 4]);
/// glGetVertexAttribivNV
/// * `pname` group: VertexAttribEnumNV
pub type glGetVe... | Rust | 0 |
et_actor_dof_properties(envs[0], franka_handles[0])
franka_lower_limits = franka_dof_props['lower']
franka_upper_limits = franka_dof_props['upper']
franka_ranges = franka_upper_limits - franka_lower_limits
franka_mids = 0.5 * (franka_upper_limits + franka_lower_limits)
franka_num_dofs = len(franka_dof_props)
# overrid... | Python | 1 |
autifulSoup(content, "lxml")
title_soup = soup.find('li', class_='doc')
if title_soup:
return 'http://webcatplus.nii.ac.jp' + dict(title_soup.find('div', class_='t').a.attrs)['href']
else:
return None
def asin2webcaturl(asin):
if asin[0].isdigit():
#そのままISBNとしてurlをつくる
... | Python | 1 |
if self.inference_table.is_inference_ready:
self.clear_inference_table()
output_embeds = self._forward()
else:
if not self.inference_table.is_inference_ready:
output_embeds = self._forward()
self.set_i... | Python | 1 |
import os
import shutil
import pathlib
def remove_pycache(directory_path: str):
"""Recursively traverses the provided directory and removes all __pycache__
subdirectories.
"""
for root, dirs, files in os.walk(directory_path):
if "__pycache__" in dirs:
pycache_path = os.path.join(ro... | Python | 1 |
xout2_ = txout2.clone();
let mut outputs = vec![(txout1, "ignore"), (txout2, "ignore")];
sort_outputs(&mut outputs);
assert_eq!(
&outputs,
&vec![(txout2_, "ignore"), (txout1_, "ignore")]
);
}
#[test]
fn sort_output_by_script_pubkey() {
let txout1 = TxOut {
value: 100,
script_pubkey: Builde... | Rust | 0 |
Bit 9 - Software or Hardware Selection for the Source"]
#[inline(always)]
pub fn src_h2sel(&mut self) -> SRC_H2SEL_W {
SRC_H2SEL_W { w: self }
}
#[doc = "Bit 13 - Software or Hardware Selection for the Destination"]
#[inline(always)]
pub fn dst_h2sel(&mut self) -> DST_H2SEL_W {
D... | Rust | 0 |
# Copyright (c) 2023-2025 Carnegie Mellon University.
# NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE
# ENGINEERING INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS.
# CARNEGIE MELLON UNIVERSITY MAKES NO WARRANTIES OF ANY KIND,
# EITHER EXPRESSED OR IMPLIED, AS TO ANY MATTER INCLUDING, BUT
# NOT LI... | Python | 1 |
ATOR # will replace all forward slashes, and ASCII backslash, with Full Width Solidus Operator
# Date format separators to preserve in date patterns
DATE_SEPARATORS = {
'.', # period
'-', # hyphen
SLASH_REPLACEMENT, # for any slash in original
}
# Characte... | Python | 1 |
import numpy as np
from scipy.interpolate import CubicSpline, splprep, splev
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# 1. 生成曲线测试数据(非直线)
def generate_curve_data(num_segments=5, points_per_segment=10):
"""生成连接的空间曲线段(使用正弦函数构造曲线)"""
np.random.seed(42)
segments = []
last_poin... | Python | 1 |
{}/skill/{}", BACKEND_ADDRESS, id);
let request = Request::new(url)
.method(Method::Get)
.header(Header::custom("Accept-Language", "en"));
orders.perform_cmd(async {
let response = fetch(request).await.expect("HTTP request failed");
if response.status().is_ok() {
see... | Rust | 0 |
def configure():
import qutip
qutip.settings.atol = 1e-6 # TODO config
| Python | 1 |
s_gender_restriction = models.BooleanField(null=True)
gender_restriction = models.IntegerField(
choices = [(tag, tag.value) for tag in GenderType],
null=True
)
can_cook = models.BooleanField(null=True)
allow_pet = models.BooleanField(null=True)
has_perperty_registration = models.Bool... | Python | 1 |
XED_IFORM_VCVTUSI2SS_XMMf32_XMMf32_MEMu32_AVX512 = 2441,
XED_IFORM_VCVTUSI2SS_XMMf32_XMMf32_MEMu64_AVX512 = 2442,
XED_IFORM_VDBPSADBW_XMMu16_MASKmskw_XMMu8_MEMu8_IMM8_AVX512 = 2443,
XED_IFORM_VDBPSADBW_XMMu16_MASKmskw_XMMu8_XMMu8_IMM8_AVX512 = 2444,
XED_IFORM_VDBPSADBW_YMMu16_MASKmskw_YMMu8_MEMu8_I... | Rust | 0 |
历史任务中查看")
def run(self):
# 执行任务
super(QuickInnerFlow, self).run()
# 跳过任务执行结果,直接进入下一流程
from backend.ticket.flow_manager.manager import TicketFlowManager
TicketFlowManager(ticket=self.ticket).run_next_flow()
class IgnoreResultInnerFlow(InnerFlow):
"""
内置可忽略执行结果任务流程... | Python | 1 |
KEY_FN_F10,
KEY_FN_F11,
KEY_FN_F12,
KEY_FN_1,
KEY_FN_2,
KEY_FN_D,
KEY_FN_E,
KEY_FN_F,
KEY_FN_S,
KEY_FN_B,
KEY_BRL_DOT1,
KEY_BRL_DOT2,
KEY_BRL_DOT3,
KEY_BRL_DOT4,
KEY_BRL_DOT5,
KEY_BRL_DOT6,
KE... | Rust | 0 |
when:
parallel_state.is_pipeline_last_stage()
"""
return data
@contextmanager
def forward_context(self) -> Generator[None, None, None]:
"""No explicit precision casting. Inputs are supposed to be manually casted."""
try:
yield
finally:
... | Python | 1 |
rce_size: chunk.len(),
data: chunk.0,
compression: None,
})
}
}
/// Chunk data.
#[inline]
pub fn data(&self) -> &[u8] {
&self.data[..]
}
/// Size of chunk.
#[inline]
pub fn len(&self) -> usize {
self.data.len()
}
... | Rust | 0 |
# coding: utf-8
from resources.lib.handler.requestHandler import cRequestHandler
from resources.lib.parser import cParser
from resources.hosters.hoster import iHoster
#from resources.lib.comaddon import VSlog
from resources.lib.packer import cPacker
class cHoster(iHoster):
def __init__(self):
iHoster.__... | Python | 1 |
PR_SET_FPEMU = 10,
PR_GET_TIMING = 13,
PR_SET_TIMING = 14,
PR_SET_NAME = 15,
PR_GET_NAME = 16,
PR_GET_ENDIAN = 19,
PR_SET_ENDIAN = 20,
PR_GET_SECCOMP = 21,
PR_SET_SECCOMP = 22,
PR_CAPBSET_READ = 23,
PR_CAPBSET_DROP = 24,
PR_GET_TSC = 25,
PR_SET_TSC = 26,
PR_GET_SECURE... | Rust | 0 |
> name,
None => "Aleph Zero Development",
}
}
pub fn account_ids(&self) -> Vec<AccountId> {
match &self.account_ids {
Some(ids) => ids
.iter()
.map(|id| {
AccountId::from_string(id.as_str())
.exp... | Rust | 0 |
send_auto(socket: *const nl_sock, msg: *const ::message::nl_msg) -> i32;
fn nl_sendmsg(socket: *const nl_sock, msg: *const ::message::nl_msg, hdr: *const ::message::nlmsghdr) -> i32;
}
pub struct NetlinkSocket {
pub ptr: *const nl_sock,
}
pub fn alloc() -> Option<NetlinkSocket> {
let ptr = unsafe { nl_so... | Rust | 0 |
from pyrogram import filters
from pyrogram.types import Message
from pyrogram.errors import PeerIdInvalid
from Biolink.utils.database import has_link
def register(app):
@app.on_message(filters.new_chat_members)
async def handle_new_member(client, message: Message):
for user in message.new_chat_members:... | Python | 1 |
_MetricsConstants ("android/media/MediaPlayer$MetricsConstants") extends crate::java::lang::Object {
// // Not emitting: Non-public method
// /// [MetricsConstants](https://developer.android.com/reference/android/media/MediaPlayer.MetricsConstants.html#MetricsConstants())
// fn new<'env>(__jni_... | Rust | 0 |
_labels = 1. - data['labels']['missing_rate_l'].to(device)
effectiveness_labels = torch.cat([torch.ones(len(sentiment_labels)*8), torch.zeros(len(sentiment_labels)*8)]).long().to(device)
label = {'sentiment_labels': sentiment_labels, 'completeness_labels': completeness_labels, 'effectiveness_labels': ef... | Python | 1 |
ow = padded_flex_row(&buttons, ui);
let mut column = Column::new();
let mut mid_row = Row::new();
mid_row.set_flex(patcher, 3.0);
mid_row.set_flex(scope, 2.0);
let mid_row = mid_row.ui(&[patcher, scope], ui);
column.set_flex(mid_row, 3.0);
column.set_flex(piano, 1.0);
let column = column... | Rust | 0 |
taframe[i],lw=0,marker='.',label=i)
# plt.ylabel('Estimated groundwater level (mNGF)')
# plt.legend()
# plt.grid(True)
# plt.xticks(rotation=45)
# plt.show()
#
# for i in estimated_dataframe.columns:
# # plt.plot(estimated_dataframe_w_lin_reg.index, estimated_dataframe_w_lin_reg[i], lw=0, marker='.', label=i, color... | Python | 1 |
Bound::None => write!(f, "(-\u{221e}, ")?, // infinity symbol
RangeBound::Open(v) => write!(f, "({}, ", v)?,
RangeBound::Closed(v) => write!(f, "[{}, ", v)?,
}
match &self.end {
RangeBound::None => write!(f, "\u{221e})")?,
RangeBound::Open(v) => write!(f, ... | Rust | 0 |
#
# tag_metadata.py
#
# Copyright 2024, Paul McGuire
#
import pyparsing as pp
ppu = pp.unicode
# associate "alphabet" tag with different Unicode character sets
latin = pp.Word(ppu.Latin1.alphas) + pp.Tag("alphabet", "Latin")
greek = pp.Word(ppu.Greek.alphas) + pp.Tag("alphabet", "Greek")
japanese = pp.Word(ppu.Japane... | Python | 1 |
ser_session(user):
return UserManager.E_BAD_SESSION
project = Project(project_name=project_name, user_name=user_name)
return ProjectManager.get_project_info(user.user_name, project)
@staticmethod
def get_user_projects(session_id: int):
"""
lists all of the users proj... | Python | 1 |
"""
YAML serializer.
Requires PyYaml (https://pyyaml.org/), but that's checked for in __init__.
"""
import collections
import datetime
import decimal
import yaml
from django.core.serializers.base import DeserializationError
from django.core.serializers.python import Deserializer as PythonDeserializer
from django.co... | Python | 1 |
State {
selected_date: Arc::new(Utc::today()),
};
AppLauncher::with_window(main_window)
.use_simple_logger()
.configure_env(|env, _| {
env.set(
theme::WINDOW_BACKGROUND_COLOR,
Color::rgb8(0x29, 0x29, 0x29),
);
env.set(t... | Rust | 0 |
tion and scaling them up by 1<<15. This is because
// vqrdmulhq_n_s16(a, b) is effectively equivalent to (a*b)>>15 (except for possibly some
// slight differences in rounding).
// The code here is effectively equivalent to the calls to "kernel" in idct.rs, except that it
// doesn't apply any further sc... | Rust | 0 |
b_T = b.T.copy(order=b_order)
assert_almost_equal(a_T.dot(b), a.T.dot(b), decimal=prec)
assert_almost_equal(b_T.dot(a), b.T.dot(a), decimal=prec)
# (b'.a)' = a'.b
assert_almost_equal(b.T.dot(a), a.T.dot(b).T, decimal=prec)
ass... | Python | 1 |
_str()? {
"serif" => Ok(Family::Serif),
"sans-serif" => Ok(Family::SansSerif),
"cursive" => Ok(Family::Cursive),
"fantasy" => Ok(Family::Fantasy),
"monospace" => Ok(Family::Monospace),
family => Ok(Family::Name(family)),
},
}
}
/// fin... | Rust | 0 |
which is twice larger in every block. The number of channels in outer 1x1
convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048
channels, and in Wide ResNet-50-2 has 2048-1024-2048.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (b... | Python | 1 |
"page_size" => page_size = v.parse::<usize>()?,
_ => {}
};
}
let collection_builder = crate::collections::CollectionBuilder {
subject: resource.get_subject().into(),
property,
value,
sort_by,
sort_desc,
current_page,
page_s... | Rust | 0 |
[float(aspect_ratio) for aspect_ratio in cfg.aspect_ratios],
cfg.scales_per_octave,
cfg.normalize_coordinates
)
elif anchor_generator_config.WhichOneof(
'anchor_generator_oneof') == 'flexible_grid_anchor_generator':
cfg = anchor_generator_config.flexible_grid_anchor_generator
... | Python | 1 |
nal_output_path = os.path.join(config.OUTPUT_DIR, final_output_filename)
final_path = text_overlay.add_text_overlay(
image_path=temp_img_path,
user_title=user_title,
user_concept_note=user_concept_note,
output_path=final_output_path,
placement_templat... | Python | 1 |
r',
name='base_link_transform',
output='screen',
arguments=['0', '0', '0', f'{math.pi/2}', '0', '0', 'base_link', 'd435i_camera_link'],
condition=IfCondition(LaunchConfiguration('rosbag'))
)
sb_rosbag_condition = IfCondition(
PythonExpression(
[
... | Python | 1 |
#!/usr/bin/env fbpython
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under both the MIT license found in the
# LICENSE-MIT file in the root directory of this source tree and the Apache
# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
# of this source... | Python | 1 |
helps,
// we parallelize the butterfly operation within the chunk.
//
// if chunk_size > MIN_CHUNK_SIZE_FOR_PARALLELIZATION
if gap > MIN_CHUNK_SIZE_FOR_PARALLELIZATION / 2 {
cfg_iter_mut!(lo).zip(hi).enumerate().for_each(butterfly_fn);... | Rust | 0 |
from fastapi import APIRouter
from pydantic import BaseModel
from models.text_model import text_model
from datetime import datetime
router = APIRouter()
# Request model
class PhishingPredictRequest(BaseModel):
text: str
# Response model
class PhishingPredictResponse(BaseModel):
label: str # "phishing"... | Python | 1 |
del is None:
return {'error': 'Model yüklenemedi'}
result = predictor.predict_text(text)
if result is None:
return {'error': 'Tahmin yapılamadı'}
# Chatbot ile uyumlu format
return {
'category': result['predicted_category'],
... | Python | 1 |
ls::HttpsConnectorBuilder::new().with_native_roots();
#[cfg(feature = "https-only")]
let builder = builder.https_only();
#[cfg(not(feature = "https-only"))]
let builder = builder.https_or_http();
#[cfg(feature = "rustls-http1")]
let builder = builder.enable_http1();
... | Rust | 0 |
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | Python | 1 |
`
"""
tn = true_negative(input, target)
fp = false_positive(input, target)
denom = tn + fp
if any(denom == 0):
logger.warning("Zero division in specificity")
return tn / denom
def f1_score(input: Tensor,
target: Tensor
) -> Tensor:
"""Calculate f1 score
... | Python | 1 |
subscription = self.login_sp(sp)
if 'subscriptionId' in sp:
# Set active subscription if sp contains it.
self.set_active_subscription(sp['subscriptionId'])
env['ARM_SUBSCRIPTION_ID'] = sp['subscriptionId']
else:
# No subscrip... | Python | 1 |
()
.try_sub(Decimal::from(OBLIGATION_LOAN))
.unwrap();
assert_eq!(
obligation_state.borrowed_liquidity_wads,
expected_obligation_interest
);
let expected_obligation_total = Decimal::from(OBLIGATION_LOAN)
.try_add(expected_obligation_interest)
.unwrap();
... | Rust | 0 |
tags=["anthropic"],
metadata=ANY_DICT,
start_time=ANY_BUT_NONE,
end_time=ANY_BUT_NONE,
type="llm",
usage=EXPECTED_ANTHROPIC_USAGE_DICT,
model=ANY_STRING.starting_with(MODEL_FOR_TESTS_SHORT),
provider="ant... | Python | 1 |
task_info.write_message(logger.as_ref(), level, message);
}
Ok(LoggerMessage::NewLogger(logger, level, output)) =>
task_info.add_logger(logger, level, output),
Ok(LoggerMessage::PoisonPill) => {
break;
}
Ok(LoggerMessage::RegisterLevelString(level, string)) => {... | Rust | 0 |
<f64>::zeros((4, nelems).f());
#[cfg(feature = "parallel")]
par_azip!((mut quat_c in ori.axis_iter_mut(Axis(1)), ref quat in self.ori.axis_iter(Axis(1))) {
quat_c[0] = quat[0];
quat_c[1] = -1.0_f64 * quat[1];
quat_c[2] = -1.0_f64 * quat[2];
quat_c[3] = -1... | Rust | 0 |
s += 1
second = self._tournament(rng, k)
diversity = self._op(first, second)
return first, second
def tournament(
self,
rng: RandomNumberGenerator,
cost_evaluator: CostEvaluator,
k: int = 2,
) -> Solution:
"""
Selects a solution f... | Python | 1 |
sult<Vec<Extra>> {
Self::parse_append_many(vec![], it)
}
}
/// Declares the information used to process some portion of the content.
/// Each technique conforms to an associated profile.
/// In the COLLADA spec, this element is called "`<technique>` (core)".
#[derive(Clone, Debug)]
pub struct Technique {
... | Rust | 0 |
warnings.filterwarnings("ignore", category=UserWarning, module="matplotlib")
warnings.filterwarnings("ignore", category=UnicodeWarning, module="matplotlib")
warnings.filterwarnings("ignore", category=UserWarning, module="pymatgen")
if args.primitive_axis == "auto":
pa = args.primitive_axis
elif... | Python | 1 |
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from contextlib import contextmanager
from api.config import get_settings
settings = get_settings()
# Criar engine do SQLAlchemy
engine = create_engine(
settings.DB_URL,
conne... | Python | 1 |
x = abs(agent.state.p_pos[p])
bound_rew -= bound(x)
rew += bound_rew
return rew
def observation(self, agent, world):
# get positions of all entities in this agent's reference frame
entity_pos = []
for entity in world.landmarks: # world.entitie... | Python | 1 |
from scrapy import Spider
from scrapy.http import JsonRequest, Response
from locations.dict_parser import DictParser
from locations.hours import DAYS, OpeningHours
class ThomasPhilippsSpider(Spider):
name = "thomas_philipps"
item_attributes = {"brand": "Thomas Philipps Sonderposten", "brand_wikidata": "Q1424... | Python | 1 |
"operation"),
},
timestamp=msg.get("timestamp"),
session_context={"session_id": msg.get("session_id")},
)
def _validate_message_structure(self, msg: Dict) -> bool:
"""Validate message has required structure."""
required_fields = ["type"]
return al... | Python | 1 |
,
Host::Domain(name) => match Host::parse(name) {
Ok(Host::Ipv4(ip)) => IpAddr::V4(ip),
Ok(Host::Ipv6(ip)) => IpAddr::V6(ip),
_ => return Err(ParseError::InvalidIpv4Address),
},
Host::Ipv4(ip) => IpAddr::V4(ip),
... | Rust | 0 |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def countPairs(self, root: TreeNode, distance: int) -> int:
def traverse_tree(curr_node,pre... | Python | 1 |
log::trace!("Rerolling random placement {}", item);
continue;
}
}
return Some(item)
}
}
}
use num::rational::Ratio;
use num::BigUint;
use serde::{Deserialize, Serialize};
use crate::helpers::{closest_packable_fee_amount, pack_fee_amount, unpack... | Rust | 0 |
from nupe.file.views.image_upload import ProfileImageViewSet
| Python | 1 |
ators::huge_boot_bump_allocator::*;
use memory::HugeFrame;
use paging::Page;
use paging::PageLike;
use structures::FrameStore;
use super::FixedFrameRecycler;
use super::FrameLikeAllocator;
use super::FrameRecycler;
use super::PostBootAllocator;
pub struct BootAllocator {
frame_allocator: Option<FixedFrameRecycler<Fra... | Rust | 0 |
from typing import Callable, List, Optional
import json
from posts__claude_util_client import completions_with_backoff
def init_categorize_message(
model_name,
system_prompt,
temperature,
generate_shots: Optional[Callable[[str], List]] = None,
):
"""Initialize a function to analyze sentiment in a... | Python | 1 |
options`: Current formatter options
#[must_use]
#[inline]
fn always_show_segment_register(options: &FastFormatterOptions) -> bool {
options.always_show_segment_register()
}
/// Always show the size of memory operands
///
/// Default | Value | Example | Example
/// --------|-------|---------|--------
/// &nb... | Rust | 0 |
Result<Vec<usize>, Error> {
let mut s = String::new();
file.read_line(&mut s)?;
s.pop();
s.split(' ')
.map(|w| w.parse::<usize>().map_err(Into::into))
.collect()
}
fn test<EK: EdmondsKarp<i32>>(n: usize, file: &mut dyn BufRead) -> Result<String, Error> {
let ndices = read_ints(file... | Rust | 0 |
, v[:split_ix]
data = split_data
gym_settings['timesteps'] -= 3 # from all the offsets computed above
data['meta'] = gym_settings
return data
def get_dataset(experiment_name, save_dir, **kwargs):
'''Returns a dataset bult on top of OpenAI Gym observations. Also constructs
the dataset if no saved ... | Python | 1 |
def find_blank(board):
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == '_':
return i, j
def is_valid_move(board, i, j):
if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]):
return False
return True
def swap(board, i1, j1, i2,... | Python | 1 |
HandRank::FullHouse { .. } => 7,
HandRank::Flush { .. } => 6,
HandRank::Straight { .. } => 5,
HandRank::ThreeOfAKind { .. } => 4,
HandRank::TwoPair { .. } => 3,
HandRank::Pair { .. } => 2,
HandRank::Highest { .. } => 1,
... | Rust | 0 |
from dash import Dash, html
from dash.dependencies import Output, Input
app = Dash(__name__)
app.layout = html.Div(
[html.Button("Click me", id="home-button"), html.Div(id="home-output")]
)
app.clientside_callback(
"dash_clientside.clientside.home_function",
Output("home-output", "children"),
Input("... | Python | 1 |
mut cinfo: crate::jpeglib_h::j_decompress_ptr,
mut compptr: *mut crate::jpeglib_h::jpeg_component_info,
mut input_data: crate::jpeglib_h::JSAMPARRAY,
mut output_data_ptr: *mut crate::jpeglib_h::JSAMPARRAY,
) {
*output_data_ptr = crate::stddef_h::NULL as crate::jpeglib_h::JSAMPARRAY;
/* safety ch... | Rust | 0 |
# 请先安装 OpenAI SDK: `pip3 install openai httpx-socks`
from openai import OpenAI
import httpx
from httpx_socks import SyncProxyTransport
# 可用的 GPT-3.5 模型列表
AVAILABLE_MODELS = [
"gpt-3.5-turbo", # 最常用的模型,性价比高
"gpt-3.5-turbo-0125", # 2024年1月25日更新的版本
"gpt-3.5-turbo-1106", # 2023年11月6日更新的版本
... | Python | 1 |
# Copyright (c) 2020, 2023 Rocky Bernstein
def ifstmt(self, lhs, n, rule, ast, tokens, first, last):
first_offset = tokens[first].off2int(prefer_last=False)
if lhs == "ifstmtl":
if last == n:
last -= 1
pass
if tokens[last].attr and isinstance(tokens[last].attr, int):... | Python | 1 |
tring,
basename: String,
string_tables: Arc< BinaryChunks >,
symbol_table_count: u16,
symbol_tables_chunks: BinaryChunks,
symbol_tables: Vec< SymbolTable >,
symbols: Option< Symbols >,
data: Option< Arc< BinaryData > >,
debug_data: Option< Arc< BinaryData > >,
load_headers: Vec< Load... | Rust | 0 |
f = open('password.txt', 'r')
flag = ""
for i in range(32):
flag+="x"
for line in f:
line = line.strip()
index = int(line.split("(")[1].split(")")[0] )
value = line.split('==')[1].replace("'", "").split("&&")[0]
tmp = list(flag)
tmp[index]=value
flag = ''.join(tmp)
flag = "picoCTF{" + flag + "}"
print(flag)... | Python | 1 |
import FWCore.ParameterSet.Config as cms
from SimCalorimetry.HGCalAssociatorProducers.hitToTracksterAssociator_cfi import hitToTracksterAssociator
hitToTrackstersAssociationLinking = hitToTracksterAssociator.clone(
tracksters = cms.InputTag("ticlTrackstersMerge"),
)
hitToTrackstersAssociationPR = hitToTracksterA... | Python | 1 |
import sys, os
lines = []
with open('final.s') as f:
lines = f.readlines()
# all the symbols found in inlined function, provided by
# func_inline_diversify.ml
symbols = []
with open('inline_symbols.txt') as f:
symbols = f.readlines()
# get rid of space; newline and ":"
symbols = list(map(lambda s : s.replac... | Python | 1 |
itbuf = BitVecWriter::<Endian>::default();
bitbuf.write_string("Hello, world!");
bitbuf.write_string_nul("Hello, world!");
assert_eq!(bitbuf.into_bytes(), b"Hello, world!Hello, world!\0");
}
);
test!(
test_write_bytes_lsb,
test_write_bytes_msb,
bench_write_bytes_lsb,
bench_write_bytes_msb,
{
let mut bitb... | Rust | 0 |
#🔹 Challenge 4: Word Counter
#Ask user to enter a sentence.
#Count how many times the word “python” appears.
sentence = input("Enter a sentence: ").lower()
count = sentence.count("python")
print(f"The word 'python' appeared {count} times.")
| Python | 1 |
c_graph
def build_model(self, exec_mode):
feed_shape = list(self.feed_shape[0])
if self.is_ipu_mode(exec_mode):
feed_shape[0] = 1
x = paddle.static.data(
name=self.feed_list[0], shape=feed_shape, dtype='float32'
)
with paddle.static.ipu_shard_guard(in... | Python | 1 |
from __future__ import annotations
from typing import TYPE_CHECKING
from narwhals._compliant import LazyExprNamespace
from narwhals._compliant.any_namespace import ListNamespace
from narwhals._duckdb.utils import F
if TYPE_CHECKING:
from narwhals._duckdb.expr import DuckDBExpr
class DuckDBExprListNamespace(
... | Python | 1 |
class Shortcode():
def __init__(self, Unprompted):
self.Unprompted = Unprompted
self.description = "It's a for loop."
def preprocess_block(self, pargs, kwargs, context):
return True
def run_block(self, pargs, kwargs, context, content):
final_string = ""
this_var = ""
test = pargs[0]
expr = pargs[1]
... | Python | 1 |
def solve(grid):
h = len(grid)
w = len(grid[0]) if h else 0
mapping = {0: 8, 8: 0, 6: 7, 7: 6}
res = [row[:] for row in grid]
for r in range(h):
if grid[r][0] == 4 and grid[r][w-1] == 4:
for c in range(1, w-1):
v = grid[r][c]
if v in mapping:
... | Python | 1 |
debug_assert!(index < $count);
let width = $msb - $lsb + 1;
let lsb = $lsb + index*width;
let msb = lsb + width - 1;
self.set_bit_range(msb, lsb, value);
}
};
(@field $(#[$attribute:meta])* ($($vis:tt)*) $t:ty, $into:ty, _, $setter:ident: $msb:expr,
$... | Rust | 0 |
from users_core.utils.phrases import phrases
from users_core.keyboards.return_to_main_keyboard import get_keyboard
from aiogram import Bot, Router, F
from aiogram.types import CallbackQuery, FSInputFile, InputMediaPhoto
support_router = Router()
async def get_support(call: CallbackQuery, bot: Bot):
media = Inp... | Python | 1 |
[doc = "0x1c4 - DEVICE End Point Pipe Status Clear"]
pub epstatusclr6: self::device::EPSTATUSCLR,
#[doc = "0x1c5 - DEVICE End Point Pipe Status Set"]
pub epstatusset6: self::device::EPSTATUSSET,
#[doc = "0x1c6 - DEVICE End Point Pipe Status"]
pub epstatus6: self::device::EPSTATUS,
#[doc = "0x1c7... | Rust | 0 |
ord_equal!(GrLex::cmp(mdeg![0, 0, 0], mdeg![0, 0, 0]));
assert_ord_equal!(GrLex::cmp(mdeg![1, 0, 0], mdeg![1, 0, 0]));
assert_ord_equal!(GrLex::cmp(mdeg![1, 2, 3], mdeg![1, 2, 3]));
assert_ord_equal!(GrLex::cmp(mdeg![0, 0, 1], mdeg![0, 0, 1]));
assert_ord_less!(GrLex::cmp(mdeg![2, 2, 0]... | Rust | 0 |
RNO";
match env::var(env_name) {
Ok(p) => match p.parse::<i32>() {
Ok(i) => Some(Errno(i)),
Err(_) => None,
},
Err(_) => None,
}
})
);
pub static LIKELIHOOD_CERTAIN_PCT: f32 = 100f32;
macro_rules! returnError(
($fd: expr,... | Rust | 0 |
lopers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at... | Rust | 0 |
level";
impl FinalizedVersionRange {
/// Attempts to create an instance from a HashMap, panics if the min/max labels do not exist as
/// keys in the HashMap (Initially was
fn from_map(version_range_map: &HashMap<String, i16>) -> Self {
debug!("Attempting to build from HashMap: {:?}", version_range_... | Rust | 0 |
// FIXME (#2535): this is very shaky and probably gets ABIs wrong all
// over the place
fn build_direct_fn(ccx: @mut CrateContext,
decl: ValueRef,
item: @ast::foreign_item,
tys: &ShimTypes,
cc: lib::llvm::CallConv)... | Rust | 0 |
root_hash, m)
.expect("Creation of mocked account should be a success.");
let new_hash = match commit_result {
CommitResult::Success(new_hash) => new_hash,
other => panic!("Commiting changes to test History failed: {:?}.", other),
};
let reader = hist
... | Rust | 0 |
if value in self.builtin_types:
yield index, Keyword.Type, value
continue
if value in self.builtin_classes:
yield index, Name.Class, value
continue
yield index, token, value
tokens = {
'ro... | Python | 1 |
import sys
import inspect
#WARNING! Dont use inspect.stack()! its very very very slow.
def getFrames(deep=2):
if deep is None or deep == 0:
deep = 1
frames = []
for x in list(range(2, 3 + deep)):
try:
frames.append(sys._getframe(x))
except Exception:
break
return frames
#printCallSequence(5)
#14:13:... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.