text
string
label_name
string
labels
int64
import time from talon import Context, Module, actions, settings ctx = Context() mod = Module() mod.tag("pop_twice_to_wake", desc="tag for enabling pop twice to wake in sleep mode") mod.setting( "double_pop_speed_minimum", type=float, desc="""Shortest time in seconds to accept a second pop to trigger ad...
Python
1
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 your // option. This file may not be copied, modified, or dist...
Rust
0
src/weights.rs // --template=./.maintain/frame-weight-template.hbs #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_staking. pu...
Rust
0
iner; fn next(&mut self) -> Option<Self::Item> { loop { match self.units.next() { Some(None) => {} Some(Some(item)) => { return Some(item); } None => { return None; } } } } } impl<Container, S> IntoIterator for Dynamic<Co...
Rust
0
IP_W { OC3IP_W { w: self } } #[doc = "Bits 24:25"] #[inline(always)] pub fn int3is(&mut self) -> INT3IS_W { INT3IS_W { w: self } } #[doc = "Bits 26:28"] #[inline(always)] pub fn int3ip(&mut self) -> INT3IP_W { INT3IP_W { w: self } } #[doc = "Writes raw bit...
Rust
0
CAPITAL LETTER O WITH CARON "Ǫ", // U+01EA: LATIN CAPITAL LETTER O WITH OGONEK "Ǭ", // U+01EC: LATIN CAPITAL LETTER O WITH OGONEK AND MACRON "Ǿ", // U+01FE: LATIN CAPITAL LETTER O WITH STROKE AND ACUTE "Ȍ", // U+020C: LATIN CAPITAL LET...
Rust
0
SA_SWVERSION_MAJOR_NAME: &'static [u8; 3usize] = b"12\0"; pub const XTENSA_SWVERSION_LICENSE_NAME: &'static [u8; 5usize] = b"12.0\0"; pub const XCHAL_CA_BYPASS: u32 = 2; pub const XCHAL_CA_BYPASSBUF: u32 = 6; pub const XCHAL_CA_WRITETHRU: u32 = 2; pub const XCHAL_CA_WRITEBACK: u32 = 2; pub const XCHAL_HAVE_CA_WRITEBACK...
Rust
0
)); assert_eq!(result.get(1), current.get(1)); assert_eq!(result.get(2), imported.get(1)); } } // Copyright 2019 Zhizhesihai (Beijing) Technology Limited. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You ...
Rust
0
::*, genome::Genome, problem::Problem, niche::Niche, generation::*, genocide::Genocide, environment::Envionment, survival::SurvivalCriteria, survival::ParentalCriteria }; /// Default environment for the NEAT algorithm as described in the paper. /// /// These are very basi...
Rust
0
_cache_bytes: 512 * 1024 * 1024, ephemeral: false, } } } pub mod collatz; pub mod factors; pub mod fib; pub mod integer; pub mod primes; <filename>src/arch/x86/x86_mem.rs use crate::mem as basic; #[inline(always)] #[cfg(any(target_arch = "x86_64", target_arch = "x86"))] pub fn _memmem_impl(hays...
Rust
0
"get details"], "git 'get details'"), ([b"git", b"get details"], "git 'get details'"), (["git", "-C", Path("foo"), "gitify"], "git -C foo gitify"), ("git 'get details'", "git 'get details'"), (b"git 'get details'", "git 'get details'"), (Path("git-get-details"), "git-get-details"...
Python
1
import os import sys if len(sys.argv) != 2: print("Usage: python createday.py <day>") exit(1) i = int(sys.argv[1]) # Ensure we don't overwrite dest = "day" + f"{i:02}" + ".rs" if os.path.isfile(dest): print(f"File {dest} already exists. Exiting.") exit(1) # Read the code template f_template = open("t...
Python
1
= "Current Host Transmit Descriptor Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [current_host_transmit_descriptor](current_host_transmit_descriptor) module"] pub type CURRENT_HOST_TRAN...
Rust
0
g1, Bls12_381, Fr, g2}; use ark_ec::{ models::short_weierstrass_jacobian::GroupAffine, AffineCurve, PairingEngine, ProjectiveCurve, models::short_weierstrass_jacobian::GroupProjective, }; use ark_ff::{PrimeField, BigInteger256}; use ark_poly::univariate::DensePolynomial as DensePoly; use blst::{blst_fp, blst_fp...
Rust
0
fo(f"Storing Excel in SMB storage: DONE in {time() - start:0.5f}s") else: logger.info( "The variables SMB_USER, SMB_PWD and SMB_DIR_OUTPUT are not set, " "the Excel file will not be stored in SMB storage." ) def get_dicom_tags( session: requests.Session, base_url: str, ...
Python
1
ons.py',176), ('args -> exp COMMA args','args',3,'p_args','Parsing_Javascript_Expressions.py',179), ('exp -> exp ANDAND exp','exp',3,'p_exp_binop','Parsing_Javascript_Expressions.py',186), ('exp -> exp OROR exp','exp',3,'p_exp_binop','Parsing_Javascript_Expressions.py',187), ('exp -> exp EQUALEQUAL exp','exp',3...
Python
1
DataSize::from_bytes( lost_pages * BASE_PAGE_SIZE + lost_large_pages * LARGE_PAGE_SIZE ) ); } debug!( "NCache#{} added {} base-pages and {} large-pages.", self.node, self.base_page_addresses.len() - base_count_before_po...
Rust
0
*v = *x; } } } indices } fn array_argmax<T: PartialOrd + Copy + Bounded, D: RemoveAxis>( input: &ArrayView<T, D>, axis: Axis, ) -> Array<u32, D::Smaller> { let mut indices = Array::zeros(input.raw_dim().remove_axis(axis)); ...
Rust
0
Feed your entity body to this, then pass the `finish` /// result to a request or response. pub struct PayloadHasher(Box<dyn crypto::Hasher>); impl PayloadHasher { /// Create a new PayloadHasher. The `content_type` should be lower-case and should /// not include parameters. The digest is assumed to be the same...
Rust
0
b name: String, pub url: String, } #[derive(Serialize, Deserialize, Clone, Debug)] pub struct ResourceList { pub count: usize, pub next: Option<String>, pub previous: Option<String>, pub results: Vec<Resource>, } #[derive(Serialize, Deserialize, Clone, Debug)] pub struct NamedResourceList { pu...
Rust
0
# # Python 3.6 # from sklearn.datasets import load_iris from matplotlib import pyplot as plt iris = load_iris() print(iris.keys()) print("iris.keys() = {0}".format(iris.keys())) data = iris['data'] print("iris.data.shape = {0}".format(data.shape)) feature_names = iris['feature_names'] print("data.feature_names ...
Python
1
nt(f"Coordinate with the highest SMAPE: {highest_smape_key}, De?er: {highest_smape_value:.2f}%") # Coordinates and values coord = highest_smape_key y_true = all_true_values[coord].flatten() # Flattening the array for use y_pred = all_predictions[coord].flatten() dates = pd.date_range(start="2019-01-01", periods=len(...
Python
1
let attr = pt; animals.push(Animal { pos, attr }); } // init humans input! {m: usize} for _ in 0..m { input! {hx: usize, hy: usize} let pos = Pos { x: hx - 1, y: hy - 1, }; humans.push(Human { pos }); } // init room for...
Rust
0
state = hass.states.get(entity_id) call.assert_called_once() @pytest.mark.usefixtures("entity_registry_enabled_by_default") async def test_update_streaming( hass: HomeAssistant, snapshot: SnapshotAssertion, mock_vehicle_data: AsyncMock, mock_add_listener: AsyncMock, ) -> None: """...
Python
1
x_concurrency; let method: reqwest::Method = reqwest::Method::from_str(&cfg.method.to_uppercase())?; let include = RegexSet::new(&cfg.include)?; let exclude = RegexSet::new(&cfg.exclude)?; // Offline mode overrides the scheme let schemes = if cfg.offline { vec!["file".to_string()] } els...
Rust
0
from agent.dst.dst_action import DSTAction class State: def __init__(self): self.history = [] self.dst = None self.dst_class = None self.conversation = [] def get_state(self): pass def get_tts_output(self): if self.dst_class is None: ini...
Python
1
DnsConfig { DnsConfig::System } } /// Security Config #[derive(Clone, Debug, Default)] pub struct SecurityConfig { pub replay_attack: SecurityReplayAttackConfig, } #[derive(Clone, Debug, Default)] pub struct SecurityReplayAttackConfig { pub policy: ReplayAttackPolicy, } /// Balancer Config #[deri...
Rust
0
l get this file transferred to us (before all the copies), so if we come across it later again, # we can copy from _this_ copy (e.g. we only upload it once, and copy thereafter). dst_list.record_md5(relative_file, md5) update_list[relative_file] = src_list[rel...
Python
1
def Simpson(f, a, b, n=500): """ Return the approximation of the integral of f from a to b using Simpson's rule with n intervals. """ if a > b: print 'Error: a=%g > b=%g' % (a, b) return None # Check that n is even if n % 2 != 0: print 'Error: n=%d is not an even int...
Python
1
_MAXMOD: FifoChannels = 3; #[doc = "< \\brief fifo channel reserved for the dswifi library."] pub const FIFO_DSWIFI: FifoChannels = 4; #[doc = "< \\brief fifo channel reserved for dsi sdmmc control."] pub const FIFO_SDMMC: FifoChannels = 5; #[doc = "< \\brief fifo channel reserved for firmware access."] pub const...
Rust
0
, has_cleared, description, entries, } } } impl PartialOrd for Transaction { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { self.date().partial_cmp(&other.date()) } } impl TryFrom<&TransactionOpts> for Transaction { type Error = ...
Rust
0
o_short, meta = "HOST")] pub manager_bind_host: String, /// Sets port Manager listens on (default: 5115) #[options(no_short, meta = "PORT")] pub manager_bind_port: u16, /// Enables distributed load test Worker mode #[options(no_short)] pub worker: bool, /// Sets host Worker connects to (...
Rust
0
se: # Procesează alte câmpuri raw_text = self.extract_text_from_region(image, [x1, y1, x2, y2], field_name=class_name) cleaned_text = self.clean_extracted_text(raw_text, class_name) extracted_info[class_name]...
Python
1
ity Management (SCIM) with the identity provider. """ return pulumi.get(self, "scim_config") @_builtins.property @pulumi.getter def type(self) -> pulumi.Output[_builtins.str]: """ The type of identity provider. To determine the value for a specific provider, refer to our [de...
Python
1
AutoModelForCausalLM.from_pretrained(args.hf_ckpt_path, trust_remote_code=True, torch_dtype=config.torch_dtype) for p in hf_model.parameters(): p.fill_(torch.nan) mg_model = load_megatron_model(args) # NOTE: return a state_dict for saving (to support MTP) hf_model = convert_...
Python
1
Write}; use std::mem; use std::panic; use std::pin::Pin; use std::slice; use std::sync::atomic::{self, AtomicBool, AtomicUsize, Ordering}; use std::sync::{Arc, Condvar, Mutex, MutexGuard}; use std::task::{Context, Poll}; use std::thread; use std::time::Duration; use async_channel::{bounded, Receiver}; use async_task:...
Rust
0
te is invalid but that shouldn't be /// possible, because it must have already been validated, such as for foreign /// key lookups. const DATABASE_INTEGRITY: &str = "Database state invalid despite passing validation?!"; /// A collection of [Tables] with various generated indexes. pub struct Database { tables: ...
Rust
0
(0..args.handles).map(|_| Vec::with_capacity(args.num_rounds)).collect(); for _ in 0..args.num_rounds { sleep(Duration::from_millis(args.ms_per_round as u64)); for (i, num_writes) in writes.iter().enumerate() { let write = num_writes.swap(0, Ordering::Relaxed); throug...
Rust
0
finished."); } } } <reponame>mgjm/hexutil<gh_stars>0 #[doc(hidden)] #[macro_export] macro_rules! private_metadata { ($ty:ident, $len:expr,) => {}; ($ty:ident, $len:expr, default, $($presets:ident,)*) => { $crate::private_metadata!($ty, $len, serde,); }; ($ty:ident, $len:expr, serde,...
Rust
0
String; } impl Padding for i64 { fn pad_zero(self) -> String { let day_string = format!("{}{}", 0, self); (&day_string[day_string.len() - 2..]).to_owned() } } impl Time { pub(crate) fn now() -> Option<Self> { let stamp = match SystemTime::now().duration_since(UNIX_EPOCH) { ...
Rust
0
figs/ffhq256.yaml", metavar="FILE", help="path to config file", type=str, ) parser.add_argument( "opts", help="Modify config options using the command-line", default=None, nargs=argparse.REMAINDER, ) args = parser.parse_args() cfg = get_cfg_de...
Python
1
import nashpy as nash import numpy as np import matplotlib.pyplot as plt def plot_strategy(d_strategy, w_strategy, eu_d, eu_w): fig, axes = plt.subplots(2, 2, sharey='row') x = np.arange(1, len(d_strategy) + 1) # Plot each vector as a bar chart in the subplots axes[0, 0].bar(x, d_strategy) axes[0,...
Python
1
vCsr::new(), pmpaddr50: ReadWriteRiscvCsr::new(), pmpaddr51: ReadWriteRiscvCsr::new(), pmpaddr52: ReadWriteRiscvCsr::new(), pmpaddr53: ReadWriteRiscvCsr::new(), pmpaddr54: ReadWriteRiscvCsr::new(), pmpaddr55: ReadWriteRiscvCsr::new(), pmpaddr56: ReadWriteRiscvCsr::new(), pmpaddr57: ReadW...
Rust
0
] # part 2: add bottom-up path for i in range(0, used_backbone_levels - 1): inter_outs[i + 1] += self.downsample_convs[i](inter_outs[i]) outs = [] outs.append(inter_outs[0]) outs.extend([ self.pafpn_convs[i - 1](inter_outs[i]) for i in r...
Python
1
(value = "https://data.stat.gov.lv/pxweb/lv/OSP_PUB/START__VEK__IK__IKR/IKR060/", prop_nr = "P854", is_reference = True, rank = "preferred") # commiting the data data_gdp = wdi_core.WDQuantity(value=gdp, prop_nr = 'P2131', qualifiers=[point_in_time, deter...
Python
1
self.set_vals_to_rec(); } // Set the values to the ElsetRec object. fn set_vals_to_rec(&mut self) { let deg2rad= 0.0174532925199433; let xpdotp = 229.1831180523293; self.rec.elnum = self.elnum; self.rec.revnum = self.revnum; self.rec.satnum = self.o...
Rust
0
I\xa4\x9a\xca}@\xc5\xa9v\xb1\xdb\x1c#\x15q\ \xd9\x84\xa7<st\xed\xeb\xa5\xf5\xbc}&\xe2\xde?\ \xaa\x9b\xfe\xcfj\xd5\xda\x95#\xa7\xeey\xdb\xd3\xabJ\ \x15!\x09%>NT\xdf\x1a\xc2\xf1Y}\x1e\x0b\x0e\ \xc2\xdc\xdb\xd6\xdb@\xb5\xb7\xdf{7Q\xa7\x7fF\x0a\ \x9c\xef,\xab\xdb\xdcF\xb6\x17\xc7\x94#S\x8a2~\ 8Mg=:\x19\x96\xf2\xd7\xa9m}\xa...
Python
1
1.clone(); let access_policy_2 = (en.clone() | de.clone() | fr.clone()) & sec_level_1.clone(); let access_policy_3 = (de.clone() | fr.clone() | en.clone()) & sec_level_1.clone(); // We must have the equality assert_eq!(access_policy_1, access_policy_2); assert_eq!(access_policy_1, access_policy_3);...
Rust
0
ion. approx((-normal1).mean, -normal1.mean) approx((-normal1).var, normal1.var) # Test substraction. approx((normal1 - normal2).mean, normal1.mean - normal2.mean) approx((normal1 - normal2).var, normal1.var + normal2.var) approx(normal1.__rsub__(normal2).mean, normal2.mean - normal1.mean) a...
Python
1
import sys import time from datetime import datetime from colorama import Fore, Style, init class PrettyLogger: def __init__(self, use_timestamp=True): self.use_timestamp = use_timestamp def _get_time(self): return datetime.now().strftime('%Y-%m-%d %H:%M:%S') if self.use_timestamp else '' ...
Python
1
eData, PipelineData, Signature, SyntaxShape, Value}; #[derive(Clone)] pub struct GitCheckout; impl Command for GitCheckout { fn name(&self) -> &str { "git checkout" } fn usage(&self) -> &str { "Checkout a git revision" } fn signature(&self) -> nu_protocol::Signature { Sig...
Rust
0
.generate( &func.wire_func_name(), &params .iter() .map(std::ops::Deref::deref) .collect::<Vec<_>>(), return_type, &format!( " {}.{}({}, move || {{ {} }}) ...
Rust
0
] ) ) self.is_locked = False def is_runnable(self): ct = self.context if ct.gripper_has_block and ct.has_placement_target_eff_T: eff_T = ct.robot.arm.get_fk_T() thresh_met = math_util.transforms_are_close( ct.placement_tar...
Python
1
][0] kpt_b_id = BODY_PARTS_KPT_IDS[part_id][1] for i in range(len(connections)): num = 0 for j in range(len(pose_entries)): if pose_entries[j][kpt_a_id] == connections[i][0]: pose_entries[j][kpt_b_id] = connections[i][1]...
Python
1
::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [master](master) module"] pub type MASTER = crate::Reg<u32, _MASTER>; #[allow(missing_docs)] #[doc(hidden)] pub struct _MASTER; #[doc = "`read()` method returns [master::R](master::R) reader structure"...
Rust
0
=1) else: inp = (inp, ) feats = [self.intro(x) for x in inp] feats = self.body(*feats) out = torch.cat([self.up(x) for x in feats], dim=1) out = out + inp_hr return out class NAFSSR(Local_Base, NAFNetSR): def __init__(self, *args, train_size=(1, 6, 30, 90...
Python
1
_CERT_DIST_POINT_ERR_INDEX_SHIFT) & CROSS_CERT_DIST_POINT_ERR_INDEX_MASK } STRUCT!{struct CERT_PAIR { Forward: CERT_BLOB, Reverse: CERT_BLOB, }} pub type PCERT_PAIR = *mut CERT_PAIR; STRUCT!{struct CRL_ISSUING_DIST_POINT { DistPointName: CRL_DIST_POINT_NAME, fOnlyContainsUserCerts: BOOL, fOnlyContai...
Rust
0
enum; /// GetPointervPName /// * [`GL_DEBUG_CALLBACK_FUNCTION`] /// * [`GL_DEBUG_CALLBACK_USER_PARAM`] pub type GetPointervPName = GLenum; /// GetTextureParameter /// * [`GL_TEXTURE_ALPHA_SIZE`] /// * [`GL_TEXTURE_BLUE_SIZE`] /// * [`GL_TEXTURE_BORDER_COLOR`] /// * [`GL_TEXTURE_GREEN_SIZE`] /// * [`GL_TEXTURE_HEIGHT`...
Rust
0
FromStr::from_str(x.borrow()) .map_err(|_| ())) } fn nth_value<A:FromStr>(&mut self, i: usize) -> Result<A, ()> { self.nth(i).ok_or(()) .and_then(|x| FromStr::from_str(x.borrow()).map_err(|_| ())) } } pub trait NextStr<'a> { fn next_str(&mut self) -> Result<&'a str, ()>; ...
Rust
0
(), result).with_context(|| { format!( "Failed to write result as JSON to {}", output_path.display() ) })?; } else { serde_json::to_writer(guard.deref(), result).with_context(|| { format!( "Failed to write result as ...
Rust
0
p = Self::network_hrp(network); bech32::encode( hrp, self.to_jumbled_bytes(hrp).to_base32(), Variant::Bech32m, ) .expect("hrp is invalid") } } /// Trait for for Unified containers, that exposes the items within them. pub trait Container { /// The type...
Rust
0
hildren, None) } else { Node::NibbledBranch(partial.to_stored_range(common), children, None) } }; // always replace because whatever we get out here // is not the branch we started with. let branch_action = self.insert_inspector(branch, key, value, old_val)? .unwrap_node();...
Rust
0
from typing import Final from rotkehlchen.chain.decoding.types import CounterpartyDetails from rotkehlchen.chain.evm.types import string_to_evm_address from rotkehlchen.types import ChainID CPT_GEARBOX: Final = 'gearbox' GEARBOX_CPT_DETAILS: Final = CounterpartyDetails( identifier=CPT_GEARBOX, label='Gearbox'...
Python
1
None, gt_offsets, img_metas) # TODO: Support empty tensor input. #2280 if offset_results['loss_offset'] is not None: losses.update(offset_results['loss_offset']) return losses def generate_g...
Python
1
from typing import Any from unittest import mock from requests.exceptions import RequestException from core import tumblr_client def test_remote_story_text_parts(remote_story: tumblr_client.RemoteStory): assert len(remote_story.text_parts) == 2 assert remote_story.text_parts[0] == "This is a story text" ...
Python
1
::signed(validator_1_controller), ValidatorPrefs::default(), )); assert_ok!(Staking::validate( Origin::signed(validator_2_controller), ValidatorPrefs::default() )); assert_ok!(Staking::nominate( Origin::signed(nominator_controller), vec![validator_1_stash, validator_2_stash], )); ...
Rust
0
or better cache behavior warmup_iters = 5 with torch.no_grad(): for _ in range(warmup_iters): _ = model(inputs) # Timed run with more iterations for better measurement iters = 50 # Increased from 20 torch.cuda.synchronize() start = time.time() with torch.no_grad(): for _ in range(iters): _ = m...
Python
1
time.sleep(0.1) else: pytest.fail("File did not appear in mount directory within 10 seconds") assert name in os.listdir(src_dir) assert name in os.listdir(mnt_dir) # Compare relevant stat attributes src_stat = os.stat(src_name) mnt_stat = os.stat(mnt_name) assert src_stat.st_mod...
Python
1
from keras import backend as K def _get_accuracy(y_true, y_pred, mask, sparse_target=False): y_pred = K.argmax(y_pred, -1) if sparse_target: y_true = K.cast(y_true[:, :, 0], K.dtype(y_pred)) else: y_true = K.argmax(y_true, -1) judge = K.cast(K.equal(y_pred, y_true), K.floatx()) if ...
Python
1
LAST LIMIT <n>` to make sure the null values will not be selected - There are columns with similar names but different meanings, you can find the most accurate columns in the right table based on the 【Summary of each table】 【Response format】 Your response should be in this format: Analysis: **[Your analysis]** Correct...
Python
1
128; const ENUM_FLAG = 256; const AUTO_INCREMENT_FLAG = 512; const TIMESTAMP_FLAG = 1024; const SET_FLAG = 2048; const NO_DEFAULT_VALUE_FLAG = 4096; const ON_UPDATE_NOW_FLAG = 8192; const NUM_FLAG = 32768; const PART_KEY_FLAG = 16384; const GROUP_...
Rust
0
reason="Not yet implemented for ArrayManager", ) skip_array_manager_invalid_test = pytest.mark.skipif( _get_option("mode.data_manager", silent=True) == "array", reason="Test that relies on BlockManager internals or specific behaviour", ) skip_copy_on_write_not_yet_implemented = pytest.mark.xfail( get_o...
Python
1
OpCS; pub struct NoOpSPI; pub struct NoOpTimer; impl OutputPin for NoOpCS { type Error = Infallible; fn set_low(&mut self) -> Result<(), Self::Error> { Ok(()) } fn set_high(&mut self) -> Result<(), Self::Error> { Ok(()) } } impl Write<u8> for NoOpSPI { type Error = Infallible...
Rust
0
_leap_year) { return Err(Error::OutOfRange); } // Work out the number of days from the start of 1970 to now, // which is a multiple of the number of years... let days = years * 365 // Plus the number of days between the start of 2000 and the // start...
Rust
0
"b(==)" | "b(>)" | "b(>=)" | "b(<)" | "b(<=)" | "u(exp)" | "u(log)" | "sprop" | "selp" => { println!("got some"); children[0].clone() }, _ => panic!("Unknown udf {}", op) } } pub fn optimize(lgraph: EGraph, roots: Vec<u32>) -> Vec<RecExpr<Math>> { // Tr...
Rust
0
Err(E::invalid_value(Unexpected::Str(v), &self)) } } fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: serde::de::Error, { ...
Rust
0
path = dirs_next::cache_dir() .ok_or_else(|| anyhow!("failed to find os cache dir."))?; path.push("gitui"); fs::create_dir_all(&path)?; Ok(path) } pub fn get_app_config_path() -> Result<PathBuf> { let mut path = if cfg!(target_os = "macos") { dirs_next::home_dir().map(|h| h.join(".config")) } else { dirs_...
Rust
0
-update-committer should trigger a reboot regardless of the /// config. Additionally, the inspect state should reflect the system being unhealthy. We could /// split this up into several tests, but instead we combine them to reduce redundant lines of code. /// We could do helper fns, but we decided not to given guidanc...
Rust
0
est"); //assert_ne!(trade_volume.len(), 0, "zero len trade vol"); //assert_ne!(trade_volume[0].len(), 0, "zero len trade vol"); //assert_eq!( // trade_volume[0][0].data_date.len(), // 10, // "date format incorrect" //); }use crate::{DecisionTree, EngineBase, EngineConfig, EngineResu...
Rust
0
-cassandra-keyspace.html) resource type. #[derive(Debug, Default)] pub struct Keyspace { properties: KeyspaceProperties } /// Properties for the `Keyspace` resource. #[derive(Debug, Default)] pub struct KeyspaceProperties { /// Property [`KeyspaceName`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserG...
Rust
0
") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; if val { *byte |= mask; } else { *byte &= !mask; } } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { debug_asse...
Rust
0
filepath = os.path.normpath(os.path.join(blend_file_directory, filepath)) return make_relative_path(filepath, start) def strip_blender_path_prefix(path): is_relative = False BLENDER_RELATIVE_PATH_PREFIX = '//' prefix_length = len(BLENDER_RELATIV...
Python
1
reduced_trace = parse_full_trace(reduced_spike_out, fuzzerstate.is_design_64bit) # Compare the traces # compare_parsed_traces(expected_trace, spikecheck_trace) compare_parsed_traces(expected_trace, reduced_trace, instr_addrs) # Takes a fuzzerstate after its basic blocks were generated. # Does the ad...
Python
1
import ScriptEnv ScriptEnv.Initialize("Ansoft.ElectronicsDesktop") oDesktop.RestoreWindow() oProject = oDesktop.GetActiveProject() oDesign = oProject.GetActiveDesign() oEditor = oDesign.SetActiveEditor("3D Modeler") unit=oEditor.GetModelUnits() def getpts(pts_list): pts=[] segs=[] n=0 for x, y, z in pt...
Python
1
); config.ed25519_keys = Some(ed25519_keys); let mut binrep = Binrep::<NOOPProgress>::from_config(config).unwrap(); // new binrep instance let tmp = tempfile::tempdir().unwrap(); // new tmp dir binrep.pull("cargo", &v1, &tmp, true).await.unwrap(); } // delegate_impl // // Copyright (C) 2019 SOFe // //...
Rust
0
from fastapi import APIRouter, BackgroundTasks, Depends, Header, Query, Request from backend.api.v1.auth.services import WhatsappTokenValidator from backend.api.v1.webhook import examples from backend.api.v1.webhook.models import WhatsappWebhookUpdates from backend.api.v1.webhook.services import WhatsappService rout...
Python
1
output_dir.push("public"); let rendered_guide_path = output_dir.join("guide.html"); let mut rendered_guide = File::open(rendered_guide_path).expect("could not open rendered guide"); let mut contents = String::new(); rendered_guide .read_to_string(&mut contents) .expect("cou...
Rust
0
rip("!bp ") start = time() try: bp_link = await direct_link_checker(link, True) end = time() if not is_excep_link(link): bp_link = ( f"┎ <b>Source Link:</b> {link}\n┃\n┖ <b>Bypass Link:</b> {bp_link}" ) ...
Python
1
T> where O: BitOrder { unsafe { from_raw_parts_unchecked_mut( BitPtr::from_mut_slice(&mut self[..]), $n * T::Mem::BITS as usize, ) } } #[doc(hidden)] #[inline(always)] #[cfg(not(tarpaulin_include))] fn const_elts() -> usize { $n } } )+ }; } view_bits!( 1, 2, 3, 4, 5, 6,...
Rust
0
, num_program_data_slots, true)); new_population.push(vm::Program::new(&prog2, num_program_data_slots, true)); } // if the number of programs is odd, just copy one of the best ones without recombining if programs.len() % 2 == 1 { new_population.push(best_programs[rng.gen_range(0, best_progr...
Rust
0
]) << 8 | u16::cast_from(line[index])) } convert_u16 }; let output_data = &mut plane_data.data; let width = plane_data.cfg.width; let height = plane_data.cfg.height; for y in 0..height { // Filter: [4 -17 114 35 -9 1]/128, derived from a 6-tap Lanczos window. let in_...
Rust
0
# Arquivo: src/generators/train_fibonacci_2d.py import tensorflow as tf import numpy as np import os import matplotlib.pyplot as plt # Imports corrigidos para refletir a nova estrutura de pastas from src.models.wgan_dcgan_model import WGAN_GP from src.utils.utils_spectrogram import generate_spectrogram, IMG_SIZE # --...
Python
1
ch.cuda.empty_cache() # 假设args是你的参数配置,且已经正确设置 exp_main = Exp_Main(args) # 加载整个模型 exp_main.model = torch.load('/home/willy/research/apartment/checkpoints/Electricity_96_96_SegRNN_custom_ftM_sl96_pl96_dm512_dr0.1_rtgru_dwpmf_sl48_test_0_ausdata/complete_model.pt') exp_main.model.to(exp_main.device) # Make sure the mod...
Python
1
ell_params[f"sell-cross-{i}"] INT = self.sell_params[f"sell-int-{i}"] REAL = self.sell_params[f"sell-real-{i}"] DFIND = dataframe[IND] DFCRS = dataframe[CRS] if OPR == ">": conditions.append(DFIND > DFCRS) elif OPR == "=": ...
Python
1
match validation_errors { Ok(_) => (), Err(e) => { let res: DatabaseError = e.into(); return Err(res.into()); } }; let venue = event .venue(conn)? .ok_or_else(|| ApplicationError::unprocessable("Cannot publish this event on Facebook without a venu...
Rust
0
_ => Err(de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(FieldVisitor) } } struct DurationVisitor; impl<'de> Visitor<'de> for DurationVisitor { type Value...
Rust
0
front. * If capacity exceeded, evicts the LRU node. Args: key (int): The key to add or update. value (int): The value associated with the key. """ if key in self.hashmap: # Remove the old node self._remove(self.hashmap[key]) # Ins...
Python
1
features: `\"Win32_UI_Shell\"`*"] pub fn IUnknown_GetSite(punk: ::windows_sys::core::IUnknown, riid: *const ::windows_sys::core::GUID, ppv: *mut *mut ::core::ffi::c_void) -> ::windows_sys::core::HRESULT; #[doc = "*Required features: `\"Win32_UI_Shell\"`, `\"Win32_Foundation\"`*"] #[cfg(feature = "Win32_Fou...
Rust
0
_zero(value: &u64) -> bool { *value != 0 } fn as_mut(_value: &mut Self::Value) -> ReflectValueMut { unimplemented!() } } impl RuntimeTypeHashable for RuntimeTypeU64 { fn hash_map_get<'a, V>(map: &'a HashMap<u64, V>, key: ReflectValueRef) -> Option<&'a V> { match key { ...
Rust
0
inline] fn is_valid(&self) -> bool { self.week >= 1 && self.week <= self.year.num_weeks() } } impl<Y> Valid for ODate<Y> where Y: Year, { #[inline] fn is_valid(&self) -> bool { self.day >= 1 && self.day <= self.year.num_days() } } pub trait Year { fn is_leap(&self) -> bool;...
Rust
0