text
string
label_name
string
labels
int64
'checkpoint-epoch:{}{}{}.pth.tar'.format(epoch, monitor_str, best_str))) def poisson_blend(input, output, mask): """ * inputs: - input (torch.Tensor, required) Input tensor of Completion Network, ...
Python
1
#!/usr/bin/env python3 """Demo script showing multi-mirror source configuration.""" import asyncio import os from pypi_query_mcp.config import get_repository_manager, get_settings async def demo_multi_mirror_configuration(): """Demonstrate multi-mirror source configuration.""" print("🔧 PyPI Query MCP Serve...
Python
1
class Solution: def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: ans = [] max_heap = [[-nums[i], i] for i in range(k)] heapq.heapify(max_heap) ans.append(-max_heap[0][0]) for i in range(k, len(nums)): heapq.heappush(max_heap, [-n...
Python
1
าสโลวะเกีย' 'Spanish' 'ภาษาสเปน' 'Swedish' 'ภาษาสวีเดน' 'Thai' 'ภาษาไทย' 'Turkish' 'ตุรกี' use crate::internal::*; use tract_core::ops::element_wise::ElementWiseOp; submit_op_pulsifier!(ElementWiseOp, pulsify); fn pulsify( op: &ElementWiseOp, _source:...
Rust
0
0b0010_0000; const INPUT_MASK: u8 = 0b0000_1111; const SELECT_MASK: u8 = 0b0011_0000; pub enum Button { Right = 0, Left = 1, Up = 2, Down = 3, A = 4, B = 5, Select = 6, Start = 7, } pub struct Joypad { p1: u8, // P1 register pressed: [bool; 8], // Button pressed s...
Rust
0
torizing %s" % attr, tns) tensor_list.append((attr,tns)) if concat: return tf.concat([t[1] for t in tensor_list], axis=-1) else: return OrderedDict(tensor_list) def get_tensor_from_attr_dims( self, tensor, attr_list, attr_dims={}, attr_kwargs={}, sto...
Python
1
= pango_sys::pango_font_description_from_string(font_name.as_ptr()); gtk_sys::gtk_widget_modify_font(widget.to_glib_none().0, font_desc); pango_sys::pango_font_description_free(font_desc); } } pub fn text_buffer_insert_with_tag_by_name(buffer: &gtk::TextBuffer, ...
Rust
0
"""Physical unit conversion parameters (ro,vo) are not """ """compatible between this wrapper and the wrapped potential""" ) # Transfer unit system if set for wrapped potential, but not here phys_wrapped = get_physical(self._pot, include_set=True) if not self._roSet and phys_...
Python
1
s=building_data[0].keys()) writer.writeheader() writer.writerows(building_data) else: result_dictionary.pop("is_building", None) unit_data.append(result_dictionary) with open(config.unit_properties_path, 'w', newline='', encoding='utf-8') a...
Python
1
oes not include iteration at head of the weight list. Set # iteration to 0. if len(params) == len(weights) + 1: weights = [np.array(0)] + weights super(Adagrad, self).set_weights(weights) @classmethod def from_config(cls, config, custom_objects=None): """Creates an optimizer from its config. ...
Python
1
ptr.is_null(), "Null pointer passed."); Event(ptr) } /// Ensures this contains a null event and returns a mutable pointer to it. fn _alloc_new(&mut self) -> *mut cl_event { assert!(self.0.is_null(), "ocl_core::Event::alloc_new: An 'Event' cannot be \ used as target for event cre...
Rust
0
0][0] v[ind] = 1 vel[0:l,i] = v avg = np.nanmean(Faxons[:,0:40,:],axis=1) vel_row = [] avg_row=[]; for i in range(avg.shape[1]): avg_row.append(avg[:,i]) vel_row.append(vel[:,i]) avg_row = np.concatenate(avg_row) vel_row = np.concatenate(vel_row) ind = np...
Python
1
results scores = {} total_model_usage = None score_metadata = { "ensemble_size": ensemble_size, "prompt_count": len(prompts), "system_prompt_count": len(system_prompts), } for result in results: if isinstance(result, BaseException): continue # Skip faile...
Python
1
R: MonoOpcodeEnum = 307; pub const MonoOpcodeEnum_MONO_CEE_MONO_DYN_CALL: MonoOpcodeEnum = 308; pub const MonoOpcodeEnum_MONO_CEE_MONO_MEMORY_BARRIER: MonoOpcodeEnum = 309; pub const MonoOpcodeEnum_MONO_CEE_UNUSED71: MonoOpcodeEnum = 310; pub const MonoOpcodeEnum_MONO_CEE_UNUSED72: MonoOpcodeEnum = 311; pub const MonoO...
Rust
0
""" Problem: 237. Top K Frequent Elements Constraints: - 1 <= nums.length <= 10^5 - -10^4 <= nums[i] <= 10^4 - k is in the range [1, the number of unique elements in the array]. - The answer is guaranteed to be unique. Time Complexity: O(n log n) - Space Complexity: O(n) - """ # Original Solution class Solution: ...
Python
1
NOT_IMPLEMENTED) } fn peer_remove(_req: HttpRequest) -> HttpResponse { HttpResponse::new(http::StatusCode::NOT_IMPLEMENTED) } fn main() { let listen_address = "[::]:8088"; let mut ssl_acceptor = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap(); ssl_acceptor .set_private_key_file("...
Rust
0
\u{200d}♂\u{fe0f}", codepoint: "1F9DC 1F3FE 200D 2642 FE0F", status: crate::Status::FullyQualified, introduction_version: 5f32, name: "merman: medium-dark skin tone", group: "People & Body", subgroup: "person-fantasy", is_variant: false, variants: &[crate::Emoji { glyph: "🧜🏾\u{...
Rust
0
e for a transaction const G_TX_DATA_NON_ZERO: usize = 68; // Paid for every transaction const G_TRANSACTION: usize = 21000; // Paid for contract create const G_CREATE: usize = 32000; // verify signature pub fn verify_tx_sig(crypto: Crypto, hash: &H256, sig_bytes: &[u8]) -> Result<Vec<u8>, ()> { if sig_bytes.len() ...
Rust
0
lement(086); pub const FRANCIUM: Element = Element(087); pub const RADIUM: Element = Element(088); pub const ACTINIUM: Element = Element(089); pub const THORIUM: Element = Element(090); pub const PROTACTINIUM: Element = Element(091); pub const URANIUM: Element = Element(0...
Rust
0
/ Checking that the uncleaned_pubkeys are not pre-maturely removed // such that when the slots are rooted, and can actually be cleaned, then the // delta keys are still there. db.clean_accounts(None, false, None); db.print_accounts_stats("post-clean1"); // Check stores > 0 ...
Rust
0
->IsValid(); }) } pub fn module(&self) -> SBModule { cpp!(unsafe [self as "SBSymbolContext*"] -> SBModule as "SBModule" { return self->GetModule(); }) } pub fn line_entry(&self) -> SBLineEntry { cpp!(unsafe [self as "SBSymbolContext*"] -> SBLineEntry as "SBLin...
Rust
0
>(diagnostic); } } #[derive(Debug)] pub struct Files { files: codespan::Files<Arc<str>>, paths: HashMap<PathBuf, FileId>, pub internal: Span, } impl Files { pub fn query(&mut self, path: &std::path::Path) -> Option<(FileId, Arc<str>)> { match self.paths.get(path) { Some(file) => Some((file.clone(), self.fil...
Rust
0
e: {lr}") if momentum < 0.0: raise ValueError(f"Invalid momentum value: {momentum}") if weight_decay < 0.0: raise ValueError(f"Invalid weight_decay value: {weight_decay}") defaults = dict( lr=lr, momentum=momentum, dampening=dampening,...
Python
1
catch_expr, } } pub fn return_type(&self) -> &DamlType<'a> { &self.return_type } pub fn try_expr(&self) -> &DamlExpr<'a> { self.try_expr.as_ref() } pub fn var(&self) -> &str { &self.var } pub fn catch_expr(&self) -> &DamlExpr<'a> { self.ca...
Rust
0
''' Reverse words in a string medium string, split, reverse ''' ''' A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space. Return a string of the words in reverse order concatenated by a single space. Note that s may contain leading or trailing spaces or mult...
Python
1
n crate bytes; extern crate chrono; extern crate chrono_humanize; #[macro_use] extern crate clap; extern crate edgelet_core; extern crate failure; #[macro_use] extern crate futures; extern crate tabwriter; extern crate tokio; use futures::Future; mod error; mod list; mod logs; mod restart; mod unknown; mod version; ...
Rust
0
)] pub enum Type { /// The `bool` type. Bool, /// The `int{N}` type. Int(usize), /// The `uint{N}` type. UInt(usize), /// The custom user-defined type. Custom(String), } impl Default for Type { fn default() -> Self { Self::UInt(compiler_common::BITLENGTH_FIELD) } } impl...
Rust
0
#[doc = "0x2b4 - Cache Data Storage (mid-upper word)"] pub dataw2s3mu: DATAW2SMU, #[doc = "0x2b8 - Cache Data Storage (mid-lower word)"] pub dataw2s3ml: DATAW2SML, #[doc = "0x2bc - Cache Data Storage (lowermost word)"] pub dataw2s3lm: DATAW2SLM, #[doc = "0x2c0 - Cache Data Storage (uppermost...
Rust
0
# # animals = ['dog', 'cat', 'bird','fish'] # # # # humans = ["철수","영희","광수"] # # # # animals.extend(humans) # 리스트 확장 # # print(len(animals)) # # # # 값 추가 # # # animals.append('monkey') # # # # # # 값 삭제 # # # # animals.remove('monkey') # # # del animals[2] # # # print(animals) # # # animals.clear() # # # print(animals)...
Python
1
"""Implementation of FFN block in the style of Transformers.""" from functools import partial from torch import nn from src.models.sequence.base import SequenceModule from src.models.nn import LinearActivation, DropoutNd class FFN(SequenceModule): def __init__( self, d_input, e...
Python
1
iplication( input_state[0][col], 0x0b ) ^ multiplication( input_state[1][col], 0x0d ) ^ multiplication( input_state[2][col], 0x09 ) ^ multiplication( input_state[3][col], 0x0e ); } return output_state; } fn multiplication( multiplicand : u8, multiplier : u8 ) -> u8 { let mu...
Rust
0
continue res.append(r[offset+1:offset+1+length]) offset += length + 1 return res def _gen_text_field_samples(response, table: str) -> List[_Sample]: mysql_raw = response['_source']['layers']['mysql_raw'] mysql = response['_source']['layers']['mysql'] num_fields = int(mysql[0]['...
Python
1
from coincheck import order,market import settings from nose.tools import * import os,sys import time market_info = market.Market().ticker() def get_n_min_dai(minute=0,tz='UTC'): ''' return :minute: before time. ''' from datetime import datetime,timedelta from pytz import timezone return (date...
Python
1
sampsPerChan: uInt64, ) -> int32; } extern "C" { pub fn DAQmxCfgHandshakingTiming( taskHandle: TaskHandle, sampleMode: int32, sampsPerChan: uInt64, ) -> int32; } extern "C" { pub fn DAQmxCfgBurstHandshakingTimingImportClock( taskHandle: TaskHandle, sampleMode: in...
Rust
0
Article(pub_date=now, headline='ooF') a12.save() a13 = Article(pub_date=now, headline='foobarbaz') a13.save() a14 = Article(pub_date=now, headline='zoocarfaz') a14.save() a15 = Article(pub_date=now, headline='barfoobaz') a15.save() a16 = Article(pub_date=n...
Python
1
pub fn adc_isc_dcinss2(&self) -> ADC_ISC_DCINSS2R { let bits = ((self.bits >> 18) & 1) != 0; ADC_ISC_DCINSS2R { bits } } #[doc = "Bit 19 - Digital Comparator Interrupt Status on SS3"] #[inline(always)] pub fn adc_isc_dcinss3(&self) -> ADC_ISC_DCINSS3R { let bits = ((self.bits >...
Rust
0
(LR**3), axis=-1 ).real ) self._coef_5 = ( dt * jnp.mean( (-4 - 3 * LR - LR**2 + jnp.exp(LR) * (4 - LR)) / (LR**3), axis=-1 ).real ) def step_fourier( self, u_hat: Complex[Array, "E ... (N//2)+1"], ) -> Com...
Python
1
ame("host") .short("h") .long("host") .value_name("HOST") .help("xREPL host") .required(false), ) .arg( Arg::with_name("port") .short("p") .long("port") .value_name...
Rust
0
); } let client = builder.build().unwrap(); Self { token: Mutex::new(None), client, } } pub(crate) fn request<T>(&self) -> SpotifyRequest<'_, (), T> { SpotifyRequest { client: self, request: Builder::new(), body...
Rust
0
.72125391563537 */ // "ISS (ZARYA)\n1 25544U 98067A 08264.51782528 -.00002182 00000-0 -11606-4 0 2927\n2 25544 51.6416 247.4627 0006703 130.5360 325.0288 15.72125391563537" pub fn parse_tle(tle_str: &str) -> TLE { // let name = match &tle_str[0..23].lines().next() { // None => Str...
Rust
0
ome(13)); ast.nodes.assert_node(12, Some(13), None, None); ast.nodes.assert_node(13, Some(10), Some(12), Some(14)); ast.nodes.assert_node(14, Some(13), None, None); ast.nodes.assert_node(16, Some(6), Some(10), Some(18)); ast.nodes.assert_node(18, Some(16), None, None); as...
Rust
0
_u32(self.spacing[0])?; out.write_str(",")?; out.write_u32(self.spacing[1])?; out.write_str(" outline=")?; out.write_u32(self.outline)?; out.write_str("\n")?; Ok(()) } } pub struct CommonTag { pub line_height: u32, pub base: i32, pub scale_w: u32, pub...
Rust
0
not current_qubits.isdisjoint(next_qubits) and current_ancestors.isdisjoint(next_descendants) and current_descendants.isdisjoint(next_ancestors) ): # can be merged current_ancestors = current_ancestors |...
Python
1
ln!("{}", s); std::process::exit(0); } "-V" | "--version" => { println!("{} {}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION")); std::process::exit(0); } "-d" | "--debug" => { args.flag_debug = true; } "-v" | "--verbose"...
Rust
0
# # Copyright (c) 2023 Airbyte, Inc., all rights reserved. # import json from pathlib import Path from typing import Tuple from google.cloud import storage # type: ignore from google.oauth2 import service_account # type: ignore from pipelines import main_logger from pipelines.consts import GCS_PUBLIC_DOMAIN def u...
Python
1
# coding=utf-8 # Copyright 2018 The Tensor2Tensor Authors. # # 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 applicable...
Python
1
# Sample data containing multiple text items BASIC_EXAMPLE = { "session": { "session_id": "719f30a1-03bb-4d41-a654-138da5c43547", "user_id": "193a9e01-8849-4e1f-a42a-a859fa7f2ad3", "user_name_hash": "6511c5688bbb87798128695a283411a26da532df06e6e931a53416e379ddda0e", "platform": "red...
Python
1
STR", domain="slow") as fsm: with m.State("FETCH_INSTR"): m.d.slow += instr.eq(mem[pc[2:32]]) m.next = "FETCH_REGS" with m.State("FETCH_REGS"): m.d.slow += [ rs1.eq(regs[rs1Id]), rs2.eq(regs[rs2Id]) ...
Python
1
ue if the hostname is an IP address, False otherwise. """ if six.PY3 and isinstance(hostname, six.binary_type): # IDN A-label bytes are ASCII compatible. hostname = hostname.decode('ascii') families = [socket.AF_INET] if hasattr(socket, 'AF_INET6'): families.append(socket.AF_INE...
Python
1
ds)]) def forward(self, x): pred_invade = [] pred_surgery = [] x = self.maxpool(x) x = x.squeeze(2).squeeze(2).squeeze(2) for i in range(self.num_heads): pred_invade.append(self.invade_classifiers[i](x)) pred_surgery.append(self.surgery_classi...
Python
1
W,H,D=resolutions resolutions = torch.tensor(resolutions).float().to(device).view(-1) arrangeX = torch.linspace(0, W-1, W).long().to(device) arrangeY = torch.linspace(0, H-1, H).long().to(device) arrangeZ = torch.linspace(0, D-1, D).long().to(device) gridD, girdH, gridW = torch.meshgrid([arrangeZ, arrangeY, arra...
Python
1
tList", params, headers=headers) response = json.loads(body) model = models.DescribeIgnoreRuleEffectHostListResponse() model._deserialize(response["Response"]) return model except Exception as e: if isinstance(e, TencentCloudSDKException): ...
Python
1
usize, usize) { let offset = subslice.as_ptr() as usize - data.as_ptr() as usize; let mut line_breaks = memchr::memrchr_iter(b'\n', &data[..offset]); match line_breaks.next() { None => (1, offset + 1), Some(i) => (line_breaks.count() + 2, offset - i), } } /// Read a text file (UTF-8) into a string. fn read_tex...
Rust
0
import RPi.GPIO as GPIO from time import sleep import airtable as airtable # Pins for Motor Driver Inputs Motor1A = 35 Motor1B = 37 Motor1E = 38 SWIN1 = 18 #ground 14 SWIN2 = 16 #ground 20 def setup(): GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) # GPIO Numbering GPIO.setup(Motor1A,GPIO.OUT) ...
Python
1
use compressed LMDB') parser.add_argument("--batch_size", type=int, help="batch size for evaluation") parser.add_argument('--n_workers', type=int, default=4, help="number of data workers") parser.add_argument('--pin_mem', action='store_true', ...
Python
1
hw.clone(), irq.clone())); let joypad = Device::new(Joypad::new(hw.clone(), irq.clone())); let timer = Device::new(Timer::new(irq.clone())); let serial = Device::new(Serial::new(hw.clone(), irq.clone())); let mbc = Device::new(Mbc::new(hw.clone(), rom.to_vec())); let cgb = Device...
Rust
0
"""Tool to get the weather from openweathermap.""" from __future__ import annotations import os import httpx from pydantic import BaseModel, Field from portia.errors import ToolHardError, ToolSoftError from portia.tool import Tool, ToolRunContext class WeatherToolSchema(BaseModel): """Input for WeatherTool.""...
Python
1
"with_user_use"); assert_eq!( runner.ok("a {\ \n @import \"other\";\ \n}\n"), "b {\ \n c: d;\ \n}\n" ); } } #[test] #[ignore] // unexepected error fn property_only() { let runner = runner().with_cwd("property_only"); asser...
Rust
0
the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY ...
Rust
0
er { /// For inserts, we store a pointer to the leaf node containing the inserted item. This is only /// used for inserts so we don't need to modify multiple entries when the inserted item is /// moved. InsPtr(NonNull<NodeLeaf<YjsSpan2, DocRangeIndex, DEFAULT_IE, DEFAULT_LE>>), /// For deletes we n...
Rust
0
PROCESSOR_AUTO_STREAM_CAPS = 16i32; #[doc = "*Required features: `\"Win32_Graphics_Direct3D11\"`*"] pub const D3D11_VIDEO_PROCESSOR_AUTO_STREAM_CAPS_IMAGE_STABILIZATION: D3D11_VIDEO_PROCESSOR_AUTO_STREAM_CAPS = 32i32; #[doc = "*Required features: `\"Win32_Graphics_Direct3D11\"`*"] pub const D3D11_VIDEO_PROCESSOR_AUTO_S...
Rust
0
from google.cloud import bigquery; from google.cloud.bigquery import dbapi; import pandas as pd import pdb from dateutil.relativedelta import relativedelta def compute_paients_demog(client_name, patient_id , query_demog): # pdb.set_trace() client = bigquery.Client(client_name); conn = dbapi.connect(client...
Python
1
/// /// To convert a number `0-8` into [Operation](enum.Operation.html) use `Operation::from(number)`. pub fn from_symbol(symbol: u8) -> Result<Operation, String> { use Operation::*; match symbol { b'M' => Ok(AlnMatch), b'I' => Ok(Insertion), b'D' => Ok(Delet...
Rust
0
"def" .to_owned() .pipe_ref(|key| map.get_index_by_key(key)) .unwrap() .pipe(|index| map.get_key_by_index(index)), "def".to_owned().pipe(Rc::new).pipe_ref(Some), "exist", ); assert_eq!(map.get_key_by_index(Index::from(999)), None, "not exist"); } ...
Rust
0
} #[derive(PartialEq, Eq, Hash, Clone, Copy)] pub struct LiteralNumeric<'ast> { pub loc: Loc, pub span: Span, pub raw: &'ast [char], pub value: Numberic, } impl<'ast> fmt::Debug for LiteralNumeric<'ast> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "LiteralNumeric({:?...
Rust
0
fn main() -> IO<i64> { let ioval = IOGetInt(|i: i64| -> { return IOPutInt(i + 1, IORet(i +42)); }); return ioval; } use std::io::Error as IoError; use std::io::Cursor; use std::io::ErrorKind; use std::fmt::Debug; use std::marker::PhantomData; use std::path::Path; use fluvio_future::fs::File; us...
Rust
0
from os.path import join as opj import numpy as np from matplotlib import pyplot as plt from argparse import ArgumentParser def parse_args(): parser = ArgumentParser(description="flagperf_monitor_vis") parser.add_argument("--node_log_dir", type=str, required=True) args = parser.parse_args() return arg...
Python
1
ghtsAttributeMetadata): The attribute this trend is for. trend_metrics (google.ads.googleads.v21.services.types.TrendInsightMetrics): Metrics associated with this trend. trend (google.ads.googleads.v21.enums.types.InsightsTrendEnum.InsightsTrend): The direction of tre...
Python
1
(); } #[maybe_async] #[maybe_async_test] #[ignore] async fn test_user_unfollow_users() { let mut users = vec![]; let user_id1 = String::from("exampleuser01"); users.push(user_id1); oauth_client() .await .user_unfollow_users(&users) .await .unwrap(); } #[maybe_async] #[m...
Rust
0
= rooms.read().await; u64::try_from(rooms.len()).expect("too many rooms").write(&mut *writer).await?; for room_name in rooms.keys() { room_name.write(&mut *writer).await?; } } //TODO keep room list up to date let room = match LobbyClientMessage::read(&mut reader).await? {...
Rust
0
from queue import PriorityQueue # Define the city map city_map = [ [13, 13, 16, 8, 'x', 19, 1, 18, 13, 8, 'x', 7, 'x'], ['x', 13, 'x', 15, 'x', 12, 20, 1, 13, 19, 4, 17, 'x'], ['x', 12, 9, 11, 13, 12, 2, 12, 19, 5, 19, 16, 8], ['x', 12, 18, 19, 'x', 7, 'x', 12, 3, 2, 'x', 16, 11], ['x', 7, 'x', 'x...
Python
1
amedRead, FramedWrite}; #[test] fn decode() { let runtime = Runtime::new().unwrap(); let buf: &[u8] = include_bytes!(concat!( env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/case1.jsonrpc" )); let reader = FramedRead::new(buf, LspDecoder::default()); ...
Rust
0
import time class TelephoneSystem: def __init__(self): self.current_call = None self.call_status = "Idle" def make_call(self, number): if self.call_status == "Idle": self.current_call = number self.call_status = "Dialing" print(f"Dialing {number}..."...
Python
1
<'id, C> where C: GetUnchecked, { type Output = C::Item; #[inline(always)] fn index(&self, index: Index<'id>) -> &Self::Output { unsafe { self.container.unchecked(index.index) } } } impl<'id, C> ops::IndexMut<Index<'id>> for Container<'id, C> where C: GetUncheckedMut, { #[inline(al...
Rust
0
() } } #[allow(non_camel_case_types)] struct TestTypesSingular_bytes_field_acc_type; static TestTypesSingular_bytes_field_acc: TestTypesSingular_bytes_field_acc_type = TestTypesSingular_bytes_field_acc_type; impl ::protobuf::reflect::FieldAccessor<TestTypesSingular> for TestTypesSingular_bytes_field_acc_type { ...
Rust
0
-> bool { self & MASK_LEFT != MASK_LEFT } #[inline] pub fn empty_right(self) -> bool { self & MASK_RIGHT != MASK_RIGHT } #[inline] pub fn empty_bottom(self) -> bool { self & MASK_BOTTOM != MASK_BOTTOM } #[inline] pub fn empty_top(self) -> bool { se...
Rust
0
elf.all_candidates = [ self.data.get(i, 0)[0]['labels'][0] for i in range(self.num_episodes()) ] else: self.all_candidates = shared['all_candidates'] def add_candidates(self, sample, seed): """ Add 16 candidates...
Python
1
, cpu.read_pci(base) & !val.bits()); } } bitflags! { pub struct PciCommand: u32 { const IO_SPACE = 0b0000_0000_0000_0001; const MEM_SPACE = 0b0000_0000_0000_0010; const BUS_MASTER = 0b0000_0000_0000_0100; const INT_DISABLE = 0b0000_0100_0000_0000; } } /// PCI...
Rust
0
r!r"r#rrorlr$r)rs@r&rr'F3FcFdFFr%rc8\rSrSrS\S\S\SS4SjrS SjrS rg) _Textvaluer6rGr*Nc(XlX lX0lg)Nrr6rG)rirr6...
Python
1
&[], ) .unwrap(); ret.sort_by_key(|x| match x { Mismatch::MismatchLines(x) => x.source_path.clone(), Mismatch::MissingFile(x) => x.source_path.clone(), }); assert_eq!(ret.len(), 4); assert!( matches!(&ret[0], Mismatch::Mi...
Rust
0
ileSystemPathPlugValueWidget", "null" : "", } def __plugWidgetType( plug ) : return __widgetTypes.get( plug.node().parameterMetadata( plug, "widget" ) ) def __plugNoduleType( plug ) : if isinstance( plug, ( Gaffer.SplinefColor3fPlug, Gaffer.SplineffPlug ) ) : return "" elif plug.node().parameterMetadata( p...
Python
1
from typing import Optional from dynamite_nsm import exceptions from dynamite_nsm.services.base import process from dynamite_nsm.services.filebeat import profile as profile class CallFilebeatProcessError(exceptions.CallProcessError): def __init__(self, message): """Thrown when filebeat process encounters...
Python
1
import json, types, time from rbacx.storage import HotReloader class _Guard: def __init__(self): self.policy=None def set_policy(self, p): self.policy = p def test_hot_reloader_json_error_and_suppression(monkeypatch): class BadGoodSrc: def __init__(self): self._bad = True def etag(self): ...
Python
1
# -*- coding: utf-8 -*- # @Time : 2021/3/26 下午3:52 # @Author : gavin # @FileName: PNN.py # @Software: PyCharm # @Blog :https://blog.csdn.net/weixin_35154281 from ProductLayer import Productlayer from torch import nn from DNN import DNN import torch from torch.nn import functional as F class PNN(nn.Module): ...
Python
1
struct SeqNT { a: Vec<Simple<i32>>, n: Vec<Simple<i32>>, } #[test] fn test_seq_type() { let obj = SeqNT{ a: vec![], n: vec![ Simple{a: "foo".to_string(), b: 42, val: Body(3)}, Simple{a: "bar".to_string(), b: 2, val: Body(14)}, ], }; assert_eq!(to_xml(obj), r#"<SeqNT><Simple a="foo" b="42...
Rust
0
return 0, 0, 0 p_min, p_avg, p_max = stats(st.session_state.processing_latencies) u_min, u_avg, u_max = stats(st.session_state.ui_latencies) e_min, e_avg, e_max = stats(st.session_state.end_to_end_latencies) st.write(f"**Processing Latency:** min: `{p_min*1000:.2f}ms` avg: `{p_avg*1000:.2f}ms` ...
Python
1
memsz_cell(memsz: u64) -> Cell { Cell::new(&format!("{:<#x} ", memsz)).style_spec("bFg") } pub fn x_cell(num: u64) -> Cell { Cell::new(&format!("{:#x}", num)) } pub fn cell<T: ToString>(n: T) -> Cell { Cell::new(&format!("{}", n.to_string())) } pub fn bool_cell(b: bool) -> Cell { let cell = Cell::ne...
Rust
0
assert!(paste.store_url(None, &config).is_err()); config.server.max_content_length = Byte::from_str("30k").unwrap(); let url = String::from("https://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg"); let mut paste = Paste { data: url.as_bytes().to_vec(), type_: Past...
Rust
0
ng ",i," motor settings.") ref = init_pos[i] + amplitude * math.sin(2.0 * math.pi * freq * t) # Sine wave pattern v_ref = 2.0 * math.pi * freq * amplitude * math.cos(2.0 * math.pi * freq * t) p_err = ref - robot_if.GetMotor(i).GetPosition() # Pos...
Python
1
ding.Thread(target=self.docker_command, args=(container, command)) thread.start() return thread def start_container(self, container, scale): if self.check_compose_file(): try: if scale == 1: subprocess.run(["docker", "compose", "-f", compose_f...
Python
1
import numpy as np import paddle from .base_layers import Dense class AtomEmbedding(paddle.nn.Layer): """ Initial atom embeddings based on the atom type Parameters ---------- emb_size: int Atom embeddings size """ def __init__(self, num_embeddings, emb_size): sup...
Python
1
Set::new(), HashSet::new()); for path in home .filter_map(|dir| dir.ok()?.path().read_dir().ok()) .flat_map(|dir| dir.flatten()) .map(|s| s.path()) { if let Some(name) = path.file_name().and_then(|s| s.to_str()) { let CrateVersion { name, ...
Rust
0
"past_key_values": past_key_values, "use_cache": kwargs.get("use_cache"), "attention_mask": attention_mask, "pixel_values": pixel_values, "image_sizes": image_sizes, } ) return model_inputs # Copied from transformers.mo...
Python
1
idth - s.len() - 1) as i32, 1); } if self.feedback_countdown > 0 { self.feedback_countdown -= 1; self.text_buffer.draw_string(&self.feedback_string, 1, (self.view_height - 2) as i32); } self.text_buffer.print(); self.count += 1; } pub fn show_feedback(&mut self, string: S...
Rust
0
EAP_CONFIG_INPUT_FIELD_ARRAY; pub type EAP_CRED_RESP = EAP_CONFIG_INPUT_FIELD_ARRAY; pub type EAP_CRED_LOGON_REQ = EAP_CONFIG_INPUT_FIELD_ARRAY; pub type EAP_CRED_LOGON_RESP = EAP_CONFIG_INPUT_FIELD_ARRAY; STRUCT! {struct EAP_CRED_EXPIRY_REQ { curCreds: EAP_CONFIG_INPUT_FIELD_ARRAY, newCreds: EAP_CONFIG_INPUT_...
Rust
0
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2020 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
Python
1
{c_int}; #[derive(Debug)] #[repr(C)] pub struct CvPoint { pub x: c_int, pub y: c_int, } #[link(name="opencv", kind="static")] extern { fn cvPoint(x: c_int, y: c_int) -> CvPoint; } #[test] fn it_works() { unsafe { let p = cvPoint(4, 5); println!("got: {:?}", p); } } // Copyright (c...
Rust
0
}, 4 => { ::protobuf::rt::read_proto3_enum_with_unknown_fields_into(wire_type, is, &mut self.version, 4, &mut self.unknown_fields)? }, _ => { ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_f...
Rust
0
w2, w3, w4, w_o, p_drop_conv, p_drop_hidden) pofy_nodrop = convnet_model(X, w, w2, w3, w4, w_o, 0., 0.) params = [w, w2, w3, w4, w_o] else: raise RuntimeError("Unreachable") cost_drop = -cgt.mean(categorical.loglik(y, pofy_drop)) updates = rmsprop_updates(cost_drop, params, stepsize...
Python
1
import matplotlib.pyplot as plt from ppga.base.statistics import Statistics figsize = (16, 10) dpi = 200 def fitness_trend(stats: Statistics): generations = [g for g in range(len(stats.max))] plt.figure(figsize=figsize, dpi=dpi) plt.title("Fitness trend") plt.xlabel("Generation") plt.ylabel("Fi...
Python
1