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
ImpConcat-Recall.py
#!/usr/bin/env python # coding: utf-8 # # fMRI Data Loading and Normalization in Python # **V.0.2 - Beta, [Contributions](#contributions)** # # ### Goal of this script # 1. load the fMRI data into python # - 3 recall runs # 2. create an average brain mask from multiple runs # - ses01_brain (3 recall r...
# In[18]: #truncate first n_trunc TRs #confounds_trunc=confounds_selected[3:end] epi_trunc=[] #https://github.com/INCF/BrainImagingPipelines/blob/master/bips/workflows/gablab/wips/scripts/modular_nodes.py print('Number of runs to concatenate:', n_runs_recall) for run in range(firstrun,lastrun+1):#lastrun+1 ou...
import nipype.interfaces.fsl as fsl import nipype.interfaces.freesurfer as fs import os if smooth_type == 'susan': if fwhm == 0: return in_file smooth = create_susan_smooth() smooth.base_dir = out_dir#os.getcwd() smooth.inputs.inputnode.fwhm = fwhm smooth....
identifier_body
ImpConcat-Recall.py
#!/usr/bin/env python # coding: utf-8 # # fMRI Data Loading and Normalization in Python # **V.0.2 - Beta, [Contributions](#contributions)** # # ### Goal of this script # 1. load the fMRI data into python # - 3 recall runs # 2. create an average brain mask from multiple runs # - ses01_brain (3 recall r...
coords = np.where(avg_mask.get_fdata()) bold_vol=[] bold_vol=np.zeros((avg_mask.shape[0], avg_mask.shape[1], avg_mask.shape[2], epi_mask_data.shape[0])) bold_vol[coords[0], coords[1], coords[2], :] = epi_mask_data.T print('epi_mask_data shape:', bold_vol.shape) output_name = (out_dir + 'ses-01/'...
avg_mask.shape
random_line_split
ImpConcat-Recall.py
#!/usr/bin/env python # coding: utf-8 # # fMRI Data Loading and Normalization in Python # **V.0.2 - Beta, [Contributions](#contributions)** # # ### Goal of this script # 1. load the fMRI data into python # - 3 recall runs # 2. create an average brain mask from multiple runs # - ses01_brain (3 recall r...
(in_file, mask_file, fwhm, smooth_type): import nipype.interfaces.fsl as fsl import nipype.interfaces.freesurfer as fs import os if smooth_type == 'susan': if fwhm == 0: return in_file smooth = create_susan_smooth() smooth.base_dir = out_dir#os.getcwd() smooth...
mod_smooth
identifier_name
ImpConcat-Recall.py
#!/usr/bin/env python # coding: utf-8 # # fMRI Data Loading and Normalization in Python # **V.0.2 - Beta, [Contributions](#contributions)** # # ### Goal of this script # 1. load the fMRI data into python # - 3 recall runs # 2. create an average brain mask from multiple runs # - ses01_brain (3 recall r...
else: confounds_all=np.vstack([confounds_all,confounds_selected]) print(confounds_selected.shape[0]) print(ntr) print(sum(ntr[0])) # In[15]: mask_imgs=[] for run in range(firstrun,lastrun+1): mask_name = ses1_dir + sub + '_ses-01_task-recall_run-0%i_space-MNI152NLin2009cAsym_desc-brain_mask.nii.gz'...
confounds_all=confounds_selected
conditional_block
test_unihan.py
"""Tests for unihan data download and processing.""" import logging import os import shutil import pytest from unihan_etl import __version__, constants, process from unihan_etl._compat import PY2 from unihan_etl.process import DEFAULT_OPTIONS, UNIHAN_ZIP_PATH, Packager, zip_has_files from unihan_etl.test import asser...
assert [] == not_in_columns, "normalize filters columns not specified." assert set(in_columns).issubset( set(columns) ), "normalize returns correct columns specified + ucn and char." def test_normalize_simple_data_format(fixture_dir): """normalize turns data into simple data format (SDF)."""...
in_columns.append(v)
conditional_block
test_unihan.py
"""Tests for unihan data download and processing.""" import logging import os import shutil import pytest from unihan_etl import __version__, constants, process from unihan_etl._compat import PY2 from unihan_etl.process import DEFAULT_OPTIONS, UNIHAN_ZIP_PATH, Packager, zip_has_files from unihan_etl.test import asser...
(normalized_data, columns): items = normalized_data in_columns = ['kDefinition', 'kCantonese'] for v in items: assert set(columns) == set(v.keys()) items = process.listify(items, in_columns) not_in_columns = [] # columns not selected in normalize must not be in result. for v in i...
test_normalize_only_output_requested_columns
identifier_name
test_unihan.py
"""Tests for unihan data download and processing.""" import logging import os import shutil import pytest from unihan_etl import __version__, constants, process from unihan_etl._compat import PY2 from unihan_etl.process import DEFAULT_OPTIONS, UNIHAN_ZIP_PATH, Packager, zip_has_files from unihan_etl.test import asser...
{ 'fields': ['kDefinition'], 'zip_path': str(dest_path), 'work_dir': str(mock_test_dir.join('downloads')), 'destination': str(data_path.join('unihan.csv')), }, ) ) p.download(urlretrieve_fn=urlretrieve) assert os...
mock_zip_file.copy(dest_path) p = Packager( merge_dict( test_options.copy,
random_line_split
test_unihan.py
"""Tests for unihan data download and processing.""" import logging import os import shutil import pytest from unihan_etl import __version__, constants, process from unihan_etl._compat import PY2 from unihan_etl.process import DEFAULT_OPTIONS, UNIHAN_ZIP_PATH, Packager, zip_has_files from unihan_etl.test import asser...
def test_extract_zip(mock_zip, mock_zip_file, tmpdir): zf = process.extract_zip(str(mock_zip_file), str(tmpdir)) assert len(zf.infolist()) == 1 assert zf.infolist()[0].file_size == 218 assert zf.infolist()[0].filename == "Unihan_Readings.txt" def test_normalize_only_output_requested_columns(normal...
data_path = tmpdir.join('data') dest_path = data_path.join('data', 'hey.zip') def urlretrieve(url, filename, url_retrieve, reporthook=None): mock_zip_file.copy(dest_path) p = Packager( merge_dict( test_options.copy, { 'fields': ['kDefinition'], ...
identifier_body
bg.rs
//! Background layer rendering use super::{Ppu, SnesRgb}; /// BG layer scanline cache. /// /// This cache stores a prerendered scanline of all background layers. The cache is created lazily /// (when BG layer pixels are looked up), so we will not waste time caching a disabled BG layer. #[derive(Default)] pub struct B...
(&mut self) { self.valid = false; } } impl BgCache { /// Invalidates the BG cache of all layers fn invalidate_all(&mut self) { self.layers[0].valid = false; self.layers[1].valid = false; self.layers[2].valid = false; self.layers[3].valid = false; } } /// Collect...
invalidate
identifier_name
bg.rs
//! Background layer rendering use super::{Ppu, SnesRgb}; /// BG layer scanline cache. /// /// This cache stores a prerendered scanline of all background layers. The cache is created lazily /// (when BG layer pixels are looked up), so we will not waste time caching a disabled BG layer. #[derive(Default)] pub struct B...
let color_bits = self.color_bits_for_bg(bg_num); if color_bits == 8 { // can use direct color mode debug_assert!(self.cgwsel & 0x01 == 0, "NYI: direct color mode"); } let mut tile_x = x.wrapping_add(hofs) / tile_size as u16; let tile_y = y.wrapping_add(vo...
random_line_split
builtin_func.go
package eval // Builtin functions. import ( "bufio" "encoding/json" "errors" "fmt" "io" "math" "os" "reflect" "regexp" "runtime" "strconv" "strings" "syscall" "time" "github.com/elves/elvish/sys" "github.com/elves/elvish/util" ) var builtinFns []*BuiltinFn // BuiltinFn is a builtin function. type B...
&BuiltinFn{"print", wrapFn(print)}, &BuiltinFn{"println", wrapFn(println)}, &BuiltinFn{"pprint", pprint}, &BuiltinFn{"into-lines", wrapFn(intoLines)}, &BuiltinFn{"from-lines", wrapFn(fromLines)}, &BuiltinFn{"rat", wrapFn(ratFn)}, &BuiltinFn{"put", put}, &BuiltinFn{"put-all", wrapFn(putAll)}, &Built...
&BuiltinFn{":", nop}, &BuiltinFn{"true", nop},
random_line_split
builtin_func.go
package eval // Builtin functions. import ( "bufio" "encoding/json" "errors" "fmt" "io" "math" "os" "reflect" "regexp" "runtime" "strconv" "strings" "syscall" "time" "github.com/elves/elvish/sys" "github.com/elves/elvish/util" ) var builtinFns []*BuiltinFn // BuiltinFn is a builtin function. type B...
throw(err) } out <- FromJSONInterface(v) } } // each takes a single closure and applies it to all input values. func each(ec *EvalCtx, f FnValue) { in := ec.ports[0].Chan in: for v := range in { // NOTE We don't have the position range of the closure in the source. // Ideally, it should be kept in the C...
{ return }
conditional_block
builtin_func.go
package eval // Builtin functions. import ( "bufio" "encoding/json" "errors" "fmt" "io" "math" "os" "reflect" "regexp" "runtime" "strconv" "strings" "syscall" "time" "github.com/elves/elvish/sys" "github.com/elves/elvish/util" ) var builtinFns []*BuiltinFn // BuiltinFn is a builtin function. type B...
func _log(ec *EvalCtx, fname string) { maybeThrow(util.SetOutputFile(fname)) } func _exec(ec *EvalCtx, args ...string) { if len(args) == 0 { args = []string{"elvish"} } var err error args[0], err = ec.Search(args[0]) maybeThrow(err) err = ec.store.Close() if err != nil { fmt.Fprintln(os.Stderr, err) } ...
{ out := ec.ports[1].File // XXX dup with main.go buf := make([]byte, 1024) for runtime.Stack(buf, true) == cap(buf) { buf = make([]byte, cap(buf)*2) } out.Write(buf) }
identifier_body
builtin_func.go
package eval // Builtin functions. import ( "bufio" "encoding/json" "errors" "fmt" "io" "math" "os" "reflect" "regexp" "runtime" "strconv" "strings" "syscall" "time" "github.com/elves/elvish/sys" "github.com/elves/elvish/util" ) var builtinFns []*BuiltinFn // BuiltinFn is a builtin function. type B...
(ec *EvalCtx, args []Value) { var dir string if len(args) == 0 { dir = mustGetHome("") } else if len(args) == 1 { dir = ToString(args[0]) } else { throw(ErrArgs) } cdInner(dir, ec) } func cdInner(dir string, ec *EvalCtx) { err := os.Chdir(dir) if err != nil { throw(err) } if ec.store != nil { // X...
cd
identifier_name
settings.py
""" Copyright 2018 ООО «Верме» Настройки проекта outsourcing """ import os import logging import tempfile from .settings_local import DEBUG from datetime import timedelta # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #...
EAL_IP',)
identifier_body
settings.py
""" Copyright 2018 ООО «Верме» Настройки проекта outsourcing """ import os import logging import tempfile from .settings_local import DEBUG from datetime import timedelta # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #...
'level': 'DEBUG', }, }, } try: from .wfm_admin import ADMIN_COLUMNS, ADMIN_SECTIONS except ImportError: ADMIN_SECTIONS = {} ADMIN_COLUMNS = [] DATA_UPLOAD_MAX_MEMORY_SIZE = 100 * 1024 * 1024 # 10 MB DATA_UPLOAD_MAX_NUMBER_FIELDS = 10000 # AXES config def username_getter(reques...
'handlers': ['db', 'console'],
random_line_split
settings.py
""" Copyright 2018 ООО «Верме» Настройки проекта outsourcing """ import os import logging import tempfile from .settings_local import DEBUG from datetime import timedelta # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #...
похоже, это всё больше не работает, потому что вместо request'а тут какой-то socket request = getattr(record, 'request', None) if request and hasattr(request, 'user'): # user record.user = request.user else: record.user = '--' if request and hasattr(request, 'M...
identifier_name
settings.py
""" Copyright 2018 ООО «Верме» Настройки проекта outsourcing """ import os import logging import tempfile from .settings_local import DEBUG from datetime import timedelta # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #...
s %(message)s' }, }, 'handlers': { 'file_main': { 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, 'logs', 'main.log'), 'formatter': 'stamp', 'filters': ['main'], }, 'console': { 'class': 'logging.Strea...
name)s.%(module)
conditional_block
chainmaker_yaml_types.go
/* Copyright (C) BABEC. All rights reserved. Copyright (C) THL A29 Limited, a Tencent company. All rights reserved. SPDX-License-Identifier: Apache-2.0 */ package localconf import ( "chainmaker.org/chainmaker-go/logger" "gopkg.in/yaml.v2" "io/ioutil" "io/fs" ) type nodeConfig struct { Type string ...
Url string `yaml:"url"` Auth string `yaml:"auth"` DB int `yaml:"db"` MaxIdle int `yaml:"max_idle"` MaxActive int `yaml:"max_active"` IdleTimeout int `yaml:"idle_timeout"` CacheTimeout int `yaml:"cache_timeout"` } type clientConfig struct { OrgId stri...
type redisConfig struct {
random_line_split
chainmaker_yaml_types.go
/* Copyright (C) BABEC. All rights reserved. Copyright (C) THL A29 Limited, a Tencent company. All rights reserved. SPDX-License-Identifier: Apache-2.0 */ package localconf import ( "chainmaker.org/chainmaker-go/logger" "gopkg.in/yaml.v2" "io/ioutil" "io/fs" ) type nodeConfig struct { Type string ...
fig.SqlDbConfig.DbPrefix = config.DbPrefix } if config.ResultDbConfig != nil && config.ResultDbConfig.SqlDbConfig != nil && config.ResultDbConfig.SqlDbConfig.DbPrefix == "" { config.ResultDbConfig.SqlDbConfig.DbPrefix = config.DbPrefix } if config.ContractEventDbConfig != nil && config.ContractEventDbConfig....
.HistoryDbConfig.SqlDbConfig.DbPrefix == "" { config.HistoryDbCon
conditional_block
chainmaker_yaml_types.go
/* Copyright (C) BABEC. All rights reserved. Copyright (C) THL A29 Limited, a Tencent company. All rights reserved. SPDX-License-Identifier: Apache-2.0 */ package localconf import ( "chainmaker.org/chainmaker-go/logger" "gopkg.in/yaml.v2" "io/ioutil" "io/fs" ) type nodeConfig struct { Type string ...
c (c *CMConfig) GetBlockChains() []BlockchainConfig { return c.BlockChainConfig }
list fun
identifier_name
chainmaker_yaml_types.go
/* Copyright (C) BABEC. All rights reserved. Copyright (C) THL A29 Limited, a Tencent company. All rights reserved. SPDX-License-Identifier: Apache-2.0 */ package localconf import ( "chainmaker.org/chainmaker-go/logger" "gopkg.in/yaml.v2" "io/ioutil" "io/fs" ) type nodeConfig struct { Type string ...
.setDefault() return config.ContractEventDbConfig } func (config *StorageConfig) GetDefaultDBConfig() *DbConfig { lconfig := &LevelDbConfig{ StorePath: config.StorePath, WriteBufferSize: config.WriteBufferSize, BloomFilterBits: config.BloomFilterBits, BlockWriteBufferSize: config.WriteBuf...
GetContractEventDbConfig() *DbConfig { if config.ContractEventDbConfig == nil { return config.GetDefaultDBConfig() } config
identifier_body
topology.rs
// //! Copyright 2020 Alibaba Group Holding Limited. //! //! 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 ...
#[inline] pub fn count_edges(&self) -> usize { self.count } } #[cfg(test)] mod test { use super::*; use std::path::PathBuf; #[test] fn test_segment_list() { let mut list = SegmentList::new(6); for i in 0..1024 { list.push(i); } for ...
{ self.neighbors.len() }
identifier_body
topology.rs
// //! Copyright 2020 Alibaba Group Holding Limited. //! //! 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 ...
(id: u64) -> Self { Vertex { id, #[cfg(feature = "padding")] padding_1: [0; 8], #[cfg(feature = "padding")] padding_2: [0; 7] } } } pub struct NeighborIter { cursor: usize, len: usize, inner: Arc<Vec<u64>> } impl NeighborIter ...
new
identifier_name
topology.rs
// //! Copyright 2020 Alibaba Group Holding Limited. //! //! 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 ...
if peers == 1 || (d % peers as u64) as u32 == partition { let n = neighbors.entry(*d).or_insert(Vec::new()); if !directed { n.push(*s); count += 1; } } } let mut arc_neighbors = HashMap::new()...
count += 1; }
random_line_split
lib.rs
//! Contract module which acts as a timelocked controller. When set as the //! owner of an `Ownable` smart contract, it enforces a timelock on all //! `onlyOwner` maintenance operations. This gives time for users of the //! controlled contract to exit before a potentially dangerous maintenance //! operation is applied....
impl<E> Default for Data<E> where E: Env, { fn default() -> Self { Self { min_delay: Lazy::new(E::Timestamp::from(1_u8)), timestamps: StorageHashMap::default(), } } } impl<E: Env> Data<E> {} /// The `EventEmit` impl the event emit api for component. pub trait Event...
pub fn new() -> Self { Self::default() } }
random_line_split
lib.rs
//! Contract module which acts as a timelocked controller. When set as the //! owner of an `Ownable` smart contract, it enforces a timelock on all //! `onlyOwner` maintenance operations. This gives time for users of the //! controlled contract to exit before a potentially dangerous maintenance //! operation is applied....
/// Execute an operation's call. /// /// Emits a `CallExecuted` event. fn _call( &mut self, id: [u8; 32], target: E::AccountId, value: E::Balance, data: Vec<u8>, ) { let mut receiver = <Receiver as FromAccountId<E>>::from_account_id(targe...
{ assert!( self.is_operation_ready(&id), "TimelockController: operation is not ready" ); Storage::<E, Data<E>>::get_mut(self) .timestamps .insert(id, E::Timestamp::from(_DONE_TIMESTAMP)); }
identifier_body
lib.rs
//! Contract module which acts as a timelocked controller. When set as the //! owner of an `Ownable` smart contract, it enforces a timelock on all //! `onlyOwner` maintenance operations. This gives time for users of the //! controlled contract to exit before a potentially dangerous maintenance //! operation is applied....
(&self, id: &[u8; 32]) -> bool { self.get_timestamp(id) > E::Timestamp::from(_DONE_TIMESTAMP) } /// Returns whether an operation is ready or not. fn is_operation_ready(&self, id: &[u8; 32]) -> bool { let timestamp = self.get_timestamp(id); timestamp > E::Timestamp::from(_DONE_TIMEST...
is_operation_pending
identifier_name
scheduling.rs
use super::*; use crate::domain::scheduling::*; use chrono::{DateTime, SecondsFormat}; use futures::{Async, Future, Stream}; use std::sync::{Arc, Mutex, MutexGuard}; use std::time::Duration; use tokio::timer::{ delay_queue::{Expired, Key as DelayQueueKey}, DelayQueue, }; enum DelayQueueItem<T> { TaskS...
( &mut self, response_tx: CommandResponseSender, command: TaskSchedulingCommand<T>, ) { let result = match command { TaskSchedulingCommand::RescheduleAll(task_schedules) => { self.scheduled_tasks .lock_inner() .resch...
handle_command
identifier_name
scheduling.rs
use super::*; use crate::domain::scheduling::*; use chrono::{DateTime, SecondsFormat}; use futures::{Async, Future, Stream}; use std::sync::{Arc, Mutex, MutexGuard}; use std::time::Duration; use tokio::timer::{ delay_queue::{Expired, Key as DelayQueueKey}, DelayQueue, }; enum DelayQueueItem<T> { TaskS...
impl<T> TaskSchedulingActor<T> where T: TaskSchedule + Send + std::fmt::Debug, { pub fn create( task_scheduler: Box<dyn TaskScheduler<TaskSchedule = T> + Send>, ) -> ( impl Future<Item = (), Error = ()>, TaskSchedulingActionSender<T>, TaskSchedulingNotificationReceiver, )...
scheduled_tasks: ScheduledTasks<T>, }
random_line_split
scheduling.rs
use super::*; use crate::domain::scheduling::*; use chrono::{DateTime, SecondsFormat}; use futures::{Async, Future, Stream}; use std::sync::{Arc, Mutex, MutexGuard}; use std::time::Duration; use tokio::timer::{ delay_queue::{Expired, Key as DelayQueueKey}, DelayQueue, }; enum DelayQueueItem<T> { TaskS...
} impl<T> Stream for ScheduledTasks<T> { type Item = <DelayQueue<DelayQueueItem<T>> as Stream>::Item; type Error = <DelayQueue<DelayQueueItem<T>> as Stream>::Error; fn poll(&mut self) -> Result<Async<Option<Self::Item>>, Self::Error> { self.lock_inner().poll() } } #[derive(Debug, Clone, Copy...
{ ScheduledTasks(self.0.clone()) }
identifier_body
messenger.ts
import * as Mixins from './mixins' import * as tools from './tools' import * as _eventsApi from './events-api' import { EventMap, EventsDefinition } from './events-api' const { mixins, define, extendable } = Mixins, { omit, once, isEmpty, keys } = tools, { EventHandler, trigger0, trigger1, trigger2, trigge...
// Update tail event if the list has any events. Otherwise, clean up. if (remaining.length) { events[name] = remaining; } else { delete events[name]; } } return events; }; // Reduces the event callbacks into a map of `{event: onceWrapper}`. // `offer` ...
{ const handler = handlers[j]; if ( callback && callback !== handler.callback && callback !== handler.callback._callback || context && context !== handler.context ) { remaining.push(handler); } else { ...
conditional_block
messenger.ts
import * as Mixins from './mixins' import * as tools from './tools' import * as _eventsApi from './events-api' import { EventMap, EventsDefinition } from './events-api' const { mixins, define, extendable } = Mixins, { omit, once, isEmpty, keys } = tools, { EventHandler, trigger0, trigger1, trigger2, trigge...
; // Reduces the event callbacks into a map of `{event: onceWrapper}`. // `offer` unbinds the `onceWrapper` after it has been called. /** @hidden */ function onceMap(map, name, callback, offer) { if (callback) { const _once : _eventsApi.Callback = map[name] = once(function() { offer(name, _once...
{ if (!events) return; let i = 0, listening; const context = options.context, listeners = options.listeners; // Delete all events listeners and "drop" events. if (!name && !callback && !context) { const ids = keys(listeners); for (; i < ids.length; i++) { listening = li...
identifier_body
messenger.ts
import * as Mixins from './mixins' import * as tools from './tools' import * as _eventsApi from './events-api' import { EventMap, EventsDefinition } from './events-api' const { mixins, define, extendable } = Mixins, { omit, once, isEmpty, keys } = tools, { EventHandler, trigger0, trigger1, trigger2, trigge...
{ constructor( public context, public listeners : Listeners ){} } // The reducing API that removes a callback from the `events` object. /** @hidden */ function offApi(events : _eventsApi.EventsSubscription, name, callback, options : OffOptions ) { if (!events) return; let i = 0, listening; const cont...
OffOptions
identifier_name
messenger.ts
import * as Mixins from './mixins' import * as tools from './tools' import * as _eventsApi from './events-api' import { EventMap, EventsDefinition } from './events-api' const { mixins, define, extendable } = Mixins, { omit, once, isEmpty, keys } = tools, { EventHandler, trigger0, trigger1, trigger2, trigge...
/** @hidden */ class ListeningTo { count : number = 0 constructor( public obj, public objId, public id, public listeningTo ){} } /** @hidden */ export interface ListeningToMap { [ id : string ] : ListeningTo } /** @hidden */ export interface Listeners { [ id : string ] : Messenger } // Guard the `li...
};
random_line_split
Client_V1.1.py
#Version 1.1 #Draft Time: Wed 16 Sep 2020 11:43 # importing the necessary libraries from enum import Enum from gi.repository import GLib #class enumerates the types of media that can be displayed class media_type_t(Enum): MEDIA_TYPE_QRCODE = 0 MEDIA_TYPE_IMAGE = 1 MEDIA_TYPE_GIF = 2 #class enumerates the type...
(self): global card_type if card_type == 5 or card_type == 13: card_bgcolor = int(input('\nEnter Background Color: ')) #reads background color from user #assumed to be a integer value print('\nBackground color set to: {}\n'.format(card_bgcolor)) else: print('\nBackground color set b...
BackGround_Color
identifier_name
Client_V1.1.py
#Version 1.1 #Draft Time: Wed 16 Sep 2020 11:43 # importing the necessary libraries from enum import Enum from gi.repository import GLib #class enumerates the types of media that can be displayed class media_type_t(Enum): MEDIA_TYPE_QRCODE = 0 MEDIA_TYPE_IMAGE = 1 MEDIA_TYPE_GIF = 2 #class enumerates the type...
print('Input value does not match any defined card types') exit() elif screen_type == 1: i = 6 #to display count of ENUM listing for types in card_type_t_50: print('{}'.format(i), types) i += 1 card_type = int(input('Enter ENUM index (6-13)\nSelect Card type: ')) #re...
except:
random_line_split
Client_V1.1.py
#Version 1.1 #Draft Time: Wed 16 Sep 2020 11:43 # importing the necessary libraries from enum import Enum from gi.repository import GLib #class enumerates the types of media that can be displayed class media_type_t(Enum): MEDIA_TYPE_QRCODE = 0 MEDIA_TYPE_IMAGE = 1 MEDIA_TYPE_GIF = 2 #class enumerates the type...
""" Child-Method 4 This Shows or hides the Flipper """ #parameter 4 flipper_visibility = -1 def FlipperVisibility(self): global screen_type if screen_type == 1: choice = int(input('FLIPPER Visibility (0=HIDE/1=SHOW): ')) #reads users choice to either show or hide flipper. ...
global slot_index global screen_type #parameter 3 if screen_type == 1: slot_index = int(input('Enter the slot index (0=LEFT/1=RIGHT): ')) print('Slot index set as: {}\n'.format(slot_index))
identifier_body
Client_V1.1.py
#Version 1.1 #Draft Time: Wed 16 Sep 2020 11:43 # importing the necessary libraries from enum import Enum from gi.repository import GLib #class enumerates the types of media that can be displayed class media_type_t(Enum): MEDIA_TYPE_QRCODE = 0 MEDIA_TYPE_IMAGE = 1 MEDIA_TYPE_GIF = 2 #class enumerates the type...
""" Child-Method 4 This Shows or hides the Flipper """ #parameter 4 flipper_visibility = -1 def FlipperVisibility(self): global screen_type if screen_type == 1: choice = int(input('FLIPPER Visibility (0=HIDE/1=SHOW): ')) #reads users choice to either show or hide flipper. ...
slot_index = int(input('Enter the slot index (0=LEFT/1=RIGHT): ')) print('Slot index set as: {}\n'.format(slot_index))
conditional_block
VIEW3D_MT_armature_context_menu.py
# 「3Dビュー」エリア > アーマチュアの「編集」モード > 「アーマチュアコンテクストメニュー」 (Wキー) # "3D View" Area > "Edit" Mode with Armature > "Armature Context Menu" (W Key) import bpy, mathutils import re from bpy.props import * SUFFIX_TPL = (".R",".L",".r",".l","_R","_L","_r","_l",".right",".left",".Right",".Left","_right","_left","_Right","_Left") ##...
lace selected bones' names by using regular expression" bl_options = {'REGISTER', 'UNDO'} isAll : BoolProperty(name="Apply to All Bones", default=False) pattern : StringProperty(name="Target text", default="^") repl : StringProperty(name="New Text", default="") @classmethod def poll(cls, context): if context....
ion" bl_description = "Rep
identifier_name
VIEW3D_MT_armature_context_menu.py
# 「3Dビュー」エリア > アーマチュアの「編集」モード > 「アーマチュアコンテクストメニュー」 (Wキー) # "3D View" Area > "Edit" Mode with Armature > "Armature Context Menu" (W Key) import bpy, mathutils import re from bpy.props import * SUFFIX_TPL = (".R",".L",".r",".l","_R","_L","_r","_l",".right",".left",".Right",".Left","_right","_left","_Right","_Left") ##...
ame', expand=True) box = self.layout.box() if self.use_rename == 'True': row = box.row(align=True) row.label(text="Use Root Bones' Names as New Names") row.prop(self, 'use_root', text="") row = box.split(factor=0.4, align=True) row.label(text="Bones' Order") row.prop(self, 'order', text="") row...
row = self.layout.row() row.use_property_split = True row.prop(self, 'threshold') self.layout.prop(self, 'use_ren
identifier_body
VIEW3D_MT_armature_context_menu.py
# 「3Dビュー」エリア > アーマチュアの「編集」モード > 「アーマチュアコンテクストメニュー」 (Wキー) # "3D View" Area > "Edit" Mode with Armature > "Armature Context Menu" (W Key) import bpy, mathutils import re from bpy.props import * SUFFIX_TPL = (".R",".L",".r",".l","_R","_L","_r","_l",".right",".left",".Right",".Left","_right","_left","_Right","_Left") ##...
new_names = [self.new_name] + [f"{name_head}{num+1:03}" for num in range(len(selectedBones)-1)] elif self.start_from == 'ZERO': new_names = [f"{name_head}{num:03}" for num in range(len(selectedBones))] elif self.start_from == 'ONE': new_names = [f"{name_head}{num+1:03}" for num in range(len(selectedBo...
if self.use_rename: name_head = f"{self.new_name}{self.name_sep}" if self.start_from == 'NO':
random_line_split
VIEW3D_MT_armature_context_menu.py
# 「3Dビュー」エリア > アーマチュアの「編集」モード > 「アーマチュアコンテクストメニュー」 (Wキー) # "3D View" Area > "Edit" Mode with Armature > "Armature Context Menu" (W Key) import bpy, mathutils import re from bpy.props import * SUFFIX_TPL = (".R",".L",".r",".l","_R","_L","_r","_l",".right",".left",".Right",".Left","_right","_left","_Right","_Left") ##...
ld = self.threshold for bone in selectedBones: bone = arm.bones[bone.name] temp = [x for x in bone.head_local] head_interval = [(x-threshold, x+threshold) for x in [temp[0]*(-1)] + temp[1:]] temp = [x for x in bone.tail_local] tail_interval = [(x-threshold, x+threshold) for x in [temp[0]*(-1)] + temp[1...
CT') bpy.ops.object.mode_set(mode='OBJECT') thresho
conditional_block
handler.rs
// Copyright 2019 Parity Technologies (UK) Ltd. // // 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 use, copy, modify, mer...
KeepAlive::Yes } else { KeepAlive::No } } fn poll(&mut self) -> Poll<ProtocolsHandlerEvent<protocol::Ping, (), PingResult>, Self::Error> { if let Some(result) = self.pending_results.pop_back() { if let Ok(PingSuccess::Ping { .. }) = result { ...
random_line_split
handler.rs
// Copyright 2019 Parity Technologies (UK) Ltd. // // 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 use, copy, modify, mer...
e => panic!("Unexpected event: {:?}", e) } } h.inject_dial_upgrade_error((), ProtocolsHandlerUpgrErr::Timeout); match tick(&mut h) { Err(PingFailure::Timeout) => { assert_eq!(h.failures, h.config.max_failures.get()); } ...
{}
conditional_block
handler.rs
// Copyright 2019 Parity Technologies (UK) Ltd. // // 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 use, copy, modify, mer...
(config: PingConfig) -> Self { PingHandler { config, next_ping: Delay::new(Instant::now()), pending_results: VecDeque::with_capacity(2), failures: 0, _marker: std::marker::PhantomData } } } impl<TSubstream> ProtocolsHandler for PingHandler...
new
identifier_name
handler.rs
// Copyright 2019 Parity Technologies (UK) Ltd. // // 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 use, copy, modify, mer...
fn inject_fully_negotiated_outbound(&mut self, rtt: Duration, _info: ()) { // A ping initiated by the local peer was answered by the remote. self.pending_results.push_front(Ok(PingSuccess::Ping { rtt })); } fn inject_event(&mut self, _: Void) {} fn inject_dial_upgrade_error(&mut self...
{ // A ping from a remote peer has been answered. self.pending_results.push_front(Ok(PingSuccess::Pong)); }
identifier_body
dict.rs
use bitflags::bitflags; use std::{ffi::CStr, fmt, marker::PhantomData}; pub trait ReadableDict { /// Obtain the pointer to the raw `spa_dict` struct. fn get_dict_ptr(&self) -> *const spa_sys::spa_dict; /// An iterator over all raw key-value pairs. /// The iterator element type is `(&CStr, &CStr)`. ...
() { let (_strings, _items, raw) = make_raw_dict(2); let dict = unsafe { ForeignDict::from_ptr(&raw) }; let mut iter = dict.iter_cstr(); assert_eq!( ( CString::new("K0").unwrap().as_c_str(), CString::new("V0").unwrap().as_c_str() )...
test_iter_cstr
identifier_name
dict.rs
use bitflags::bitflags; use std::{ffi::CStr, fmt, marker::PhantomData}; pub trait ReadableDict { /// Obtain the pointer to the raw `spa_dict` struct. fn get_dict_ptr(&self) -> *const spa_sys::spa_dict; /// An iterator over all raw key-value pairs. /// The iterator element type is `(&CStr, &CStr)`. ...
} fn size_hint(&self) -> (usize, Option<usize>) { let bound: usize = unsafe { self.next.offset_from(self.end) as usize }; // We know the exact value, so lower bound and upper bound are the same. (bound, Some(bound)) } } pub struct Iter<'a> { inner: CIter<'a>, } impl<'a> Iter...
{ None }
conditional_block
dict.rs
use bitflags::bitflags; use std::{ffi::CStr, fmt, marker::PhantomData}; pub trait ReadableDict { /// Obtain the pointer to the raw `spa_dict` struct. fn get_dict_ptr(&self) -> *const spa_sys::spa_dict; /// An iterator over all raw key-value pairs. /// The iterator element type is `(&CStr, &CStr)`. ...
}
{ let (_strings, _items, raw) = make_raw_dict(1); let dict = unsafe { ForeignDict::from_ptr(&raw) }; assert_eq!(r#"{"K0": "V0"}"#, &format!("{:?}", dict)) }
identifier_body
dict.rs
use bitflags::bitflags; use std::{ffi::CStr, fmt, marker::PhantomData}; pub trait ReadableDict { /// Obtain the pointer to the raw `spa_dict` struct. fn get_dict_ptr(&self) -> *const spa_sys::spa_dict; /// An iterator over all raw key-value pairs. /// The iterator element type is `(&CStr, &CStr)`. ...
fn is_empty(&self) -> bool { self.len() == 0 } /// Returns the bitflags that are set for the dict. fn flags(&self) -> Flags { Flags::from_bits_truncate(unsafe { (*self.get_dict_ptr()).flags }) } /// Get the value associated with the provided key. /// /// If the dict doe...
random_line_split
nodekeeper.go
/* * Copyright 2018 Insolar * * 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...
func (nk *nodekeeper) updateUnsyncPulse() { for _, node := range nk.unsync { node.PulseNum = nk.pulse } count := len(nk.unsync) if count != 0 { log.Infof("NodeKeeper: updated pulse for %d stored unsync nodes", count) } } func hashWriteChecked(hash hash.Hash, data []byte) { n, err := hash.Write(data) if n ...
{ nk.cacheUnsyncCalc = nil nk.cacheUnsyncSize = 0 }
identifier_body
nodekeeper.go
/* * Copyright 2018 Insolar * * 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...
nk.unsync = append(nk.unsync, node) tm := time.Now().Add(nk.timeout) nk.unsyncTimeout = append(nk.unsyncTimeout, tm) return nil } func (nk *nodekeeper) AddUnsyncGossip(nodes []*core.ActiveNode) error { nk.unsyncLock.Lock() defer nk.unsyncLock.Unlock() if nk.state != awaitUnsync { return errors.New("Cannot ...
{ return errors.Wrap(err, "Error adding local unsync node") }
conditional_block
nodekeeper.go
/* * Copyright 2018 Insolar * * 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...
(nodes []*core.ActiveNode) error { for _, node := range nodes { if node.PulseNum != nk.pulse { return errors.Errorf("Node ID:%s pulse:%d is not equal to NodeKeeper current pulse:%d", node.NodeID.String(), node.PulseNum, nk.pulse) } } return nil } func (nk *nodekeeper) checkReference(nodes []*core.ActiveN...
checkPulse
identifier_name
nodekeeper.go
/* * Copyright 2018 Insolar * * 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...
// Sync initiate transferring unsync -> sync, sync -> active. If approved is false, unsync is not transferred to sync. Sync(approved bool) // AddUnsync add unsync node to the local unsync list. // Returns error if node's PulseNumber is not equal to the NodeKeeper internal PulseNumber. AddUnsync(*core.ActiveNode) e...
// SetPulse sets internal PulseNumber to number. SetPulse(number core.PulseNumber)
random_line_split
curiosity-rl.py
''' curiosity-rl.py Curiosity driven RL Framework ''' from __future__ import print_function import tensorflow as tf import numpy as np from scipy.misc import imsave # Unused ... now import time import uw_random import config import pyosr import rlargs import a2c import a2c_overfit import a2c_mp import dqn imp...
task_index=args.task_index, config=session_config) if args.job_name == 'ps': engine = ParamServer(args, server) else: assert args.job_name == 'worker', "--job_name should be either ps or worker" engine = DistributedTrainer(args, cluster, server, mpqueue) retur...
session_config = tf.ConfigProto() session_config.gpu_options.allow_growth = True server = tf.train.Server(cluster, job_name=args.job_name,
random_line_split
curiosity-rl.py
''' curiosity-rl.py Curiosity driven RL Framework ''' from __future__ import print_function import tensorflow as tf import numpy as np from scipy.misc import imsave # Unused ... now import time import uw_random import config import pyosr import rlargs import a2c import a2c_overfit import a2c_mp import dqn imp...
(args, global_step, batch_normalization): ''' if len(args.egreedy) != 1 and len(args.egreedy) != args.threads: assert False,"--egreedy should have only one argument, or match the number of threads" ''' advcore = curiosity.create_advcore(learning_rate=1e-3, args=args, batch_normalization=batch_no...
create_trainer
identifier_name
curiosity-rl.py
''' curiosity-rl.py Curiosity driven RL Framework ''' from __future__ import print_function import tensorflow as tf import numpy as np from scipy.misc import imsave # Unused ... now import time import uw_random import config import pyosr import rlargs import a2c import a2c_overfit import a2c_mp import dqn imp...
return hooks def _create_trainer(self, args): self.bnorm = tf.placeholder(tf.bool, shape=()) if args.batchnorm else None self.gs = tf.contrib.framework.get_or_create_global_step() self.trainer, self.advcore = create_trainer(args, self.gs, batch_normalization=self.bnorm) def r...
class PretrainLoader(tf.train.SessionRunHook): def __init__(self, advcore, ckpt): self.advcore = advcore self.ckpt = ckpt def after_create_session(self, session, coord): self.advcore.load_pretrain(session, self.ckpt) ...
conditional_block
curiosity-rl.py
''' curiosity-rl.py Curiosity driven RL Framework ''' from __future__ import print_function import tensorflow as tf import numpy as np from scipy.misc import imsave # Unused ... now import time import uw_random import config import pyosr import rlargs import a2c import a2c_overfit import a2c_mp import dqn imp...
def get_hooks(self): hooks = [tf.train.StopAtStepHook(last_step=self.trainer.total_iter)] if self.args.viewinitckpt: class PretrainLoader(tf.train.SessionRunHook): def __init__(self, advcore, ckpt): self.advcore = advcore self.ck...
super(TEngine, self).__init__(args) self.mts_master = '' self.mts_is_chief = True self.tid = 0
identifier_body
settings.go
package settingscontroller import ( "encoding/json" "net/http" "os" "reflect" "rest-api-golang/src/dbContext/companyservice" "rest-api-golang/src/dbContext/logssystemservice" "rest-api-golang/src/dbContext/logsuserservice" "rest-api-golang/src/dbContext/privilegeroluserservice" "rest-api-golang/src/dbContext/...
else { expireDate = now.Add(2 * time.Minute) } //update IdSession sessionUser := sessionuserservice.FindToId(getIdSession) sessionUser.Token = tokenString sessionUser.TokenExpire = expireDate sessionuserservice.UpdateOne(sessionUser) logUser := "Inicio Session .." logsuserservice.Add(1, c...
{ expireDate = now.AddDate(0, 0, 1) }
conditional_block
settings.go
package settingscontroller import ( "encoding/json" "net/http" "os" "reflect" "rest-api-golang/src/dbContext/companyservice" "rest-api-golang/src/dbContext/logssystemservice" "rest-api-golang/src/dbContext/logsuserservice" "rest-api-golang/src/dbContext/privilegeroluserservice" "rest-api-golang/src/dbContext/...
func isNoBarAndLessThanTenChar(a models.GenericList, value1 string) bool { return !strings.HasPrefix(a.Value1, value1) } var GetUser = func(w http.ResponseWriter, r *http.Request) { // listProvinces := genericlistservice.GetListForIdCompanyAndIdentity("", "provinces") // list := genericlistservice.GetListForIdCo...
{ contentType := reflect.TypeOf(arr) contentValue := reflect.ValueOf(arr) newContent := reflect.MakeSlice(contentType, 0, 0) for i := 0; i < contentValue.Len(); i++ { if content := contentValue.Index(i); cond(content.Interface()) { newContent = reflect.Append(newContent, content) } } return newContent.Int...
identifier_body
settings.go
package settingscontroller import ( "encoding/json" "net/http" "os" "reflect" "rest-api-golang/src/dbContext/companyservice" "rest-api-golang/src/dbContext/logssystemservice" "rest-api-golang/src/dbContext/logsuserservice" "rest-api-golang/src/dbContext/privilegeroluserservice" "rest-api-golang/src/dbContext/...
(a models.GenericList, value1 string) bool { return !strings.HasPrefix(a.Value1, value1) } var GetUser = func(w http.ResponseWriter, r *http.Request) { // listProvinces := genericlistservice.GetListForIdCompanyAndIdentity("", "provinces") // list := genericlistservice.GetListForIdCompanyAndIdentity("", "municipies...
isNoBarAndLessThanTenChar
identifier_name
settings.go
package settingscontroller import ( "encoding/json" "net/http" "os" "reflect" "rest-api-golang/src/dbContext/companyservice" "rest-api-golang/src/dbContext/logssystemservice" "rest-api-golang/src/dbContext/logsuserservice" "rest-api-golang/src/dbContext/privilegeroluserservice" "rest-api-golang/src/dbContext/...
// newUser := models.IUser{ // DateAdd: time.Now(), // IdCompany: "55555555", // IdRol: "144444", // Image: "imagen", // LastLogin: time.Now(), // LastName: "apellido", // Name: "NOmbre", // Password: utils.Encript([]byte("231154")), // Status: 1, // NickName: "usuario1", // ...
// result := usersservice.FindToId("5e795d655d554045401496e6") // result.NickName = "ADMIN23" // fmt.Println(usersservice.UpdateOne(result)) // fmt.Println(result.ID)
random_line_split
Code_Projet_ML.py
# -*- coding: utf-8 -*- """ Created on Wed May 18 22:56:15 2020 @author: paulg """ import sys sys.version import numpy as np import matplotlib.pyplot as plt import pandas as pd import csv import seaborn as sns ######################## DATA TREATMENT ########################################################...
("Mot\tApparition\tRdt mensuel moyen") print("==================================") for i in range(len(result)): print("\n{}\t{}\t{}".format(result[i][0],result[i][1],result[i][2].round(4))) #DataFrame contenant la liste des mots filtrés, leurs rendements moyens et leurs nombres d'apparitions df = pd.DataFrame(...
t_moy_m]) # Sortie Tableau énoncé print
conditional_block
Code_Projet_ML.py
# -*- coding: utf-8 -*- """ Created on Wed May 18 22:56:15 2020 @author: paulg """ import sys sys.version import numpy as np import matplotlib.pyplot as plt import pandas as pd import csv import seaborn as sns ######################## DATA TREATMENT ########################################################...
print(data.dtypes) #On récupère la liste des tickers list_tickers=data.TICKER.unique().tolist() #Modification de la base ( date et ajout de données sur les varaitions futures de volume) data['annee']= pd.to_datetime(data.annee*10000+data.mois*100+data.jour,format='%Y%m%d') data.rename(columns={'annee': 'date'}, ...
data.head() #Affichage des caractéristiques print("Nombre de lignes : {}\nNombre de colonnes : {}\n".format(len(data), len(data.columns))) data['recommandation'] = pd.to_numeric(data['recommandation']) #on convertit en numeric la donnée de l'apparition du mot 'recommandation'
random_line_split
normalizer.py
""" Copyright © 2021-2022 The Johns Hopkins University Applied Physics Laboratory LLC 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 right...
ste_data: dict = {}, data_range: defaultdict = None, method: str = "task", scale: int = 100, offset: int = 1, ) -> None: """Constructor for Normalizer. Args: perf_measure (str): Name of column to use for metrics calculations. data (pd....
data: pd.DataFrame,
random_line_split
normalizer.py
""" Copyright © 2021-2022 The Johns Hopkins University Applied Physics Laboratory LLC 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 right...
return data elif self.method == "run": data.loc[:, self.perf_measure] = ( (data[self.perf_measure].to_numpy() - self.run_min) / (self.run_max - self.run_min) * self.scale ) + self.offset return data
n self.data_range.keys(): task_min = self.data_range[task]["min"] task_max = self.data_range[task]["max"] task_data = data.loc[ data["task_name"] == task, self.perf_measure ].to_numpy() if task_m...
conditional_block
normalizer.py
""" Copyright © 2021-2022 The Johns Hopkins University Applied Physics Laboratory LLC 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 right...
thod: str) -> bool: """Validates normalization method. Args: method (str): Normalization method. Raises: ValueError: If method is not in list of valid methods. Returns: bool: True if validation succeeds. """ if method not in self.va...
_method(self, me
identifier_name
normalizer.py
""" Copyright © 2021-2022 The Johns Hopkins University Applied Physics Laboratory LLC 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 right...
_validate_method(self, method: str) -> bool: """Validates normalization method. Args: method (str): Normalization method. Raises: ValueError: If method is not in list of valid methods. Returns: bool: True if validation succeeds. """ ...
tes data range object. Args: data_range (defaultdict): Dictionary object for data range. task_names (Set[str]): Set of task names in the data. Raises: TypeError: If data range is not a dictionary object. KeyError: If data range is not defined for all tas...
identifier_body
lib.rs
//! # Substrate Enterprise Sample - Product Tracking pallet #![cfg_attr(not(feature = "std"), no_std)] use codec::alloc::string::ToString; use core::convert::TryInto; use frame_support::{ debug, decl_error, decl_event, decl_module, decl_storage, dispatch, ensure, sp_runtime::offchain::{ self as rt_off...
// --- Offchain worker methods --- fn process_ocw_notifications(block_number: T::BlockNumber) { // Check last processed block let last_processed_block_ref = StorageValueRef::persistent(b"product_tracking_ocw::last_proccessed_block"); let mut last_processed_block: u32 = mat...
{ ensure!( props.len() <= SHIPMENT_MAX_PRODUCTS, Error::<T>::ShipmentHasTooManyProducts, ); Ok(()) }
identifier_body
lib.rs
//! # Substrate Enterprise Sample - Product Tracking pallet #![cfg_attr(not(feature = "std"), no_std)] use codec::alloc::string::ToString; use core::convert::TryInto; use frame_support::{ debug, decl_error, decl_event, decl_module, decl_storage, dispatch, ensure, sp_runtime::offchain::{ self as rt_off...
let status = shipment.status.clone(); // Create shipping event let event = Self::new_shipping_event() .of_type(ShippingEventType::ShipmentRegistration) .for_shipment(id.clone()) .at_location(None) .with_readings(vec![])...
.registered_at(<timestamp::Module<T>>::now()) .with_products(products) .build();
random_line_split
lib.rs
//! # Substrate Enterprise Sample - Product Tracking pallet #![cfg_attr(not(feature = "std"), no_std)] use codec::alloc::string::ToString; use core::convert::TryInto; use frame_support::{ debug, decl_error, decl_event, decl_module, decl_storage, dispatch, ensure, sp_runtime::offchain::{ self as rt_off...
} fn notify_listener(ev: &ShippingEvent<T::Moment>) -> Result<(), &'static str> { debug::info!("notifying listener: {:?}", ev); let request = sp_runtime::offchain::http::Request::post(&LISTENER_ENDPOINT, vec![ev.to_string()]); let timeout = sp_io::offchain::ti...
{ last_processed_block_ref.set(&last_processed_block); debug::info!( "[product_tracking_ocw] Notifications successfully processed up to block {}", last_processed_block ); }
conditional_block
lib.rs
//! # Substrate Enterprise Sample - Product Tracking pallet #![cfg_attr(not(feature = "std"), no_std)] use codec::alloc::string::ToString; use core::convert::TryInto; use frame_support::{ debug, decl_error, decl_event, decl_module, decl_storage, dispatch, ensure, sp_runtime::offchain::{ self as rt_off...
(block_number: T::BlockNumber) { // Check last processed block let last_processed_block_ref = StorageValueRef::persistent(b"product_tracking_ocw::last_proccessed_block"); let mut last_processed_block: u32 = match last_processed_block_ref.get::<T::BlockNumber>() { Some(Som...
process_ocw_notifications
identifier_name
app.rs
use audio; use audio::cpal; use find_folder; use glium::glutin; use state; use std; use std::cell::{Cell, RefCell}; use std::collections::HashMap; use std::marker::PhantomData; use std::path::PathBuf; use std::sync::{mpsc, Arc}; use std::thread; use std::time::Duration; use window::{self, Window}; use ui; /// An **App...
model, sample_rate: None, channels: None, frames_per_buffer: None, device: None, sample_format: PhantomData, } } } impl Proxy { /// Wake up the application! /// /// This wakes up the **App**'s inner event loop and inserts a...
random_line_split
app.rs
use audio; use audio::cpal; use find_folder; use glium::glutin; use state; use std; use std::cell::{Cell, RefCell}; use std::collections::HashMap; use std::marker::PhantomData; use std::path::PathBuf; use std::sync::{mpsc, Arc}; use std::thread; use std::time::Duration; use window::{self, Window}; use ui; /// An **App...
}
{ self.events_loop_proxy.wakeup() }
identifier_body
app.rs
use audio; use audio::cpal; use find_folder; use glium::glutin; use state; use std; use std::cell::{Cell, RefCell}; use std::collections::HashMap; use std::marker::PhantomData; use std::path::PathBuf; use std::sync::{mpsc, Arc}; use std::thread; use std::time::Duration; use window::{self, Window}; use ui; /// An **App...
(&self) -> Result<PathBuf, find_folder::Error> { let exe_path = std::env::current_exe()?; find_folder::Search::ParentsThenKids(5, 3) .of(exe_path.parent().expect("executable has no parent directory to search").into()) .for_folder(Self::ASSETS_DIRECTORY_NAME) } /// Begin ...
assets_path
identifier_name
app.rs
use audio; use audio::cpal; use find_folder; use glium::glutin; use state; use std; use std::cell::{Cell, RefCell}; use std::collections::HashMap; use std::marker::PhantomData; use std::path::PathBuf; use std::sync::{mpsc, Arc}; use std::thread; use std::time::Duration; use window::{self, Window}; use ui; /// An **App...
else { self.process_fn_tx.borrow().as_ref().unwrap().clone() }; audio::stream::Builder { event_loop: self.event_loop.clone(), process_fn_tx: process_fn_tx, model, sample_rate: None, channels: None, frames_per_buffer: N...
{ let event_loop = self.event_loop.clone(); let (tx, rx) = mpsc::channel(); let mut loop_context = audio::stream::LoopContext::new(rx); thread::Builder::new() .name("cpal::EventLoop::run thread".into()) .spawn(move || event_loop.run(move |i...
conditional_block
elns.py
import json from pathlib import Path import ipywidgets as ipw import requests_cache import traitlets as tl from aiida import orm from aiidalab_eln import get_eln_connector from IPython.display import clear_output, display ELN_CONFIG = Path.home() / ".aiidalab" / "aiidalab-eln-config.json" ELN_CONFIG.parent.mkdir( ...
else: self.modify_settings.disabled = True send_button.disabled = True self.message.value = f"""Warning! The access to ELN is not configured. Please follow <a href="{self.path_to_root}/aiidalab-widgets-base/notebooks/eln_configure.ipynb" target="_blank">the link</a> to config...
] self.eln, msg = connect_to_eln() if self.eln: tl.dlink((self, "node"), (self.eln, "node"))
random_line_split
elns.py
import json from pathlib import Path import ipywidgets as ipw import requests_cache import traitlets as tl from aiida import orm from aiidalab_eln import get_eln_connector from IPython.display import clear_output, display ELN_CONFIG = Path.home() / ".aiidalab" / "aiidalab-eln-config.json" ELN_CONFIG.parent.mkdir( ...
return ( None, "No ELN instance was provided, the default ELN instance is not configured either. Set a default ELN or select an ELN instance.", ) class ElnImportWidget(ipw.VBox): node = tl.Instance(orm.Node, allow_none=True) def __init__(self, path_to_root="../", **kwargs): ...
if eln_instance in config: eln_config = config[eln_instance] eln_type = eln_config.pop("eln_type", None) else: # The selected instance is not present in the config. return None, f"Didn't find configuration for the '{eln_instance}' instance." # If the ELN type cannot...
conditional_block
elns.py
import json from pathlib import Path import ipywidgets as ipw import requests_cache import traitlets as tl from aiida import orm from aiidalab_eln import get_eln_connector from IPython.display import clear_output, display ELN_CONFIG = Path.home() / ".aiidalab" / "aiidalab-eln-config.json" ELN_CONFIG.parent.mkdir( ...
(self): config = self.get_config() default_eln = config.pop("default", None) if ( default_eln not in config ): # Erase the default ELN if it is not present in the config self.write_to_config(config) default_eln = None self.eln_instance.option...
update_list_of_elns
identifier_name
elns.py
import json from pathlib import Path import ipywidgets as ipw import requests_cache import traitlets as tl from aiida import orm from aiidalab_eln import get_eln_connector from IPython.display import clear_output, display ELN_CONFIG = Path.home() / ".aiidalab" / "aiidalab-eln-config.json" ELN_CONFIG.parent.mkdir( ...
def get_config(self): try: with open(ELN_CONFIG) as file: return json.load(file) except (FileNotFoundError, json.JSONDecodeError, KeyError): return {} def update_list_of_elns(self): config = self.get_config() default_eln = config.pop("de...
with open(ELN_CONFIG, "w") as file: json.dump(config, file, indent=4)
identifier_body
list_buffer.go
package item import ( "fmt" "math" "github.com/phil-mansfield/rogue/error" ) // BufferIndex is an integer type used to index into ListBuffer. // // Since BufferIndex may be changed to different size or to a type of unknown // signage, all BufferIndex literals must be constructed from 0, 1, // MaxBufferCount, and ...
// Singleton creates a singleton list containing only the given item. // // Singleton returns an error if it is passed // an uninitialized item, or if the buf is full. // // It is correct to call buf.IsFull() prior to all calls to // buf.Singleton(), since it is not possible to switch upon the type of error // to ide...
{ buf.Buffer = make([]Node, defaultBufferLength) buf.FreeHead = 0 buf.Count = 0 for i := 0; i < len(buf.Buffer); i++ { buf.Buffer[i].Item.Clear() buf.Buffer[i].Prev = BufferIndex(i - 1) buf.Buffer[i].Next = BufferIndex(i + 1) } buf.Buffer[0].Prev = NilIndex buf.Buffer[len(buf.Buffer)-1].Next = NilIndex }
identifier_body
list_buffer.go
package item import ( "fmt" "math" "github.com/phil-mansfield/rogue/error" ) // BufferIndex is an integer type used to index into ListBuffer. // // Since BufferIndex may be changed to different size or to a type of unknown // signage, all BufferIndex literals must be constructed from 0, 1, // MaxBufferCount, and ...
buf.internalDelete(idx) return nil } func (buf *ListBuffer) internalDelete(idx BufferIndex) { buf.internalUnlink(idx) if buf.FreeHead != NilIndex { buf.internalLink(idx, buf.FreeHead) } node := &buf.Buffer[idx] node.Item.Clear() node.Next = buf.FreeHead node.Prev = NilIndex buf.FreeHead = idx buf.Cou...
{ desc := fmt.Sprintf( "Item at idx, %d, has the Type value Uninitialized.", idx, ) return error.New(error.Value, desc) }
conditional_block
list_buffer.go
package item import ( "fmt"
"math" "github.com/phil-mansfield/rogue/error" ) // BufferIndex is an integer type used to index into ListBuffer. // // Since BufferIndex may be changed to different size or to a type of unknown // signage, all BufferIndex literals must be constructed from 0, 1, // MaxBufferCount, and NilIndex alone. type BufferInd...
random_line_split
list_buffer.go
package item import ( "fmt" "math" "github.com/phil-mansfield/rogue/error" ) // BufferIndex is an integer type used to index into ListBuffer. // // Since BufferIndex may be changed to different size or to a type of unknown // signage, all BufferIndex literals must be constructed from 0, 1, // MaxBufferCount, and ...
(item Item) (BufferIndex, *error.Error) { if buf.IsFull() { desc := fmt.Sprintf( "buf has reached maximum capacity of %d Items.", MaxBufferCount, ) return NilIndex, error.New(error.Value, desc) } else if item.Type == Uninitialized { return NilIndex, error.New(error.Value, "item is uninitialized.") } ...
Singleton
identifier_name
run_swmm_DDPG.py
""" This script runs Deep Q-Network RL algorithm for control of stormwater systems using a SWMM model as the environment Author: Benjamin Bowes Date: May 10, 2019 """ import os import numpy as np import matplotlib.pyplot as plt from pyswmm import Simulation, Nodes, Links from smart_stormwater_rl.RL_DDPG...
temp_new_flood = np.asarray([St1.flooding, St2.flooding, J3.flooding]) temp_new_valve = np.asarray([R1.current_setting, R2.current_setting]) node_new_states = np.append(temp_new_height, temp_new_flood) # input_new_states = np.append(node_new_states, temp_new_valve).res...
# Observe next state temp_new_height = np.asarray([St1.depth, St2.depth])
random_line_split
run_swmm_DDPG.py
""" This script runs Deep Q-Network RL algorithm for control of stormwater systems using a SWMM model as the environment Author: Benjamin Bowes Date: May 10, 2019 """ import os import numpy as np import matplotlib.pyplot as plt from pyswmm import Simulation, Nodes, Links from smart_stormwater_rl.RL_DDPG...
St1_depth_episode = [] St2_depth_episode = [] J3_depth_episode = [] St1_flooding_episode = [] St2_flooding_episode = [] J3_flooding_episode = [] R1_position_episode = [] R2_position_episode = [] episode += 1 # initialize simulation sim = Simulation(swmm_inp)...
actor.load_weights(os.path.join(actor_dir, save_model_name + "_actor.h5")) critic.load_weights(os.path.join(critic_dir, save_model_name + "_critic.h5"))
conditional_block
export.go
// Copyright 2020 Google LLC // // 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 ...
// Append to files list files = append(files, objectName) batchCount++ recordCount = 1 } exp, done, err = it.Next() } if err != nil { return fmt.Errorf("iterating infections: %v", err) } // Create a file for the remaining keys objectName := fmt.Sprintf(eb.FilenameRoot+"%s-%d", eb.StartTimesta...
{ return err }
conditional_block
export.go
// Copyright 2020 Google LLC // // 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 ...
OnlyLocalProvenance: false, // include federated ids } ) it, err := s.db.IterateInfections(ctx, criteria) if err != nil { return fmt.Errorf("iterating infections: %v", err) } defer it.Close() exp, done, err := it.Next() // TODO(lmohanan): Watch for context deadline for !done && err == nil { if exp !=...
UntilTimestamp: eb.EndTimestamp, IncludeRegions: eb.IncludeRegions, ExcludeRegions: eb.ExcludeRegions,
random_line_split
export.go
// Copyright 2020 Google LLC // // 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 ...
func (s *BatchServer) createFile(ctx context.Context, objectName string, exposureKeys []*model.Infection, eb model.ExportBatch, batchCount int) error { // Add ExportFile entry with Status Pending ef := model.ExportFile{ Filename: objectName, BatchID: eb.BatchID, Region: "", // TODO(lmohanan) figure out whe...
{ logger := logging.FromContext(ctx) logger.Infof("Creating files for export config %v, batchID %v", eb.ConfigID, eb.BatchID) logger.Infof("MaxRecords %v, since %v, until %v", s.bsc.MaxRecords, eb.StartTimestamp, eb.EndTimestamp) logger.Infof("Included regions %v, ExcludedRegions %v ", eb.IncludeRegions, eb.Exclud...
identifier_body
export.go
// Copyright 2020 Google LLC // // 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 ...
(w http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithTimeout(r.Context(), s.bsc.CreateTimeout) defer cancel() logger := logging.FromContext(ctx) // Obtain lock to make sure there are no other processes working to create batches. lock := "create_batches" unlockFn, err := s.db.Lock(ctx, lock, s.bs...
CreateBatchesHandler
identifier_name
unlinked_file.rs
//! Diagnostic emitted for files that aren't part of any crate. use std::iter; use hir::{db::DefDatabase, DefMap, InFile, ModuleSource}; use ide_db::{ base_db::{FileId, FileLoader, SourceDatabase, SourceDatabaseExt}, source_change::SourceChange, RootDatabase, }; use syntax::{ ast::{self, edit::IndentL...
() { cov_mark::check!(unlinked_file_skip_fix_when_mod_already_exists); check_no_fix( r#" //- /main.rs #[cfg(never)] mod foo; //- /foo.rs $0 "#, ); } #[test] fn unlinked_file_with_cfg_on() { check_diagnostics( r#" //- /main.rs #[cfg(not(never))] mod f...
unlinked_file_with_cfg_off
identifier_name
unlinked_file.rs
//! Diagnostic emitted for files that aren't part of any crate. use std::iter; use hir::{db::DefDatabase, DefMap, InFile, ModuleSource}; use ide_db::{ base_db::{FileId, FileLoader, SourceDatabase, SourceDatabaseExt}, source_change::SourceChange, RootDatabase, }; use syntax::{ ast::{self, edit::IndentL...
}
{ check_fix( r#" //- /main.rs mod bar { } //- /bar/foo/mod.rs $0 "#, r#" mod bar { mod foo; } "#, ); }
identifier_body
unlinked_file.rs
//! Diagnostic emitted for files that aren't part of any crate. use std::iter; use hir::{db::DefDatabase, DefMap, InFile, ModuleSource}; use ide_db::{ base_db::{FileId, FileLoader, SourceDatabase, SourceDatabaseExt}, source_change::SourceChange, RootDatabase, }; use syntax::{ ast::{self, edit::IndentL...
mod foo; "#, ); } #[test] fn unlinked_file_insert_in_empty_file_mod_file() { check_fix( r#" //- /main.rs //- /foo/mod.rs $0 "#, r#" mod foo; "#, ); check_fix( r#" //- /main.rs mod bar; //- /bar.rs // bar module //- /bar/foo/mod.rs $0 "#, ...
"#, r#"
random_line_split
h2ctypes.py
"""A generator of ctypes wrappers for C libraries. """ from collections import namedtuple import ctypes try: from ctypes import wintypes except ValueError: class wintypes: """Standard types defined by :file:`Windows.h`. """ BYTE = ctypes.c_ubyte DWORD = ctypes.c_uint32 ...
(self): """Parse ``typedef enum``'s. """ # Notes on enum types # # GCC: # # Normally, the type is unsigned int if there are no negative values in # the enumeration, otherwise int. If -fshort-enums is specified, then # if there are negative values i...
parse_enums
identifier_name
h2ctypes.py
"""A generator of ctypes wrappers for C libraries. """ from collections import namedtuple import ctypes try: from ctypes import wintypes except ValueError: class wintypes: """Standard types defined by :file:`Windows.h`. """ BYTE = ctypes.c_ubyte DWORD = ctypes.c_uint32 ...
n_stars -= 1 try: ctype = self.types[pointed_to] except KeyError: raise ParseError if n_stars: ctype = as_ctype(ctype) for _ in range(n_stars): ctype = ctypes.POINTER(ctype) if array_size is not None: ctype =...
if pointed_to in ("char", "wchar_t", "void") and n_stars >= 1: pointed_to += "*"
random_line_split
h2ctypes.py
"""A generator of ctypes wrappers for C libraries. """ from collections import namedtuple import ctypes try: from ctypes import wintypes except ValueError: class wintypes: """Standard types defined by :file:`Windows.h`. """ BYTE = ctypes.c_ubyte DWORD = ctypes.c_uint32 ...
setattr(self, fname, prohibited) def errcheck(retcode, func, args): """Return all (deref'ed) arguments on success, raise exception on failure. """ if retcode in func.success_codes: return func.argtuple_t(*[deref(arg) for arg in args]) else: raise DLLError(type(func.success_cod...
raise AttributeError( "{} is not a public function of the DLL".format(fname))
identifier_body
h2ctypes.py
"""A generator of ctypes wrappers for C libraries. """ from collections import namedtuple import ctypes try: from ctypes import wintypes except ValueError: class wintypes: """Standard types defined by :file:`Windows.h`. """ BYTE = ctypes.c_ubyte DWORD = ctypes.c_uint32 ...
func.__annotations__["return"] = restype module_globals[fname] = func module_all.append(fname) class Parser: """A stateful C header parser. An instance of the parser keeps tracks of the ``#defines``, whether of constants or of types (no other preprocessor macro is han...
func.__annotations__[arg] = argtype
conditional_block
lib.rs
//! ## clickhouse-rs //! Asynchronous [Yandex ClickHouse](https://clickhouse.yandex/) client library for rust programming language. //! //! ### Installation //! Library hosted on [crates.io](https://crates.io/crates/clickhouse-rs/). //! //! ```toml //! [dependencies] //! clickhouse-rs = "*" //! ``` //! //! ### Supporte...
g(test)] pub(crate) mod test_misc { use crate::*; use std::env; use lazy_static::lazy_static; lazy_static! { pub static ref DATABASE_URL: String = env::var("DATABASE_URL").unwrap_or_else(|_| { "tcp://localhost:9000?compression=lz4&ping_timeout=1s&retry_timeout=2s".into() })...
tokio::time::timeout(timeout, future).await? } #[cf
identifier_body
lib.rs
//! ## clickhouse-rs //! Asynchronous [Yandex ClickHouse](https://clickhouse.yandex/) client library for rust programming language. //! //! ### Installation //! Library hosted on [crates.io](https://crates.io/crates/clickhouse-rs/). //! //! ```toml //! [dependencies] //! clickhouse-rs = "*" //! ``` //! //! ### Supporte...
} Ok(Packet::Exception(e)) => return Err(Error::Server(e)), Err(e) => return Err(Error::Io(e)), _ => return Err(Error::Driver(DriverError::UnexpectedPacket)), } } self.inner = h; self.context.server_info = info.unwrap()...
match packet { Ok(Packet::Hello(inner, server_info)) => { info!("[hello] <- {:?}", &server_info); h = Some(inner); info = Some(server_info);
random_line_split