text
string
label_name
string
labels
int64
reater than zero")); Ok(()) } } } #[test] fn can_apply_completed_transfer() -> Result<()> { // Act let (actor, sk_set) = get_actor_and_replicas_sk_set(15)?; let debit = get_debit(&actor)?; let mut actor = actor; actor.apply(ActorEv...
Rust
0
e advised to be careful about the points they pass, as the /// point not being on the curve, intentional or not, will never result in /// an error. pub fn point_model_to_curve(&self, point: &Point<3>) -> Point<1> { match self { Self::Circle(curve) => curve.point_model_to_curve(point), ...
Rust
0
; use serde_test::Token; #[test] fn test_stage_instance() { let value = StageInstance { channel_id: Id::new(100), guild_id: Id::new(200), guild_scheduled_event_id: Some(Id::new(300)), id: Id::new(400), privacy_level: PrivacyLevel::GuildOnl...
Rust
0
""" Модуль для тестирования эндпоинтов по работе с отзывами. Этот модуль содержит набор тестов для проверки корректности работы API-эндпоинтов. Используются как асинхронные, так и синхронные тесты с помощью библиотек `pytest`, `httpx` и `TestClient` из FastAPI. Асинхронные тесты выполняются с использованием `httpx.As...
Python
1
_pointers)] #![allow(dead_code)] #![allow(missing_docs)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] #![allow(unsafe_code)] #![allow(unused_imports)] #![allow(unused_results)] //! Generated file from `playlist4content.proto` use protobuf::Message...
Rust
0
from typing import Optional, Tuple from pydantic import BaseModel from qdrant_client import AsyncQdrantClient from qdrant_client import models as qdrant_models from .args import Args from .config import config from .logger import logger from .os_env import OsEnv _qdrant_client: Optional[AsyncQdrantClient] = None c...
Python
1
s json_file: data = json.load(json_file) # Sort the data by 'nodes' data = sorted(data, key=lambda x: x['nodes']) # Depending on the 'all' flag, process the data differently if no_diff: for d in data: results.add_dict(d) results.plot(title) else: fo...
Python
1
 c@sCddlmZdZdddYZdd dYZdS( i(trpccCs)t|}t|}|tj|<|S(N(tWrappedObjectTreeItemtidRt objecttable(titemtwrappertoid((sRemoteObjectBrowser.pytremote_ob...
Python
1
Unknown => ffi::NM_SETTING_TUN_MODE_UNKNOWN, Self::Tun => ffi::NM_SETTING_TUN_MODE_TUN, Self::Tap => ffi::NM_SETTING_TUN_MODE_TAP, Self::__Unknown(value) => value, } } } #[doc(hidden)] impl FromGlib<ffi::NMSettingTunMode> for SettingTunMode { unsafe fn from_glib(valu...
Rust
0
w::Result; use futures::future::Future; use generust_example_project_controllers::routes::add_routes; use generust_example_project_service::AppConfig; use std::time::SystemTime; pub(crate) fn start_server(cfg: &AppConfig, port_tx: &std::sync::mpsc::Sender<u16>) -> Result<()> { let server = { let cfg = cfg.clone(...
Rust
0
(self.to_glib_none().0, "notify::input-hints", transmute(notify_input_hints_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _) } } #[cfg(any(feature = "v3_6", feature = "dox"))] fn connect_property_input_purpose_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId ...
Rust
0
[derive(Serialize, Deserialize, Queryable, Insertable, AsChangeset, Debug)] pub struct Usuario { pub id: Option<i32>, pub usuario: String, pub senha: String, pub email: String, pub telefone: String, pub cargo: i32, } /* #[derive(Insertable, Debug)] #[table_name = "users"] pub struct NewUser<'a>...
Rust
0
_req: super::notification_service::SendNotificationChannelVerificationCodeRequest, sink: ::grpcio::UnarySink<super::empty::Empty>) { grpcio::unimplemented_call!(ctx, sink) } fn get_notification_channel_verification_code(&mut self, ctx: ::grpcio::RpcContext, _req: super::notification_service::GetNotific...
Rust
0
re)) } } impl From<RVkeywitness> for Vkeywitness { fn from(vkeywitness: RVkeywitness) -> Self { Self { vkey: vkeywitness.vkey().into(), signature: vkeywitness.signature().into(), } } } #[no_mangle] pub unsafe extern "C" fn cardano_vkeywitness_make_vkey_witness( tx_body_hash: TransactionHas...
Rust
0
import numpy as np from rlkit.data_management.simple_replay_buffer import SimpleReplayBuffer from gym.spaces import Box, Discrete, Tuple class MultiTaskReplayBuffer(object): def __init__( self, max_replay_buffer_size, env, tasks, goal_radius, ): ...
Python
1
(target, 0u8, meta.layout.size()), InitialValue::Uninit => (), } meta } } impl Drop for Reserved<'_> { fn drop(&mut self) { if let InitialValue::Value(ptr) = self.initial_value { // We have to drop the initial value that was not used. if let Some(dro...
Rust
0
ot_graph.to_string() dot_string = dot_string.replace(".weight", "_weight") dot_string = dot_string.replace(".bias", "_bias") # the following code snippet is how to plot in networkx, but it does not look nice # new_dot_graph = pydot.graph_from_dot_data(dot_string) # new_dot_graph ...
Python
1
from django.urls import path from .views import index,about_us,tobacco_varieties,stock_update,contact,csractivity,csrdetails,version urlpatterns = [ path('',index,name='index'), path('about/',about_us,name='about_us'), path('tobacco-varieties/',tobacco_varieties,name='tobacco_varieties'), path('stock...
Python
1
] pub struct StdinLogReader { pid: Pid, stderr_fd: RawFd, } impl Drop for StdinLogReader { /// Await the redo-log instance we redirected stderr to. fn drop(&mut self) { // never actually close fd#1 or fd#2; insanity awaits. // replace it with something else instead. // Since our...
Rust
0
# SPDX-FileCopyrightText: Copyright 2025 Arm Limited and/or its affiliates <open-source-office@arm.com> # SPDX-License-Identifier: Apache-2.0 import pytest import os from metis.engine import MetisEngine from metis.vector_store.chroma_store import ChromaStore from llama_index.core.settings import Settings from llama_in...
Python
1
led = self.checker.create_safe_pattern(safe_pattern) # Assert assert compiled is not None assert hasattr(compiled, "search") assert hasattr(compiled, "match") @pytest.mark.unit def test_create_safe_pattern_dangerous(self): """Test creating safe pattern fails for dangero...
Python
1
f"Expected progress 100, but got {scoring_request.progress}", ) expected_calls = 15 self.assertEqual( mock_handle_get_analysis.call_count, expected_calls, f"Expected {expected_calls} calls to ha...
Python
1
23") fig = px.line(table_1, x='Year', y=['Transport', 'Mining (Quarries)', 'Finance and property', 'Trade', 'Manufacturing', 'Domestic (Including households)', 'Agriculture', 'Energy and water', 'Others', 'Construction', 'PPA'], title='National Electricity Consumption by Economic Sector Over Time') st.plotly_ch...
Python
1
#!/bin/env python3 # SPDX-FileCopyrightText: © 2016 Herbert Poetzl <herbert@13thfloor.at> # SPDX-License-Identifier: GPL-2.0-only import sys from smbus import SMBus from bitarray import bitarray from axiom_jtag import * from axiom_mxo2 import * i2c = SMBus(2) jtag = JTag(i2c) jtag.on() jtag.reset() idcode = jta...
Python
1
EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEOR...
Rust
0
#!/usr/bin/env python # # Copyright 2016 Cisco Systems, Inc. # # 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
Python
1
ut, named_in, named_state, dash_duo): app = Dash(__name__) app.layout = html.Div( [ html.Div("Hi", id="in"), html.Div("gh", id="state"), html.Div(id="out1"), html.Div(id="out2"), ] ) def make_args(*a): args = [] kwargs = {}...
Python
1
# -*- coding: utf-8 -*- ''' Manage running applications. Similar to `ps`, you can treat running applications as unix processes. On OS X, there is a higher level Cocoa functionality (see NSApplication) which responds to events sent through the notification center. This module operates at that level. :maintainer: M...
Python
1
tion::ecdsa; use attestation::verifier::ServerVerifier; pub fn decode_spid(hex: &str) -> sgx_spid_t { let mut spid = sgx_spid_t::default(); let hex = hex.trim(); if hex.len() < 16 * 2 { println!("Input spid file len ({}) is incorrect!", hex.len()); return spid; } let decoded_vec =...
Rust
0
dio/aacp', 'audio/3gpp', 'audio/flac', 'audio/mp3', 'audio/mp4', 'audio/mpeg', 'audio/ogg', 'audio/wav', 'audio/x-wav', 'audio/webm', 'audio/x-m4a', 'text/csv', 'application/xml', 'application/zip', 'application/x-zip-compressed', 'application/geo+json', ] DI...
Python
1
MembersList.parse_list(p); // test_err ts enum_no_r_curly // enum {; // enum A {; p.expect(T!['}']); Present(m.complete(p, TS_ENUM_DECLARATION)) } pub(crate) fn parse_ts_type_alias_declaration(p: &mut Parser) -> ParsedSyntax { if !is_at_contextual_keyword(p, "type") && !is_at_contextual_keywo...
Rust
0
'a, T> ViewMut<'a, T> { /// Returns the number of non-fixed dimensions in the view. pub fn num_dims(&self) -> usize { self.bounds.len() } /// Splits the view on the given dimension. pub fn split(&mut self, logical_dim: usize) -> Vec<ViewMut<T>> { // Build the fixed index vector. ...
Rust
0
)) } <filename>pulsar-client/src/consumer/get_message.rs use pulsar_binary_protocol_spec::{ client_channel_messages::{ handler_reply_consumer_channel_message::HandlerReplyConsumerGetMessageChannelMessage, ConsumerSendHandlerChannelMessage, }, futures_channel::oneshot::channel, MessageCom...
Rust
0
r(label_posits[0]), 'y': str(label_posits[1]), 'z': str(label_posits[2])}, 'backgroundColor': "'black'", 'backgroundOpacity': '0.3', 'fontOpacity': '1', 'fontSize': str(labelsize), 'fontColor': "white", 'inFront': 'true'}) view_ats.zoomTo() ...
Python
1
] = True else: trials_all.non[i, j] = True if enr_e2c.info[i] in seen_attacks and test_u2c.info[j] in seen_attacks: trials_seen.non[i, j] = True elif ( enr_e2c.info[i] not in seen_attacks and test_u2c...
Python
1
if seen is None: seen = {} if eq(start, goal): paths.append(path) if id(start) in seen: if seen[id(start)] is start: return if maxDepth is not None: if maxDepth == 0: return maxDepth -= 1 seen[id(start)] = start # Make an alias for ...
Python
1
"""This script generates a Python codec module from a Windows Code Page. It uses the function MultiByteToWideChar to generate a decoding table. """ import ctypes from ctypes import wintypes from gencodec import codegen import unicodedata def genwinmap(codepage): MultiByteToWideChar = ctypes.windll.kernel32.Multi...
Python
1
atty; let fd = STDOUT_FILENO; let is_tty: bool = unsafe { isatty(fd) == 1 }; if !is_tty { return None; } let (rows, cols) = unsafe { let mut winsize = WinSize { ws_row: 0, ws_col: 0, ws_xpixel: 0, ws_ypixel: 0, }; ioc...
Rust
0
, "z").len(), 1); assert_eq!(get!(private, public, 1, "q").len(), 0); assert_eq!(get!(private, public, 2, "x").len(), 1); assert_eq!(get!(private, public, 2, "y").len(), 1); assert_eq!(get!(private, public, 2, "z").len(), 1); assert_eq!(get!(private, public, 2, "q").len(), 0); assert_eq!(get!(...
Rust
0
from django.shortcuts import render # Create your views here. def home(request): return render(request,'home.html') def result(request): num1=int(request.GET.get('Number1')) num2=int(request.GET.get('Number2')) if request.GET.get('add') == "": ans= num1 + num2 elif request.GET.get('subtr...
Python
1
tree.make_energy() }) ), condition_decorator!("Ensure Can Grow", |tree: &mut Tree| { tree.can_grow() }, action!("Grow", |tree: &mut Tree| { tree.grow() }) ), ...
Rust
0
where V: SharedTrait, HE: SharedTrait, { /// Adds a vertex as a custom weight in the hypergraph. /// Returns the index of the vertex. pub fn add_vertex(&mut self, weight: V) -> VertexIndex { self.vertices .entry(weight) .or_insert(IndexSet::with_capacity(0)); ...
Rust
0
2082, -97.60368, 0f32), Location::from_degrees(30.32173, -97.60008, 0f32), Location::from_degrees(30.32329, -97.59958, 0f32), Location::from_degrees(30.32545, -97.60066, 0f32), Location::from_degrees(30.32608, -97.60201, 0f32), Location::from_degrees(30.32613, -97.60339, 0f32), ...
Rust
0
ter_ok::<_, io::Error>(iter::repeat(d).take(nmessages))) .and_then(move |_| stream.fold(0, |n, d| Ok::<_, io::Error>(n + d.len()))) .map(move |n| t.unbounded_send(n).expect("send to channel")); Either::B(f) } }; ...
Rust
0
#Write a function to find minimum of three numbers. def min_of_three(a,b,c): if (a <= b) and (a <= c): smallest = a elif (b <= a) and (b <= c): smallest = b else: smallest = c return smallest
Python
1
{ let s = StdString::from_iter(iter); String::from(&s) } } /// Implements the `+` operator for concatenating two strings. /// /// This consumes the `String` on the left-hand side and re-uses its buffer (growing it if /// necessary). This is done to avoid allocating a new `String` and copying the e...
Rust
0
info("owner", &[]); let res = execute(deps.as_mut(), env.clone(), info, msg).unwrap(); assert_eq!(0, res.messages.len()); let msg = ExecuteMsg::AcceptOwnership {}; let env = mock_env(); let info = mock_info("owner", &[]); let res = execute(deps.as_mut(), env.clone(), info, msg); match res {...
Rust
0
/// /// #[derive(Api, Debug, Serialize, Deserialize)] /// #[api(name = "list-records", response = Vec<Record>)] /// # #[api(core = bonsaidb_core)] /// struct ListRecords { /// starting_id: u64, /// } /// /// #[derive(Debug, Serialize, Deserialize, Clone)] /// struct Record { /// title: String, /// } /// ``` pu...
Rust
0
tion["segmentation"].tolist() json.dump(json_results, f, indent=2) print(f"✅ Prediction completed!") print(f"📊 Found {results['num_detections']} instruments") print(f"💾 Results saved to: {output_dir}") return results if __name__ == "__main__": # Example usage print("Testing Mask R-...
Python
1
import string from django.db.models import Count, Q from tournaments.models import Round from utils.misc import generate_identifier_string from .models import Person, Region, Team def regions_ordered(t): """Need to redo the region IDs so the CSS classes will be consistent. This assumes there aren't huge am...
Python
1
37=static_atom_mask_37[nitrogen_mask], residue_indices=residue_indices[nitrogen_mask], chain_index=chain_index[nitrogen_mask], valid_atom_mask=valid_atom_mask, nitrogen_mask=nitrogen_mask, num_residues=num_residues, ) def _parse_mdtraj_hdf5( source: str | StringIO | pathlib.Path, chain_id: S...
Python
1
#!/usr/bin/env python3 import os from common import ( run_kiwix_build, main_project_versions, release_versions, make_archive, create_desktop_image, update_flathub_git, upload_archive, fix_macos_rpath, BASE_DIR, OS_NAME, COMPILE_CONFIG, MAKE_RELEASE, notarize_macos_b...
Python
1
&'a mut W { self.variant(PAD17STRNGW::HIGH) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] ...
Rust
0
.op); gen.emit_getvar(vi as u16, ei as u16); try!(self.arg.compile(sym, gen)); gen.emit_call(1); Ok(()) } } <filename>src/pki/client.rs /// Creates a certificate with the client extensions enabled pub fn create_client_certificate(pki_name: &str, ca_name: &str, name: &str)...
Rust
0
) register( id="MiniHack-Zap-v0", entry_point="minihack.envs.skills_simple:MiniHackZap", ) register( id="MiniHack-Read-v0", entry_point="minihack.envs.skills_simple:MiniHackRead", ) # Fixed version of tasks register( id="MiniHack-Eat-Fixed-v0", entry_point="minihack.envs.skills_simple:MiniHack...
Python
1
dialog.show() def about(self): import pandasgui dialog = QtWidgets.QDialog(self) layout = QtWidgets.QVBoxLayout() dialog.setLayout(layout) layout.addWidget(QtWidgets.QLabel(f"Version: {pandasgui.__version__}")) layout.addWidget(QtWidgets.QLabel( f...
Python
1
sible completions. (For class instances, class members are also considered.) WARNING: this can still invoke arbitrary C code, if an object with a __getattr__ hook is evaluated. """ import re m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text) if not m: retu...
Python
1
6 /r` /// /// `AVX512VL and AVX512-FP16` /// /// `16/32/64-bit` EVEX_Vfcmulcph_xmm_k1z_xmm_xmmm128b32 = 4426, /// `VFCMULCPH ymm1 {k1}{z}, ymm2, ymm3/m256/m32bcst` /// /// `EVEX.256.F2.MAP6.W0 D6 /r` /// /// `AVX512VL and AVX512-FP16` /// /// `16/32/64-bit` EVEX_Vfcmulcph_ymm_k1z_ymm_ymmm256b32 = 4427, //...
Rust
0
r correctness if we run with NCCL_GRAPH_MIXING_SUPPORT=0, # which requires that graph launch and non-captured launch to not overlap (I think, # that's how I interpret the documentation). I'm not sure if this is required. if torch.distributed.is_initialized(): torch.distributed.barrie...
Python
1
_var_part_insts_v1) <ref_hybrid> blk_head_a); // %cond = SLT <@int64> %i %n ssa! ((vm, hybrid_var_part_insts_v1) <int1> blk_head_cond); inst! ((vm, hybrid_var_part_insts_v1) blk_head_slt: blk_head_cond = CMPOP (CmpOp::SLT) blk_head_i blk_head_n ); // BRANCH2 %cond %bod...
Rust
0
asarray([[0, 1, 7, 6, 1, 0] for _ in range(5)]) comp(stirling2(n, k, exact=False), ans, **kwargs) def test_temme_rel_max_error(self): # python integers with arbitrary precision are *not* allowed as # object type in numpy arrays are inconsistent from api perspective x = list(range(5...
Python
1
3. A Model Registry model like projects/123/locations/us-central1/models/456 """ if not model_name: raise ValueError("model_name must be specified.") if re.match(r"^gs://", model_name): self._model = CustomModel(gcs_uri=model_name) elif re.match(r"^proj...
Python
1
u8] = out.as_bytes(); f.write_all(out_bytes).expect("Could not write file"); println!("cargo:rerun-if-env-changed={}", name); } fn main() { let out_dir = env::var("OUT_DIR").expect("No out dir"); let dest_path = Path::new(&out_dir).join("constants.rs"); let f = File::create(&dest_path).expect("Cou...
Rust
0
e_id.to_port_tree_id_0(); if !self.may_send(deploy_port_tree_id).context(CellagentError::Chain { func_name: _f, comment: S("") })? { return Err(CellagentError::MayNotSend { func_name: _f, cell_id: self.cell_id, tree_id: deploy_tree_id }.into()); } let manifest = app_msg.get_payload()...
Rust
0
rPrint::new(&id, root_output, &build_targets, &install_paths); Ok(CPackage { version, root_path, capi_config, build_targets, install_paths, finger_print, }) } } pub fn cbuild( ws: &mut Workspace, config: &Config, a...
Rust
0
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
Python
1
_points(&instance, 12); // Ensure we can use the new points now add_one.call(1).unwrap(); assert_eq!( get_remaining_points(&instance), MeteringPoints::Remaining(8) ); add_one.call(1).unwrap(); assert_eq!( get_remaining_points(&instanc...
Rust
0
[`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields ...
Rust
0
e rendering. use core::{ fmt::{Debug, Formatter, Result}, marker::PhantomData, mem::MaybeUninit, ops::Range, }; use embedded_graphics::{prelude::*, style::TextStyle}; /// Pixel iterator to render boxes using a single color. /// /// This struct may be used to implement custom rendering algorithms. Inte...
Rust
0
"try putting the name of your desired case in quotation marks e.g. \"snake\"", )), _ => Err(RenderError::new(format!( "case '{}' not supported", case_type.render() ))), }?; let value = h .param(1) .o...
Rust
0
-> usize { self.parent.index() } /// The total number of workers in the computation. pub fn peers(&self) -> usize { self.parent.peers() } } impl<'a, G, T> AsWorker for Child<'a, G, T> where G: ScopeParent, T: Timestamp+Refines<G::Timestamp> { fn index(&self) -> usize { self.parent.index() } fn...
Rust
0
.X ) p_s_and_t_given_0_E = compute_batched_over0_posterior_distribution( X_t=E_t, Qt=Qt.E, Qsb=Qsb.E, Qtb=Qtb.E ) # Dim of these two tensors: bs, N, d0, d_t-1 weighted_X = pred_X.unsqueeze(-1) * p_s_and_t_given_0_X # bs, n, ...
Python
1
from PyQt5 import QtWidgets from PyQt5.QtWidgets import QTableWidgetItem, QPushButton, QWidget, QHBoxLayout, QMessageBox from src.database.DAO.admin.CategoryDAO import CategoryDAO def edit_item(row, category_id, parent=None): """ Xử lý sự kiện khi nhấn nút Sửa Args: row: Dòng được chọn cat...
Python
1
"This bit indicates an em4 wake-up request occurred on pin A0"] A0, #[doc = "This bit indicates an em4 wake-up request occurred on pin A6"] A6, #[doc = "This bit indicates an em4 wake-up request occurred on pin C9"] C9, #[doc = "This bit indicates an em4 wake-up request occurred on pin F1"] ...
Rust
0
| b.0.partial_cmp(&a.0).unwrap()); // do actual sorting by exp concept.payload.beliefsByUsage = temp.iter().map(|v| Arc::clone(&v.1)).collect(); // extract Arc back // keep under AIKR concept...
Rust
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2023/6/6 00:41 @Author : alexanderwu @File : test_chromadb_store.py """ from metagpt.document_store.chromadb_store import ChromaStore # @pytest.mark.skip() def test_chroma_store(): """FIXME:chroma使用感觉很诡异,一用Python就挂,测试用例里也是""" # 创建 ChromaStore 实例...
Python
1
""" code, result = self.client.getData(vs.CHINADATAGOLDCLOSEPRICE%(indicID, indicName, beginDate, endDate, field)) return _ret_data(code, result) def USDataGDP(self, indicID='', indicName='', beginDate='', endDate='', field=''): """ 包含美国GDP数据,具体指标可参见API文档;历史数据从1947年开始,按季...
Python
1
self._log("All methods failed, using 127.0.0.1") return "127.0.0.1" def update_location(self, new_location): """更新節點地區設定""" available_locations = ["Asia", "Africa", "North America", "South America", "Europe", "Oceania", "Unknown"] if new_location in available_location...
Python
1
from PyQt6.QtCore import Qt from PyQt6.QtGui import QStandardItemModel from opensnitch.customwidgets.generictableview import GenericTableModel from opensnitch.utils import sockets class NetstatTableModel(GenericTableModel): def __init__(self, tableName, headerLabels): super().__init__(tableName, headerLab...
Python
1
y(&output.stdout).trim().to_string(); if response.contains(" changed") { let num: String = response.trim_start().split(" ").take(1).collect(); Some(format!("Modified {}", num)) } else { None } } fn status() -> Option<String> { let output = Command::new("git") .args(vec![...
Rust
0
# Copyright (C) 2012 Anaconda, Inc # SPDX-License-Identifier: BSD-3-Clause """ Code in ``conda.base`` is the lowest level of the application stack. It is loaded and executed virtually every time the application is executed. Any code within, and any of its imports, must be highly performant. Conda modules importable f...
Python
1
)] pub struct Manifest { /// The maximum depth of a version number. /// /// This specifies the maximum number of parts. There is no limit if `None` is set. pub max_depth: Option<usize>, /// Whether to ignore text parts in version strings. pub ignore_text: bool, } /// Version manifest implement...
Rust
0
norables --font-funcs=ft", ), "A|\ B.alt@639,0|\ E.alt1@1639,0" ); } #[test] fn morx_20_004() { assert_eq!( shape( "text-rendering-tests/fonts/TestMORXTwenty.ttf", "\u{0041}\u{0045}", "--font-size=1000 --ned --remove-default-ignorabl...
Rust
0
def fun(): try: f=open("d:\\FileDemo1.java","r") finally: print("I will always execute") print("Done") fun()
Python
1
map(|v| v.to_string()), }); } Ok(dependencies) } /// Parse dependencies from project galaxy.yml file. pub fn get_galaxy_yml_dependencies( file_path: &std::path::PathBuf, global_dependencies: &std::collections::HashMap<String, String>, ) -> Result<std::collections::HashSet<vouch_lib::extension:...
Rust
0
::process::spawn::options::Options; use lumen_rt_full::scheduler::{Scheduler, Spawned}; use crate::test::r#loop; use crate::test::strategy::term::binary; use crate::test::strategy::term::binary::sub::{bit_offset, byte_count, byte_offset}; use super::strategy; pub fn arc_process_subbinary_to_arc_process_subbinary_two...
Rust
0
the received frame Noise, /// RX buffer overrun Overrun, #[doc(hidden)] _Extensible, } /// Interrupt event pub enum Event { /// RX buffer Not Empty (new data available) Rxne, /// Transmission Complete Tc, /// TX buffer Empty (more data can be send) Txe, } /// Serial interf...
Rust
0
n_function!(RESETN, 0, 6); fixed_pin_function!(CLKIN, 0, 7); fixed_pin_function!(VDDCMP, 0, 8); #[cfg(test)] mod test { #[test] fn test_swm() { let swm = unsafe { &mut *::SWM }; assert_eq!(address(&swm.pinassign[0]), 0x4000_c000); assert_eq!(address(&swm.pinenable[0]), 0x4000_c1c0); ...
Rust
0
_glyph(num).expect("glyph not found"); let denom_glyph = font.get_glyph(denom).expect("glyph not found"); let mut glyph = num_glyph.clone(); glyph.glyphname = dst.to_string(); for layer in &mut glyph.layers { if let Some((wght, wdth)) =...
Rust
0
r, Token(usize), } pub struct TcpClient { socket: SOCKET, } pub trait HasRawHandle { fn raw_handle(&self) -> HANDLE; } impl TcpClient { fn from_accept(socket: SOCKET) -> TcpClient { TcpClient { socket: socket } } } impl HasRawHandle for TcpClient { fn raw_handle(&self) -> HANDLE { ...
Rust
0
as u32) << OFFSET; self.w } } impl W { #[doc = r" Reset value of the register"] #[inline] pub fn reset_value() -> W { W { bits: 0 } } #[doc = r" Writes raw bits to the register"] #[inline] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.b...
Rust
0
} } #pragma version(1) #pragma rs java_package_name(com.example.android.rs.nbody_gl) #pragma rs_fp_relaxed float espSqr = .2f; // will be constant folded float dt = 0.5f; // will be constant folded float3 half_dt = {0.25f, 0.25f, 0.25f}; // will be constant folded rs_al...
Rust
0
---------------------------------------------------------- # If Statements #------------------------------------------------------------------------- def test_if_else(): # TODO: prevent duplication? @check_ast( ['s.if0', 's.in0', 's.in1'], ['s.out.v', 's.out.v'] ) def if_else( s ): if s.if0: s.out.v = ...
Python
1
tring::from("from"), pos: 0, } ); assert_eq!( s.scan(), Token { tok: T_LPAREN, lit: String::from("("), pos: 4, } ); assert_eq!( s.scan(), Token { tok: T_IDENT, lit: String::from("bucke...
Rust
0
result.append([card for card in max_set_meld if card != meld_card]) return result def get_all_run_melds_for_suit(cards: List[Card], suit: str) -> List[List[Card]]: cards_for_suit = [card for card in cards if card.suit == suit] cards_for_suit_count = len(cards_for_suit) cards_for_suit = sorted(car...
Python
1
import torch import numpy as np from elevate3d.core.models import Generator from elevate3d.utils.download_manager import DownloadManager import albumentations as A from albumentations.pytorch import ToTensorV2 def load_generator(model_path=None, device="cpu"): if model_path is None: download_manager = Dow...
Python
1
import uuid from flask_wtf import FlaskForm from .schema import ListField, DictField from wtforms import StringField, BooleanField from wtforms.validators import DataRequired, AnyOf, ValidationError, Length, Optional from internal.entity.dataset_entity import ProcessType, DEFAULT_PROCESS_RULE from internal.model import...
Python
1
assert_eq!(Header::Neg(u64::MAX), Header::decode(&buf).unwrap().0); let buf = [0x5f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe]; assert_eq!(Header::Neg(u64::MAX), Header::decode(&buf).unwrap().0); } #[test] fn roundtrip_compact() { let mut buf = Vec::new(); ass...
Rust
0
from dataclasses import dataclass, field from typing import Dict from dbt.contracts.graph.node_args import ModelNodeArgs # all these are just exports, they need "noqa" so flake8 will not complain. from dbt.contracts.graph.manifest import Manifest # noqa from dbt.node_types import AccessType, NodeType # noqa from db...
Python
1
import os from contextlib import ExitStack, contextmanager, redirect_stderr, redirect_stdout from ase import Atoms @contextmanager def suppress_print(out: bool = True, err: bool = False): """Suppress stdout and/or stderr.""" with ExitStack() as stack: devnull = stack.enter_context(open(os.devnull, "...
Python
1