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
Transformer_prac.py
Logsoftmax๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค self.const = np.sqrt(d_k) # d_k๋Š”? def forward(self, Q, K, V, att_mask): # att_mask๋Š” score = torch.matmul(Q,K.transpose(-1,-2))/self.const # tranpose: ์ฃผ์–ด์ง„ dim0๊ณผ dim1์ด ์„œ๋กœ ๋ฐ”๊ฟ˜๋‹ค score.masked_fill_(att_mask, -1e9) # masked! # masked_fill_(mask, value) mask๋Š” boolean...
enc_input, dec_input, target_batch = make_batch(sentence) outputs, enc_self_attns, dec_self_attns, dec_enc_attns = model(enc_input, dec_input) loss = criterion(outputs, target_batch.contiguous().view(-1)) print('Epoch:','%04d'%(epoch+1), 'cost = '.format(loss)) loss.backward()
random_line_split
importer.go
the cfg. ModifiedBy string `gae:"modified_by"` // ModifiedTS is the time when this entity was last modified. ModifiedTS time.Time `gae:"modified_ts"` } var GroupNameRe = regexp.MustCompile(`^([a-z\-]+/)?[0-9a-z_\-\.@]{1,100}$`) // GroupBundle is a map where k: groupName, v: list of identities belonging to group ...
if entry == nil { return nil, 0, errors.New("entry is nil") } if entry.Name == "" { return nil, 0, errors.New("entry not found in tarball upload names") } if !contains(caller.Email(), entry.AuthorizedUploader) { return nil, 0, errors.New(fmt.Sprintf("%q is not an authorized uploader", caller.Email())) } ...
{ g, err := GetGroupImporterConfig(ctx) if err != nil { return nil, 0, err } gConfigProto, err := g.ToProto() if err != nil { return nil, 0, errors.Annotate(err, "issue getting proto from config entity").Err() } caller := auth.CurrentIdentity(ctx) var entry *configspb.GroupImporterConfig_TarballUploadEntry ...
identifier_body
importer.go
// including removal of groups that are on the server, but no longer present in // the tarball. // Plain list format should have one userid per line and can only describe a single // group in a single system. Such groups will be added to 'external/*' groups // namespace. Removing such group from importer config will r...
// Each tarball may have groups from multiple external systems, but groups from // some external system must not be split between multiple tarballs. When importer // sees <external group system name>/* in a tarball, it modifies group list from // that system on the server to match group list in the tarball _exactly_,
random_line_split
importer.go
nil, err } if _, ok := bundles[system]; !ok { bundles[system] = make(GroupBundle) } bundles[system][filename] = identities } return bundles, nil } func loadGroupFile(identities string, domain string) ([]identity.Identity, error) { members := make(map[identity.Identity]bool) memsSplit := strings.Split(i...
{ systemGroups = append(systemGroups, gID) }
conditional_block
importer.go
the cfg. ModifiedBy string `gae:"modified_by"` // ModifiedTS is the time when this entity was last modified. ModifiedTS time.Time `gae:"modified_ts"` } var GroupNameRe = regexp.MustCompile(`^([a-z\-]+/)?[0-9a-z_\-\.@]{1,100}$`) // GroupBundle is a map where k: groupName, v: list of identities belonging to group ...
(ctx context.Context) (*GroupImporterConfig, error) { groupsCfg := &GroupImporterConfig{ Kind: "GroupImporterConfig", ID: "config", } switch err := datastore.Get(ctx, groupsCfg); { case err == nil: return groupsCfg, nil case err == datastore.ErrNoSuchEntity: return nil, err default: return nil, error...
GetGroupImporterConfig
identifier_name
storeserv.py
verify=True): """ HPE 3PAR constructor. :param str address: Hostname or IP address of HPE 3PAR array (management address). Web Services API should be enabled for this array (disabled by default). To enable Web Services API you should check 3PAR OS command: s...
return self._query(url, 'GET') def post(self, url, body): """ Perform HTTP POST request to HPE 3PAR array. Method used to create new objects. :param str url: URL address. Base part of url address is generated automatically and you should not care about it. Examp...
" Perform HTTP GET request to HPE 3PAR array. Method used to get information about objects. :param str url: URL address. Base part of url address is generated automatically and you should not care about it. Example of valid url: 'system' or 'volumes'. All available url's...
identifier_body
storeserv.py
% (self._base_url, url.strip('/')) request = requests.Request(method, path, **kwargs) prep = request.prepare() LOG.debug('%s(`%s`)', method, prep.url) LOG.debug('Request body = `%s`', prep.body) # Perform request with runtime measuring with warnings.catch_warnings(): ...
exit__(s
identifier_name
storeserv.py
verify=True): """ HPE 3PAR constructor. :param str address: Hostname or IP address of HPE 3PAR array (management address). Web Services API should be enabled for this array (disabled by default). To enable Web Services API you should check 3PAR OS command: s...
elif status == 403: # 403 (forbidden) => Wrong user or password raise AuthError('Cannot connect to StoreServ. ' 'Authentification error: %s', data['desc']) def close(self): """ Close Rest API session. :return: None """ ...
lf._headers.update({'X-HP3PAR-WSAPI-SessionKey': data['key']}) self._key = data['key']
conditional_block
storeserv.py
LOG = logging.getLogger('hpestorapi.storeserv') class StoreServ: """ HPE 3PAR array implementation class. """ def __init__(self, address, username, password, port=None, ssl=True, verify=True): """ HPE 3PAR constructor. :param str address: Hostname or IP address of HPE 3PA...
if __name__ == "__main__": pass
random_line_split
repository_repository.py
('ir.module.module', string='Modules') module_count = fields.Integer('Modules') state = fields.Selection(string="Estado", selection=[('draft', 'Borrador'), ('cloned', 'Clonado'), ('enabled', 'Enabled'), ('disabled', 'Disabled')], default='draf...
else: return False def info(self): branch = self._repo.active_branch.name curr_rev = self._repo.rev_parse(branch) git = self.info_base() source = self._repo.remotes.origin.url.split('@') if len(source) > 1: source = "https://" + sourc...
self._repo = Repo(self._path) return True
conditional_block
repository_repository.py
('ir.module.module', string='Modules') module_count = fields.Integer('Modules') state = fields.Selection(string="Estado", selection=[('draft', 'Borrador'), ('cloned', 'Clonado'), ('enabled', 'Enabled'), ('disabled', 'Disabled')], default='draf...
'target': 'current', 'domain': [('id', 'in', self.module_ids.ids)] } def install_requirements(self): try: requirement_file = self.path + '/requirements.txt' if os.path.exists(requirement_file): subprocess.check_call(["pip3", "install",...
'res_model': 'ir.module.module', 'view_type': 'form', 'view_mode': 'kanban,tree,form',
random_line_split
repository_repository.py
ir.module.module', string='Modules') module_count = fields.Integer('Modules') state = fields.Selection(string="Estado", selection=[('draft', 'Borrador'), ('cloned', 'Clonado'), ('enabled', 'Enabled'), ('disabled', 'Disabled')], default='draft'...
(path): return [module for module in os.listdir(path) if any(map( lambda f: isfile(path_join(path, module, f)), ( '__manifest__.py', '__openerp__.py')))] class Git(): _source_http = None _source_git = None _repo = None _user = None _pass = None _path = None _output_...
find_modules
identifier_name
repository_repository.py
('ir.module.module', string='Modules') module_count = fields.Integer('Modules') state = fields.Selection(string="Estado", selection=[('draft', 'Borrador'), ('cloned', 'Clonado'), ('enabled', 'Enabled'), ('disabled', 'Disabled')], default='draf...
class Git(): _source_http = None _source_git = None _repo = None _user = None _pass = None _path = None _output_list = [] def __init__(self, path=None, user=None, password=None): self._path = path self._user = user self._pass = password def remove(self): ...
return [module for module in os.listdir(path) if any(map( lambda f: isfile(path_join(path, module, f)), ( '__manifest__.py', '__openerp__.py')))]
identifier_body
mod.rs
use anyhow::{anyhow, Result}; use bevy_ecs::{ ComponentId, DynamicFetch, DynamicFetchResult, DynamicQuery, DynamicSystem, EntityBuilder, QueryAccess, StatefulQuery, TypeAccess, TypeInfo, World, }; use bincode::DefaultOptions; use fs::OpenOptions; use io::IoSlice; use mem::ManuallyDrop; use quill::ecs::TypeLayou...
todo, u32, vec, };
random_line_split
mod.rs
LazyInit<NativeFunc<(WasmPtr<RawBuffer>, u32)>>, rpcs: Arc<Mutex<HashMap<String, Box<dyn Fn(&mut Buffer, &PluginEnv<S>) -> Result<()> + Send>>>>, state: Arc<Mutex<S>>, layouts: Arc<Mutex<Layouts>>, } impl<S: Send + Sync + 'static> Clone for PluginEnv<S> { fn clone(&self) -> Self { Self { ...
write
identifier_name
mod.rs
, Function, HostEnvInitError, Instance, LazyInit, Memory, Module, NativeFunc, Store, Type, ValueType, WasmPtr, WasmTypeList, WasmerEnv, JIT, LLVM, }; use wasmer_wasi::WasiState; use serde::{de::DeserializeOwned, Deserialize, Serialize}; #[derive(Default)] struct PluginEnv<S> { memory: LazyInit<Memory>, ...
} struct Buffer<'a> { memory: &'a Memory, // fn reserve(ptr: WasmPtr<u8, Array>, cap: u32, len: u32, additional: u32) reserve: &'a NativeFunc<(WasmPtr<RawBuffer>, u32)>, raw: WasmPtr<RawBuffer>, } #[repr(C)] #[derive(Debug, Clone, Copy)] struct RawBuffer { ptr: WasmPtr<u8, Array>, cap: u32, ...
{ let mut query = DynamicQuery::default(); query.access = self.access(layouts)?; // TODO: TypeInfo Ok(query) }
identifier_body
scheduler.rs
: usize) -> Result<Worker> { let client = reqwest::Client::builder().timeout(None).build()?; let mut url = format!("{}/analyze_address", url); if timeout > 0 { url.push_str("_timeout"); } let timeout = Duration::from_secs((timeout * 60) as u64); Ok(Worker { ...
fn add_worker(&self, worker: Worker) { self.queue.lock().unwrap().push(worker); } fn get_worker(&self) -> WorkerHandle { let worker; loop { if let Some(w) = self.queue.lock().unwrap().pop() { worker = Some(w); break; } ...
{ let s = Scheduler::new(); for url in &urls { s.queue.lock().unwrap().push(Worker::new(url, timeout).unwrap()); // if the workers can not connect initially fail } s }
identifier_body
scheduler.rs
: usize) -> Result<Worker> { let client = reqwest::Client::builder().timeout(None).build()?; let mut url = format!("{}/analyze_address", url); if timeout > 0 { url.push_str("_timeout"); } let timeout = Duration::from_secs((timeout * 60) as u64); Ok(Worker { ...
(path: &str) -> (Arc<Mutex<Vec<(usize, String)>>>, usize) { let mut acc_list = String::new(); File::open(path) .expect("Could not open account list") .read_to_string(&mut acc_list) .expect("Could not read account list"); let acc_vec: Vec<(usize, String)> = acc_list .lines() ...
parse_account_list
identifier_name
scheduler.rs
timeout: usize) -> Result<Worker> { let client = reqwest::Client::builder().timeout(None).build()?; let mut url = format!("{}/analyze_address", url); if timeout > 0 { url.push_str("_timeout"); } let timeout = Duration::from_secs((timeout * 60) as u64); Ok(Wor...
} res } } impl<'a> Drop for WorkerHandle<'a> { fn drop(&mut self) { if !self.kill { let worker = self .worker .take() .expect("Worker replaced before adding back"); self.scheduler.add_worker(worker) } else {...
}
random_line_split
scheduler.rs
* 60) as u64); Ok(Worker { client, url: url, timeout, }) } fn analyze(&self, address: Address) -> Result<AnalysisSuccess> { info!("Analyzing {:x}", address.0); let mut res = if self.timeout > Duration::from_secs(0) { self ...
{ res.0 = true; }
conditional_block
lib.rs
<Body>) -> Option<BoxFuture<'_, Response<Body>>>; } impl Handler for Arc<dyn Handler> { fn handles(&self, request: &Request<Body>) -> Option<BoxFuture<'_, Response<Body>>> { (**self).handles(request) } } impl TestServer { /// return the scheme of the TestServer fn scheme(&self) -> &'static str...
<'a>( listener: &'a mut fuchsia_async::net::TcpListener, ) -> impl Stream<Item = std::io::Result<fuchsia_async::net::TcpStream>> + 'a { use std::task::{Context, Poll}; #[pin_project::pin_project] struct AcceptStream<'a> { #[pin] listener: &'a mut fuchsia_async::net::TcpListener, } ...
accept_stream
identifier_name
lib.rs
<Body>) -> Option<BoxFuture<'_, Response<Body>>>; } impl Handler for Arc<dyn Handler> { fn handles(&self, request: &Request<Body>) -> Option<BoxFuture<'_, Response<Body>>> { (**self).handles(request) } } impl TestServer { /// return the scheme of the TestServer fn scheme(&self) -> &'static str...
else { (None, false) }; let task = fasync::Task::spawn(async move { let listener = accept_stream(&mut listener); let listener = listener .map_err(Error::from) .map_ok(|conn| fuchsia_hyper::TcpStream { stream: conn }); le...
{ // build a server configuration using a test CA and cert chain let mut tls_config = rustls::ServerConfig::new(rustls::NoClientAuth::new()); tls_config.set_single_cert(cert_chain, private_key).unwrap(); let tls_acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(tls_conf...
conditional_block
lib.rs
<Body>) -> Option<BoxFuture<'_, Response<Body>>>; } impl Handler for Arc<dyn Handler> { fn handles(&self, request: &Request<Body>) -> Option<BoxFuture<'_, Response<Body>>> { (**self).handles(request) } } impl TestServer { /// return the scheme of the TestServer fn scheme(&self) -> &'static str...
} AcceptStream { listener } } #[cfg(not(target_os = "fuchsia"))] fn accept_stream<'a>( listener: &'a mut async_net::TcpListener, ) -> impl Stream<Item = std::io::Result<async_net::TcpStream>> + 'a { listener.incoming() } fn parse_cert_chain(mut bytes: &[u8]) -> Vec<rustls::Certificate> { rustls:...
{ let mut this = self.project(); match this.listener.async_accept(cx) { Poll::Ready(Ok((conn, _addr))) => Poll::Ready(Some(Ok(conn))), Poll::Ready(Err(err)) => Poll::Ready(Some(Err(err))), Poll::Pending => Poll::Pending, } }
identifier_body
lib.rs
<Body>) -> Option<BoxFuture<'_, Response<Body>>>; } impl Handler for Arc<dyn Handler> { fn handles(&self, request: &Request<Body>) -> Option<BoxFuture<'_, Response<Body>>> { (**self).handles(request) } } impl TestServer { /// return the scheme of the TestServer fn scheme(&self) -> &'static str...
/// A builder to construct a `TestServer`. #[derive(Default)] pub struct TestServerBuilder { handlers: Vec<Arc<dyn Handler>>, https_certs: Option<(Vec<rustls::Certificate>, rustls::PrivateKey)>, } impl TestServerBuilder { /// Create a new TestServerBuilder pub fn new() -> Self { Self::default(...
/// Create a Builder pub fn builder() -> TestServerBuilder { TestServerBuilder::new() } }
random_line_split
concurrent_ntlm_auth_requests.py
if num> len(sequences): num = len(sequences) choices = random.sample(sequences,num) return choices def popen_curl_request(url,user,eth,proxy='172.17.33.23:8080',cert='rootCA.cer'): curl_cmd = 'curl --cacert {0} --interface {1} --proxy-user {2}:Firewall1 --proxy-ntlm -x {3} {4} &'.fo...
quences.append(prefix+str(i))
conditional_block
concurrent_ntlm_auth_requests.py
subp = subprocess.Popen(curl_cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,close_fds=True)#,encoding="utf-8") try: subp.wait(2) #็ญ‰ๅพ…่ถ…ๆ—ถ except Exception as e: print('curl_request_timeout, error: ',e) return if subp.poll() == 0: print(subp.communicate(...
def popen_curl_request(url,user,eth,proxy='172.17.33.23:8080',cert='rootCA.cer'): curl_cmd = 'curl --cacert {0} --interface {1} --proxy-user {2}:Firewall1 --proxy-ntlm -x {3} {4} &'.format( cert,eth,user,proxy,url)
random_line_split
concurrent_ntlm_auth_requests.py
{3} {4} &'.format( cert,eth,user,proxy,url) subp = subprocess.Popen(curl_cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,close_fds=True)#,encoding="utf-8") try: subp.wait(2) #็ญ‰ๅพ…่ถ…ๆ—ถ except Exception as e: print('curl_request_timeout, error: ',e) return ...
172.18.1.', cert='rootCA.cer',is_same_url=False, is_http=False,debug=False): """ one ip/eth<--> one user """ i = 0 #count = max(len(urls),user_num,eth_num) #for url in urls: for i in range(max(user_num,eth_num)): url = '' if is_same_url: if is_http: ...
ip_prefix = '
identifier_name
concurrent_ntlm_auth_requests.py
3} {4} &'.format( cert,eth,user,proxy,url) subp = subprocess.Popen(curl_cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,close_fds=True)#,encoding="utf-8") try: subp.wait(2) #็ญ‰ๅพ…่ถ…ๆ—ถ except Exception as e: print('curl_request_timeout, error: ',e) return ...
else: #ๆ— ๅ่ฎฎๅคด้ƒจ๏ผŒ้ป˜่ฎคๅŠ httpๅ่ฎฎ url_list[i] = "https://" + url_list[i] return url_list def get_eth_user_index(sequence=0,user_start=30,user_num=10,eth_start=0,e th_num=254): """ inet 172.18.1.1/16 brd 172.18.255.255 scope global secondary eth0:0 inet 172.18.1.254/16 brd 172.18.255....
ๅˆ†็ฑปๆต‹่ฏ•๏ผŒๆต‹่ฏ•ๆ–‡ไปถไธญๅญ˜ๆ”พๅคง้‡็š„urlๅœฐๅ€ :param from_file: str :return: list๏ผŒ URL_list๏ผˆGenerator๏ผ‰ """ txtfile = open(from_file, 'r',encoding='utf-8') url_list = txtfile.readlines() for i in range(0,len(url_list)): url_list[i] = url_list[i].replace('\n','') # print(url_list[i]) if ur...
identifier_body
spline.rs
_vec(); if control_points.len() == 2 { kind = SliderSplineKind::Linear; } if control_points.len() == 3 && Math::is_line( control_points[0].to_float::<f64>().unwrap(), control_points[1].to_float::<f64>().unwrap(), control_poi...
self.cumulative_lengths[idx].into_inner(), ); let proportion = (length - len1) / (len2 - len1); let (p1, p2) = (self.spline_points[idx - 1], self.spline_points[idx]); (p2 - p1) * P::new(proportion, proportion) + p1 } ...
let (len1, len2) = ( self.cumulative_lengths[idx - 1].into_inner(),
random_line_split
spline.rs
_vec(); if control_points.len() == 2 { kind = SliderSplineKind::Linear; } if control_points.len() == 3 && Math::is_line( control_points[0].to_float::<f64>().unwrap(), control_points[1].to_float::<f64>().unwrap(), control_poi...
(control_points: &[P], l: &mut [P], r: &mut [P], midpoints_buf: &mut [P]) { let count = control_points.len(); midpoints_buf.copy_from_slice(control_points); for i in 0..count { l[i] = midpoints_buf[0]; r[count - i - 1] = midpoints_buf[count - i - 1]; for j in 0..count - i - 1 { ...
subdivide
identifier_name
spline.rs
_vec(); if control_points.len() == 2 { kind = SliderSplineKind::Linear; } if control_points.len() == 3 && Math::is_line( control_points[0].to_float::<f64>().unwrap(), control_points[1].to_float::<f64>().unwrap(), control_poi...
/// Calculate the angle at the given length on the slider fn angle_at_length(&self, length: f64) -> P { let _length_notnan = NotNan::new(length).unwrap(); // match self.cumulative_lengths.binary_search(&length_notnan) { // Ok(_) => {} // Err(_) => {} // } ...
{ self.spline_points.last().cloned().unwrap() }
identifier_body
spline.rs
_vec(); if control_points.len() == 2 { kind = SliderSplineKind::Linear; } if control_points.len() == 3 && Math::is_line( control_points[0].to_float::<f64>().unwrap(), control_points[1].to_float::<f64>().unwrap(), control_poi...
let diff = (t1 - t0).abs(); let pixel_length = pixel_length.unwrap_or(radius * diff); // circumference is 2 * pi * r, slider length over circumference is length/(2 * pi * r) let direction_unit = (t1 - t0) / (t1 - t0).abs(); let new_t1 = t0...
{ let (p1, p2, p3) = (points[0], points[1], points[2]); let (center, radius) = Math::circumcircle(p1, p2, p3); // find the t-values of the start and end of the slider let t0 = (center.y - p1.y).atan2(p1.x - center.x); let mut mid = (center...
conditional_block
pattern.rs
// This is the search method from the Searcher trait /// let matches = same_add.search(&egraph); /// let matched_eclasses: Vec<Id> = matches.iter().map(|m| m.eclass).collect(); /// assert_eq!(matched_eclasses, vec![a11, a22]); /// ``` /// /// [`FromStr`]: std::str::FromStr #[derive(Debug, PartialEq, Clone)] pub struct...
lf) -> Vec<Var> { Pattern::vars(self) } } impl<L, A> Applier<L, A> for Pattern<L> where L: Language, A: Analysis<L>, { fn get_pattern_ast(&self) -> Option<&PatternAst<L>> { Some(&self.ast) } fn apply_matches( &self, egraph: &mut EGraph<L, A>, matches: &[...
(&se
identifier_name
pattern.rs
Display> Pattern<L> { /// Pretty print this pattern as a sexp with the given width pub fn pretty(&self, width: usize) -> String { self.ast.pretty(width) } } /// The language of [`Pattern`]s. /// #[derive(Debug, Hash, PartialEq, Eq, Clone, PartialOrd, Ord)] pub enum ENodeOrVar<L> { /// An enode...
}; ids[i] = id;
random_line_split
pattern.rs
// This is the search method from the Searcher trait /// let matches = same_add.search(&egraph); /// let matched_eclasses: Vec<Id> = matches.iter().map(|m| m.eclass).collect(); /// assert_eq!(matched_eclasses, vec![a11, a22]); /// ``` /// /// [`FromStr`]: std::str::FromStr #[derive(Debug, PartialEq, Clone)] pub struct...
fn vars(&self) -> Vec<Var> { Pattern::vars(self) } } impl<L, A> Applier<L, A> for Pattern<L> where L: Language, A: Analysis<L>, { fn get_pattern_ast(&self) -> Option<&PatternAst<L>> { Some(&self.ast) } fn apply_matches( &self, egraph: &mut EGraph<L, A>, ...
let substs = self.program.run(egraph, eclass); if substs.is_empty() { None } else { let ast = Some(Cow::Borrowed(&self.ast)); Some(SearchMatches { eclass, substs, ast, }) } }
identifier_body
pattern.rs
} } impl<L: Language + Display> Pattern<L> { /// Pretty print this pattern as a sexp with the given width pub fn pretty(&self, width: usize) -> String { self.ast.pretty(width) } } /// The language of [`Pattern`]s. /// #[derive(Debug, Hash, PartialEq, Eq, Clone, PartialOrd, Ord)] pub enum ENodeOrV...
let n = e.clone().map_children(|child| ids[usize::from(child)]); trace!("adding: {:?}", n); egraph.add(n) }
conditional_block
main.rs
v| v.set_year(bib.year())), } } } #[derive(Serialize, Deserialize)] enum Degree { BS, MS, PhD, } impl Degree { fn
(&self) -> String { match self { Self::BS => "Bachelor of Science".into(), Self::MS => "Master of Science".into(), Self::PhD => "PhD".into(), } } } #[derive(Serialize, Deserialize)] struct Education { institution: String, degree: Degree, major: String, duration: DateRange, #[serde(skip_serializing_i...
to_resume_string
identifier_name
main.rs
fn deserialize<D: Deserializer<'a>>(d: D) -> Result<Self, D::Error> { let s = String::deserialize(d)?; s.parse().map_err(serde::de::Error::custom) } } #[derive(Serialize, Deserialize, Debug)] #[serde(untagged)] enum Citation { Raw(String), RawWithYear { text: String, year: Option<u32> }, Url(citation::UrlCita...
} impl<'a> Deserialize<'a> for DateRange {
random_line_split
readbuf.rs
/// A borrowed byte buffer which is incrementally filled and initialized. /// /// This type is a sort of "double cursor". It tracks three regions in the buffer: a region at the beginning of the /// buffer that has been logically filled with data, a region that has been initialized at some point but not yet /// logicall...
random_line_split
readbuf.rs
some point but not yet /// logically filled, and a region at the end that is fully uninitialized. The filled region is guaranteed to be a /// subset of the initialized region. /// /// In summary, the contents of the buffer can be visualized as: /// ```not_rust /// [ capacity ] /// [ filled | ...
/// Returns a mutable reference to the initialized portion of the cursor. #[inline] pub fn init_mut(&mut self) -> &mut [u8] { // SAFETY: We only slice the initialized part of the buffer, which is always valid unsafe { MaybeUninit::slice_assume_init_mut(&mut self.buf.buf[self.bu...
{ // SAFETY: We only slice the initialized part of the buffer, which is always valid unsafe { MaybeUninit::slice_assume_init_ref(&self.buf.buf[self.buf.filled..self.buf.init]) } }
identifier_body
readbuf.rs
{ buf, filled: 0, init: 0 } } } impl<'data> BorrowedBuf<'data> { /// Returns the total capacity of the buffer. #[inline] pub fn capacity(&self) -> usize { self.buf.len() } /// Returns the length of the filled part of the buffer. #[inline] pub fn len(&self) -> usize { s...
write
identifier_name
replicated_session.go
/block" "github.com/m3db/m3/src/dbnode/storage/bootstrap/result" "github.com/m3db/m3/src/dbnode/storage/index" "github.com/m3db/m3/src/dbnode/topology" "github.com/m3db/m3/src/x/ident" m3sync "github.com/m3db/m3/src/x/sync" xtime "github.com/m3db/m3/src/x/time" ) type newSessionFn func(Options) (clientSession, e...
{ s.log.Error("could not close async session: %v", zap.Error(err)) }
conditional_block
replicated_session.go
/block" "github.com/m3db/m3/src/dbnode/storage/bootstrap/result" "github.com/m3db/m3/src/dbnode/storage/index" "github.com/m3db/m3/src/dbnode/topology" "github.com/m3db/m3/src/x/ident" m3sync "github.com/m3db/m3/src/x/sync" xtime "github.com/m3db/m3/src/x/time" ) type newSessionFn func(Options) (clientSession, e...
// WriteTagged value to the database for an ID and given tags. func (s replicatedSession) WriteTagged( namespace, id ident.ID, tags ident.TagIterator, t xtime.UnixNano, value float64, unit xtime.Unit, annotation []byte, ) error { return s.replicate(replicatedParams{ namespace: namespace, id: id, t: ...
{ return s.replicate(replicatedParams{ namespace: namespace, id: id, t: t.Add(-s.writeTimestampOffset), value: value, unit: unit, annotation: annotation, }) }
identifier_body
replicated_session.go
/storage/block" "github.com/m3db/m3/src/dbnode/storage/bootstrap/result" "github.com/m3db/m3/src/dbnode/storage/index" "github.com/m3db/m3/src/dbnode/topology" "github.com/m3db/m3/src/x/ident" m3sync "github.com/m3db/m3/src/x/sync" xtime "github.com/m3db/m3/src/x/time" ) type newSessionFn func(Options) (clientSe...
annotation: annotation, tags: tags, useTags: true, }) } // Fetch values from the database for an ID. func (s replicatedSession) Fetch( namespace, id ident.ID, startInclusive, endExclusive xtime.UnixNano, ) (encoding.SeriesIterator, error) { return s.session.Fetch(namespace, id, startInclusive, endExc...
id: id, t: t.Add(-s.writeTimestampOffset), value: value, unit: unit,
random_line_split
replicated_session.go
/block" "github.com/m3db/m3/src/dbnode/storage/bootstrap/result" "github.com/m3db/m3/src/dbnode/storage/index" "github.com/m3db/m3/src/dbnode/topology" "github.com/m3db/m3/src/x/ident" m3sync "github.com/m3db/m3/src/x/sync" xtime "github.com/m3db/m3/src/x/time" ) type newSessionFn func(Options) (clientSession, e...
(opts Options) error { if opts.TopologyInitializer() == nil { return nil } session, err := s.newSessionFn(opts) if err != nil { return err } s.session = session return nil } func (s *replicatedSession) setAsyncSessions(opts []Options) error { sessions := make([]clientSession, 0, len(opts)) for i, oo := r...
setSession
identifier_name
shadow_logger.rs
::io::stdout(); let stdout_locked = stdout_unlocked.lock(); let mut stdout = std::io::BufWriter::new(stdout_locked); while toflush > 0 { let record = match self.records.pop() { Some(r) => r, None => { // This can happen if another ...
{ set_buffering_enabled(buffering_enabled != 0) }
identifier_body
shadow_logger.rs
(panic_info); })); Ok(()) } /// A logger specialized for Shadow. It attaches simulation context to log /// entries (e.g. sim time, running process, etc.). It's also designed for /// high performance to accomodate heavy logging from multiple threads. pub struct ShadowLogger { // Channel used to send comman...
enabled
identifier_name
shadow_logger.rs
. pub struct ShadowLogger { // Channel used to send commands to the logger's thread. // // The Sender half of a channel isn't Sync, so we must protect it with a // Mutex to make ShadowLogger be Sync. This is only accessed once per // thread, though, to clone into the thread-local SENDER. command...
}
random_line_split
raw_data_process.py
') as f: for line in f: stopwords.add(line.strip()) return stopwords class ProcessedData: def __init__(self, question, question_label, background, background_label): self.question = question self.question_label = question_label self.background = background s...
trip('ไบŽ') # ้•ฟๅบฆไธ็ฌฆๅˆๆˆ–ๅชๅŒ…ๅซๆ•ฐๅญ—ๅ’Œๅญ—ๆฏ if len(word.text) < self.least_word_len or word.text.isnumeric(): _words.remove(word) return _words @staticmethod def generate_tags(sequence_len: int, words: [Word]): """ ๆ นๆฎ้•ฟๅบฆๅ’Œไฝ็ฝฎ็ดขๅผ•ไบง็”ŸBIOๆ ‡็ญพ :param sequence_len: ้•ฟๅบฆ ...
word.s
identifier_name
raw_data_process.py
') as f: for line in f: stopwords.add(line.strip()) return stopwords class ProcessedData: def __init__(self, question, question_label, background, background_label): self.question = question self.question_label = question_label self.background = background s...
question = total_question['question'] # ่ทณ่ฟ‡ๆฒกๆœ‰่ƒŒๆ™ฏไฟกๆฏๆˆ–่งฃๆž็š„้ข˜็›ฎ if not background or not explain or len(explain) < 50: continue # ้ข„ๅค„็† background = preprocess(background) explain = preprocess(explain) ...
# ๅค„็†raw_data for idx, total_question in enumerate(raw_data): # ๆๅ–่ƒŒๆ™ฏๅ’Œ่งฃๆž background = total_question[background_key] explain = total_question['explanation']
random_line_split
raw_data_process.py
# ๅค„็†่ฟ‡็จ‹ไธญ็š„่ฏ้ข‘็ปŸ่ฎก {word : freq} self.words_counter = defaultdict(int) # ็ปŸ่ฎกๆ€ป้•ฟๅบฆ๏ผŒ่ฎพ็ฝฎๅˆ้€‚max_len {len : freq} self.length_counter = defaultdict(int) # ๅค„็†ๅฎŒ็š„word้›†ๅˆ self.processed_data: [ProcessedData] = [] def _get_same_word(self, source: str, target: str): """ ้ๅކๅŽŸ...
if not os.path.exists(store_data_path): os.makedirs(store_data_path) processor = RawProcessor(file_paths=file_paths, store_path=store_data_path, use_cut=use_cut,
identifier_body
raw_data_process.py
') as f: for line in f: stopwords.add(line.strip()) return stopwords class ProcessedData: def __init__(self, question, question_label, background, background_label): self.question = question self.question_label = question_label self.background = background s...
word) for word in jieba.tokenize(source)] target_cut = [Word(*word) for word in jieba.tokenize(target)] for word in source_cut: if word in target_cut and word.text not in STOPWORDS and len(word.text) >= self.least_word_len: res_words.append(word) return res_words ...
ut(self, source: str, target: str): """ ไฝฟ็”จ็ป“ๅทดๅˆ†่ฏๆฅๆŠฝๅ–็›ธๅŒ่ฏ """ res_words: [Word] = [] source_cut = [Word(*
conditional_block
exchange_endpoint0.py
eth_account import algosdk from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import scoped_session from sqlalchemy.orm import load_only from datetime import datetime import sys from models import Base, Order, Log engine = create_engine('sqlite:///orders.db') Base.metadata.bind = engine DBSession = sessionma...
print a dictionary nicely def print_dict(d): for key, value in d.items(): print(key, ' : ', value) """ End of helper methods """ @app.route('/trade', methods=['POST']) def trade(): print("In trade endpoint") if request.method == "POST": print("--------...
rn { c.name: getattr(row, c.name) for c in row.__table__.columns } #
identifier_body
exchange_endpoint0.py
eth_account import algosdk from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import scoped_session from sqlalchemy.orm import load_only from datetime import datetime import sys from models import Base, Order, Log engine = create_engine('sqlite:///orders.db') Base.metadata.bind = engine DBSession = sessionma...
# print(len(order_list)) # pick the first one in the list match_order = order_list[0] # Set the filled field to be the current timestamp on both orders # Set counterparty_id to be the id of the other order match_order.filled = datetime.now() current_order.filled ...
# If a match is found between order and existing_order if (len(order_list) > 0): # print(" order_list_length")
random_line_split
exchange_endpoint0.py
eth_account import algosdk from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import scoped_session from sqlalchemy.orm import load_only from datetime import datetime import sys from models import Base, Order, Log engine = create_engine('sqlite:///orders.db') Base.metadata.bind = engine DBSession = sessionma...
# check whether the input contains all 7 fields of payload for column in columns: if not column in content['payload'].keys(): print( f"{column} not received by Trade" ) print( json.dumps(content) ) log_message(content) ret...
t( f"{field} not received by Trade" ) print( json.dumps(content) ) log_message(content) return jsonify( False )
conditional_block
exchange_endpoint0.py
eth_account import algosdk from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import scoped_session from sqlalchemy.orm import load_only from datetime import datetime import sys from models import Base, Order, Log engine = create_engine('sqlite:///orders.db') Base.metadata.bind = engine DBSession = sessionma...
create_session() order_obj = Log(message=d) g.session.add(order_obj) shutdown_session() # convert a row in DB into a dict def row2dict(row): return { c.name: getattr(row, c.name) for c in row.__table__.columns } # print a dictionary nicely def print_dict(d): for key, valu...
message(d):
identifier_name
wxpayv3.go
// StWxPayRawResp ๅ›žๅค type StWxPayRawResp struct { ID string `json:"id"` CreateTime time.Time `json:"create_time"` ResourceType string `json:"resource_type"` EventType string `json:"event_type"` Summary string `json:"summary"` Resource struct { OriginalType string `json:"ori...
jsoniter "github.com/json-iterator/go" "github.com/parnurzeal/gorequest" )
random_line_split
wxpayv3.go
"` DiscountRefund int `json:"discount_refund"` PayerRefund int `json:"payer_refund"` PayerTotal int `json:"payer_total"` Refund int `json:"refund"` SettlementRefund int `json:"settlement_refund"` SettlementTotal int `json:"settlement_total"` Total int ...
]string) (string, error) { var buf bytes.Buffer for _, col := range cols { buf.WriteString(col) buf.WriteString("\n") } sign, err := RsaSign(buf.String(), key, crypto.SHA256) if err != nil { return "", err } return sign, nil } // WxPayV3Sign v3็ญพๅ func WxPayV3Sign(mchid, keySerial string, key *rsa.PrivateK...
ateKey, cols [
identifier_name
wxpayv3.go
nil { return err } hashed := sha256.Sum256([]byte(checkStr)) err = rsa.VerifyPKCS1v15(rsaPublicKey, crypto.SHA256, hashed[:], oldSign) return err } // WxPayV3GetHeaderByKey ่Žทๅ–ๅคด func WxPayV3GetHeaderByKey(header map[string][]string, key string) (string, error) { v, ok := header[key] if !ok { return "", fmt.E...
if rawResp.EventType != "REFUND.SUCCESS" { return nil, fmt.Errorf("error event_type: %s", rawResp.EventType) } if rawResp.ResourceType != "encrypt-resource" { return nil, fmt.Errorf("error resource_type: %s", rawResp.ResourceType) } originalType := rawResp.Resource.OriginalType if originalType != "refund" { ...
identifier_body
wxpayv3.go
time.Time `json:"success_time"` Amount struct { Total int `json:"total"` Refund int `json:"refund"` PayerTotal int `json:"payer_total"` PayerRefund int `json:"payer_refund"` } `json:"amount"` UserReceivedAccount string `json:"user_received_account"` } // RsaSign ็ญพๅ func RsaSign(signConte...
originalType := rawResp.Resource.OriginalType if originalType != "transaction
conditional_block
functions.py
5), (x, y, 50, 50), width=1) def print_log(): font = pygame.font.Font(None, 25) text_coord = 25 for line in all_logs: string_rendered = font.render(line, 1, pygame.Color('yellow')) intro_rect = string_rendered.get_rect() text_coord += 10 intro_rect.top = text_coord ...
s[0] def draw_white_rect(x, y): pygame.draw.rect(sc, (255, 255, 25
identifier_body
functions.py
_size * 2)) elif cur_level == 2: texture_wall = load_image("image/stone_wall2.png") texture_wall = pygame.transform.scale(texture_wall, (cell_size * 2, cell_size * 2)) else: texture_wall = load_image("image/wall3.jpg") texture_wall = pygame.transform.scale(texture_wall, (cell_siz...
name = "" if event.type == pygame.MOUSEBUTTONDOWN: if button_exit.push_button(event.pos): gameover(name, killed_monsters) text = font.render(name, True, (255, 255, 255)) rect = text.get_rect() rect.center = (600, 400) ...
if event.unicode.isalpha(): name += event.unicode elif event.key == K_BACKSPACE: name = name[:-1] elif event.key == K_RETURN:
random_line_split
functions.py
_size * 2)) elif cur_level == 2: texture_wall = load_image("image/stone_wall2.png") texture_wall = pygame.transform.scale(texture_wall, (cell_size * 2, cell_size * 2)) else: texture_wall = load_image("image/wall3.jpg") texture_wall = pygame.transform.scale(texture_wall, (cell_siz...
button_exit.draw() sc.blit(text, rect) sc.blit(title, (500, 250)) pygame.display.flip() def exchange_equipment_inventory(inventory, hero): obj = inventory.get_selected_cell() if obj.get_type() == "weapon": old_w = hero.replace_weapon(obj) inventory.board[invent...
0)
conditional_block
functions.py
* 2)) elif cur_level == 2: texture_wall = load_image("image/stone_wall2.png") texture_wall = pygame.transform.scale(texture_wall, (cell_size * 2, cell_size * 2)) else: texture_wall = load_image("image/wall3.jpg") texture_wall = pygame.transform.scale(texture_wall, (cell_size * 2...
ted_cell[0]][inventory.selected_cell[1]] = old_w if obj.get_name() == "Leg_armor1" or obj.get_name() == 'Leg_armor2': old_w = hero.replace_leg(obj) inventory.board[inventory.selected_cell[0]][inventory.selected_cell[1]] = old_w if obj.get_name() == "
entory.board[inventory.selec
identifier_name
machine.go
!= nil { if !apierrors.IsNotFound(err) { return nil, err } } else { machine.vmInstance = vm } return machine, nil } // IsTerminal Reports back if the VM is either being requested to terminate or is terminate // in a way that it will never recover from. func (m *Machine) IsTerminal() (bool, string, error)...
return 0, err } if retryDuration > 0 { return retryDuration, nil } } // now, when the node is drained (or vmiDeleteGraceTimeoutDurationSeconds has passed), we can delete the VMI propagationPolicy := metav1.DeletePropagationForeground err = m.client.Delete(m
retryDuration, err := m.drainNode(wrkldClstr) if err != nil {
random_line_split
machine.go
, "", nil } return false, "", nil } // Exists checks if the VM has been provisioned already. func (m *Machine) Exists() bool { return m.vmInstance != nil } // Create creates a new VM for this machine. func (m *Machine) Create(ctx gocontext.Context) error { m.machineContext.Logger.Info(fmt.Sprintf("Creating VM wi...
setVmiDeletionGraceTime
identifier_name
machine.go
!= nil { if !apierrors.IsNotFound(err) { return nil, err } } else { machine.vmInstance = vm } return machine, nil } // IsTerminal Reports back if the VM is either being requested to terminate or is terminate // in a way that it will never recover from. func (m *Machine) IsTerminal() (bool, string, error)...
switch runStrategy { case kubevirtv1.RunStrategyAlways: // VM should recover if it is down. return false, "", nil case kubevirtv1.RunStrategyManual: // If VM is manually controlled, we stay out of the loop return false, "", nil case kubevirtv1.RunStrategyHalted, kubevirtv1.RunStrategyOnce: if m.vmiInsta...
{ return false, "", err }
conditional_block
machine.go
] = m.machineContext.Cluster.Name virtualMachine.Labels[infrav1.KubevirtMachineNameLabel] = m.machineContext.KubevirtMachine.Name virtualMachine.Labels[infrav1.KubevirtMachineNamespaceLabel] = m.machineContext.KubevirtMachine.Namespace virtualMachine.Spec.Template.ObjectMeta.Labels[infrav1.KubevirtMachineNameLa...
{ m.machineContext.Logger.Info(fmt.Sprintf("setting the %s annotation", infrav1.VmiDeletionGraceTime)) graceTime := time.Now().Add(vmiDeleteGraceTimeoutDurationSeconds * time.Second).UTC().Format(time.RFC3339) patch := fmt.Sprintf(`{"metadata":{"annotations":{"%s": "%s"}}}`, infrav1.VmiDeletionGraceTime, graceTime) ...
identifier_body
header.go
, value := range header{ if ( srtcolindexInt==key){ sortColName = value } } fmt.Println(sortColName) tconf["ActionCol"] ="true" // config for action column tconf["ActionCol_param"] ="ID" // config for parameter of action tconf["ActionCol_edit"] ="true" // config for edit click tconf["ActionCo...
tconf["test_js"] = `alert("from webserver")` arr_sysrole := datatables.DataList(`sysrole_get 2`) type Data struct { Rights string Conf map[string]string Arr_Sysrole [][]string } tmpl := template.New("Hadd.html").Funcs(local_FuncMap) var err error if tmpl, err = tmpl.ParseFiles("admin/membe...
random_line_split
header.go
.New("Hadd.html").Funcs(local_FuncMap) var err error if tmpl, err = tmpl.ParseFiles("admin/member_role/Hadd.html"); err != nil { fmt.Println(err) } err1 := tmpl.Execute(w,&Data{rights , tconf ,arr_sysrole}) if err1 != nil { http.Error(w, err1.Error(), http.StatusInternalServerError) } }else { ...
HDeleteHandler
identifier_name
header.go
){ tconf["ActionCol_delete"] ="true" // config for delete click } if( strings.Contains(dec_rights, "HDetails") ){ tconf["ActionCol_detail"] ="true" // config for delete click } //end rights for tables //_,session_user_id := login.Get_account_info(r) session_user_id := 1 //static here ses...
{ //db_raw ,err, _,_ := config.Ap_sql(`LBR_OTHdr_Get 1 ,`+Hdr_id,1) db_raw ,err, _,_ := config.Ap_sql(`dailysumhdr_get 1,`+Hdr_id,1) if err != nil { panic(err.Error()) } var r Dailysumhdr_get for db_raw.Next() { err = db_raw.Scan(&r.ID, &r.Branch,&r.Docdate,&r.Remarks) if err != ...
identifier_body
header.go
Col_param"] ="ID" // config for parameter of action tconf["ActionCol_edit"] ="true" // config for edit click tconf["ActionCol_edit_is_modal"] ="false" // config for edit click //tconf["ActionCol_edit_url"] ="/timekeeping/overtime_logs/OvertimeLogsHeaderEdit?rights="+rights+"&h_id=" // config for edit click ...
{ r.ParseForm() item_id := r.Form["item_id"][0] username, _ := login.Get_account_info(r) Org_id :=login.Get_session_org_id(r) str_OrgID :=strconv.Itoa(Org_id) var returnData[] string for key ,_ := range r.Form["tag"] { tag := r.Form["tag"][key] value_input := r.Form["value_input"][key] remarks ...
conditional_block
main.rs
fmt::Result {self.as_never()} } impl ErrorTrait for Never {} } #[macro_use] mod rect; mod network; mod absm; pub struct Setup { ///Map from input device coordinates to output client coordinates. pub mapping: Mapping, ///Specify a minimum and a maximum on the final client coordinates. pub clip: Rect<i32>, ...
impl Default for Config { fn default()->Config { let screen_res=get_screen_resolution(); Config{ target: Rect{min: pair!(_=>0),max: screen_res}, source: Rect{min: pair!(_=>0.05),max: pair!(_=>0.95)}, clip: Rect{min: pair!(_=>0),max: screen_res}, correct_device_orientation: true, ...
///Whether to attempt to do ADB port forwarding automatically. ///The android device needs to have `USB Debugging` enabled. pub android_attempt_usb_connection: bool, }
random_line_split
main.rs
orientation"); }else{ println!("device orientation is aligned with client orientation"); } }else{ println!("device orientation correction is disabled"); } //Apply config device source area proportions let mut source=Rect{ min: source.map(|int| int as f32).denormaliz...
//Parse arguments let exec_path; let cfg_path; { let mut args=env::args(); exec_path=args.next().expect("first argument should always be executable path!"); cfg_path=args.next().unwrap_or_else(|| String::from("config.txt")); } //Load configuration let config=Config::load_path(&cfg_path); ...
identifier_body
main.rs
fmt::Result {self.as_never()} } impl ErrorTrait for Never {} } #[macro_use] mod rect; mod network; mod absm; pub struct Setup { ///Map from input device coordinates to output client coordinates. pub mapping: Mapping, ///Specify a minimum and a maximum on the final client coordinates. pub clip: Rect<i32>, ...
AsRef<Path>>(path: P,config: &Config)->Result<()> { use std::process::{Command}; let local_port=match config.remote { Remote::Tcp(_,port)=>port, _ => { println!("not connecting through tcp, skipping adb port forwarding"); return Ok(()) }, }; println!("attempting to adb port forward u...
_adb_forward<P:
identifier_name
offset-monitor.rs
} } fn run(cfg: Config) -> Result<()> { let mut client = KafkaClient::new(cfg.brokers.clone()); client.set_group_offset_storage(cfg.offset_storage); try!(client.load_metadata_all()); // ~ if no topic specified, print all available and be done. if cfg.topic.is_empty() { let ts = client....
let _ = write!(self.fmt_buf, "({})", curr_lag); let _ = write!(self.out_buf, " {1:<0$}", self.lag_width, self.fmt_buf); } } else { for p in partitions { let _ = write!(self.out_buf, " {1:>0$}", self.offset_width, p.c...
self.fmt_buf.clear();
random_line_split
offset-monitor.rs
} } fn run(cfg: Config) -> Result<()> { let mut client = KafkaClient::new(cfg.brokers.clone()); client.set_group_offset_storage(cfg.offset_storage); try!(client.load_metadata_all()); // ~ if no topic specified, print all available and be done. if cfg.topic.is_empty() { let ts = client.top...
{ prev_latest: i64, curr_latest: i64, curr_lag: i64, } impl Default for Partition { fn default() -> Self { Partition { prev_latest: -1, curr_latest: -1, curr_lag: -1, } } } struct State { offsets: Vec<Partition>, lag_decr: i64, } impl S...
Partition
identifier_name
offset-monitor.rs
} } fn run(cfg: Config) -> Result<()> { let mut client = KafkaClient::new(cfg.brokers.clone()); client.set_group_offset_storage(cfg.offset_storage); try!(client.load_metadata_all()); // ~ if no topic specified, print all available and be done. if cfg.topic.is_empty() { let ts = client.top...
fn print_head(&mut self, num_partitions: usize) -> Result<()> { self.out_buf.clear(); { // ~ format use std::fmt::Write; let _ = write!(self.out_buf, "{1:<0$}", self.time_width, "time"); if self.print_summary { let _ = write!(self.out...
{ Printer { out: out, timefmt: "%H:%M:%S".into(), fmt_buf: String::with_capacity(30), out_buf: String::with_capacity(160), time_width: 10, offset_width: 11, diff_width: 8, lag_width: 6, print_diff: cfg.di...
identifier_body
export_animation.py
for i in range(2): if isinstance(pos[i], (int, float)): pos[i] = pos[i] - half_size[i] pos[i] = int(coreapi.global_scale * pos[i]) clip = clip.set_position(pos) else: clip = clip.set_position(pos) if scale[0] != 1.0 or scale[1...
if clip_info.start is not None: clip = clip.set_start(clip_info.start) # Adjust volume by keypoints if len(clip_info.vol_keypoints) > 0: clip = _adjust_mpy_audio_clip_volume(clip, clip_info.vol_keypoints) clips.append(clip) if ...
if clip_info.loop: # pylint: disable=maybe-no-member clip = clip.fx(afx.audio_loop, duration=duration) else: duration = min(duration, clip.duration) if clip_info.subclip: duration = min( ...
conditional_block
export_animation.py
_info.fadeout = prev_clip_info.crossfade def _export_video(*, resolution, audio_only): resolution = [int(x * coreapi.global_scale) for x in resolution] audio_clips = [] # Update clip duration for each track for track in datastruct.video_tracks.values(): _update_clip_duration(track) # TO...
s = f.read() cwd = os.getcwd()
random_line_split
export_animation.py
audio subclip if clip_info.subclip is not None: duration = clip_info.subclip[1] - clip_info.subclip[0] audio_clip = audio_clip.subclip( clip_info.subclip[0], clip_info.subclip[1] ) else: ...
used_recordings = set() unused_recordings = [] apis = {"record": (lambda f, **kargs: used_recordings.add(f))} _parse_text(s, apis=apis) files = [f for f in glob.glob("record/*") if os.path.isfile(f)] files = [f.replace("\\", "/") for f in files] for f in files: if f not in used_record...
identifier_body
export_animation.py
.subclip[0] audio_clip = audio_clip.subclip( clip_info.subclip[0], clip_info.subclip[1] ) else: duration = clip_info.duration duration = min(duration, audio_clip.duration) audio_cl...
_parse_text
identifier_name
mock.rs
>; type OnKilledAccount = (); type OnNewAccount = (); type OnSetCode = (); type Origin = Origin; type PalletInfo = PalletInfo; type SS58Prefix = SS58Prefix; type SystemWeightInfo = (); type Version = (); } parameter_types! { pub const ExistentialDeposit: u128 = 1; } impl pallet_balances::Config for Test { typ...
{ System::events().pop().expect("Event expected").event }
identifier_body
mock.rs
type Block = frame_system::mocking::MockBlock<Test>; // Configure a mock runtime to test the pallet. construct_runtime!( pub enum Test where Block = Block, NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Pallet, Call, Config, Storage, Event<T>}, Timestamp: pallet_timest...
pub type Balance = u128; pub type BlockNumber = u64; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
random_line_split
mock.rs
Weight = 1024; pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); pub const SS58Prefix: u8 = 42; } impl frame_system::Config for Test { type AccountData = pallet_balances::AccountData<Balance>; type AccountId = AccountId; type BaseCallFilter = Everything; type...
<Ks: OpaqueKeys>(_: bool, keys: &[(u64, Ks)], _: &[(u64, Ks)]) { SessionChangeBlock::set(System::block_number()); dbg!(keys.len()); SessionHandlerCollators::set(keys.iter().map(|(a, _)| *a).collect::<Vec<_>>()) } fn on_before_session_ending() {} fn on_disabled(_: u32) {} } impl pallet_session::Config for Te...
on_new_session
identifier_name
mock.rs
{ pub const ExistentialDeposit: u128 = 1; } impl pallet_balances::Config for Test { type AccountStore = System; type Balance = Balance; type DustRemoval = (); type Event = Event; type ExistentialDeposit = ExistentialDeposit; type MaxLocks = (); type MaxReserves = (); type ReserveIdentifier = [u8; 4]; type We...
{ None }
conditional_block
test_agent.py
.append(uid) continue pred_list, rel_set = topk_matches[uid][::-1], test_user_products[uid] if len(pred_list) == 0: continue dcg = 0.0 hit_num = 0.0 for i in range(len(pred_list)): if pred_list[i] in rel_set: dcg += 1. / (log(i...
new_path = path + [(relation, next_node_type, next_node_id)] new_path_pool.append(new_path) new_probs_pool.append(probs + [p]) path_pool = new_path_pool probs_pool = new_probs_pool if hop < 2: state_pool = env._batch_get_state(path_poo...
next_node_type = KG_RELATION[path[-1][1]][relation]
conditional_block
test_agent.py
.append(uid) continue pred_list, rel_set = topk_matches[uid][::-1], test_user_products[uid] if len(pred_list) == 0: continue dcg = 0.0 hit_num = 0.0 for i in range(len(pred_list)): if pred_list[i] in rel_set: dcg += 1. / (log(i...
uid = path[0][2] if uid not in pred_paths: continue pid = path[-1][2] if pid not in pred_paths[uid]: pred_paths[uid][pid] = [] path_score = scores[uid][pid] path_prob = reduce(lambda x, y: x * y, probs) pred_paths[uid][pid].append((path_sco...
random_line_split
test_agent.py
dcg += 1. / (log(i + 2) / log(2)) hit_num += 1 # idcg idcg = 0.0 for i in range(min(len(rel_set), len(pred_list))): idcg += 1. / (log(i + 2) / log(2)) ndcg = dcg / idcg recall = hit_num / len(rel_set) precision = hit_num / len(p...
"""Compute metrics for predicted recommendations. Args: topk_matches: a list or dict of product ids in ascending order. """ invalid_users = [] # Compute metrics precisions, recalls, ndcgs, hits, fairness = [], [], [], [], [] test_user_idxs = list(test_user_products.keys()) for uid in...
identifier_body
test_agent.py
.append(uid) continue pred_list, rel_set = topk_matches[uid][::-1], test_user_products[uid] if len(pred_list) == 0: continue dcg = 0.0 hit_num = 0.0 for i in range(len(pred_list)): if pred_list[i] in rel_set: dcg += 1. / (log(i...
(batch_acts): batch_masks = [] for acts in batch_acts: num_acts = len(acts) act_mask = np.zeros(model.act_dim, dtype=np.uint8) act_mask[:num_acts] = 1 batch_masks.append(act_mask) return np.vstack(batch_masks) state_pool = env.reset(uids) # n...
_batch_acts_to_masks
identifier_name
non_blocking.rs
will drop the `_guard` and any remaining logs should get flushed /// # } /// } /// ``` #[must_use] #[derive(Debug)] pub struct WorkerGuard { handle: Option<JoinHandle<()>>, sender: Sender<Msg>, shutdown: Sender<()>, } /// A non-blocking writer. /// /// While the line between "blocking" and "non-blocking" ...
write
identifier_name
non_blocking.rs
backpressure will be exerted on senders, causing them to block their /// respective threads until there is available capacity. /// /// [non-blocking]: NonBlocking /// Recommended to be a power of 2. pub const DEFAULT_BUFFERED_LINES_LIMIT: usize = 128_000; /// A guard that flushes spans/events associated to a [`NonBlo...
Ok(buf_size) } fn flush(&mut self) -> io::Result<()> { Ok(()) } #[inline] fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { self.write(buf).map(|_| ()) } } impl<'a> MakeWriter<'a> for NonBlocking { type Writer = NonBlocking; fn make_writer(&'a self) -> ...
{ return match self.channel.send(Msg::Line(buf.to_vec())) { Ok(_) => Ok(buf_size), Err(_) => Err(io::Error::from(io::ErrorKind::Other)), }; }
conditional_block
non_blocking.rs
backpressure will be exerted on senders, causing them to block their /// respective threads until there is available capacity. /// /// [non-blocking]: NonBlocking /// Recommended to be a power of 2. pub const DEFAULT_BUFFERED_LINES_LIMIT: usize = 128_000; /// A guard that flushes spans/events associated to a [`NonBlo...
/// /// By default, the built `NonBlocking` will be lossy. pub fn lossy(mut self, is_lossy: bool) -> NonBlockingBuilder { self.is_lossy = is_lossy; self } /// Override the worker thread's name. /// /// The default worker thread name is "tracing-appender". pub fn thread_n...
random_line_split
non_blocking.rs
backpressure will be exerted on senders, causing them to block their /// respective threads until there is available capacity. /// /// [non-blocking]: NonBlocking /// Recommended to be a power of 2. pub const DEFAULT_BUFFERED_LINES_LIMIT: usize = 128_000; /// A guard that flushes spans/events associated to a [`NonBlo...
/// Override the worker thread's name. /// /// The default worker thread name is "tracing-appender". pub fn thread_name(mut self, name: &str) -> NonBlockingBuilder { self.thread_name = name.to_string(); self } /// Completes the builder, returning the configured `NonBlocking`. ...
{ self.is_lossy = is_lossy; self }
identifier_body
key.rs
/// /// // Until here memory buffer is read/write. Turns-it into a key /// let key = ProtKey::new(buf_rnd); /// /// // Or more simply, like this with exactly the same result /// let key: ProtKey8 = ProtBuf::new_rand_os(32).into_key(); /// /// { /// // Request access in read-mode /// let key_read = key.read(); /...
} /// An RAII protected key with write access /// /// This instance is the result of a `write` request on a `ProtKey`. Its /// raw memory may only be written during the lifetime of this object. pub struct ProtKeyWrite<'a, T: Copy + 'a, A: KeyAllocator + 'a> { ref_key: RefMut<'a, ProtBuf<T, A>>, } impl<'a, T: Co...
{ self.ref_key.fmt(f) }
identifier_body
key.rs
); /// /// // Until here memory buffer is read/write. Turns-it into a key /// let key = ProtKey::new(buf_rnd); /// /// // Or more simply, like this with exactly the same result /// let key: ProtKey8 = ProtBuf::new_rand_os(32).into_key(); /// /// { /// // Request access in read-mode /// let key_read = key.read()...
} impl<'a, T: Copy, A: KeyAllocator> Drop for ProtKeyRead<'a, T, A> { fn drop(&mut self) { self.read_ctr.set(self.read_ctr.get().checked_sub(1).unwrap()); if self.read_ctr.get() == NOREAD { unsafe { <A as KeyAllocator>::protect_none( self.ref_key.as_p...
pub fn clone_it(&self) -> ProtKeyRead<T, A> { ProtKeyRead::new(Ref::clone(&self.ref_key), self.read_ctr.clone()) }
random_line_split
key.rs
/// /// // Until here memory buffer is read/write. Turns-it into a key /// let key = ProtKey::new(buf_rnd); /// /// // Or more simply, like this with exactly the same result /// let key: ProtKey8 = ProtBuf::new_rand_os(32).into_key(); /// /// { /// // Request access in read-mode /// let key_read = key.read(); /...
(&self) -> ProtKey<T, A> { ProtKey::new(self.read().clone()) } } impl<T: Copy, A: KeyAllocator> PartialEq for ProtKey<T, A> { fn eq(&self, other: &ProtKey<T, A>) -> bool { match (self.try_read(), other.try_read()) { (Some(ref s), Some(ref o)) => *s == *o, (_, _) => false...
clone
identifier_name
laptop.pb.go
} func (m *Laptop) GetKeyboard() *Keyboard { if m != nil { return m.Keyboard } return nil } type isLaptop_Weight interface { isLaptop_Weight() } type Laptop_WeightKg struct { WeightKg float64 `protobuf:"fixed64,10,opt,name=weight_kg,json=weightKg,proto3,oneof"` } type Laptop_WeightLb struct { WeightLb float...
return "" } func init() { proto.RegisterType((*Laptop)(nil), "pc.Laptop") proto.RegisterType((*CreateLaptopRequest)(nil), "pc.CreateLaptopRequest") proto.RegisterType((*CreateLaptopResponse)(nil), "pc.CreateLaptopResponse") } func init() { proto.RegisterFile("laptop.proto", fileDescriptor_28a7e4886f546705) } v...
{ return m.ID }
conditional_block
laptop.pb.go
} func (m *Laptop) GetKeyboard() *Keyboard { if m != nil { return m.Keyboard } return nil } type isLaptop_Weight interface { isLaptop_Weight() } type Laptop_WeightKg struct { WeightKg float64 `protobuf:"fixed64,10,opt,name=weight_kg,json=weightKg,proto3,oneof"` } type Laptop_WeightLb struct { WeightLb floa...
func (m *CreateLaptopResponse) Reset() { *m = CreateLaptopResponse{} } func (m *CreateLaptopResponse) String() string { return proto.CompactTextString(m) } func (*CreateLaptopResponse) ProtoMessage() {} func (*CreateLaptopResponse) Descriptor() ([]byte, []int) { return fileDescriptor_28a7e4886f546705, []int...
random_line_split
laptop.pb.go
() *Screen { if m != nil { return m.Screen } return nil } func (m *Laptop) GetKeyboard() *Keyboard { if m != nil { return m.Keyboard } return nil } type isLaptop_Weight interface { isLaptop_Weight() } type Laptop_WeightKg struct { WeightKg float64 `protobuf:"fixed64,10,opt,name=weight_kg,json=weightKg,pr...
GetScreen
identifier_name