file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
pageserver.rs | //
// Main entry point for the Page Server executable
//
use log::*;
use pageserver::defaults::*;
use serde::{Deserialize, Serialize};
use std::{
env,
net::TcpListener,
path::{Path, PathBuf},
str::FromStr,
thread,
};
use zenith_utils::{auth::JwtAuth, logging, postgres_backend::AuthType};
use anyho... |
// Initialize tenant manager.
tenant_mgr::init(conf);
// keep join handles for spawned threads
let mut join_handles = vec![];
// initialize authentication for incoming connections
let auth = match &conf.auth_type {
AuthType::Trust | AuthType::MD5 => None,
AuthType::ZenithJWT ... | {
info!("daemonizing...");
// There shouldn't be any logging to stdin/stdout. Redirect it to the main log so
// that we will see any accidental manual fprintf's or backtraces.
let stdout = log_file.try_clone().unwrap();
let stderr = log_file;
let daemonize = Daemonize::... | conditional_block |
pageserver.rs | //
// Main entry point for the Page Server executable
//
use log::*;
use pageserver::defaults::*;
use serde::{Deserialize, Serialize};
use std::{
env,
net::TcpListener,
path::{Path, PathBuf},
str::FromStr,
thread,
};
use zenith_utils::{auth::JwtAuth, logging, postgres_backend::AuthType};
use anyho... |
auth_validation_public_key_path,
auth_type,
relish_storage_config,
})
}
}
fn main() -> Result<()> {
let arg_matches = App::new("Zenith page server")
.about("Materializes WAL stream to pages and serves them to the postgres")
.arg(
Arg::wit... | random_line_split | |
executor.rs | //! Functions for setting configuration and executing the generator.
use cpp_to_rust_generator::common::errors::Result;
use cpp_to_rust_generator::common::{log, toml};
use cpp_to_rust_generator::common::file_utils::{PathBufWithAdded, repo_crate_local_path};
use cpp_to_rust_generator::config::{Config, CacheUsage, Debug... | type1.doc = Some(doc.0);
if let CppTypeKind::Enum { ref mut values } = type1.kind {
let enum_namespace = if let Some(index) = type1.name.rfind("::") {
type1.name[0..index + 2].to_string()
} else {
String::new()
... | for type1 in &mut cpp_data.types {
match parser.doc_for_type(&type1.name) {
Ok(doc) => {
// log::debug(format!("Found doc for type: {}", type1.name)); | random_line_split |
executor.rs | //! Functions for setting configuration and executing the generator.
use cpp_to_rust_generator::common::errors::Result;
use cpp_to_rust_generator::common::{log, toml};
use cpp_to_rust_generator::common::file_utils::{PathBufWithAdded, repo_crate_local_path};
use cpp_to_rust_generator::config::{Config, CacheUsage, Debug... | (cpp_methods: &mut [CppMethod], data: &mut DocParser) -> Result<()> {
for cpp_method in cpp_methods {
if let Some(ref info) = cpp_method.class_membership {
if info.visibility == CppVisibility::Private {
continue;
}
}
if let Some(ref declaration_code) = cpp_method.declaration_code {
... | find_methods_docs | identifier_name |
set3.rs | use std::collections::VecDeque;
use std::time::{SystemTime, UNIX_EPOCH};
use std::{u8, u16};
use rand::{self, Rng};
use rand::distributions::{IndependentSample, Range};
use rayon::iter::{IntoParallelIterator, ParallelIterator};
use errors::*;
use prelude::*;
use set1::{decrypt_single_byte_xor_cipher, break_repeating_... |
pub fn get_mt19937_ciphertext() -> Result<(u16, Vec<u8>)> {
let mut thread_rng = rand::thread_rng();
let prefix_len = Range::new(0, u8::MAX).ind_sample(&mut thread_rng);
let mut plaintext = random_bytes(prefix_len as usize)?;
plaintext.extend(b"AAAAAAAAAAAAAA");
let seed = Range::new(0, u16::MAX).ind_samp... | {
let key: Vec<_> = MersenneTwister::new(seed as u32).keystream().take(data.len()).collect();
fixed_xor(data, &key)
} | identifier_body |
set3.rs | use std::collections::VecDeque;
use std::time::{SystemTime, UNIX_EPOCH};
use std::{u8, u16};
use rand::{self, Rng};
use rand::distributions::{IndependentSample, Range};
use rayon::iter::{IntoParallelIterator, ParallelIterator};
use errors::*;
use prelude::*;
use set1::{decrypt_single_byte_xor_cipher, break_repeating_... | }
let (_, key) = break_repeating_key_xor(&concated_ciphertext, min_length..min_length + 1);
let mut result = Vec::new();
for ciphertext in ciphertexts {
result.push(fixed_xor(ciphertext, &key));
}
// this only extracts min_length bytes for each ciphertext
// TODO extract the rest of the plaintexts..... | for ciphertext in ciphertexts {
println!("{:?}", ciphertext.len());
concated_ciphertext.extend(&ciphertext[..min_length]); | random_line_split |
set3.rs | use std::collections::VecDeque;
use std::time::{SystemTime, UNIX_EPOCH};
use std::{u8, u16};
use rand::{self, Rng};
use rand::distributions::{IndependentSample, Range};
use rayon::iter::{IntoParallelIterator, ParallelIterator};
use errors::*;
use prelude::*;
use set1::{decrypt_single_byte_xor_cipher, break_repeating_... | () -> Result<Vec<u8>> {
let mut thread_rng = rand::thread_rng();
let prefix_len = Range::new(0, u8::MAX).ind_sample(&mut thread_rng);
let mut plaintext = random_bytes(prefix_len as usize)?;
plaintext.extend(b"user_id=123456&expires=1000");
let unix_duration = SystemTime::now().duration_since(UNIX_EPOCH)?;
... | generate_password_reset_token | identifier_name |
set3.rs | use std::collections::VecDeque;
use std::time::{SystemTime, UNIX_EPOCH};
use std::{u8, u16};
use rand::{self, Rng};
use rand::distributions::{IndependentSample, Range};
use rayon::iter::{IntoParallelIterator, ParallelIterator};
use errors::*;
use prelude::*;
use set1::{decrypt_single_byte_xor_cipher, break_repeating_... |
}
}
}
let vec = Vec::from(result);
if is_pkcs7_padded(&vec) {
unpad_pkcs7(&vec)
} else {
Ok(vec)
}
}
pub fn get_base64_strings() -> Result<Vec<Vec<u8>>> {
let mut base64_strings = Vec::new();
base64_strings.push(from_base64_string("SSBoYXZlIG1ldCB0aGVtIGF0IGNsb3NlIG9mIGRheQ==")?);
b... | {
result.push_front(previous_block[i] ^ z ^ padding);
c1_suffix.push_front(z);
break;
} | conditional_block |
mm.rs | //! The virtual and physical memory manager for the kernel
use core::marker::PhantomData;
use core::mem::size_of;
use core::mem::MaybeUninit;
use core::ops::{Deref, DerefMut};
use core::alloc::{Layout, GlobalAlloc};
use core::sync::atomic::{AtomicU64, AtomicPtr, Ordering};
use alloc::boxed::Box;
use alloc::collections... | {
/// Virtual address of the next `FreeListNode`
next: usize,
/// Number of free slots in `free_mem`
free_slots: usize,
/// Virtual addresses of free allocations
free_addrs: [*mut u8; 0],
}
/// A free list which holds free entries of `size` bytes in a semi-linked list
/// table thingy.
p... | FreeListNode | identifier_name |
mm.rs | //! The virtual and physical memory manager for the kernel
use core::marker::PhantomData;
use core::mem::size_of;
use core::mem::MaybeUninit;
use core::ops::{Deref, DerefMut};
use core::alloc::{Layout, GlobalAlloc};
use core::sync::atomic::{AtomicU64, AtomicPtr, Ordering};
use alloc::boxed::Box;
use alloc::collections... | let total_phys = core!().boot_args
.total_physical_memory.load(Ordering::Relaxed);
// Get physical memory in use
let phys_inuse =
total_phys - GLOBAL_ALLOCATOR.free_physical.load(Ordering::Relaxed);
print!("Allocs {:8} | Frees {:8} | Physical {:10.2} MiB / {:10.2} MiB | \
... | /// Print the allocation statistics to the screen
pub fn print_alloc_stats() {
// Get total amount of physical memory | random_line_split |
mm.rs | //! The virtual and physical memory manager for the kernel
use core::marker::PhantomData;
use core::mem::size_of;
use core::mem::MaybeUninit;
use core::ops::{Deref, DerefMut};
use core::alloc::{Layout, GlobalAlloc};
use core::sync::atomic::{AtomicU64, AtomicPtr, Ordering};
use alloc::boxed::Box;
use alloc::collections... |
}
}
/// A wrapper on a range set to allow implementing the `PhysMem` trait
pub struct PhysicalMemory;
impl PhysMem for PhysicalMemory {
unsafe fn translate(&mut self, paddr: PhysAddr, size: usize)
-> Option<*const u8> {
self.translate_mut(paddr, size).map(|x| x as *const u8)
}
un... | {
// Check if there is room for this allocation in the free stack,
// or if we need to create a new stack
if self.head == 0 ||
(*(self.head as *const FreeListNode)).free_slots == 0 {
// No free slots, create a new stack out of the freed vaddr
... | conditional_block |
main.rs | use wgpu::util::DeviceExt;
use winit::{
event::*,
event_loop::{ControlFlow, EventLoop},
window::WindowBuilder,
};
use log::{debug, info, error};
use winit::window::Window;
#[macro_use]
extern crate bitflags;
#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
struct Vertex {
po... | {
surface: wgpu::Surface,
device: wgpu::Device,
queue: wgpu::Queue,
sc_desc: wgpu::SwapChainDescriptor,
swap_chain: wgpu::SwapChain,
size: winit::dpi::PhysicalSize<u32>,
mouse_pos: cgmath::Point2<f64>,
render_pipeline: wgpu::RenderPipeline,
vertex_buffer: wgpu::Buffer,
index_buf... | State | identifier_name |
main.rs | use wgpu::util::DeviceExt;
use winit::{
event::*,
event_loop::{ControlFlow, EventLoop},
window::WindowBuilder,
};
use log::{debug, info, error};
use winit::window::Window;
#[macro_use]
extern crate bitflags;
#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
struct Vertex {
po... | let diffuse_rgba = diffuse_image.as_rgba8().expect("Can't transform image info");
use image::GenericImageView;
let dimensions = diffuse_image.dimensions();
let texture_size = wgpu::Extent3d {
width: dimensions.0,
height: dimensions.1,
// All textures... | random_line_split | |
main.rs | use wgpu::util::DeviceExt;
use winit::{
event::*,
event_loop::{ControlFlow, EventLoop},
window::WindowBuilder,
};
use log::{debug, info, error};
use winit::window::Window;
#[macro_use]
extern crate bitflags;
#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
struct Vertex {
po... |
};
render_pass.set_pipeline(&self.render_pipeline);
render_pass.set_bind_group(0, &self.diffuse_bind_group, &[]);
render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
render_pass.set_index_buffer(data.0.slice(..), wgpu::IndexFormat::Uint16);
... | {
(&self.index_buffer, self.num_indices)
} | conditional_block |
main.rs | use wgpu::util::DeviceExt;
use winit::{
event::*,
event_loop::{ControlFlow, EventLoop},
window::WindowBuilder,
};
use log::{debug, info, error};
use winit::window::Window;
#[macro_use]
extern crate bitflags;
#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
struct Vertex {
po... |
fn input(&mut self, event: &WindowEvent) -> bool {
match event {
WindowEvent::CursorMoved {position, ..} => {
self.mouse_pos.x = position.x;
self.mouse_pos.y = position.y;
// debug!("Mouse moved to point: {:?}", self.mouse_pos);
t... | {
self.size = new_size;
self.sc_desc.width = new_size.width;
self.sc_desc.height = new_size.height;
self.swap_chain = self.device.create_swap_chain(&self.surface, &self.sc_desc);
} | identifier_body |
PEATSAplugin.py | #!/usr/bin/env python
#
# Protein Engineering Analysis Tool DataBase (PEATDB)
# Copyright (C) 2010 Damien Farrell & Jens Erik Nielsen
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either ver... |
self.labboklist = self.parent.labbookSheetsSelector(body)
self.labboklist.grid(row=0,column=1,sticky='news')
bf=Frame(body)
bf.grid(row=1,column=1,sticky='ew')
b=Button(bf,text='Merge into main table', command=lambda: self.mergeTable(main=True))
b.pack(... | if self.matrices[m] != None:
self.showMatrix(fr,self.matrices[m], m) | conditional_block |
PEATSAplugin.py | #!/usr/bin/env python
#
# Protein Engineering Analysis Tool DataBase (PEATDB)
# Copyright (C) 2010 Damien Farrell & Jens Erik Nielsen
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either ver... | (text):
if not hasattr(self.DB.meta,'peatsa_jobs'):
return 1
if text in self.DB.meta.peatsa_jobs:
return -1
else:
return 1
def close():
jobdlg.destroy()
def loadmuts():
filename=tkFileDial... | validatename | identifier_name |
PEATSAplugin.py | #!/usr/bin/env python
#
# Protein Engineering Analysis Tool DataBase (PEATDB)
# Copyright (C) 2010 Damien Farrell & Jens Erik Nielsen
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either ver... |
def manageJobsButtons(self, parent):
fr1 = Frame(parent)
Button(fr1,text='View Results',command=self.showAllResults,bg='#ccFFFF').pack(side=TOP,fill=BOTH,expand=1)
fr1.pack(fill=BOTH)
Button(fr1,text='Merge Results',command=self.mergeCurrent).pack(side=TOP,fill=BOTH,expand=1)
... | random_line_split | |
PEATSAplugin.py | #!/usr/bin/env python
#
# Protein Engineering Analysis Tool DataBase (PEATDB)
# Copyright (C) 2010 Damien Farrell & Jens Erik Nielsen
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either ver... |
def checkJobsDict(self):
"""Check jobs data structure exists"""
if not hasattr(self.DB.meta,'peatsa_jobs'):
from ZODB.PersistentMapping import PersistentMapping
self.DB.meta.peatsa_jobs = PersistentMapping()
def storeJob(self, name, job):
""... | """add a space to the end of the word"""
word = word + " "
st.insert('end', word)
end_index = st.index('end')
begin_index = "%s-%sc" % (end_index, len(word) + 1)
st.tag_add(tag, begin_index, end_index)
st.tag_config(tag, foreground=fg, background=bg)
return | identifier_body |
Weather.py |
import math
import pickle
import datetime, time
import numpy as np
class Weather:
def __init__(self, wfile, lines=0):
""" Weather Constructor
Args:
wfile (str): input weather file
lines (int, optional): number of lines of the input file to read
"""
self.wf... |
def getTargetNames(self):
""" Get target names
Returns:
Target names
"""
return self.targetNames
def getNrTargets(self):
""" Get number of targets
Returns:
Number of targets
"""
return self.targetNames.size
def getF... | """ Get number of weather observations read from file
Returns:
Number of weather observations
"""
return len(self.data) | identifier_body |
Weather.py |
import math
import pickle
import datetime, time
import numpy as np
class Weather:
def __init__(self, wfile, lines=0):
""" Weather Constructor
Args:
wfile (str): input weather file
lines (int, optional): number of lines of the input file to read
"""
self.wf... | (self, obsData):
""" Calculate the time relative to set sample start time for a given data point
Args:
obsData (list): Observation data for single time point
Returns:
relTime (str): Time relative to set sample start time (hours)
"""
# get unix time for st... | _getRelTime | identifier_name |
Weather.py |
import math
import pickle
import datetime, time
import numpy as np
class Weather:
def __init__(self, wfile, lines=0):
""" Weather Constructor
Args:
wfile (str): input weather file
lines (int, optional): number of lines of the input file to read
"""
self.wf... |
elif (streamHeader == 'BASIC'):
self.dataStream = 2
else:
print "Error: unecognised data stream from file %s" % (self.wfile)
return -1
# read data
inputData = []
for line in weatherData:
entries = line.split()
inputD... | self.dataStream = 1 | conditional_block |
Weather.py | import math
import pickle
import datetime, time
import numpy as np
class Weather:
def __init__(self, wfile, lines=0):
""" Weather Constructor
Args:
wfile (str): input weather file
lines (int, optional): number of lines of the input file to read
"""
self.wfi... | return stats[:,features]
else:
return stats
def findStations(self, coords=[], offset=[], minThreshold=10, maxThreshold=100):
""" Find the nearet observation station to a given location
Args:
coords (list(str1, str2)): Latitude and Longitude of location
... | features = [self._getFIdx(f) for f in features] | random_line_split |
TD_Functions.py | # coding=utf-8
# Copyright (C) 2012 Allis Tauri <allista@gmail.com>
#
# degen_primer is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
... | #if |x| or |xx|
elif f_next-f_match < 4:
NN1 = seq_str[r_next:r_next+2]
RV1 = seq_str[f_next-1:f_next+1][::-1]
dG += MismatchNN[NN1][RV1] + dG_Na
continue
#internal loop
elif f_next-f_match < 31:
dG += loop_d... | nue
| conditional_block |
TD_Functions.py | # coding=utf-8
# Copyright (C) 2012 Allis Tauri <allista@gmail.com>
#
# degen_primer is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
... | elif fwd_matches[0] > 0 and rev_matches[0] == seq_len-1:
dG += DanglingNN['X'+seq_str[fwd_matches[0]]][seq_str[fwd_matches[0]-1]]
#check for 'left' terminal mismatch
elif fwd_matches[0] > 0 and rev_matches[0] < seq_len-1:
dG += Terminal_mismatch_mean
#check for 'left' terminal AT
eli... | random_line_split | |
TD_Functions.py | # coding=utf-8
# Copyright (C) 2012 Allis Tauri <allista@gmail.com>
#
# degen_primer is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
... | def
def calculate_Tr(seq_rec, r):
primer_Tr = NN_Tr(seq_rec.seq, r)
feature = source_feature(seq_rec)
add_PCR_conditions(feature)
feature.qualifiers['T-'+str(r)] = str(primer_Tr)
return primer_Tr
#end def
def calculate_Tm(seq_rec):
primer_Tm = NN_Tm(seq_rec.seq)
... | feature.qualifiers['C_Na'] = str(C_Na)+ ' mM'
feature.qualifiers['C_Mg'] = str(C_Mg)+ ' mM'
feature.qualifiers['C_dNTP'] = str(C_dNTP)+' mM'
feature.qualifiers['C_DNA'] = str(C_DNA)+ ' nM'
feature.qualifiers['C_Primer'] = str(C_Prim)+' uM'
feature.qual... | identifier_body |
TD_Functions.py | # coding=utf-8
# Copyright (C) 2012 Allis Tauri <allista@gmail.com>
#
# degen_primer is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
... | conc_str = ''
spacer = max(len(str(C_Na)),
len(str(C_Mg)),
len(str(C_dNTP)),
len(str(C_DNA)),
len(str(C_Prim)),
len(str(C_DMSO)))
conc_str += 'C(Na) = ' + str(C_Na) + ' '*(spacer-len(str(C_Na))) +' mM\n'
conc_s... | t_PCR_conditions():
| identifier_name |
upload.rs | //! The uploading logic was mostly reverse engineered; I wrote it down as
//! documentation at https://warehouse.readthedocs.io/api-reference/legacy/#upload-api
use crate::build_context::hash_file;
use anyhow::{bail, Context, Result};
use base64::engine::general_purpose::STANDARD;
use base64::Engine;
use bytesize::Byt... | | Err(keyring::Error::PlatformFailure(_)) => {}
Err(err) => {
eprintln!("⚠️ Warning: Failed to remove password from keyring: {err}")
}
}
}
bail!("Username and/or passw... | Err(keyring::Error::NoEntry)
| Err(keyring::Error::NoStorageAccess(_)) | random_line_split |
upload.rs | //! The uploading logic was mostly reverse engineered; I wrote it down as
//! documentation at https://warehouse.readthedocs.io/api-reference/legacy/#upload-api
use crate::build_context::hash_file;
use anyhow::{bail, Context, Result};
use base64::engine::general_purpose::STANDARD;
use base64::Engine;
use bytesize::Byt... | config
}
fn load_pypi_cred_from_config(config: &Ini, registry_name: &str) -> Option<(String, String)> {
if let (Some(username), Some(password)) = (
config.get(registry_name, "username"),
config.get(registry_name, "password"),
) {
return Some((username, password));
}
None
}
/// ... | config_path.push(".pypirc");
if let Ok(pypirc) = fs::read_to_string(config_path.as_path()) {
let _ = config.read(pypirc);
}
}
| conditional_block |
upload.rs | //! The uploading logic was mostly reverse engineered; I wrote it down as
//! documentation at https://warehouse.readthedocs.io/api-reference/legacy/#upload-api
use crate::build_context::hash_file;
use anyhow::{bail, Context, Result};
use base64::engine::general_purpose::STANDARD;
use base64::Engine;
use bytesize::Byt... | // Attempts to fetch the password from the keyring (if enabled)
/// and falls back to the interactive password prompt.
fn get_password(_username: &str) -> String {
#[cfg(feature = "keyring")]
{
let service = env!("CARGO_PKG_NAME");
let keyring = keyring::Entry::new(service, _username);
i... | Registry {
username,
password,
url,
}
}
}
/ | identifier_body |
upload.rs | //! The uploading logic was mostly reverse engineered; I wrote it down as
//! documentation at https://warehouse.readthedocs.io/api-reference/legacy/#upload-api
use crate::build_context::hash_file;
use anyhow::{bail, Context, Result};
use base64::engine::general_purpose::STANDARD;
use base64::Engine;
use bytesize::Byt... | : String,
}
#[derive(Debug, Deserialize)]
struct OidcTokenResponse {
value: String,
}
#[derive(Debug, Deserialize)]
struct MintTokenResponse {
token: String,
}
/// Trusted Publisher support for GitHub Actions
fn resolve_pypi_token_via_oidc(registry_url: &str) -> Result<Option<String>> {
if env::var_os("G... | ponse {
audience | identifier_name |
armature.py | from .animation import *
from .logger import *
from .package_level import *
import bpy
from math import radians
from mathutils import Vector, Matrix
DEFAULT_LIB_NAME = 'Same as filename'
#===============================================================================
class Bone:
def __init__(self, bpyBone, bpySke... |
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@staticmethod
def get_matrix(bpyBone, matrix_world, doParentMult):
SystemMatrix = Matrix.Scale(-1, 4, Vector((0, 0, 1))) * Matrix.Rotation(radians(-90), 4, 'X')
if (bpyBone.parent and doParentMult):
r... | return Bone.get_matrix(self.posedBone, self.matrix_world, doParentMult) | identifier_body |
armature.py | from .animation import *
from .logger import *
from .package_level import *
import bpy
from math import radians
from mathutils import Vector, Matrix
DEFAULT_LIB_NAME = 'Same as filename'
#===============================================================================
class Bone:
def __init__(self, bpyBone, bpySke... |
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def append_animation_pose(self, frame, force = False):
currentBoneMatrix = self.get_bone_matrix()
if (force or not same_matrix4(currentBoneMatrix, self.previousBoneMatrix)):
self.animation.frames.append(f... | self.animation = Animation(ANIMATIONTYPE_MATRIX, ANIMATIONLOOPMODE_CYCLE, 'anim', '_matrix')
self.previousBoneMatrix = None | conditional_block |
armature.py | from .animation import *
from .logger import *
from .package_level import *
import bpy
from math import radians
from mathutils import Vector, Matrix
DEFAULT_LIB_NAME = 'Same as filename'
#===============================================================================
class Bone:
def __init__(self, bpyBone, bpySke... | (bpyBone, matrix_world, doParentMult):
SystemMatrix = Matrix.Scale(-1, 4, Vector((0, 0, 1))) * Matrix.Rotation(radians(-90), 4, 'X')
if (bpyBone.parent and doParentMult):
return (SystemMatrix * matrix_world * bpyBone.parent.matrix).inverted() * (SystemMatrix * matrix_world * bpyBone.matrix)... | get_matrix | identifier_name |
armature.py | from .animation import *
from .logger import *
from .package_level import *
import bpy
from math import radians
from mathutils import Vector, Matrix
DEFAULT_LIB_NAME = 'Same as filename'
#===============================================================================
class Bone:
def __init__(self, bpyBone, bpySke... | def getMeshesForRig(scene, skeleton, prepForShapekeys = False):
meshes = []
for object in [object for object in scene.objects]:
if object.type == 'MESH' and len(object.vertex_groups) > 0 and skeleton == object.find_armature():
meshes.append(object)
print('meshes with armature: ' ... | random_line_split | |
poller.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# jan 2014 bbb garden shield attempt
# AKA
'''
Sensors:
analog level sensor, pin AIN0
TMP102 i2c temperature sensor, address 0x48
(if add0 is grounded) or 0x49 (if pulled up)
Outputs:
Analog RGB LED strip
I2C display(?)
Pump Activate/Deactivate (GPIO pin)
Some measureme... | # temp1 = adc.read_raw(thermistor1)
temp1 = adc.read_raw(thermistor1)
time.sleep(1)
print 'temp1 raw %s' % temp1
temp1 = convert_thermistor_special(temp1)
readings['bedTemp'] = temp1
print 'converted bed_temp is %s' % temp1
# # do conversion per
# # http://learn.adafruit.com/the... | random_line_split | |
poller.py |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# jan 2014 bbb garden shield attempt
# AKA
'''
Sensors:
analog level sensor, pin AIN0
TMP102 i2c temperature sensor, address 0x48
(if add0 is grounded) or 0x49 (if pulled up)
Outputs:
Analog RGB LED strip
I2C display(?)
Pump Activate/Deactivate (GPIO pin)
Some measurem... |
else:
print 'shutting off pump at %s' % datetime.datetime.today().minute
gpio.output(pumpPin,gpio.LOW)
else:
print 'it is the actuator quiet period, between 11pm and 6am'
gpio.output(pumpPin,gpio.LOW)
print 'starting sampling at'
print datetime.datetime.now(tzlocal(... | print 'we are in the first %s minutes of the hour, so pump should be on.' % PUMP_DURATION
gpio.output(pumpPin,gpio.HIGH) | conditional_block |
poller.py |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# jan 2014 bbb garden shield attempt
# AKA
'''
Sensors:
analog level sensor, pin AIN0
TMP102 i2c temperature sensor, address 0x48
(if add0 is grounded) or 0x49 (if pulled up)
Outputs:
Analog RGB LED strip
I2C display(?)
Pump Activate/Deactivate (GPIO pin)
Some measurem... |
def convert_thermistor(raw):
# convert the value to resistance
# print 'was given %s' % raw
raw = SERIESRESISTOR/((1800.0/raw) - 1.0)
# raw = float(SERIESRESISTOR / float(raw))
print 'Thermistor resistance '
print raw
steinhart = raw/THERMISTORNOMINAL # (R/Ro)
steinhart = log(stei... | print 'sensor read'
global readings
readings = {}
# value = ADC.read("AIN1")
# adc returns value from 0 to 1.
# use read_raw(pin) to get V values
# tank = adc.read(tankPin)
tank = adc.read(tankPin) # have to read twice due to bbio bug
print 'tank is %s' % tank
time.sleep(1)
... | identifier_body |
poller.py |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# jan 2014 bbb garden shield attempt
# AKA
'''
Sensors:
analog level sensor, pin AIN0
TMP102 i2c temperature sensor, address 0x48
(if add0 is grounded) or 0x49 (if pulled up)
Outputs:
Analog RGB LED strip
I2C display(?)
Pump Activate/Deactivate (GPIO pin)
Some measurem... | ():
print 'state_display'
width = disp.width
height = disp.height
image = Image.new('1', (width, height))
# Get drawing object to draw on image.
draw = ImageDraw.Draw(image)
# Load default font.
# font = ImageFont.load_default()
# Alternatively load a TTF font.
# Some other nice... | do_state_display | identifier_name |
ddpg.py | """
Implementation of DDPG - Deep Deterministic Policy Gradient
Algorithm and hyperparameter details can be found here:
http://arxiv.org/pdf/1509.02971v2.pdf
The algorithm is tested on the Pendulum-v0 OpenAI gym task
and developed with tflearn + Tensorflow
Author: Patrick Emami
"""
import tensorflow as tf
imp... | (probabilities):
choice = int(np.random.choice(ACTION_SPACE, 1, p=probabilities))
return choice
def main(_):
with tf.Session() as sess:
# TODO: reduce network sizes. keep all states stop editing this ver, add dropout in successor
env = gym.make(ENV_NAME)
np.random.seed(RANDOM_SEED)
... | choose_action | identifier_name |
ddpg.py | """
Implementation of DDPG - Deep Deterministic Policy Gradient
Algorithm and hyperparameter details can be found here:
http://arxiv.org/pdf/1509.02971v2.pdf
The algorithm is tested on the Pendulum-v0 OpenAI gym task
and developed with tflearn + Tensorflow
Author: Patrick Emami
"""
import tensorflow as tf
imp... |
if __name__ == '__main__':
tf.app.run() | with tf.Session() as sess:
# TODO: reduce network sizes. keep all states stop editing this ver, add dropout in successor
env = gym.make(ENV_NAME)
np.random.seed(RANDOM_SEED)
tf.set_random_seed(RANDOM_SEED)
env.seed(RANDOM_SEED)
# Ensure action bound is symmetric
#... | identifier_body |
ddpg.py | """
Implementation of DDPG - Deep Deterministic Policy Gradient
Algorithm and hyperparameter details can be found here:
http://arxiv.org/pdf/1509.02971v2.pdf
The algorithm is tested on the Pendulum-v0 OpenAI gym task
and developed with tflearn + Tensorflow
Author: Patrick Emami
"""
import tensorflow as tf
imp... | ACTION_PROB_DIMS = 2
ACTION_BOUND = 1
ACTION_SPACE = [0, 1]
# ===========================
# Utility Parameters
# ===========================
# Render gym env during training
RENDER_ENV = True
# Use Gym Monitor
GYM_MONITOR_EN = True
# Gym environment
ENV_NAME = 'CartPole-v0'
# Directory for storing gym results
MONITO... | # Soft target update param
TAU = 0.05
STATE_DIM = 4
ACTION_DIM = 1 | random_line_split |
ddpg.py | """
Implementation of DDPG - Deep Deterministic Policy Gradient
Algorithm and hyperparameter details can be found here:
http://arxiv.org/pdf/1509.02971v2.pdf
The algorithm is tested on the Pendulum-v0 OpenAI gym task
and developed with tflearn + Tensorflow
Author: Patrick Emami
"""
import tensorflow as tf
imp... | tf.app.run() | conditional_block | |
lab3.py | import re
import datetime
from pyspark.sql import Row
month_map = {'Jan': 1, 'Feb': 2, 'Mar':3, 'Apr':4, 'May':5, 'Jun':6, 'Jul':7,
'Aug':8, 'Sep': 9, 'Oct':10, 'Nov': 11, 'Dec': 12}
def parse_apache_time(s):
""" Convert Apache time format into a Python datetime object
Args:
s (str): date and tim... |
size_field = match.group(9)
if size_field == '-':
size = long(0)
else:
size = long(match.group(9))
return (Row(
host = match.group(1),
client_identd = match.group(2),
user_id = match.group(3),
date_time = parse_apache_time(match.group(4... | return (logline, 0) | conditional_block |
lab3.py | import re
import datetime
from pyspark.sql import Row
month_map = {'Jan': 1, 'Feb': 2, 'Mar':3, 'Apr':4, 'May':5, 'Jun':6, 'Jul':7,
'Aug':8, 'Sep': 9, 'Oct':10, 'Nov': 11, 'Dec': 12}
def parse_apache_time(s):
""" Convert Apache time format into a Python datetime object
Args:
s (str): date and tim... |
parsed_logs, access_logs, failed_logs = parseLogs()
APACHE_ACCESS_LOG_PATTERN = '^(\S+) (\S+) (\S+).*\[([\w:\/]+\s[+\-]\d{4})\] "(\S+) (\S*)( *\S+ *)*" (\d{3}) (\S+)'
parsed_logs, access_logs, failed_logs = parseLogs()
Test.assertEquals(failed_logs.count(), 0, 'incorrect failed_logs.count()')
Test.assertEquals(p... | """ Read and parse log file """
parsed_logs = (sc
.textFile(logFile)
.map(parseApacheLogLine)
.cache())
access_logs = (parsed_logs
.filter(lambda s: s[1] == 1)
.map(lambda s: s[0])
.cache())
f... | identifier_body |
lab3.py | import re
import datetime
from pyspark.sql import Row
month_map = {'Jan': 1, 'Feb': 2, 'Mar':3, 'Apr':4, 'May':5, 'Jun':6, 'Jul':7,
'Aug':8, 'Sep': 9, 'Oct':10, 'Nov': 11, 'Dec': 12}
def parse_apache_time(s):
""" Convert Apache time format into a Python datetime object
Args:
s (str): date and tim... | errors404ByHours = [x[1] for x in hourRecordsSorted.takeOrdered(30, key = lambda x: -x[0])]
Test.assertEquals(hoursWithErrors404, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23], 'incorrect hoursWithErrors404')
Test.assertEquals(errors404ByHours, [175, 171, 422, 272, 102, 95, 93,... | Test.assertTrue(hourRecordsSorted.is_cached, 'incorrect hourRecordsSorted.is_cached')
hoursWithErrors404 = hourRecordsSorted.map(lambda x: x[0]).takeOrdered(30) | random_line_split |
lab3.py | import re
import datetime
from pyspark.sql import Row
month_map = {'Jan': 1, 'Feb': 2, 'Mar':3, 'Apr':4, 'May':5, 'Jun':6, 'Jul':7,
'Aug':8, 'Sep': 9, 'Oct':10, 'Nov': 11, 'Dec': 12}
def parse_apache_time(s):
""" Convert Apache time format into a Python datetime object
Args:
s (str): date and tim... | ():
""" Read and parse log file """
parsed_logs = (sc
.textFile(logFile)
.map(parseApacheLogLine)
.cache())
access_logs = (parsed_logs
.filter(lambda s: s[1] == 1)
.map(lambda s: s[0])
.cache()... | parseLogs | identifier_name |
lib.rs | use std::ops::{Deref, DerefMut};
use std::any::Any;
use std::fmt::Debug;
use std::fmt;
pub use cod_node_derive::Node;
mod id;
mod context;
mod danger_zone;
#[cfg(test)]
mod test;
pub use id::ID;
use id::new_id;
use context::{CONTEXT, Context, PollReason, Replacement, IDMapUpdate};
use danger_zone::downcast_rc;
//... |
fn cod(&self) {
let _ = self.clone();
}
}
pub struct Child<T: NodeClone> {
inner_ref: Rc<T>,
}
pub struct ParentID(ID);
impl From<ID> for ParentID {
fn from(id: ID) -> Self { ParentID(id) }
}
impl From<&Header> for ParentID {
fn from(header: &Header) -> Self { ParentID(header.id) }
}
imp... | {
Rc::new(self.clone())
} | identifier_body |
lib.rs | use std::ops::{Deref, DerefMut};
use std::any::Any;
use std::fmt::Debug;
use std::fmt;
pub use cod_node_derive::Node;
mod id;
mod context;
mod danger_zone;
#[cfg(test)]
mod test;
pub use id::ID;
use id::new_id;
use context::{CONTEXT, Context, PollReason, Replacement, IDMapUpdate};
use danger_zone::downcast_rc;
//... | (&self) -> Rc<T> {
Rc::clone(&self.inner_ref)
}
pub fn get_id(&self) -> ID {
self.inner_ref.header().id
}
pub fn set_parent(&mut self, parent: impl Into<ParentID>) {
self.make_mut().header_mut().parent_id = Some(parent.into().0);
}
/// Deep clone and set new parent... | get_ref | identifier_name |
lib.rs | use std::ops::{Deref, DerefMut};
use std::any::Any;
use std::fmt::Debug;
use std::fmt;
pub use cod_node_derive::Node;
mod id;
mod context;
mod danger_zone;
#[cfg(test)]
mod test;
pub use id::ID;
use id::new_id;
use context::{CONTEXT, Context, PollReason, Replacement, IDMapUpdate};
use danger_zone::downcast_rc;
//... | // so going to an old state after catching an unwind _should_ be fine.
if std::thread::panicking() { return }
CONTEXT.with(|c| {
Context::poll(c, PollReason::Drop, Rc::clone(&self.inner_ref));
});
}
}
pub struct MakeMutRef<'a, T: NodeClone> {
child: &'a mut Child<T>
... | }
impl<T: NodeClone> Drop for Child<T> {
fn drop(&mut self) {
// XXX: This should only create inconsistencies in the newest version of the data, | random_line_split |
bundle.py | # Copyright (c) MONAI Consortium
# 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 law or agreed to in writing, so... | (self) -> str:
return "experiment_name"
def key_run_name(self) -> str:
return "run_name"
def key_displayable_configs(self) -> Sequence[str]:
return ["displayable_configs"]
class BundleTrainTask(TrainTask):
def __init__(
self,
path: str,
conf: Dict[str, str... | key_experiment_name | identifier_name |
bundle.py | # Copyright (c) MONAI Consortium
# 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 law or agreed to in writing, so... |
if tracking_run_name:
overrides[self.const.key_run_name()] = tracking_run_name
# external validation datalist supported through bundle itself (pass -1 in the request to use the same)
if val_ds is not None:
overrides[self.const.key_validate_dataset_data()] = val_... | overrides[self.const.key_experiment_name()] = tracking_experiment_name | conditional_block |
bundle.py | # Copyright (c) MONAI Consortium
# 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 law or agreed to in writing, so... | )
return
train_path = os.path.join(self.bundle_path, "configs", "monailabel_train.json")
multi_gpu_train_path = os.path.join(self.bundle_path, "configs", config_paths[0])
logging_file = os.path.join(self.bundle_path, "configs", "logging.conf")
... | if not config_paths:
logger.warning(
f"Ignore Multi-GPU Training; No multi-gpu train config {self.const.multi_gpu_configs()} exists" | random_line_split |
bundle.py | # Copyright (c) MONAI Consortium
# 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 law or agreed to in writing, so... |
def key_tracking(self) -> str:
return "tracking"
def key_tracking_uri(self) -> str:
return "tracking_uri"
def key_experiment_name(self) -> str:
return "experiment_name"
def key_run_name(self) -> str:
return "run_name"
def key_displayable_configs(self) -> Sequenc... | return "validate#dataset#data" | identifier_body |
__init__.py | import functools
import random
import re
import string
from enum import Enum
import PIL
import asyncio
import cachetools
import pkg_resources
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from plumeria import config
from plumeria.command import CommandError, commands, channel_only
from plu... | config.add(bomb_chance)
commands.add(start)
commands.add(click)
commands.add(flag)
commands.add(cheat) | identifier_body | |
__init__.py | import functools
import random
import re
import string
from enum import Enum
import PIL
import asyncio
import cachetools
import pkg_resources
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from plumeria import config
from plumeria.command import CommandError, commands, channel_only
from plu... |
else:
raise CommandError("You can't click that cell!")
def _in_bounds(self, x, y):
return 0 <= x < self.width and 0 <= y < self.height
def _is_bomb(self, x, y):
return self._in_bounds(x, y) and self.bomb_map[x][y]
def _count_adjacent_bombs(self, x, y):
return ... | self.state = State.WON | conditional_block |
__init__.py | import functools
import random
import re
import string
from enum import Enum
import PIL
import asyncio
import cachetools
import pkg_resources
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from plumeria import config
from plumeria.command import CommandError, commands, channel_only
from plu... | (message):
"""
Starts a game of minesweeper.
Example::
mine start
"""
key = (message.transport.id, message.server.id, message.channel.id)
if key in cache:
game = cache[key]
else:
game = Game(12, 12, scoped_config.get(bomb_chance, message.channel) / 100, random.Ran... | start | identifier_name |
__init__.py | import functools
import random
import re
import string
from enum import Enum
import PIL
import asyncio
import cachetools
import pkg_resources
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from plumeria import config
from plumeria.command import CommandError, commands, channel_only
from plu... |
def _in_bounds(self, x, y):
return 0 <= x < self.width and 0 <= y < self.height
def _is_bomb(self, x, y):
return self._in_bounds(x, y) and self.bomb_map[x][y]
def _count_adjacent_bombs(self, x, y):
return sum([
self._is_bomb(x - 1, y),
self._is_bomb(x, y - ... | self._clear_cell(x, y, set())
if self.remaining_unknown == 0:
self.state = State.WON
else:
raise CommandError("You can't click that cell!") | random_line_split |
lsh.py | """
lsh.py
Algorithms based on 'Mining of Massive Datasets'
"""
from unionfind import UnionFind
from collections import defaultdict
from collections import defaultdict, namedtuple
from copy import deepcopy
import operator
def shingle(s, k):
"""Generate k-length shingles of string s"""
k = min(len(s), k)
... |
def jaccard_sim(X, Y):
"""Jaccard similarity between two sets"""
x = set(X)
y = set(Y)
return float(len(x & y)) / len(x | y)
def jaccard_dist(X, Y):
"""Jaccard distance between two sets"""
return 1 - jaccard_sim(X, Y)
class Signature(object):
"""Signature Base class."""
def __init_... | yield hash(s) | conditional_block |
lsh.py | """
lsh.py
Algorithms based on 'Mining of Massive Datasets'
"""
from unionfind import UnionFind
from collections import defaultdict
from collections import defaultdict, namedtuple
from copy import deepcopy
import operator
def | (s, k):
"""Generate k-length shingles of string s"""
k = min(len(s), k)
for i in range(len(s) - k + 1):
yield s[i:i+k]
def hshingle(s, k):
"""Generate k-length shingles then hash"""
for s in shingle(s, k):
yield hash(s)
def jaccard_sim(X, Y):
"""Jaccard similarity between two s... | shingle | identifier_name |
lsh.py | """
lsh.py
Algorithms based on 'Mining of Massive Datasets'
"""
from unionfind import UnionFind
from collections import defaultdict
from collections import defaultdict, namedtuple
from copy import deepcopy
import operator
def shingle(s, k):
"""Generate k-length shingles of string s"""
k = min(len(s), k)
... | class Signature(object):
"""Signature Base class."""
def __init__(self, dim):
self.dim = dim
self.hashes = self.hash_functions()
def hash_functions(self):
"""Returns dim different hash functions"""
pass
def sign(self, object):
"""Return the signature for object... | random_line_split | |
lsh.py | """
lsh.py
Algorithms based on 'Mining of Massive Datasets'
"""
from unionfind import UnionFind
from collections import defaultdict
from collections import defaultdict, namedtuple
from copy import deepcopy
import operator
def shingle(s, k):
"""Generate k-length shingles of string s"""
k = min(len(s), k)
... |
class ConstrainedCluster(Cluster):
"""To fight the problem of big clusters created by the aggregation of a
large number of false positives (i.e. two items found to be a candidate
pair, but that really shouldn't belong to the same cluster), this class
introduces an extra constraint which must be met ... | """Clusters sets with Jaccard similarity above threshold with high
probability.
Algorithm based on Rajaraman, "Mining of Massive Datasets":
1. Generate set signature
2. Use LSH to map similar signatures to same buckets
3. Use UnionFind to merge buckets containing same values
"""
def __init_... | identifier_body |
denoising_autoencoder.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Learns features of inputs.
Principal Author: Matthew Alger
"""
from __future__ import division
import time
import numpy
import theano
from theano.tensor.shared_randomstreams import RandomStreams
class Denoising_Autoencoder(object):
"""
It like learns how to take... |
return self.weights.get_value(borrow=True)
def train_model(self
, epochs=100
, minibatch_size=20
, yield_every_iteration=False):
"""
Train the model against the given data.
epochs: How long to train for.
minibatch_size: How large each minibatch is.
yield_every_iteration: When to yield.
"""
if... | def get_weight_matrix(self):
"""
Get the weight matrix.
""" | random_line_split |
denoising_autoencoder.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Learns features of inputs.
Principal Author: Matthew Alger
"""
from __future__ import division
import time
import numpy
import theano
from theano.tensor.shared_randomstreams import RandomStreams
class Denoising_Autoencoder(object):
"""
It like learns how to take... | (self
, epochs=100
, minibatch_size=20
, yield_every_iteration=False):
"""
Train the model against the given data.
epochs: How long to train for.
minibatch_size: How large each minibatch is.
yield_every_iteration: When to yield.
"""
if self.input_batch is None:
raise ValueError("Denoising autoe... | train_model | identifier_name |
denoising_autoencoder.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Learns features of inputs.
Principal Author: Matthew Alger
"""
from __future__ import division
import time
import numpy
import theano
from theano.tensor.shared_randomstreams import RandomStreams
class Denoising_Autoencoder(object):
"""
It like learns how to take... |
def initialise_theano_functions(self):
"""
Compile Theano functions for symbolic variables.
"""
index = theano.tensor.lscalar("i")
batch_size = theano.tensor.lscalar("b")
validation_images = theano.tensor.matrix("vx")
validation_labels = theano.tensor.ivector("vy")
input_matrix = theano.tensor.matri... | """
Get a list of updates to make when the model is trained.
"""
da_cost = self.get_cost()
weight_gradient = theano.tensor.grad(da_cost, self.weights)
bias_gradient = theano.tensor.grad(da_cost, self.bias)
reverse_bias_gradient = theano.tensor.grad(da_cost, self.reverse_bias)
lr_cost = self.get_lr_cost... | identifier_body |
denoising_autoencoder.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Learns features of inputs.
Principal Author: Matthew Alger
"""
from __future__ import division
import time
import numpy
import theano
from theano.tensor.shared_randomstreams import RandomStreams
class Denoising_Autoencoder(object):
"""
It like learns how to take... |
print "done."
import PIL
import lib.dlt_utils as utils
import random
image = PIL.Image.fromarray(utils.tile_raster_images(
X=da.weights.get_value(borrow=True).T,
img_shape=(28, 28), tile_shape=(50, 10),
tile_spacing=(1, 1)))
image.save('../plots/{:010x}_{}_{}_{}_{}_{}.png'.format(
random.randrange(16**... | print epoch, cost
print "wrong {:.02%} of the time".format(
float(da.validate_model(validation_images, validation_labels))) | conditional_block |
webapp.py | # Copyright 2018 Autodesk, Inc. All rights reserved.
#
# Use of this software is subject to the terms of the Autodesk license agreement
# provided at the time of installation or download, or which otherwise accompanies
# this software in either electronic or hard copy form.
#
from __future__ import print_function
imp... | # /sg2jira/default[/Task/123]
# /jira2sg/default/Issue/KEY-123
# /admin/reset
try:
parsed = parse.urlparse(self.path)
# Extract additional query parameters.
# What they could be is still TBD, may be things like `dry_run=1`?
parameters = {}
... | """ | random_line_split |
webapp.py | # Copyright 2018 Autodesk, Inc. All rights reserved.
#
# Use of this software is subject to the terms of the Autodesk license agreement
# provided at the time of installation or download, or which otherwise accompanies
# this software in either electronic or hard copy form.
#
from __future__ import print_function
imp... |
class SgJiraBridgeBadRequestError(Exception):
"""
Custom exception so we can differentiate between errors we raise that
should return 4xx error codes and errors in the application which should
return 500 error codes.
"""
pass
class Server(ThreadingMixIn, BaseHTTPServer.HTTPServer):
"""... | """
Helper to extract a version number for the sg-jira-bridge module.
This will attenmpt to extract the version number from git if installed from
a cloned repo. If a version is unable to be determined, or the process
fails for any reason, we return "dev"
:returns: A major.minor.patch[.sub] version... | identifier_body |
webapp.py | # Copyright 2018 Autodesk, Inc. All rights reserved.
#
# Use of this software is subject to the terms of the Autodesk license agreement
# provided at the time of installation or download, or which otherwise accompanies
# this software in either electronic or hard copy form.
#
from __future__ import print_function
imp... | (self, format, *args):
"""
Override :class:`BaseHTTPServer.BaseHTTPRequestHandler` method to use a
standard logger.
:param str format: A format string, e.g. '%s %s'.
:param args: Arbitrary list of arguments to use with the format string.
"""
message = "%s - %s - ... | log_error | identifier_name |
webapp.py | # Copyright 2018 Autodesk, Inc. All rights reserved.
#
# Use of this software is subject to the terms of the Autodesk license agreement
# provided at the time of installation or download, or which otherwise accompanies
# this software in either electronic or hard copy form.
#
from __future__ import print_function
imp... |
if not entity_type or not entity_key:
raise SgJiraBridgeBadRequestError(
"Invalid request payload %s, unable to retrieve a Shotgun Entity type and its id."
% payload
)
# We could have a str or int here depending on how it w... | entity_type = payload.get("entity_type")
entity_key = payload.get("entity_id") | conditional_block |
test.ts | import test from 'ava'
import ApiBuilder from 'claudia-api-builder'
import * as fs from 'fs'
import authenticator, {
APIGatewayProxyEventJwt,
authenticator as authenticator2,
JwtHeader,
Secret,
SigningKeyCallback
} from '../../package/'
test('authenticator is exported', (t) => {
t.is(typeof authe... | body: '"Unauthorised: JsonWebTokenError jwt audience invalid. expected: F42ED082-799F-476B-B77E-12013F5379A5"',
statusCode: 401
})
})
/**
* ## When is a JWT not a JWT?
*/
test.cb('XWT', (t) => {
// tslint:disable-next-line:max-line-length
const TOKEN_RS512_XWT = 'eyJhbGciOiJSUzUxMiIsInR5cCI6IlhXVCJ9... | testApi(t, api, {
context: { method: 'GET', path: '/greeting' },
headers: { Authorization: 'bearer ' + TOKEN_RS512 }
}, { | random_line_split |
main.rs | extern crate hyper;
extern crate rustc_serialize;
extern crate url;
mod errors;
mod structs;
use errors::*;
use errors::ResourceError::*;
use structs::*;
use hyper::client::Client;
use std::fs::File;
use hyper::header::*;
use std::io::prelude::*;
use std::path::Path;
use std::thread;
use std::sync::Arc;
use rustc_se... |
}
#[allow(unused_must_use)]
#[allow(dead_code)]
fn save_response_to_file(url : &str, content : &str, provider : &Provider) {
let fs = provider.fs();
let id = provider.extract_id(url);
fs.store(&provider.format_file_name(&id), content);
}
trait Meshup {
fn artist_resource_by_id (&self, id : &str) -> Str... | {
std::fs::create_dir_all(Path::new(&self.directory));
let path = Path::new(&self.directory).join(id);
if !path.exists() {
File::create(path)
.and_then(|mut f| f.write_all(content.as_bytes()));
};
} | identifier_body |
main.rs | extern crate hyper;
extern crate rustc_serialize;
extern crate url;
mod errors;
mod structs;
use errors::*;
use errors::ResourceError::*;
use structs::*;
use hyper::client::Client;
use std::fs::File;
use hyper::header::*;
use std::io::prelude::*;
use std::path::Path;
use std::thread;
use std::sync::Arc;
use rustc_se... | (&self) -> SimpleFs {
match *self {
Provider::Musicbrainz => SimpleFs { directory : "tmp".to_string() },
Provider::CoverArt => SimpleFs { directory : "tmp".to_string() }
}
}
fn extract_id(&self, url: &str) -> String {
let parsed : Url = Url::parse(url).unwrap();
par... | fs | identifier_name |
main.rs | extern crate hyper;
extern crate rustc_serialize;
extern crate url;
mod errors;
mod structs;
use errors::*;
use errors::ResourceError::*;
use structs::*;
use hyper::client::Client;
use std::fs::File;
use hyper::header::*;
use std::io::prelude::*;
use std::path::Path;
use std::thread;
use std::sync::Arc;
use rustc_se... | macro_rules! musicbrainz_file {
($id : expr) => ( format!("mb_{}.json", $id))
}
macro_rules! cover_art_url {
($id : expr) => ( format!("http://coverartarchive.org/release-group/{}", $id) )
}
macro_rules! cover_art_file {
($id : expr) => ( format!("ca_{}.json", $id) )
}
#[allow(dead_code)]
#[allow(unused_must_use)... | ($id : expr) => ( format!("http://musicbrainz.org/ws/2/artist/{}?&fmt=json&inc=url-rels+release-groups", $id))
//($id : expr) => ( format!("http://localhost:8000/ws/2/artist/{}?&fmt=json&inc=url-rels+release-groups", $id))
}
| random_line_split |
memory.rs | use std::mem::transmute;
use world::World;
use geometry::Point;
use sprite::Sprite;
use util;
// In Hex's Cellar, the player's spells manipulate an u8[40] of bytes that
// affect the world around her. This file gives a "RAM map" for that array.
// Color (3 bits = 8 bright colors) and character (5 bits, offset added t... | world.player.timer_delta = value,
DAMAGE_OFFSET =>
world.player.damage_offset = unsafe { transmute(value) },
0x36 =>
// TODO: ???
{},
0x37 =>
// TODO: ???
{},
TEXT_SYNC =>
world.player.text_sync = val... |
STAIRS_DELTA =>
world.player.stairs_delta = value,
TIMER_DELTA => | random_line_split |
memory.rs | use std::mem::transmute;
use world::World;
use geometry::Point;
use sprite::Sprite;
use util;
// In Hex's Cellar, the player's spells manipulate an u8[40] of bytes that
// affect the world around her. This file gives a "RAM map" for that array.
// Color (3 bits = 8 bright colors) and character (5 bits, offset added t... | (world: &World, address: u8) -> u8 {
match address {
PLAYER_APPEARANCE =>
world.player_appearance_byte,
_ if address >= PLAYER_NAME && address < MONSTERS =>
world.player.name[(address - PLAYER_NAME) as usize],
_ if address >= MONSTERS && address < SPELL_MEMORY => {
... | peek | identifier_name |
memory.rs | use std::mem::transmute;
use world::World;
use geometry::Point;
use sprite::Sprite;
use util;
// In Hex's Cellar, the player's spells manipulate an u8[40] of bytes that
// affect the world around her. This file gives a "RAM map" for that array.
// Color (3 bits = 8 bright colors) and character (5 bits, offset added t... |
// pretend the low four bits of our u8 argument are an "i4" and sign-extend to i8
fn upcast_i4(the_i4: u8) -> i8 {
(unsafe { transmute::<u8, i8>(the_i4) } << 4) >> 4
}
fn report_player_appearance_change(world: &mut World, old: Sprite, new: Sprite) {
let new_color_name = util::color_name(new.color[0]);
l... | {
match address {
PLAYER_APPEARANCE => {
let old_sprite = Sprite::of_byte(world.player_appearance_byte, true);
let new_sprite = Sprite::of_byte(value, true);
report_player_appearance_change(world, old_sprite, new_sprite);
world.player_appearance_byte = value;
... | identifier_body |
client.rs | use crate::parser::*;
use crate::*;
use ::reqwest::blocking as reqwest;
use itertools::*;
use std::cell::RefCell;
use std::env;
use std::fs::File;
use std::io::BufWriter;
use std::io::Write;
use std::ops::Range;
use std::time::SystemTime;
use std::sync::{Arc, Mutex};
use chrono::{Utc, Local, DateTime, NaiveDateTime};
... | Command]) -> Response {
let resp = self.send(&format!(
"[4, {}, [{}]]",
self.player_key,
cs.iter().join(", ")
));
let resp = parse(resp);
self.gui("RESP", &response_to_json(&resp));
return resp;
}
}
pub fn get_num(a: &E) -> i32 {
if let E::Num(a) = a {
*a as i32
} else {
panic!("not number");... | at!(
"[3, {}, [{}, {}, {}, {}]]",
self.player_key, energy, power, cool, life
));
parse(resp)
}
pub fn command(&self, cs: &[ | identifier_body |
client.rs | use crate::parser::*;
use crate::*;
use ::reqwest::blocking as reqwest;
use itertools::*;
use std::cell::RefCell;
use std::env;
use std::fs::File;
use std::io::BufWriter;
use std::io::Write;
use std::ops::Range;
use std::time::SystemTime;
use std::sync::{Arc, Mutex};
use chrono::{Utc, Local, DateTime, NaiveDateTime};
... | {
if let Ok(_) = env::var("JUDGE_SERVER") {
return;
}
let t = match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
Ok(t) => t.as_nanos(),
_ => 0,
};
let msg = format!("###GUI\t{}\t{}\t{}\t{}\n", t, self.player_key, name, msg);
let mut printed = false;
if let Some(f) = &self.file {
... | tr) | identifier_name |
client.rs | use crate::parser::*;
use crate::*;
use ::reqwest::blocking as reqwest;
use itertools::*;
use std::cell::RefCell;
use std::env;
use std::fs::File;
use std::io::BufWriter;
use std::io::Write;
use std::ops::Range;
use std::time::SystemTime;
use std::sync::{Arc, Mutex};
use chrono::{Utc, Local, DateTime, NaiveDateTime};
... | // [src/bin/app.rs:177] &commands = [
// Pair(
// Num(
// 0,
// ),
// Pair(
// Pair(
// Num(
// 0,
// ),
// Num(
// -1,
// ),
// ),
// Nil,
// ),
// ),
// ]
let commands = commands.into_iter().ma... | let max_accelarate = get_num(&s[7]);
// [1, 1, [256, 1, [448, 2, 128], [16, 128], []], [1, [16, 128], [[[1, 0, <34, -46>, <0, 2>, [445, 0, 0, 1], 8, 128, 2], [[0, <0, -1>]]], [[0, 1, <-34, 48>, <0, 0>, [445, 0, 0, 1], 8, 128, 2], [[0, <0, -1>]]]]]] | random_line_split |
xds.go | /*
*
* Copyright 2020 gRPC 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 law or agree... | (opts ClientOptions) (credentials.TransportCredentials, error) {
if opts.FallbackCreds == nil {
return nil, errors.New("missing fallback credentials")
}
return &credsImpl{
isClient: true,
fallback: opts.FallbackCreds,
}, nil
}
// credsImpl is an implementation of the credentials.TransportCredentials
// inter... | NewClientCredentials | identifier_name |
xds.go | /*
*
* Copyright 2020 gRPC 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 law or agree... |
return nil
}
func (hi *HandshakeInfo) makeTLSConfig(ctx context.Context) (*tls.Config, error) {
hi.mu.Lock()
// Since the call to KeyMaterial() can block, we read the providers under
// the lock but call the actual function after releasing the lock.
rootProv, idProv := hi.rootProvider, hi.identityProvider
hi.m... | {
return errors.New("xds: CertificateProvider to fetch identity certificate is missing, cannot perform TLS handshake. Please check configuration on the management server")
} | conditional_block |
xds.go | /*
*
* Copyright 2020 gRPC 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 law or agree... |
// handshakeAttrKey is the type used as the key to store HandshakeInfo in
// the Attributes field of resolver.Address.
type handshakeAttrKey struct{}
// SetHandshakeInfo returns a copy of addr in which the Attributes field is
// updated with hInfo.
func SetHandshakeInfo(addr resolver.Address, hInfo *HandshakeInfo) re... | // interface which uses xDS APIs to fetch its security configuration.
type credsImpl struct {
isClient bool
fallback credentials.TransportCredentials
} | random_line_split |
xds.go | /*
*
* Copyright 2020 gRPC 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 law or agree... |
// credsImpl is an implementation of the credentials.TransportCredentials
// interface which uses xDS APIs to fetch its security configuration.
type credsImpl struct {
isClient bool
fallback credentials.TransportCredentials
}
// handshakeAttrKey is the type used as the key to store HandshakeInfo in
// the Attribut... | {
if opts.FallbackCreds == nil {
return nil, errors.New("missing fallback credentials")
}
return &credsImpl{
isClient: true,
fallback: opts.FallbackCreds,
}, nil
} | identifier_body |
oscillator.py | import numpy as np
import sys
import os
import sys
sys.path.append('src')
from scipy.constants import c, pi
from joblib import Parallel, delayed
from mpi4py.futures import MPIPoolExecutor
from mpi4py import MPI
from scipy.fftpack import fftshift, fft
import os
import time as timeit
os.system('export FONTCONFIG_PATH=/et... |
print('\a')
return None
class Band_predict(object):
def __init__(self, Df_band, nt):
self.bands = []
self.df = Df_band / nt
self.ro = []
def calculate(self, A, Df_band, over_band):
self.bands.append(Df_band)
self.ro.append(A)
if len(bands) == 1:
... | create_file_structure(kk)
_temps = create_destroy(inside_var, str(kk))
_temps.prepare_folder()
large_dic['lams'] = lams[kk]
large_dic['master_index'] = kk
large_dic[outside_var_key] = variable
if profiler_bool:
for i in range(len(D_ins)):
form... | conditional_block |
oscillator.py | import numpy as np
import sys
import os
import sys
sys.path.append('src')
from scipy.constants import c, pi
from joblib import Parallel, delayed
from mpi4py.futures import MPIPoolExecutor
from mpi4py import MPI
from scipy.fftpack import fftshift, fft
import os
import time as timeit
os.system('export FONTCONFIG_PATH=/et... |
U_original_pump = np.copy(U)
# Pass the original pump through the WDM1, port1 is in to the loop, port2
noise_new = noise_obj.noise_func_freq(int_fwm, sim_wind)
u, U = WDM_vec[0].pass_through((U, noise_new))[0]
ro = -1
t_total = 0
factors_xpm, factors_fwm,gama,tsh, w_tiled = \
... | random_line_split | |
oscillator.py | import numpy as np
import sys
import os
import sys
sys.path.append('src')
from scipy.constants import c, pi
from joblib import Parallel, delayed
from mpi4py.futures import MPIPoolExecutor
from mpi4py import MPI
from scipy.fftpack import fftshift, fft
import os
import time as timeit
os.system('export FONTCONFIG_PATH=/et... |
class Band_predict(object):
def __init__(self, Df_band, nt):
self.bands = []
self.df = Df_band / nt
self.ro = []
def calculate(self, A, Df_band, over_band):
self.bands.append(Df_band)
self.ro.append(A)
if len(bands) == 1:
return Df_band + 1
... | "-----------------------------Stable parameters----------------------------"
# Number of computing cores for sweep
num_cores = arguments_determine(1)
# maximum tolerable error per step in integration
maxerr = 1e-13
ss = 1 # includes self steepening term
Df_ba... | identifier_body |
oscillator.py | import numpy as np
import sys
import os
import sys
sys.path.append('src')
from scipy.constants import c, pi
from joblib import Parallel, delayed
from mpi4py.futures import MPIPoolExecutor
from mpi4py import MPI
from scipy.fftpack import fftshift, fft
import os
import time as timeit
os.system('export FONTCONFIG_PATH=/et... | (self, Df_band, nt):
self.bands = []
self.df = Df_band / nt
self.ro = []
def calculate(self, A, Df_band, over_band):
self.bands.append(Df_band)
self.ro.append(A)
if len(bands) == 1:
return Df_band + 1
a = (self.bands[-1] - self.bands[-2]) / (self.... | __init__ | identifier_name |
server.go | // Copyright (C) 2018 by Alberto Bregliano <alberto.bregliano@pm.me>
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to u... | tp.ResponseWriter, r *http.Request) {
//Crea p come tipo Notifica con i suoi structs
var p Notifica
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&p); err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid request payload")
return
}
defer r.Body.Close()
//fmt.Println(p) //debug
ho... | eNotificaNoVoiceCall(w ht | identifier_name |
server.go | // Copyright (C) 2018 by Alberto Bregliano <alberto.bregliano@pm.me>
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to u... | cellulare, err := url.QueryUnescape(p.Cellulare)
messaggio, err := url.QueryUnescape(p.Messaggio)
if err != nil {
respondWithError(w, http.StatusBadRequest, err.Error())
log.Fatal(err.Error())
return
}
result := fmt.Sprintf("Ok. campi ricevuti: Hostname: %s, Service: %s, Piattaforma: %s, Reperibile: %s, C... | random_line_split | |
server.go | // Copyright (C) 2018 by Alberto Bregliano <alberto.bregliano@pm.me>
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to u... | crea il file .call che serve ad Asterisk per contattare il reperibile
func CreateCall(hostname, service, piattaforma, reperibile, cellulare, messaggio string) (err error) {
//Trasforma il campo passato in una stringa di 10 numeri
cell, err := verificaCell(reperibile)
if err != nil {
log.Printf("Cellulare non gest... | a := time.Now()
giorno := ora.Weekday()
//Partiamo che non siamo in FOB
ok = false
switch giorno {
//Se è sabato siamo in fob
case time.Saturday:
//fmt.Println("E' sabato")
ok = true
//Se è domenica siamo in fob
case time.Sunday:
//fmt.Println("E' Domenica")
ok = true
//Se invece è un giorno feriale d... | identifier_body |
server.go | // Copyright (C) 2018 by Alberto Bregliano <alberto.bregliano@pm.me>
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to u... | ende gli ultimi 10 caratteri del value
cell10cifre := string(value[len(value)-10:])
//test verifica che il valore sia composto da esattamente 10 cifre
test := regexp.MustCompile(`^[0-9]{10}$`)
switch {
case test.MatchString(cell10cifre) == true:
cell = cell10cifre
default:
cell = ""
err = fmt.Errorf("Il ce... | orf("Cellulare con poche cifre: %v", len(value))
log.Println(err.Error())
return "", err
}
//cell10cifre pr | conditional_block |
mod.rs | //! # Ready-to-use NLP pipelines and models
//!
//! Based on Huggingface's pipelines, ready to use end-to-end NLP pipelines are available as part of this crate. The following capabilities are currently available:
//!
//! **Disclaimer**
//! The contributors of this repository are not responsible for any generation from ... | //! ```ignore
//! # use rust_bert::pipelines::sequence_classification::Label;
//! let output = [
//! [
//! Label {
//! text: "politics".to_string(),
//! score: 0.972,
//! id: 0,
//! sentence: 0,
//! },
//! Label {
//! text: "public ... | //! # Ok(())
//! # }
//! ```
//!
//! outputs: | random_line_split |
backfill.py | from __future__ import annotations
import asyncio
from collections import Counter
from functools import partial
import itertools
import typing
from typing import (
AsyncIterator,
Dict,
Iterable,
NamedTuple,
Optional,
Set,
Tuple,
)
from async_service import Service
from eth.abc import (
... | # 2. Look for more missing nodes in neighboring accounts and their storage, etc.
#
# 1 and 2 are a little more cleanly handled outside this iterator, so we just
# exit and let the caller deal with it.
return
async def _missing_byte... | #
# In response to these situations, we might like to:
# 1. Debug log? | random_line_split |
backfill.py | from __future__ import annotations
import asyncio
from collections import Counter
from functools import partial
import itertools
import typing
from typing import (
AsyncIterator,
Dict,
Iterable,
NamedTuple,
Optional,
Set,
Tuple,
)
from async_service import Service
from eth.abc import (
... | (
self,
address_hash_nibbles: Nibbles,
account: Account,
starting_main_root: Hash32) -> AsyncIterator[TrackedRequest]:
storage_node_iterator = self._missing_storage_hashes(
address_hash_nibbles,
account.storage_root,
starting_m... | _missing_subcomponent_hashes | identifier_name |
backfill.py | from __future__ import annotations
import asyncio
from collections import Counter
from functools import partial
import itertools
import typing
from typing import (
AsyncIterator,
Dict,
Iterable,
NamedTuple,
Optional,
Set,
Tuple,
)
from async_service import Service
from eth.abc import (
... |
else:
active_storage_completion = 0
# Log backfill state stats as a progress indicator to the user:
# - nodes: the total number of nodes collected during this backfill session
# - accts: number of accounts completed, including all... | active_storage_completion = sum(
self._complete_trie_fraction(store_tracker)
for store_tracker in self._storage_trackers.values()
) / num_storage_trackers | conditional_block |
backfill.py | from __future__ import annotations
import asyncio
from collections import Counter
from functools import partial
import itertools
import typing
from typing import (
AsyncIterator,
Dict,
Iterable,
NamedTuple,
Optional,
Set,
Tuple,
)
from async_service import Service
from eth.abc import (
... |
class TrackedRequest(NamedTuple):
tracker: TrieNodeRequestTracker
node_hash: Hash32
prefix: Nibbles
| def __init__(self) -> None:
self._trie_fog = fog.HexaryTrieFog()
self._active_prefixes: Set[Nibbles] = set()
# cache of nodes used to speed up trie walking
self._node_frontier_cache = fog.TrieFrontierCache()
def mark_for_review(self, prefix: Nibbles) -> None:
# Calling this... | identifier_body |
copy_up.go | // Copyright 2018 The gVisor 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 law or agree... |
// Take a reference on the upper Inode (transferred to
// next.Inode.overlay.upper) and make new translations use it.
next.Inode.overlay.dataMu.Lock()
childUpperInode.IncRef()
next.Inode.overlay.upper = childUpperInode
next.Inode.overlay.dataMu.Unlock()
// Invalidate existing translations through the lower In... | {
// Remember which mappings we added so we can remove them on failure.
allAdded := make(map[memmap.MappableRange]memmap.MappingsOfRange)
for seg := next.Inode.overlay.mappings.FirstSegment(); seg.Ok(); seg = seg.NextSegment() {
added := make(memmap.MappingsOfRange)
for m := range seg.Value() {
if err :... | conditional_block |
copy_up.go | // Copyright 2018 The gVisor 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 law or agree... |
// copyUpLocked creates a copy of next in the upper filesystem of parent.
//
// copyUpLocked must be called with d.Inode.overlay.copyMu locked.
//
// Returns a generic error on failure.
//
// Preconditions:
// - parent.Inode.overlay.upper must be non-nil.
// - next.Inode.overlay.copyMu must be locked writable.
// - n... | {
// Fail fast on Inode types we won't be able to copy up anyways. These
// Inodes may block in GetFile while holding copyMu for reading. If we
// then try to take copyMu for writing here, we'd deadlock.
t := d.Inode.overlay.lower.StableAttr.Type
if t != RegularFile && t != Directory && t != Symlink {
return sys... | identifier_body |
copy_up.go | // Copyright 2018 The gVisor 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 law or agree... | if err != nil {
log.Warningf("copy up failed to read symlink value: %v", err)
return syserror.EIO
}
if err := parentUpper.CreateLink(ctx, root, link, next.name); err != nil {
log.Warningf("copy up failed to create symlink: %v", err)
return syserror.EIO
}
childUpper, err := parentUpper.Lookup(ctx, ... | link, err := childLower.Readlink(ctx) | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.