file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
lib.rs
be used to prepare the initial state of the task. The frame provided to `init` is not dropped after this method returns, which means this initial state can contain Julia data. Whenever a `GeneratorTask` is successfully created a `GeneratorHandle` is returned. This handle can be used to call the `GeneratorTask` which c...
{ let io_err = IOError::new(ErrorKind::NotFound, julia_bindir_str); return Err(JlrsError::other(io_err))?; }
conditional_block
lib.rs
image_relative_path`. The first must be the absolute path to a /// directory that contains a compatible Julia binary (eg `${JULIA_DIR}/bin`), the second must /// be either an absolute or a relative path to a system image. /// /// This method will return an error if either of the two paths doesn't exist...
{ uv_async_send(handle.cast()) == 0 }
identifier_body
moves.go
Move.pos) newPos := PositionAdd(fullMove.pos, fullMove.move) board = ApplyMove(board, fullMove, updateStates) status := PieceStatus_Default if selectedPiece == Piece_Rock { status = PieceStatus_CastlingNotAllowed } SetBoardAt(&board, newPos, PieceInfo{ selectedPiece, status, info.color }) return board } // ...
if enPassantInfo.color != info.color && enPassantInfo.piece == Piece_Pawn && enPassantInfo.status == PieceStatus_EnPassantAllowed { tmpMoves := []Board{} tmpMoves = addPawnMove(board, info, fullMove, isEnPassant, tmpMoves) newMoves = append(newMoves, tmpMoves...) } } } return } // removeCheckM...
{ newx := pos.x + xDirection fullMove := FullMove{ pos, Move{ xDirection, yDirection } } if newx < 0 || newx > 7 { continue } enemyInfo := GetBoardAt(board, Position{ newx, newy }) isEnPassant := false if enemyInfo.piece != Piece_Empty { // normal capture if enemyInfo.color != info.color { new...
conditional_block
moves.go
ant { newMove = ApplyEnPassant(board, move, updateStates) } else { newMove = ApplyMove(board, move, updateStates) } newMoves = append(newMoves, newMove) return } availablePromotions := []Piece{ Piece_Queen, Piece_Rock, Piece_Bishop, Piece_Knight } for _, newPiece := range availablePromotions { statu...
initMovesMap
identifier_name
moves.go
Move.pos) newPos := PositionAdd(fullMove.pos, fullMove.move) board = ApplyMove(board, fullMove, updateStates) status := PieceStatus_Default if selectedPiece == Piece_Rock { status = PieceStatus_CastlingNotAllowed } SetBoardAt(&board, newPos, PieceInfo{ selectedPiece, status, info.color }) return board } // ...
newBoards := make([]Board, 0, len(boards)) for _, b := range boards { if len(GetPieces(b, Piece_King, color)) == 0 { // TODO: remove this, only here to debug fmt.Println("DEBUG BOARD!!") DrawBoard(b) } kingPos := GetPieces(b, Piece_King, color)[0] if !isUnderAttack(b, kingPos, color) { newBoar...
// removeCheckMoves gets rid of any moves that put the king under attack func removeCheckMoves(boards []Board, color PieceColor) []Board {
random_line_split
moves.go
Move.pos) newPos := PositionAdd(fullMove.pos, fullMove.move) board = ApplyMove(board, fullMove, updateStates) status := PieceStatus_Default if selectedPiece == Piece_Rock { status = PieceStatus_CastlingNotAllowed } SetBoardAt(&board, newPos, PieceInfo{ selectedPiece, status, info.color }) return board } // ...
if enemyInfo.piece != Piece_Empty { // normal capture if enemyInfo.color != info.color { newMoves = addPawnMove(board, info, fullMove, isEnPassant, newMoves) } } else { // try en-passant isEnPassant = true enPassantPos := Position{ newx, pos.y } enPassantInfo := GetBoardAt(board, enPas...
{ newMoves = moves yDirection := 1 if info.color == PieceColor_White { yDirection = -1 } newy := pos.y + yDirection if newy < 0 || newy > 7 { return } xDirections := []int{ -1, 1 } for _, xDirection := range xDirections { newx := pos.x + xDirection fullMove := FullMove{ pos, Move{ xDirection, yDirection ...
identifier_body
main.go
PROCESS): # # TYPE 1 (PING): # # SUBTYPE 1.1 (BEST): # # 1. ping. ...
{ fmt.Println(string(bytes)) return }
conditional_block
main.go
v2gen config (specify certain path with -config)") FlagRandom = flag.Bool("random", false, "random node index") FlagPing = flag.Bool("ping", true, "ping nodes") FlagDest = flag.String("dst", "https://cloudflare.com/cdn-cgi/trace", "test destination url (vmess ping only)") FlagCount = flag.Int("c", 3, ...
Err error } type PingInfoList []*PingInfo func (pf *PingInfoList) Len() int { return len(*pf) } func (pf *PingInfoList) Less(i, j int) bool { if (*pf)[i].Err != nil { return false } else if (*pf)[j].Err != nil { return true } if len((*pf)[i].Status.Errors) != len((*pf)[j].Status.Errors) { return le...
random_line_split
main.go
2gen config (specify certain path with -config)") FlagRandom = flag.Bool("random", false, "random node index") FlagPing = flag.Bool("ping", true, "ping nodes") FlagDest = flag.String("dst", "https://cloudflare.com/cdn-cgi/trace", "test destination url (vmess ping only)") FlagCount = flag.Int("c", 3, "p...
// set log level level, err := logrus.ParseLevel(*FlagLoglevel) if err != nil { logger.Panic(err) } logger.SetLevel(level) /* FLAG PART */ // if -v || trace, debug, info if *FlagVersion { fmt.Println(version()) return } else if level > logrus.ErrorLevel { fmt.Println(version()) } // if -init ...
{ flag.Parse() /* LOG PART */ logger := logrus.New() if *FlagLog != "-" && *FlagLog != "" { file, err := os.Create(*FlagLog) if err != nil { logrus.Fatal(err) } defer file.Close() _, err = file.Write([]byte(version() + "\n")) if err != nil { panic("cannot write into log file") } logger.O...
identifier_body
main.go
2gen config (specify certain path with -config)") FlagRandom = flag.Bool("random", false, "random node index") FlagPing = flag.Bool("ping", true, "ping nodes") FlagDest = flag.String("dst", "https://cloudflare.com/cdn-cgi/trace", "test destination url (vmess ping only)") FlagCount = flag.Int("c", 3, "p...
() int { return len(*pf) } func (pf *PingInfoList) Less(i, j int) bool { if (*pf)[i].Err != nil { return false } else if (*pf)[j].Err != nil { return true } if len((*pf)[i].Status.Errors) != len((*pf)[j].Status.Errors) { return len((*pf)[i].Status.Errors) < len((*pf)[j].Status.Errors) } return (*pf)[i]....
Len
identifier_name
round_trip.rs
99u64, 100], 6, 10); } #[test] fn float64_vec() { round_trip(&vec![0.99], 10, 16); round_trip(&vec![0.01, 0.02, 0.03, 0.04], 36, 65); } #[test] fn float32_vec() { round_trip(&vec![0.99f32], 6, 14); round_trip(&vec![0.01f32, 0.02, 0.03, 0.04], 20, 38); } #[test] fn lossy_f64_vec() { let mut data =...
{ // See also: 84d15459-35e4-4f04-896f-0f4ea9ce52a9 let data = HashMap::<u32, u32>::new(); round_trip(&data, 2, 8); }
identifier_body
round_trip.rs
01, 0.02, 0.03, 0.04], 36, 65); } #[test] fn float32_vec() { round_trip(&vec![0.99f32], 6, 14); round_trip(&vec![0.01f32, 0.02, 0.03, 0.04], 20, 38); } #[test] fn lossy_f64_vec() { let mut data = Vec::new(); for i in 0..50 { data.push(0.01 * i as f64); } let tolerance = -10; let op...
map_n_root
identifier_name
round_trip.rs
vec![99u64], 3, 8); round_trip(&vec![1u64], 2, 7); } #[test] fn int_vec() { round_trip(&vec![99u64, 100], 6, 10); } #[test] fn float64_vec() { round_trip(&vec![0.99], 10, 16); round_trip(&vec![0.01, 0.02, 0.03, 0.04], 36, 65); } #[test] fn float32_vec() { round_trip(&vec![0.99f32], 6, 14); ro...
// Show that this is much better than fixed, since this would be a minimum for exactly 0 schema overhead. assert_eq!(std::mem::size_of::<f64>() * data.len(), 400); } #[test] fn nested_float_vec() { round_trip(&vec![vec![10.0, 11.0], vec![], vec![99.0]], 24, 32); } #[test] fn array_tuple() { round_trip...
let options = encode_options! { options::LosslessFloat }; let binary = tree_buf::write_with_options(&data, &options); assert_eq!(binary.len(), 376);
random_line_split
chip8.rs
{ pub memory: [u8; 4096], // RAM pub reg: [u8; 16], // registers pub gfx: [u8; (PIXEL_W * PIXEL_H) as usize], // pixels stack: [u16; 16], // subroutine stack pub key: [u8; 16], // keypad idx: u16, // index register pc: u16, // program counter sp: u16, // s...
Chip8
identifier_name
chip8.rs
: 0x{:02x}, idx: 0x{:02x}, bytes at idx: {:02x?}", self.pc, self.idx, &self.memory[self.idx as usize..(self.idx+8) as usize]); println!("executing opcode {:02x?}", opcode); } match opcode { // skipping instruction 0XYZ // clear screen. (0x0, 0x0, 0xE, 0x0) => { self.draw_flag = true; ...
, // draw sprites at coordinate reg x, reg y (NOT X AND Y AS I ORIGINALLY DID) a width of 8 and height of z. // get z sprites from memory starting at location idx. (0xD, _, _, _) => { self.draw_flag = true; let mut pixel_unset = false; let sprites = &self.memory[self.idx as usize .. (self.idx + (z...
{ let rand_val: u8 = thread_rng().gen(); self.reg[_x] = yz & rand_val; self.pc += 2; }
conditional_block
chip8.rs
0x{:02x}, idx: 0x{:02x}, bytes at idx: {:02x?}", self.pc, self.idx, &self.memory[self.idx as usize..(self.idx+8) as usize]); println!("executing opcode {:02x?}", opcode); } match opcode { // skipping instruction 0XYZ // clear screen. (0x0, 0x0, 0xE, 0x0) => { self.draw_flag = true; ...
current_sprite_bit, current_coordinate % PIXEL_W as usize, current_coordinate / PIXEL_W as usize ); } if self.gfx[current_coordinate % self.gfx.len()] & current_sprite_bit != 0 { // if the current byte/pixel is 1, and the sprite bit is 1, pixel_unset = true; //
if super::DEBUG { println!("drawing pixel 0b{:b} at {}, {}",
random_line_split
mod.rs
PreferredType}, Context, JsArgs, JsBigInt, JsResult, JsValue, }; use boa_profiler::Profiler; use num_bigint::ToBigInt; use super::{BuiltInBuilder, BuiltInConstructor, IntrinsicObject}; #[cfg(test)] mod tests; /// `BigInt` implementation. #[derive(Debug, Clone, Copy)] pub struct BigInt;
impl IntrinsicObject for BigInt { fn init(realm: &Realm) { let _timer = Profiler::global().start_event(Self::NAME, "init"); BuiltInBuilder::from_standard_constructor::<Self>(realm) .method(Self::to_string, "toString", 0) .method(Self::value_of, "valueOf", 0) .sta...
random_line_split
mod.rs
Type}, Context, JsArgs, JsBigInt, JsResult, JsValue, }; use boa_profiler::Profiler; use num_bigint::ToBigInt; use super::{BuiltInBuilder, BuiltInConstructor, IntrinsicObject}; #[cfg(test)] mod tests; /// `BigInt` implementation. #[derive(Debug, Clone, Copy)] pub struct BigInt; impl IntrinsicObject for BigInt { ...
(realm: &Realm) { let _timer = Profiler::global().start_event(Self::NAME, "init"); BuiltInBuilder::from_standard_constructor::<Self>(realm) .method(Self::to_string, "toString", 0) .method(Self::value_of, "valueOf", 0) .static_method(Self::as_int_n, "asIntN", 2) ...
init
identifier_name
mod.rs
impl IntrinsicObject for BigInt { fn init(realm: &Realm) { let _timer = Profiler::global().start_event(Self::NAME, "init"); BuiltInBuilder::from_standard_constructor::<Self>(realm) .method(Self::to_string, "toString", 0) .method(Self::value_of, "valueOf", 0) .sta...
Ok(JsValue::new(JsBigInt::sub( &modulo, &JsBigInt::pow(&JsBigInt::new(2), &JsBigInt::new(i64::from(bits)))?, ))) } else
conditional_block
dhcpd.py
if p in event.connection.ports: if event.connection.ports[p].port_no == event.port: break else: return ipp = event.parsed.find('ipv4') if not ipp or not ipp.parsed: return if ipp.dstip not in (IP_ANY,IP_BROADCAST,self.ip_addr): return # Is it full and proper DHCP? ...
""" Launch DHCP server Defaults to serving 192.168.0.1 to 192.168.0.253 network Subnet to allocate addresses from first First'th address in subnet to use (256 is x.x.1.0 in a /16) last Last'th address in subnet to use count Alternate way to specify last address to use ip IP to use for D...
identifier_body
dhcpd.py
self.host_size = 32-network_size self.network = IPAddr(network) if last is None and count is None: self.last = (1 << self.host_size) - 2 elif last is not None: self.last = last elif count is not None: self.last = self.first + count - 1 else: raise RuntimeError("Cannot speci...
conn = core.openflow.getConnection(s.dpid) if not conn: continue if s.ports is None: return s port_no = conn.ports.get(port) if port_no is None: continue port_no = port_no.port_no for p in s.ports: p = conn.ports.get(p) if p is None: continue if p.port_...
continue
conditional_block
dhcpd.py
self.host_size = 32-network_size self.network = IPAddr(network) if last is None and count is None: self.last = (1 << self.host_size) - 2 elif last is not None: self.last = last elif count is not None: self.last = self.first + count - 1 else: raise RuntimeError("Cannot speci...
(self, item): item = IPAddr(item) if item in self.removed: return False n = item.toUnsigned() mask = (1<<self.host_size)-1 nm = (n & mask) | self.network.toUnsigned() if nm != n: return False if (n & mask) == mask: return False if (n & mask) < self.first: return False if (n & mask) ...
__contains__
identifier_name
dhcpd.py
self.host_size = 32-network_size self.network = IPAddr(network) if last is None and count is None:
else: raise RuntimeError("Cannot specify both last and count") self.removed = set() if self.count <= 0: raise RuntimeError("Bad first/last range") if first == 0: raise RuntimeError("Can't allocate 0th address") if self.host_size < 0 or self.host_size > 32: raise RuntimeError("Bad netwo...
self.last = (1 << self.host_size) - 2 elif last is not None: self.last = last elif count is not None: self.last = self.first + count - 1
random_line_split
WebGLCanvas.js
OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // // modified by Matthias Behrens (github.com/soliton4) for Broadway.js // universal module definition (function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define([], factory); ...
else { // Browser globals (root is window) root.WebGLCanvas = factory(); } }(this, function () { /** * This class can be used to render output pictures from an H264bsdDecoder to a canvas element. * If available the content is rendered using WebGL. */ function H264bsdCanvas(canvas, forceNoGL,...
{ // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. module.exports = factory(); }
conditional_block
WebGLCanvas.js
OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // // modified by Matthias Behrens (github.com/soliton4) for Broadway.js // universal module definition (function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define([], factory); ...
(canvas, forceNoGL, contextOptions) { this.canvasElement = canvas; this.contextOptions = contextOptions; if(!forceNoGL) this.initContextGL(); if(this.contextGL) { this.initProgram(); this.initBuffers(); this.initTextures(); }; }; /** * Returns true if the canvas supports WebG...
H264bsdCanvas
identifier_name
WebGLCanvas.js
OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // // modified by Matthias Behrens (github.com/soliton4) for Broadway.js // universal module definition (function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define([], factory); ...
; /** * Returns true if the canvas supports WebGL */ H264bsdCanvas.prototype.isWebGL = function() { return this.contextGL; }; /** * Create the GL context from the canvas element */ H264bsdCanvas.prototype.initContextGL = function() { var canvas = this.canvasElement; var gl = null; var validCont...
{ this.canvasElement = canvas; this.contextOptions = contextOptions; if(!forceNoGL) this.initContextGL(); if(this.contextGL) { this.initProgram(); this.initBuffers(); this.initTextures(); }; }
identifier_body
WebGLCanvas.js
OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // // modified by Matthias Behrens (github.com/soliton4) for Broadway.js // universal module definition (function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define([], factory); ...
gl.vertexAttribPointer(vertexPosRef, 2, gl.FLOAT, false, 0, 0); var texturePosBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, texturePosBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 0, 0, 0, 1, 1, 0, 1]), gl.STATIC_DRAW); var texturePosRef = gl.getAttribLocation(program, ...
var vertexPosRef = gl.getAttribLocation(program, 'vertexPos'); gl.enableVertexAttribArray(vertexPosRef);
random_line_split
thread_pool.rs
thread pool with `number_of_threads` threads. /// /// # Panics /// Panics if `number_of_threads` is 0. /// pub fn new(number_of_threads: usize) -> Self { assert!( number_of_threads > 0, "There must be at least one thread for the thread pool" ); let w...
/// Compute a task in the `ThreadPool` pub fn compute<F>(&self, task: F) where F: StaticTaskFn, { self.thread_pool .compute(Task::new(self.task_group_id, task)); } /// Execute a bunch of tasks in a scope that blocks until all tasks are finished. /// Provides a ...
{ self.thread_pool.target_thread_count }
identifier_body
thread_pool.rs
new thread pool with `number_of_threads` threads. /// /// # Panics /// Panics if `number_of_threads` is 0. /// pub fn new(number_of_threads: usize) -> Self { assert!( number_of_threads > 0, "There must be at least one thread for the thread pool" ); l...
(&self) -> usize { self.thread_pool.target_thread_count } /// Compute a task in the `ThreadPool` pub fn compute<F>(&self, task: F) where F: StaticTaskFn, { self.thread_pool .compute(Task::new(self.task_group_id, task)); } /// Execute a bunch of tasks in ...
degree_of_parallelism
identifier_name
thread_pool.rs
new thread pool with `number_of_threads` threads. /// /// # Panics /// Panics if `number_of_threads` is 0. /// pub fn new(number_of_threads: usize) -> Self { assert!( number_of_threads > 0, "There must be at least one thread for the thread pool" ); l...
else { parked_threads.push(unparker.clone()); parker.park(); } } } pub fn create_context(&self) -> ThreadPoolContext { ThreadPoolContext::new(self, self.next_group_id.fetch_add(1)) } fn compute(&self, task: Task) { self.global_queue....
{ // TODO: recover panics task.call_once(); }
conditional_block
thread_pool.rs
{ self.global_queue.push(task); // un-park a thread since there is new work if let Steal::Success(unparker) = self.parked_threads.steal() { unparker.unpark(); } } } impl Default for ThreadPool { fn default() -> Self { Self::new(num_cpus::get()) } } ///...
} }); assert_eq!(result.load(Ordering::SeqCst), NUMBER_OF_TASKS); }
random_line_split
ffi.py
new_game(self) -> "State": """Start a new game.""" return State(self, self.__sim.new_game()) def state_from_json(self, js: Union[Dict[str, Any], str]) -> "State": """Generate a State from the state json and this configuration. Parameters: js: a JSON object or s...
def __exit__(self, exc_type, exc_value, traceback): self.__del__() def clone(self) -> 'State': """Quickly make a copy of this state; should be more efficient than saving the JSON.""" return State(self.sim, state=self.get_state().copy()) def get_state(self) -> FrameState: ...
self.__state = None self.sim = None
identifier_body
ffi.py
: js: a JSON object or string containing a serialized state. """ state: FrameState = self.__sim.new_state(json_str(js)) return State(self, state=state) def to_json(self) -> Dict[str, Any]: """Get the configuration of this simulator/config as JSON""" return json.l...
raise ValueError( "Expected to apply action, but failed: {0}".format(action_int) )
conditional_block
ffi.py
(object): """ The Simulator is an instance of a game configuration. You can call new_game on it to begin. """ def __init__(self, game_name, sim=None): """ Construct a new instance. Parameters: game_name: one of "breakout", "amidar", etc. sim: option...
Simulator
identifier_name
ffi.py
, state=self.get_state().copy()) def get_state(self) -> FrameState: """Get the raw state pointer.""" assert self.__state is not None return self.__state def lives(self) -> int: """How many lives are remaining in the current state?""" return self.__state.lives() def...
return self.rstate.score()
random_line_split
api.d.ts
FromBuffer: (address: Buffer) => string; /** * Retrieves an assets name and symbol. * * @param assetID Either a {@link https://github.com/feross/buffer|Buffer} or an b58 serialized string for the AssetID or its alias. * * @returns Returns a Promise<Asset> with keys "name", "symbol...
* @param destinationChain The chainid for where the assets will be sent.
random_line_split
api.d.ts
extends JRPCAPI { /** * @ignore */ protected keychain: KeyChain; protected blockchainID: string; protected blockchainAlias: string; protected AVAXAssetID: Buffer; protected txFee: BN; /** * Gets the alias for the blockchainID if it exists, otherwise returns `undefined`. ...
EVMAPI
identifier_name
Kooi_NPacific_1D.py
with open('/home/dlobelle/Kooi_data/data_input/profiles.pickle', 'rb') as f: depth,T_z,S_z,rho_z,upsilon_z,mu_z = pickle.load(f) depth = np.array(depth) '''Loading the Kooi theoretical profiles for biological seawater properties: time-dependent. Generated in separate python file''' with open('/home/dlobelle/Kooi_...
plastic_particle
identifier_name
Kooi_NPacific_1D.py
the Kooi theoretical profiles for biological seawater properties: time-dependent. Generated in separate python file''' with open('/home/dlobelle/Kooi_data/data_input/profiles_t.pickle', 'rb') as p: depth,time,A_A_t,mu_A_t = pickle.load(p) time = np.linspace(time0,total_secs,dt_secs+1) '''General functio...
class plastic_particle(JITParticle): u = Variable('u', dtype=np.float32,to_write=False) v = Variable('v', dtype=np.float32,to_write=False) w = Variable('w',dtype=np.float32,to_write=True)
random_line_split
Kooi_NPacific_1D.py
: not time-dependent. Generated in separate python file''' with open('/home/dlobelle/Kooi_data/data_input/profiles.pickle', 'rb') as f: depth,T_z,S_z,rho_z,upsilon_z,mu_z = pickle.load(f) depth = np.array(depth) '''Loading the Kooi theoretical profiles for biological seawater properties: time-dependent. Generated...
else: w = 10.**(-3.76715 + (1.92944*math.log10(dstar)) - (0.09815*math.log10(dstar)**2.) - (0.00575*math.log10(dstar)**3.) + (0.00056*math.log10(dstar)**4.)) #------ Settling of particle ----- if delta_rho > 0: # sinks vs = (g * kin_visc * w * delta_rho)**(1./3.) else: #rises ...
w = (dstar**2.) *1.71E-4
conditional_block
Kooi_NPacific_1D.py
_pl = 1e-04 # radius of plastic (m): DEFAULT FOR FIG 1: 10-3 to 10-6 included but full range is: 10 mm to 0.1 um or 10-2 to 10-7 z = particle.depth # [m] t = particle.temp # [oC] sw_visc = particle.sw_visc # seawatar viscosity[kg m-1 s-1] aa = particle.aa ...
u = Variable('u', dtype=np.float32,to_write=False) v = Variable('v', dtype=np.float32,to_write=False) w = Variable('w',dtype=np.float32,to_write=True) temp = Variable('temp',dtype=np.float32,to_write=True) rho_sw = Variable('rho_sw',dtype=np.float32,to_write=False) kin_visc = Variable('kin_visc',dt...
identifier_body
main.rs
if std::ptr::null() == node { false } else { imgui::sys::ImGuiDockNode_IsSplitNode(node) } } } const STEP_COMMANDS: [&str; 5] = [ "step\n", "-data-list-register-values x 0 1 2 3 4 5 6 7 8 9 10\n", "-stack-list-locals 1\n", r#" -data-disassemble -s $pc -e "$p...
let _gl_context = window .gl_create_context() .expect("Couldn't create GL context"); gl::load_with(|s| video_subsystem.gl_get_proc_address(s) as _); let mut imgui = imgui::Context::create(); imgui.io_mut().config_flags |= imgui::ConfigFlags::DOCKING_ENABLE; let mut path = std::path...
{ let sdl_context = sdl2::init().unwrap(); let video_subsystem = sdl_context.video().unwrap(); let ttf_context = sdl2::ttf::init().unwrap(); { let gl_attr = video_subsystem.gl_attr(); gl_attr.set_context_profile(sdl2::video::GLProfile::Core); gl_attr.set_context_version(3, 0); ...
identifier_body
main.rs
std::ptr::null() == node
else { imgui::sys::ImGuiDockNode_IsSplitNode(node) } } } const STEP_COMMANDS: [&str; 5] = [ "step\n", "-data-list-register-values x 0 1 2 3 4 5 6 7 8 9 10\n", "-stack-list-locals 1\n", r#" -data-disassemble -s $pc -e "$pc + 20" -- 0 "#, r#" -data-read-memor...
{ false }
conditional_block
main.rs
std::ptr::null() == node { false } else { imgui::sys::ImGuiDockNode_IsSplitNode(node) } } } const STEP_COMMANDS: [&str; 5] = [ "step\n", "-data-list-register-values x 0 1 2 3 4 5 6 7 8 9 10\n", "-stack-list-locals 1\n", r#" -data-disassemble -s $pc -e "$pc +...
ui::docked_window(&ui, &mut gdb, "Vars", right_down, |ui, gdb| { ui.columns(2, im_str!("A"), true); for (k, v) in &gdb.variables { ui.text(k); ui.next_column(); ui.text(v); ui.next_column(); } }); ...
} else { ui.text_colored([x, x, x, 1.0f32], &l); } } });
random_line_split
main.rs
0); } if new_keys.contains(&Keycode::Left) { send_command("reverse-step\n", sender).unwrap(); } prev_keys = keys; imgui_sdl2.prepare_frame(imgui.io_mut(), &window, &event_pump.mouse_state()); let now = Instant::now(); let delta = now - last_frame; ...
main
identifier_name
trial.go
{ ContainerID: ptrs.Ptr(string(msg.ContainerID)), Log: msg.Message(), Level: msg.Level, }); err != nil { ctx.Log().WithError(err).Warn("dropping container log") } else { tasklogger.Insert(log) } case model.TaskLog: if log, err := t.enrichTaskLog(&msg); err != nil { ctx.Log().Wit...
{ if exit.Err != nil { ctx.Log().WithError(exit.Err).Error("trial allocation failed") } t.allocationID = nil prom.DisassociateJobExperiment(t.jobID, strconv.Itoa(t.experimentID), t.config.Labels()) // Decide if this is permanent. switch { case model.StoppingStates[t.state]: if exit.Err != nil { return t...
identifier_body
trial.go
// temporary failures fail the entire trial too easily. err = backoff.Retry(func() error { return task.DefaultService.StartAllocation( t.logCtx, ar, t.db, t.rm, specifier, ctx.Self().System(), func(ae *task.AllocationExited) { ctx.Tell(ctx.Self(), ae) }, ) }, launchRetries()) if err != nil { return ...
{ ctx.Log().WithError(err).Warn("could not terminate allocation after pause") }
conditional_block
trial.go
cover(); err != nil { return fmt.Errorf("recovering trial in prestart: %w", err) } } else { if err := t.create(ctx); err != nil { return fmt.Errorf("persisting trial in prestart: %w", err) } } t.logCtx = logger.MergeContexts(t.logCtx, logger.Context{ "trial-id": t.id, "trial-run-id": t....
(ctx *actor.Context, msg userInitiatedEarlyExit) error { switch msg.reason { case model.InvalidHP, model.InitInvalidHP: t.userInitiatedExit = &msg.reason // After a short time, force us to clean up if we're still handling messages. actors.NotifyAfter(ctx, InvalidHPKillDelay, model.StoppingKilledState) return ...
handleUserInitiatedStops
identifier_name
trial.go
cover(); err != nil { return fmt.Errorf("recovering trial in prestart: %w", err) } } else { if err := t.create(ctx); err != nil { return fmt.Errorf("persisting trial in prestart: %w", err) } } t.logCtx = logger.MergeContexts(t.logCtx, logger.Context{ "trial-id": t.id, "trial-run-id": t....
return task.DefaultService.StartAllocation( t.logCtx, ar, t.db, t.rm, specifier, ctx.Self().System(), func(ae *task.AllocationExited) { ctx.Tell(ctx.Self(), ae) }, ) }, launchRetries()) if err != nil { return err } t.allocationID = &ar.AllocationID return nil } const ( // InvalidHPKillDelay the ...
random_line_split
zhtta.rs
(|value| { //println(value.to_str()); visitor_count_local = *value; }); let mut stream = stream; let peer_name = WebServer::get_peer_name(&mut stream); ...
}); notify_chan.send(()); // Send incoming notification to responder task.
random_line_split
zhtta.rs
.clone()); // Spawn a task to handle the connection. spawn(proc() { let request_queue_arc = queue_port.recv(); //This updates counter by adding one to it. let local_arc_mut = portMut.recv(); ...
{ // Save stream in hashmap for later response. let mut stream = stream; let peer_name = WebServer::get_peer_name(&mut stream); let (stream_port, stream_chan) = Chan::new(); stream_chan.send(stream); unsafe { // Use an unsafe method, because TcpStream in Rust ...
identifier_body
zhtta.rs
::stat(other.path).size; if sizeOther > sizeSelf { return true; } else { return getPriority(self.peer_name.clone()) < getPriority(other.peer_name.clone()); } } } struct WebServer { ip: ~str, port: uint, www_dir_path: ~Path, request_que...
(stream: Option<std::io::net::tcp::TcpStream>, path: &Path) { let mut stream = stream; let msg: ~str = format!("Cannot open: {:s}", path.as_str().expect("invalid path").to_owned()); stream.write(HTTP_BAD.as_bytes()); stream.write(msg.as_bytes()); } // TODO: Safe visitor counter...
respond_with_error_page
identifier_name
zhtta.rs
<std::io::net::tcp::TcpStream>, visitor_count_local: &uint) { let mut stream = stream; let visitor_count_other : uint = visitor_count_local.clone(); let response: ~str = format!("{:s}{:s}<h1>Greetings, Krusty!</h1> <h2>Visitor count: {:u}</h2></body></html>\r\n"...
{ let semaphore = s.clone(); semaphore.acquire(); // TODO: Spawning more tasks to respond the dequeued requests concurrently. You may need a semophore to control the concurrency. semaphore.access( || { //Sending ...
conditional_block
resourceSubscription.go
client subscriber's subscription func (rs *ResourceSubscription) Unsubscribe(sub Subscriber) { rs.e.Enqueue(func() { if sub != nil { delete(rs.subs, sub) } // Directly unregister unsubscribed queries if rs.query != "" && len(rs.subs) == 0 { rs.unregister() } rs.e.removeCount(1) }) } func (rs *Re...
func (rs *ResourceSubscription) enqueueGetResponse(data []byte, err error) { rs.e.Enqueue(func() { rs, sublist := rs.processGetResponse(data, err) rs.e.mu.Unlock() defer rs.e.mu.Lock() if rs.state == stateError { for _, sub := range sublist { sub.Loaded(nil, rs.err) } } else { for _, sub := r...
{ subs := rs.subs c := int64(len(subs)) rs.subs = nil rs.unregister() rs.e.removeCount(c) rs.e.mu.Unlock() for sub := range subs { sub.Event(r) } rs.e.mu.Lock() }
identifier_body
resourceSubscription.go
return m.data, nil } // Collection represents a RES collection // https://github.com/resgateio/resgate/blob/master/docs/res-protocol.md#collections type Collection struct { Values []codec.Value data []byte } // MarshalJSON creates a JSON encoded representation of the collection func (c *Collection) MarshalJSON(...
{ data, err := json.Marshal(m.Values) if err != nil { return nil, err } m.data = data }
conditional_block
resourceSubscription.go
(e *EventSubscription, query string) *ResourceSubscription { return &ResourceSubscription{ e: e, query: query, subs: make(map[Subscriber]struct{}), } } // GetResourceType returns the resource type of the resource subscription func (rs *ResourceSubscription) GetResourceType() ResourceType { rs.e.mu.Lock()...
newResourceSubscription
identifier_name
resourceSubscription.go
ard if event happened before resource was loaded, // unless it is a reaccess. Then we let the event be passed further. if rs.state <= stateRequested && r.Event != "reaccess" { return } // Set event to target current version of the resource. r.Version = rs.version switch r.Event { case "change": if rs.reset...
rs.resetting = true
random_line_split
callgrind.ts
the given call-graph will actually be: // // start;backup;read 2 // start;backup;write 2 // end;backup;read 2 // end;backup;write 2 // // A particularly bad consequence is that the resulting flamegraph will suggest // that there was at some point a call stack that looked like // strat;backup;write, even th...
// This is the portion of the total time the given child spends within the // given parent that we'll attribute to this specific path in the call // tree. const ratio = callTreeWeight / callGraphWeightForFrame let selfWeightForFrame = callGraphWeightForFrame profile.enterFrame(fram...
}
random_line_split
callgrind.ts
>>() constructor(private fileName: string, private fieldName: string) {} private getOrInsertFrame(info: FrameInfo): Frame { return Frame.getOrInsert(this.frameSet, info) } private addToTotalWeight(frame: Frame, weight: number) { if (!this.totalWeights.has(frame)) { this.totalWeights.set(frame, ...
{ while (this.lineNum < this.lines.length) { const line = this.lines[this.lineNum++] if (/^\s*#/.exec(line)) { // Line is a comment. Ignore it. continue } if (/^\s*$/.exec(line)) { // Line is empty. Ignore it. continue } if (this.parseHeaderLine...
identifier_body
callgrind.ts
.has(child)) { childMap.set(child, weight) } else { childMap.set(child, childMap.get(child) + weight) } this.addToTotalWeight(parent, weight) } toProfile(): Profile { // To convert a call graph into a profile, we first need to identify what // the "root weights" are. "root weights"...
parseHeaderLine
identifier_name
callgrind.ts
the given call-graph will actually be: // // start;backup;read 2 // start;backup;write 2 // end;backup;read 2 // end;backup;write 2 // // A particularly bad consequence is that the resulting flamegraph will suggest // that there was at some point a call stack that looked like // strat;backup;write, even th...
// // To mitigate this explosion of the # of nodes, we ignore subtrees // whose weights are less than 0.01% of the total weight of the profile. return } // totalWeightForFrame is the total weight for the given frame in the // entire call graph. const callGraphWe...
{ // This assumption about even distribution can cause us to generate a // call tree with dramatically more nodes than the call graph. // // Consider a function which is called 1000 times, where the result is // cached. The first invocation has a complex call tree and may take ...
conditional_block
seedData.js
sRjTgj0nqHSxJGspuKC5LpMOFAZ1uc", owner: kring}, {name: "Robo Dog", description: "Whos mans?", likes: 512, genre: genres[5], image: "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTFOiXP0CwOmWn8jcWwsu5GEbsFiClNbh2jruY6ygRpW5kEh7eD", owner: kring}, {name: "Antique", description: "Take me back to 19...
{name: "Spotitube", description: "Pick your Poison", likes: 23, genre: genres[9], image: "https://techcrunch.com/wp-content/uploads/2016/07/spotify-over-youtube.png?w=730&crop=1", owner: rei}, ])
random_line_split
mesh_generator.rs
([0, 0, 0])), } } } impl MeshBuf { fn add_quad( &mut self, face: &OrientedCubeFace, quad: &UnorientedQuad, voxel_size: f32, u_flip_face: Axis3, layer: u32, ) { let start_index = self.positions.len() as u32; self.positions ....
{ let mut render_mesh = Mesh::new(PrimitiveTopology::TriangleList); let MeshBuf { positions, normals, tex_coords, layer, indices, extent, } = mesh_buf;...
conditional_block
mesh_generator.rs
_creations_per_frame(pool: &ComputeTaskPool) -> usize { 40 * pool.thread_num() } #[derive(Default)] pub struct MeshCommandQueue { commands: VecDeque<MeshCommand>, } impl MeshCommandQueue { pub fn enqueue(&mut self, command: MeshCommand) { self.commands.push_front(command); } pub fn is_emp...
(&mut self, commands: &mut Commands, meshes: &mut Assets<Mesh>) { self.entities.retain(|_, (entity, mesh)| { clear_up_entity(entity, mesh, commands, meshes); false }); self.remove_queue.retain(|_, (entity, mesh)| { clear_up_entity(entity, mesh, commands, meshe...
clear_entities
identifier_name
mesh_generator.rs
ations_per_frame(pool: &ComputeTaskPool) -> usize { 40 * pool.thread_num() } #[derive(Default)] pub struct MeshCommandQueue { commands: VecDeque<MeshCommand>, } impl MeshCommandQueue { pub fn enqueue(&mut self, command: MeshCommand)
pub fn is_empty(&self) -> bool { self.commands.is_empty() } pub fn len(&self) -> usize { self.commands.len() } pub fn clear(&mut self) { self.commands.clear(); } } // PERF: try to eliminate the use of multiple Vecs #[derive(Clone, Debug, Eq, PartialEq)] pub enum Mesh...
{ self.commands.push_front(command); }
identifier_body
mesh_generator.rs
_creations_per_frame(pool: &ComputeTaskPool) -> usize { 40 * pool.thread_num() } #[derive(Default)] pub struct MeshCommandQueue { commands: VecDeque<MeshCommand>, } impl MeshCommandQueue { pub fn enqueue(&mut self, command: MeshCommand) { self.commands.push_front(command); } pub fn is_emp...
) }); } } } LodChunkUpdate3::Merge(merge) => { for lod_key in merge.old_chunks.iter() { ...
create_mesh_for_chunk( lod_key, voxel_map, local_mesh_buffers, ),
random_line_split
mod.rs
} else { input.seek(io::SeekFrom::Start(init.stream_offset))?; let frame_index = FrameIndex::read(&mut input)?; frame_index.num_samples() }; Ok(format::Metadata { sample_rate: init.mp3_data.samplerate as u32, num_samples: Some(num_sampl...
from
identifier_name
mod.rs
Some(id3::Tag::read_from(&mut input)?) } else { None } }; // On very rare occasions, LAME is unable to find the start of the stream. index::find_stream(input)?; let stream_offset = input.seek(io::SeekFrom::Current(0))?; let hip: hip_t = hip_decode_init(); ...
} impl<F, R> Seekable for Decoder<F, R> where F: sample::Frame<Sample = i16>, R: io::Read + io::Seek + 'static, { fn seek(&mut self, position: u64) -> Result<(), SeekError> { let i = self .frame_index .frame_for_sample(position) .ok_or(SeekError::OutofRange { ...
{ self.sample_rate }
identifier_body
mod.rs
Some(id3::Tag::read_from(&mut input)?) } else { None } }; // On very rare occasions, LAME is unable to find the start of the stream. index::find_stream(input)?; let stream_offset = input.seek(io::SeekFrom::Current(0))?; let hip: hip_t = hip_decode_init(); ...
$dyn(Box::from(Decoder { input, input_buf: [0; MAX_FRAME_BYTES], hip: init.hip, frame_index, sample_rate, buffers: init.buffers, next_frame: 0, ...
num_samples: Some(frame_index.num_samples()), tag: init.tag, }; macro_rules! dyn_type { ($dyn:path) => {
random_line_split
aws.go
().WithRegion(idDoc.Region)) logrus.Debug("NewAwsClient built") return &AwsClient{ aws: client, instanceID: idDoc.InstanceID, privateIP: idDoc.PrivateIP, nicIPtoID: make(map[string]string), }, nil } // Cleanup removes any leftover resources func (c *AwsClient) Cleanup() error { logrus.Info("Delet...
time.Sleep(time.Duration(syncInterval) * time.Second) } } } } func (c *AwsClient) getRouteTable(filters []*ec2.Filter) (*ec2.RouteTable, error) { logrus.Debugf("Reading route table with filters: %+v", filters) input := &ec2.DescribeRouteTablesInput{ Filters: filters, } result, err := c.aws.DescribeR...
{ logrus.Infof("Failed to sync route table: %s", err) }
conditional_block
aws.go
Config().WithRegion(idDoc.Region)) logrus.Debug("NewAwsClient built") return &AwsClient{ aws: client, instanceID: idDoc.InstanceID, privateIP: idDoc.PrivateIP, nicIPtoID: make(map[string]string), }, nil } // Cleanup removes any leftover resources func (c *AwsClient) Cleanup() error { logrus.Info(...
(routes []*ec2.Route) []*ec2.Route { logrus.Debugf("Finding default route to internet GW") for _, route := range routes { if strings.HasPrefix(*route.GatewayId, "igw") { return []*ec2.Route{route} } } return nil } func filterRoutes(routes []*ec2.Route) (result []*ec2.Route) { logrus.Debugf("Filtering out r...
onlyDefaultRoute
identifier_name
aws.go
Client) Reconcile(rt *route.Table, eventSync bool, syncInterval int) { logrus.Debug("Entering Reconcile loop") err := c.lookupAwsSubnet() if err != nil { logrus.Panicf("Failed to lookupSubnet: %s", err) } err = c.ensureRouteTable() if err != nil { logrus.Panicf("Failed to ensure route table: %s", err) } ...
{ OUTER: for prefix, nextHop := range rt.Routes { ip, _, err := net.ParseCIDR(prefix) if err != nil { logrus.Infof("Failed to parse prefix: %s", prefix) continue } for _, subnet := range awsReservedRanges { if subnet != nil && subnet.Contains(ip) { logrus.Debugf("Ignoring IP from AWS reserved ran...
identifier_body
aws.go
idDoc.PrivateIP, nicIPtoID: make(map[string]string), }, nil } // Cleanup removes any leftover resources func (c *AwsClient) Cleanup() error { logrus.Info("Deleting own route table") myRouteTable, err := c.getRouteTable( []*ec2.Filter{ { Name: aws.String("tag:name"), Values: aws.StringSlice([]str...
} }(route, &wg)
random_line_split
table.d.ts
previously used `RenderRow` is added; else a new * `RenderRow` is * created. Once the list is complete and all data objects have been itereated * through, a diff is performed to determine the changes that need to be made to the rendered rows. * * @docs-private */ export interface RenderRow<T> { data: T; d...
export declare class CdkTable<T> implements AfterContentChecked, CollectionViewer, OnDestroy, OnInit { protected readonly _differs: IterableDiffers; protected readonly _changeDetectorRef: ChangeDetectorRef; protected readonly _elementRef: ElementRef; protected readonly _dir: Directionality; private ...
* Uses the dataSource input to determine the data to be rendered. The data can be provided either * as a data array, an Observable stream that emits the data array to render, or a DataSource with a * connect function that will return an Observable stream that emits the data array to render. */
random_line_split
table.d.ts
tlet { viewContainer: ViewContainerRef; elementRef: ElementRef; constructor(viewContainer: ViewContainerRef, elementRef: ElementRef); static ɵfac: ɵngcc0.ɵɵFactoryDef<FooterRowOutlet, never>; static ɵdir: ɵngcc0.ɵɵDirectiveDefWithMeta<FooterRowOutlet, "[footerRowOutlet]", never, {}, {}, never>; } /*...
mplements RowOu
identifier_name
strategy.py
:currDay] finVal = -1 * ((close - opens) / ((high - low) + 0.001)).iloc[-1] finVal[np.abs(finVal) < threshold] = 0.0 finVal[np.abs(finVal) > 5.0] = np.sign(finVal) * 5.0 order = pd.DataFrame(0, index = backData['open'].columns, columns = ['signal', 'qty', 'position']) order['s...
def getVolAvgPrice(self, opens, close, vol, left, right): ''' Computes the volume weighted price for the range [left, right) price = (open + close)/2 ''' avgPrice = (opens.iloc[left:right] + close.iloc[left:right])/2.0 volAvgPrice = (avgPrice * vol[left:right]).sum...
if (self.currSamples >= self.winSize): # Updating the queue and removing elements from the tree for stock in self.stockList: lastVal = self.gapQueue[stock].popleft() self.orderedGaps[stock].remove(lastVal) self.currSamples -= 1 for stock, gap ...
identifier_body
strategy.py
:currDay] finVal = -1 * ((close - opens) / ((high - low) + 0.001)).iloc[-1] finVal[np.abs(finVal) < threshold] = 0.0 finVal[np.abs(finVal) > 5.0] = np.sign(finVal) * 5.0 order = pd.DataFrame(0, index = backData['open'].columns, columns = ['signal', 'qty', 'position']) order['s...
order = pd.DataFrame(0, index = backData['open'].columns, columns = ['signal', 'qty', 'position']) opens = backData['open'][:currDay] close = backData['close'][:currDay] retVal = self.getReturn(self.retPeriod, opens) rollVol = self.getRollVol(self.volLookback, opens) a...
return rollVol def generateSignal(self, backData, currDay):
random_line_split
strategy.py
currDay] finVal = -1 * ((close - opens) / ((high - low) + 0.001)).iloc[-1] finVal[np.abs(finVal) < threshold] = 0.0 finVal[np.abs(finVal) > 5.0] = np.sign(finVal) * 5.0 order = pd.DataFrame(0, index = backData['open'].columns, columns = ['signal', 'qty', 'position']) order['si...
(Strategy): def __init__(self, config): self.volLookback = config['VOL_LOOKBACK'] self.retPeriod = config['RET_PERIOD'] self.stdDevMethod = config['STD_DEV_METHOD'] self.lag = config['LAG'] # self.volLookback = volLookback # self.retPeriod = retPeriod ...
SimpleVol
identifier_name
strategy.py
currDay] finVal = -1 * ((close - opens) / ((high - low) + 0.001)).iloc[-1] finVal[np.abs(finVal) < threshold] = 0.0 finVal[np.abs(finVal) > 5.0] = np.sign(finVal) * 5.0 order = pd.DataFrame(0, index = backData['open'].columns, columns = ['signal', 'qty', 'position']) order['si...
else: rollVol = np.std(retData) # print rollVol # return rollVol.iloc[-1] return rollVol def generateSignal(self, backData, currDay): order = pd.DataFrame(0, index = backData['open'].columns, columns = ['signal', 'qty', 'position']) opens = backData['o...
retData = retData ** 2 ewmRet = retData.ewm(span = period).mean() rollVol = np.sqrt(ewmRet) if (debug): print 'Before', retData print 'EWM', ewmRet.iloc[-1] print 'After ema:', rollVol.iloc[-1]
conditional_block
rectAreaLightShadow.ts
const directionalLightCamera = directionalLight.shadow.camera as THREE.OrthographicCamera; directionalLightCamera.far = 20; scene.add(directionalLight); const rectAreaLight = new THREE.RectAreaLight(0xffffff, 100, 1, 1); const viewportSize = new THREE.Vector2(width, height); //const rectA...
random_line_split
rectAreaLightShadow.ts
AreaLightShadow = (canvas: any) => { const width = window.innerWidth; const height = window.innerHeight; const renderer = new THREE.WebGLRenderer({canvas: canvas, antialias: true, alpha: true}) renderer.setSize(width, height) renderer.setPixelRatio(window.devicePixelRatio); renderer.shadowMap.en...
const generalUiProperties = { 'light source': 'rectAreaLight', 'scene volume': sceneBoxHelper.visible, 'shadow volume': shadowBoxHelper.visible, 'debug shadow map': false, 'debug output': 'off', }; setLightSource(generalUiProperties['light source']); const d...
{ shadowDebugPlane = new THREE.Mesh( new THREE.PlaneGeometry(5, 5), new THREE.MeshBasicMaterial({ map: rectAreaLightAndShadow.shadowMapTexture }) ); shadowDebugPlane.position.x = -8; shadowDebugPlane.position.y = 3; shadowDebugPlane.visible = false; ...
conditional_block
test_sync.py
, JoinRules from synapse.api.errors import Codes, ResourceLimitError from synapse.api.filtering import Filtering from synapse.api.room_versions import RoomVersions from synapse.handlers.sync import SyncConfig, SyncResult from synapse.rest import admin from synapse.rest.client import knock, login, room from synapse.serv...
# Blow away caches (supported room versions can only change due to a restart). self.store.get_rooms_for_user_with_stream_ordering.invalidate_all() self.store.get_rooms_for_user.invalidate_all() self.store._get_event_cache.clear() self.store._event_ref.clear() # The roo...
self.get_success( self.hs.get_datastores().main.db_pool.simple_update( "rooms", keyvalues={"room_id": room_id}, updatevalues={"room_version": "unknown-room-version"}, desc="updated-room-version", ) ...
conditional_block
test_sync.py
Types, JoinRules from synapse.api.errors import Codes, ResourceLimitError from synapse.api.filtering import Filtering from synapse.api.room_versions import RoomVersions from synapse.handlers.sync import SyncConfig, SyncResult from synapse.rest import admin from synapse.rest.client import knock, login, room from synapse...
login.register_servlets, room.register_servlets, ] def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None: self.sync_handler = self.hs.get_sync_handler() self.store = self.hs.get_datastores().main # AuthBlocking reads from the hs' config on init...
"""Tests Sync Handler.""" servlets = [ admin.register_servlets, knock.register_servlets,
random_line_split
test_sync.py
, JoinRules from synapse.api.errors import Codes, ResourceLimitError from synapse.api.filtering import Filtering from synapse.api.room_versions import RoomVersions from synapse.handlers.sync import SyncConfig, SyncResult from synapse.rest import admin from synapse.rest.client import knock, login, room from synapse.serv...
(self) -> None: """Rooms shouldn't appear under "joined" if a join loses a race to a ban. A complicated edge case. Imagine the following scenario: * you attempt to join a room * racing with that is a ban which comes in over federation, which ends up with an earlier stream_ord...
test_ban_wins_race_with_join
identifier_name
test_sync.py
, sync_config) ) # Test that global lock works self.auth_blocking._hs_disabled = True e = self.get_failure( self.sync_handler.wait_for_sync_for_user(requester, sync_config), ResourceLimitError, ) self.assertEqual(e.value.errcode, Codes.RESOURCE_LI...
"""Generate a sync config (with a unique request key).""" global _request_key _request_key += 1 return SyncConfig( user=UserID.from_string(user_id), filter_collection=Filtering(Mock()).DEFAULT_FILTER_COLLECTION, is_guest=False, request_key=("request_key", _request_key), ...
identifier_body
start-trip.js
Style: {} } this.action = null; } componentWillMount() { if (Cookies.get('user_email', 'auth_token')) { return true; } else { hashHistory.replace('/'); } } dateChangeHandler(dateString) { document.querySelector('.games').classList.remove('hide'); this.setState({startDate: dateString}); ...
else{ console.log("else ran"); hashHistory.push('/itinerary'); } } freeDayHandler(){ console.log('free day added'); } dataHandler(data) { switch (this.action){ case 'add': this.addGameHandler(data); break; case 'get': ::this.getIteneraryHandler(data); // hashHistory....
{ let local_datetime = this.state.startDate; ajax({ url:'https://shielded-hollows-39012.herokuapp.com/selectgame', type: 'POST', data: {"local_datetime": local_datetime, "itinerary_id": Cookies.get('itinerary_id'), "game_number": id.id }, headers: { 'X-Auth-Token': Cookies.get('au...
conditional_block
start-trip.js
Style: {} } this.action = null; } componentWillMount() { if (Cookies.get('user_email', 'auth_token')) { return true; } else { hashHistory.replace('/'); } } dateChangeHandler(dateString) { document.querySelector('.games').classList.remove('hide'); this.setState({startDate: dateString}); ...
this.setState({citiesWithGames: [{id:1, title: "Loading..."}]}); ///////Below, send them the city/state data. Will need to make an ajax call first ajax({ url:'https://shielded-hollows-39012.herokuapp.com/nextgame', type: 'POST', data: {"itinerary_id": Cookies.get ('itinerary_id')}, header...
{ document.querySelector('.calendar').classList.add('calendar-hidden'); document.querySelector('#show-calendar').classList.remove('show-calendar'); let local_datetime = this.state.startDate; ////////////UNCOMMENT TO TEST BACKEND DATA ajax({ url:'https://shielded-hollows-39012.herokuapp.com/selec...
identifier_body
start-trip.js
Style: {} } this.action = null; } componentWillMount() { if (Cookies.get('user_email', 'auth_token')) { return true; } else { hashHistory.replace('/'); } } dateChangeHandler(dateString) { document.querySelector('.games').classList.remove('hide'); this.setState({startDate: dateString}); ...
(){ let { citiesWithGames, startDate } = this.state; let gameDate = function(){ return moment(startDate).format('dddd, MMMM Do YYYY') === "Invalid date" ? "Click calendar to see available games" : moment(startDate).format('dddd, MMMM Do YYYY')} return( <div> <header> <Link to="/start-trip"><h1 id=...
render
identifier_name
start-trip.js
var directionsService = new google.maps.DirectionsService; var directionsDisplay = new google.maps.DirectionsRenderer; var mapDiv = document.getElementById('map'); this.setState({ mapProps: { center: {lat: 44.540, lng: -78.546}, zoom: 8, styles: [ { ...
<div id='game-picker'></div> <SSF onData={::this.dataHandler}>
random_line_split
day3.rs
other_contains_horiz, other_contains_vert) = other.contains_edge_of(self); (self_contains_horiz || other_contains_horiz) && (self_contains_vert || other_contains_vert) } } #[test] fn test_intersection() { const CLAIM_TO_COMPARE_TO: &'static str = "#0 @ 2,2: 3x3"; let claim: Claim = CLAIM_TO_COMPARE...
{ (&mut claims[i]).1 = false; (&mut claims[j]).1 = false; }
conditional_block
day3.rs
to call this twice! fn contains_edge_of(&self, other: &Self) -> (bool, bool) { let intersects_horizontally = { let bottom_in_horizontal_band = self.bottom > other.top && self.bottom <= other.bottom; let top_in_horizontal_band = self.top >= other.top && self.top < other.bottom; ...
() { const CLAIM_TO_COMPARE_TO: &'static str = "#0 @ 2,2: 3x3"; let claim: Claim = CLAIM_TO_COMPARE_TO.parse().unwrap(); for other in &[ // Close but not touching "#0 @ 1,1: 1x1", "#0 @ 2,1: 1x1", "#0 @ 3,1: 1x1", "#0 @ 4,1: 1x1", "#0 @ 5,1: 1x1", "#0...
test_intersection
identifier_name
day3.rs
encompasses first "#0 @ 1,1: 5x5", // First encompasses other "#0 @ 3,3: 1x1", // Edges "#0 @ 1,1: 2x2", "#0 @ 2,1: 2x2", "#0 @ 3,1: 2x2", "#0 @ 3,2: 2x2", "#0 @ 3,3: 2x2", "#0 @ 2,3: 2x2", "#0 @ 1,3: 2x2", "#0 @ 1,2: 2x2",...
right, .. }| { for y in *top..*bottom { for x in *left..*right {
random_line_split
day3.rs
intersects_horizontally = { let bottom_in_horizontal_band = self.bottom > other.top && self.bottom <= other.bottom; let top_in_horizontal_band = self.top >= other.top && self.top < other.bottom; bottom_in_horizontal_band || top_in_horizontal_band }; let intersects_ve...
{ assert_eq!(day3_part1(HINT_INPUT), HINT_EXPECTED_PART1_OUTPUT); }
identifier_body
train.py
privately payload = {"text": text} requests.post(url, json=payload) def get_model_and_tokenizer(args, **kwargs): # Here, you also need to define tokenizer as well # since the type of tokenizer depends on the model NUM_LABELS = 30 model = None tokenizer = None if args.model.lower().c...
VAL_BATCH_SIZE = args.val_batch_size if args.val_batch_size else BATCH_SIZE MAX_PAD_LEN = args.max_pad_len
random_line_split
train.py
(parser): # Set random seed parser.add_argument('--seed', type=int, default=None, help="random seed (default: None)") parser.add_argument('--verbose', type=str, default="n", choices=["y", "n"], help="verbose (default: n)") # Container environment par...
parse_arguments
identifier_name
train.py
_every', type=int, metavar='N', default=500, help="save model interval for every N steps (default: 500)") parser.add_argument('--save_total_limit', type=int, metavar='N', default=5, help="save total limit (choosing the best eval scores) (default: 5)") # Learning ...
bel = [] with open('dict_label_to_num.pkl', 'rb') as f: dict_label_to_num = pickle.load(f) for v in label: num_label.append(dict_label_to_num[v]) return num_label ###################################### # DATA LOADER RELATED ###################################### # TODO: bucketed_batch_in...
""" validation을 위한 metrics function """ labels = pred.label_ids preds = pred.predictions.argmax(-1) probs = pred.predictions # calculate accuracy using sklearn's function f1 = klue_re_micro_f1(preds, labels) auprc = klue_re_auprc(probs, labels) acc = metrics.accuracy_score(labels, preds) #...
identifier_body
train.py
save_every', type=int, metavar='N', default=500, help="save model interval for every N steps (default: 500)") parser.add_argument('--save_total_limit', type=int, metavar='N', default=5, help="save total limit (choosing the best eval scores) (default: 5)") # Learn...
###################################### # KLUE SPECIFICS ###################################### def klue_re_micro_f1(preds, labels): """KLUE-RE micro f1 (except no_relation)""" label_list = ['no_relation', 'org:top_members/employees', 'org:members', 'org:product', 'per:title', 'org:alterna...
dirs = glob.glob(f"{path}*") matches = [re.search(rf"%s(\d+)" % path.stem, d) for d in dirs] i = [int(m.groups()[0]) for m in matches if m] n = max(i) + 1 if i else 2 path = f"{path}{n}" if not os.path.exists(path): os.mkdir(path) return path
conditional_block
InternetMonitorClient.ts
import { getRetryPlugin, resolveRetryConfig, RetryInputConfig, RetryResolvedConfig } from "@smithy/middleware-retry"; import { HttpHandler as __HttpHandler } from "@smithy/protocol-http"; import { Client as __Client, DefaultsMode as __DefaultsMode, SmithyConfiguration as __SmithyConfiguration, SmithyResolvedCon...
import { RegionInputConfig, RegionResolvedConfig, resolveRegionConfig } from "@smithy/config-resolver"; import { getContentLengthPlugin } from "@smithy/middleware-content-length"; import { EndpointInputConfig, EndpointResolvedConfig, resolveEndpointConfig } from "@smithy/middleware-endpoint";
random_line_split
InternetMonitorClient.ts
, SmithyConfiguration as __SmithyConfiguration, SmithyResolvedConfiguration as __SmithyResolvedConfiguration, } from "@smithy/smithy-client"; import { BodyLengthCalculator as __BodyLengthCalculator, CheckOptionalClientConfig as __CheckOptionalClientConfig, Checksum as __Checksum, ChecksumConstructor as __Ch...
InternetMonitorClient
identifier_name
livestream.rs
::mpsc as bchan; pub type VideoFrame=(Vec<u8>, usize, usize, usize); use crate::inference_engine::{start_inference_service, InfererHandler}; use crate::time_now; // 10 Frames as a batch. pub struct VideoBatchContent{ pub data: Vec<u8>, pub sizes: [usize; 10], pub capture_timestamps: [usize; 10], ...
()->Self{ LiveStream{ next_client_id: 0, clients: BTreeMap::new(), cached_frames: RingBuffer::new(20), channel: channel(5), first_frame: None } } pub fn get_sender(&self)->Sender<IncomingMessage>{ self.channel.0.clone(...
new
identifier_name