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
project.py
(cloud): get_normals_prox = rospy.ServiceProxy('/feature_extractor/get_normals', GetNormals) return get_normals_prox(cloud).cluster # Helper function to create a yaml friendly dictionary from ROS messages def make_yaml_dict(test_scene_num, arm_name, object_name, pick_pose, place_pose): yaml_dict = {} y...
get_normals
identifier_name
eval_functions.py
") model_paths = [] solver_paths = [] for _, _, fnames in os.walk(save_path): model_paths = [fname for fname in fnames if 'model' in fname] solver_paths = [fname for fname in fnames if 'solver' in fname] if not model_paths or not solver_paths: raise Exception('Model or solver n...
if plot_val: if has_rec_loss: plt.plot(np.linspace(1, len(train_loss), len(val_rec_loss)), val_rec_loss, label='Val Reconstruction loss') if has_gender_loss: plt.plot(np.linspace(1, len(train_loss), len(val_gender_loss)), val_gender...
if has_rec_loss: plt.plot(np.linspace(1, len(train_loss), len(train_rec_loss)), train_rec_loss, label='Train Reconstruction loss') if has_gender_loss: plt.plot(np.linspace(1, len(train_loss), len(train_gender_loss)), train_gender_loss, label='ATr...
conditional_block
eval_functions.py
(module, grad_in, grad_out): """ If there is a negative gradient, change it to zero """ # Get last forward output corresponding_forward_output = self.forward_relu_outputs[-1] corresponding_forward_output[corresponding_forward_output > 0] = 1 ...
relu_backward_hook_function
identifier_name
eval_functions.py
def update_relus(self): """ Updates relu activation functions so that 1- stores output in forward pass 2- imputes zero for gradient values that are less than zero """ def relu_backward_hook_function(module, grad_in, grad_out): """ If ...
def hook_function(module, grad_in, grad_out): self.gradients = grad_in[0] # Register hook to the first layer first_block = list(self.model.encoder._modules.items())[0][1] first_layer = list(first_block._modules.items())[0][1] first_layer.register_backward_hook(hook_function)
identifier_body
eval_functions.py
") model_paths = [] solver_paths = [] for _, _, fnames in os.walk(save_path): model_paths = [fname for fname in fnames if 'model' in fname] solver_paths = [fname for fname in fnames if 'solver' in fname] if not model_paths or not solver_paths: raise Exception('Model or solver n...
recall_score = metrics.recall_score(gender, gender_pred) # plot figures plt.figure(figsize=(8, 8)) sns.set(font_scale=1.2) sns.heatmap( cm, annot=True, xticklabels=['M', 'F'], yticklabels=['M', 'F'], fmt=".3f", linewidths=.5, square=True, ...
accuracy_score = metrics.accuracy_score(gender, gender_pred) precision_score = metrics.precision_score(gender, gender_pred)
random_line_split
lib.rs
_2(); } fn clear_next_cell_is_invalid(neighbors: &Neighbors<'a, Self>) { neighbors.clear_next_bit_2(); } fn size(&self) -> Bytes { let data = unsafe { (self as *const CellHeader<'a>).offset(1) }; let data = data as usize; let next = self.neighbors.next_unchecked(); ...
// properly aligned? if self.header.is_aligned_to(align) { previous.set(self.next_free()); let allocated = self.as_allocated_cell(policy); return Some(allocated); } None } fn insert_into_free_list<'b>( &'b self, head: &'b Cell...
random_line_split
lib.rs
`NEXT_FREE_CELL_CAN_MERGE` bit only gets set after checking with // the policy. while (*current_free.get()).next_free_can_merge() { let current = &*current_free.get(); current.clear_next_free_can_merge(); let prev_neighbor = unchecked_unwrap( current...
dealloc
identifier_name
lib.rs
min_cell_size.0 <= split_and_aligned { let split_cell_head = split_and_aligned - size_of::<CellHeader>().0; let split_cell = unsafe { &*FreeCell::from_uninitialized( unchecked_unwrap(NonNull::new(split_cell_head as *mut u8)), Bytes(next - ...
{ if align <= size_of::<usize>() { if let Some(head) = self.size_classes.get(size) { let policy = size_classes::SizeClassAllocPolicy(&self.head); let policy = &policy as &dyn AllocPolicy<'a>; return head.with_exclusive_access(|head| { ...
identifier_body
bip32_test.go
f9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542", privKey: "xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U", pubKey: "xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRU...
pathFragment: 2147483646 + hStart, privKey: "xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc", pubKey: "xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL", }, { ...
privKey: "xprv9zFnWC6h2cLgpmSA46vutJzBcfJ8yaJGg8cX1e5StJh45BBciYTRXSd25UEPVuesF9yog62tGAQtHjXajPPdbRCHuWS6T8XA2ECKADdw4Ef", pubKey: "xpub6DF8uhdarytz3FWdA8TvFSvvAh8dP3283MY7p2V4SeE2wyWmG5mg5EwVvmdMVCQcoNJxGoWaU9DCWh89LojfZ537wTfunKau47EL2dhHKon", }, {
random_line_split
bip32_test.go
PublicChildDerivation(t *testing.T) { // Generated using https://iancoleman.github.io/bip39/ // Root key: // xprv9s21ZrQH143K2Cfj4mDZBcEecBmJmawReGwwoAou2zZzG45bM6cFPJSvobVTCB55L6Ld2y8RzC61CpvadeAnhws3CHsMFhNjozBKGNgucYm // Derivation Path m/44'/60'/0'/0: // xprv9zy5o7z1GMmYdaeQdmabWFhUf52Ytbpe3G5hduA4SghboqWe7aDG...
TestB58SerializeUnserialize
identifier_name
bip32_test.go
privKey: "xprv9z4pot5VBttmtdRTWfWQmoH1taj2axGVzFqSb8C9xaxKymcFzXBDptWmT7FwuEzG3ryjH4ktypQSAewRiNMjANTtpgP4mLTj34bhnZX7UiM", pubKey: "xpub6D4BDPcP2GT577Vvch3R8wDkScZWzQzMMUm3PWbmWvVJrZwQY4VUNgqFJPMM3No2dFDFGTsxxpG5uJh7n7epu4trkrX7x7DogT5Uv6fcLW5", }, { pathFragment: 2, privKey: "xpr...
{ hStart := FirstHardenedChild vector1 := testMasterKey{ seed: "000102030405060708090a0b0c0d0e0f", privKey: "xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi", pubKey: "xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Ru...
identifier_body
bip32_test.go
9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542", privKey: "xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U", pubKey: "xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8B...
{ // Get the private key at the given key tree path privKey, err = privKey.NewChildKey(testChildKey.pathFragment) assert.NoError(t, err) // Get this private key's public key pubKey = privKey.PublicKey() // Assert correctness assert.Equal(t, testChildKey.privKey, privKey.String()) assert.Equal(t, testC...
conditional_block
implementation.rs
() { *keyword = self.trng.get_u32().expect("couldn't get random number"); } } /// Core of the key initialization routine. Requires a `progress_modal` dialog box that has been set /// up with the appropriate notification messages by the UX layer, and a `Slider` type action which /// ...
debug_staging
identifier_name
implementation.rs
s::SELFSIGN_PRIVKEY as usize + 256/(size_of::<u32>()*8)].iter_mut()) { *dst = u32::from_be_bytes(src.try_into().unwrap()) } } update_progress(10, progress_modal, progress_action); // generate and store a root key (aka boot key), this is what is unlocked by the "boot...
{ // read until we get a buffer that's not fully filled break; }
conditional_block
implementation.rs
{ match pw_type { PasswordType::Boot => { for (&src, dst) in digest.iter().zip((*pcache_ptr).hashed_boot_pw.iter_mut()) { *dst = src; } (*pcache_ptr).hashed_boot_pw_valid = 1; } ...
update_progress(10, progress_modal, progress_action);
random_line_split
implementation.rs
the kernel region"); let sensitive_data = xous::syscall::map_memory( None, None, 0x1000, xous::MemoryFlags::R | xous::MemoryFlags::W, ).expect("couldn't map sensitive data page"); let pass_cache = xous::syscall::map_memory( None, ...
/// Reads a 128-bit key at a given index offset fn read_key_128(&mut self, index: u8) -> [u8; 16] { let mut key: [u8; 16] = [0; 16]; for (addr, word) in key.chunks_mut(4).into_iter().enumerate() { self.keyrom.wfo(utra::keyrom::ADDRESS_ADDRESS, index as u32 + addr as u32); ...
{ let mut key: [u8; 32] = [0; 32]; for (addr, word) in key.chunks_mut(4).into_iter().enumerate() { self.keyrom.wfo(utra::keyrom::ADDRESS_ADDRESS, index as u32 + addr as u32); let keyword = self.keyrom.rf(utra::keyrom::DATA_DATA); for (&byte, dst) in keyword.to_be_byte...
identifier_body
extract_patches2.py
_float=False): """ Read a region from the slide Return a numpy RBG array """ im = slide.read_region((x, y), level, (width, height)) im = im.convert('RGB') # drop the alpha channel if as_float: im = np.asarray(im, dtype=np.float32) else: im = np.asarray(im) assert im.shap...
with labels from the slides in the list inputs: - tif: tif - mask: mask - lev1: int, target zoom level for the patches, between 0 and 7 - higher resolution: lev1<lev2 - lev2: int, target zoom level for the patches, between 0 and 7 - lower resolution - num_per_imgm: int, number of patches to extr...
28 outputs: Boolean """ # get patch size patch_size = patch_mask.shape[0] # get the offset to check the 128x128 centre offset = int((patch_size - patch_centre) / 2) # sum the pixels in the 128x128 centre for the tumor mask sum_cancers = np.sum(patch_mask[offset:offset + patch_centre, ...
identifier_body
extract_patches2.py
=False): """ Read a region from the slide Return a numpy RBG array """ im = slide.read_region((x, y), level, (width, height)) im = im.convert('RGB') # drop the alpha channel if as_float: im = np.asarray(im, dtype=np.float32) else: im = np.asarray(im) assert im.shape == (...
color return masked def get_patches(slide, tumor_mask, lev, x0, y0, patch_size): """ Get patches from a slide: RBG image, tumor mask, tissue mask CENTERED at x0, y0 imputs: - slide: OpenSlide object for RGB slide images - tumor_mask: OpenSlide object for tumor masks - lev: int, target zoom lev...
d[x][y] =
identifier_name
extract_patches2.py
_B indices = np.where(tissue_mask == 1) return zip(indices[0], indices[1]) def apply_mask(im, mask, color=(1, 0, 0)): """ Return the mask as an image """ masked = np.zeros(im.shape) for x, y in mask: masked[x][y] = color return masked def get_patches(slide, tumor_mask, lev, x0, y0, patch...
# extract HEALTHY patches # repeat the above for the healthy pixels print('extra
conditional_block
extract_patches2.py
as_float=False): """ Read a region from the slide Return a numpy RBG array """ im = slide.read_region((x, y), level, (width, height)) im = im.convert('RGB') # drop the alpha channel if as_float: im = np.asarray(im, dtype=np.float32) else: im = np.asarray(im) assert im.s...
- lev1: int, target zoom level for the patches, between 0 and 7 - higher resolution: lev1<lev2 - lev2: int, target zoom level for the patches, between 0 and 7 - lower resolution - num_per_imgm: int, number of patches to extract per slide per class, usually 100 - patch_size: int, usually 299 - patch_...
inputs: - tif: tif - mask: mask
random_line_split
utils.rs
_driver::connect_to_driver; mod connect_to_driver { use anyhow::{format_err, Error}; use fidl::endpoints::Proxy as _; use fidl_fuchsia_io::{NodeProxy, OPEN_RIGHT_READABLE, OPEN_RIGHT_WRITABLE}; /// Returns a NodeProxy opened at `path`. The path is guaranteed to exist before the connection /// is op...
/// Connects to the driver at `path`, returning a proxy of the specified type. The path is /// guaranteed to exist before the connection is opened. /// /// TODO(fxbug.dev/81378): factor this function out to a common library pub async fn connect_to_driver<T: fidl::endpoints::ProtocolMarker>( ...
{ device_watcher::recursive_wait_and_open_node( &io_util::open_directory_in_namespace( "/dev", OPEN_RIGHT_READABLE | OPEN_RIGHT_WRITABLE, )?, path, ) .await }
identifier_body
utils.rs
scope = ExecutionScope::new(); dir.open( scope, OPEN_RIGHT_READABLE | OPEN_RIGHT_WRITABLE, MODE_TYPE_DIRECTORY, vfs::path::Path::dot(), ServerEnd::new(dir_server.into_channel()), ); let ns = fdio::Namesp...
// Add some arbitrary values, making sure some do not land on the bucket boundary to further
random_line_split
utils.rs
_driver::connect_to_driver; mod connect_to_driver { use anyhow::{format_err, Error}; use fidl::endpoints::Proxy as _; use fidl_fuchsia_io::{NodeProxy, OPEN_RIGHT_READABLE, OPEN_RIGHT_WRITABLE}; /// Returns a NodeProxy opened at `path`. The path is guaranteed to exist before the connection /// is op...
(num_buckets: u32) -> Vec<HistogramBucket> { (0..num_buckets + 2).map(|i| HistogramBucket { index: i, count: 0 }).collect() } /// Add a data value to the histogram. pub fn add_data(&mut self, n: i64) { // Add one to index to account for underflow bucket at index 0 let mut index = 1 ...
new_vec
identifier_name
put.go
&& senderVC[i] > replicaVC[i] { //if something else than the sender incremented clock fmt.Println("canDeliver: WE CAN'T DELIVER!!") return false } } //Otherwise, our clock is only a difference of 1 in senderID slot between the currentVC and the senderVC return true } func max(x int, y int) int {...
//If causal metadata is sent from client, we need to update the KVStore/check if we can deliver //Assume we can't so just update each time if len(d.CausalMetadata) > 0 { updateKvStore(view.PersonalView, store, currVC, s) } else if len(d.CausalMetadata) == 0 { Mu.Mutex.Lock() d.CausalMetada...
if strBody == "{}" { c.JSON(http.StatusBadRequest, gin.H{"error": "Value is missing", "message": "Error in PUT"}) } else if len(key) > keyLimit { c.JSON(http.StatusBadRequest, gin.H{"error": "Key is too long", "message": "Error in PUT"}) } else {
random_line_split
put.go
&& senderVC[i] > replicaVC[i] { //if something else than the sender incremented clock fmt.Println("canDeliver: WE CAN'T DELIVER!!") return false } } //Otherwise, our clock is only a difference of 1 in senderID slot between the currentVC and the senderVC return true } func max(x int, y int) int {...
data := &StoreVal{Value: d.Value, CausalMetadata: d.CausalMetadata} jsonData, _ := json.Marshal(data) fwdRequest, err := http.NewRequest("PUT", "http://"+s.ShardMembers[shardId][index]+"/key-value-store/"+key, bytes.NewBuffer(jsonData)) //fmt.Printf("********DATA BEING SENT: %v********", data...
{ continue }
conditional_block
put.go
(senderVC []int, replicaVC []int, view []string) bool { // conditions for delivery: // senderVC[senderslot] = replicaVC[senderslot] + 1 // senderVC[notsender] <= replicaVC[not sender] senderID := senderVC[len(view)] // sender position in VC for i := 0; i < len(view); i++ { //if sender clock isn...
canDeliver
identifier_name
put.go
func max(x int, y int) int { if x < y { return y } return x } // calculate new VC: max(senderVC, replicaVC) func updateVC(senderVC []int, replicaVC []int, view []string) []int { newVC := make([]int, len(view)) for i := 0; i < len(view); i++ { fmt.Printf("SENDERVC: %v\n", senderVC) fmt.Printf...
{ // conditions for delivery: // senderVC[senderslot] = replicaVC[senderslot] + 1 // senderVC[notsender] <= replicaVC[not sender] senderID := senderVC[len(view)] // sender position in VC for i := 0; i < len(view); i++ { //if sender clock isn't updated by 1 more if i == senderID && senderVC[i...
identifier_body
macros.rs
anstream::stdout().lock(); /// write!(lock, "hello world").unwrap(); /// # } /// ``` /// /// Use `print!` only for the primary output of your program. Use /// [`eprint!`] instead to print error and progress messages. /// /// # Panics /// /// Panics if writing to `stdout` fails for any reason **except** broken pipe. //...
/// print!("on "); /// print!("the "); /// print!("same "); /// print!("line "); /// /// stdout().flush().unwrap(); /// /// print!("this string has a newline, why not choose println! instead?\n"); /// /// stdout().flush().unwrap(); /// # } /// ``` #[cfg(feature = "auto")] #[macro_export] macro_rules! print { ($($ar...
/// /// print!("this "); /// print!("will "); /// print!("be ");
random_line_split
app.py
けて # リダイレクト先へリクエストを送る # @app.route('/authorize') def authorize(): app.logger.debug(request.url) app.logger.debug(request.method) qs = urllib.parse.urlparse(request.url) query = dict(urllib.parse.parse_qsl(qs.query)) app.logger.debug(query) # reqid を生成して、/authn でチェックする # フォームの隠しフィールドにre...
clientId = request.form['client_id'] clientSecret = request.form['client_secret'] # client_id の存在と一致のチェック if check_client_id(clientId) == False:
random_line_split
app.py
', 'kid': 'authserver', } payload = { "iss": "Auth_Server", "sub": apl_id, "aud": user_id, 'iat': int(time.time()), # 現在時刻 'exp': int(time.time()) + 3600, # 有効期限時刻 1時間 "scope": "openid profile email address phone read:appointments" } wit...
pe': scope, #request.form['scope'], 'user': request.form['username'], 'client_id': query['client_id'] }; response = redirect(url, code=302) re
conditional_block
app.py
# def check_client_id(client_id): return col_clients.find_one({'client_id': client_id},{"_id": 0}) != None # 関数 リダイレクト先指定のチェック def check_redirect(client_id,redirect_uri): doc = col_clients.find_one({'client_id': client_id},{"_id": 0}) if doc == None: return False for uri in doc['redirect_ur...
ent_id のチェック
identifier_name
app.py
): query = {"client_id": client_id, "client_secret": client_secret} return col_clients.find_one(query,{"_id": 0}) != None # 関数 クライアントIDからパスワードを得る @auth.get_password def get_pw(client_id): doc = col_clients.find_one({'client_id': client_id},{'_id': 0,'client_secret': 1 }) if doc != None: return...
# 次の処理を照合するためにDBへ保存する requests[reqid] = qs.query # 個人を認証(ログイン)フォームを表示 return render_template('authorize.html', client_id=query['client_id'], redirect_uri=query['redirect_uri'], state=query['state'], ...
# クライアントIDの存在チェック # クライアントID(アプリID)は、事前に認証サーバーに登録されていないといけない if check_client_id(query['client_id']) == False: app.logger.debug('Unknown client = ' + query['client_id']) resp = { 'error': 'Unknown client' } url = query['redirect_uri'] + "?" + urllib.parse.urlencode(resp) respo...
identifier_body
pipe.rs
::{self, Rng}; use slice; use sys::c; use sys::fs::{File, OpenOptions}; use sys::handle::Handle; //////////////////////////////////////////////////////////////////////////////// // Anonymous pipes //////////////////////////////////////////////////////////////////////////////// pub struct AnonPipe { inner: Handle,...
(&mut self) -> io::Result<bool> { let amt = match self.state { State::NotReading => return Ok(true), State::Reading => { self.pipe.overlapped_result(&mut *self.overlapped, true)? } State::Read(amt) => amt, }; self.state = State::Not...
result
identifier_name
pipe.rs
::{self, Rng}; use slice; use sys::c; use sys::fs::{File, OpenOptions}; use sys::handle::Handle; //////////////////////////////////////////////////////////////////////////////// // Anonymous pipes //////////////////////////////////////////////////////////////////////////////// pub struct AnonPipe { inner: Handle,...
} } impl
while self.result()? && self.schedule_read()? { // ... } Ok(())
random_line_split
pipe.rs
::{self, Rng}; use slice; use sys::c; use sys::fs::{File, OpenOptions}; use sys::handle::Handle; //////////////////////////////////////////////////////////////////////////////// // Anonymous pipes //////////////////////////////////////////////////////////////////////////////// pub struct AnonPipe { inner: Handle,...
pub fn into_handle(self) -> Handle { self.inner } pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> { self.inner.read(buf) } pub fn read_to_end(&self, buf: &mut Vec<u8>) -> io::Result<usize> { self.inner.read_to_end(buf) } pub fn write(&self, buf: &[u8]) -> io::Result<u...
{ &self.inner }
identifier_body
helm_release_controller.go
// \=>failed<========================== // Reconcile reads that state of the cluster for a helmreleases object and makes changes based on the state read // and what is in the helmreleases.Spec // +kubebuilder:rbac:groups=application.kubesphere.io,resources=helmreleases,verbs=get;list;watch;create;update;patc...
uninstallHelmRelease
identifier_name
helm_release_controller.go
\ ^ / | // \ | /======> / // \=>failed<========================== // Reconcile reads that state of the cluster for a helmreleases object and makes changes based on the state read // and what is in the helmreleases.Spec // +kubebuilder:rbac:g...
}
random_line_split
helm_release_controller.go
// \ ^ / | // \ | /======> / // \=>failed<========================== // Reconcile reads that state of the cluster for a helmreleases object and makes changes based on the state read // and what is in the helmreleases.Spec // +kubebui...
{ return errors.New(res.Message) }
conditional_block
helm_release_controller.go
.New("get app version failed") ErrLoadChartFailed = errors.New("load chart failed") ErrS3Config = errors.New("invalid s3 config") ErrLoadChartFromStorageFailed = errors.New("load chart from storage failed") ) var _ reconcile.Reconciler = &ReconcileHelmRelease{} // ReconcileWorkspace re...
{ var chartData []byte var err error _, chartData, err = r.GetChartData(rls) if err != nil { return err } if len(chartData) == 0 { klog.Errorf("empty chart data failed, release name %s, chart name: %s", rls.Name, rls.Spec.ChartName) return ErrAppVersionDataIsEmpty } clusterName := rls.GetRlsCluster() ...
identifier_body
cachetalk.py
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ...
if args.verbose: urllib2.install_opener(urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1))) urllib2.install_opener(urllib2.build_opener(urllib2.HTTPSHandler(debuglevel=1))) req_headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, li...
group.add_argument('-b', '--batch', nargs=2, type=str, metavar=('FILE.CSV', 'R|W'), help='In batch mode you can supply a file with a list of URLs, DELTAs, and 1/0\'s') args = parser.parse_args(args=args[1:]) if not args.url.startswith('http'): args.url = 'http://' + args.url
random_line_split
cachetalk.py
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ...
bits.append(input_bit) last_input_bit = input_bit last_poll_interval = args.poll_interval - (sliding_delta + 1) if len(bits) == args.read[
if input_bit == 1: after_fp = False else: # After False-positive and bit 0? It's still False-positive ... Go back to original cycle! args.poll_interval = initial_poll_interval
conditional_block
cachetalk.py
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ...
urllib2.install_opener(urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1))) urllib2.install_opener(urllib2.build_opener(urllib2.HTTPSHandler(debuglevel=1))) req_headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0....
parser = argparse.ArgumentParser(prog='cachetalk') parser.add_argument('url', metavar='URL', type=str, help='dead drop URL') parser.add_argument('poll_interval', metavar='SECONDS', nargs='?', type=int, help='polling intervals (i.e. the delta)') parser.add_argument('-s', '--always-syn...
identifier_body
cachetalk.py
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HO...
(string): bits = [] if string.startswith('0b'): bits = list(string[2:]) else: # Convert text to binary, use the str repr to convert to list, skip 2 bytes to jump over '0b' prefix bits = list(bin(int(binascii.hexlify(string), 16)))[2:] # We're using .pop() so it's reverse() th...
__str2bits
identifier_name
check_marathon_services_replication.py
CRITICAL. If replication_threshold is defined in the yelpsoa config for a service instance then it will be used instead. """ import argparse import logging import os from datetime import datetime from datetime import timedelta import a_sync import pysensu_yelp from paasta_tools import marathon_tools from paasta_tool...
output += output_critical if output_critical and output_ok: output += '\n\n' output += 'The following locations are OK:\n' output += output_ok if any(under_replication_per_location): status = pysensu_yelp.Status.CRITICAL output += ( ...
expected_count_per_location = int(expected_count / len(smartstack_replication_info)) output = '' output_critical = '' output_ok = '' under_replication_per_location = [] for location, available_backends in sorted(smartstack_replication_info.items()): num_available_in_...
conditional_block
check_marathon_services_replication.py
) _log( service=instance_config.service, line='Replication: %s' % output, component='monitoring', level='debug', cluster=instance_config.cluster, instance=instance_config.instance, ) def parse_args(): epilog = "PERCENTAGE is an integer value representing...
rootdir = os.path.abspath(soa_dir) return os.listdir(rootdir)
identifier_body
check_marathon_services_replication.py
CRITICAL. If replication_threshold is defined in the yelpsoa config for a service instance then it will be used instead. """ import argparse import logging import os from datetime import datetime from datetime import timedelta import a_sync import pysensu_yelp from paasta_tools import marathon_tools from paasta_tool...
( instance_config, expected_count, smartstack_replication_checker, ): """Check a set of namespaces to see if their number of available backends is too low, emitting events to Sensu based on the fraction available and the thresholds defined in the corresponding yelpsoa config. :param instanc...
check_smartstack_replication_for_instance
identifier_name
check_marathon_services_replication.py
CRITICAL. If replication_threshold is defined in the yelpsoa config for a service instance then it will be used instead. """ import argparse import logging import os from datetime import datetime from datetime import timedelta import a_sync import pysensu_yelp from paasta_tools import marathon_tools from paasta_tool...
log.debug('Got smartstack replication info for %s: %s' % (instance_config.job_id, smartstack_replication_info)) if len(smartstack_replication_info) == 0: status = pysensu_yelp.Status.CRITICAL output = ( 'Service %s has no Smartstack replication info. Make sure the dis...
random_line_split
partitionA3.py
.gainOrder[self.cells-i][1] moveNodePart = self.G.node[moveNode]["part"] if self.G.node[moveNode]["locked"]: i+=1 continue if moveNodePart == 'A': ...
if __name__ == "__main__": main(sys.argv[1:])
random_line_split
partitionA3.py
append(srcNode) for conn in range(2,numNodes+1): self.G.add_edge(srcNode, int(tmpList[conn])) self.G.node[int(tmpList[conn])]["nets"].append(srcNode) def initialize_buttons(self): """ Draw User Buttons on top of interface Start: Begin placemen...
startTimer = time.clock() self.totalCutCost = self.FMPartition(quietMode) timeDif = time.clock() - startTimer print self.totalCutCost, " ", print timeDif def FMPartition(self,q...
self.splitPlace() self.gain() self.firstRun=False self.cutCost()
conditional_block
partitionA3.py
Draw', command = self.drawCells) self.draw_button.grid(row=0, column=4) # Initialize Button States and Actions self.pause_button['state'] = 'disabled' # Boolean switch to control flow of placement process self.running = False # Boolean switch to plot place...
""" Draw circuit Connections and Cell Tags """ self.delConns() self.delTags() self.drawConns() self.drawTags()
identifier_body
partitionA3.py
self.pause_button['state'] = 'disabled' self.plot_button['state'] = 'disabled' self.draw_button['state'] = 'disabled' def pauseRunning(self): """ Pause process of SA by exiting loop """ self.start_button['state'] = 'normal' self.pause_button['state'] = 'disabl...
main
identifier_name
band.go
as, "Please wait while the artist image is generated...") // defer ctx.Atlas.DeleteMessage(tempmsg.ChannelID, tempmsg.ID) // delete message when command completes // // Want to check if an artist is supplied or not // if len(ctx.Args) > 0 { // artistName := strings.Trim(strings.Join(ctx.Args, " "), " ") // ...
random_line_split
fine_tune_Inception.py
: 17 x 17 x 768 branch1x1 = conv2d_bn(x, 192, 1, 1) branch7x7 = conv2d_bn(x, 128, 1, 1) branch7x7 = conv2d_bn(branch7x7, 128, 1, 7) branch7x7 = conv2d_bn(branch7x7, 192, 7, 1) branch7x7dbl = conv2d_bn(x, 128, 1, 1) branch7x7dbl = conv2d_bn(branch7x7dbl, 128, 7, 1) branch7x7dbl = c...
random_line_split
fine_tune_Inception.py
(self, batch, logs={}): self.acc.append(logs.get('acc')) history = AccuracyHistory() # Variables to run the script with a bat-script dropout_rate= float(sys.argv[1])#0.5 lr= float(sys.argv[2] )#1e-3 batch_size= int(sys.argv[3])#10 weights_filename= 'vgg16_weights_frac_0_3_lr_' + str(lr) +'_batch'+str...
on_epoch_end
identifier_name
fine_tune_Inception.py
history = AccuracyHistory() # Variables to run the script with a bat-script dropout_rate= float(sys.argv[1])#0.5 lr= float(sys.argv[2] )#1e-3 batch_size= int(sys.argv[3])#10 weights_filename= 'vgg16_weights_frac_0_3_lr_' + str(lr) +'_batch'+str(batch_size)+'_drop_'+str(dropout_rate)+'_epochs_30.h5' matrix_f...
self.acc.append(logs.get('acc'))
identifier_body
fine_tune_Inception.py
name + '_conv' else: bn_name = None conv_name = None bn_axis = 1 x = Convolution2D(nb_filter, nb_row, nb_col, subsample=subsample, activation='relu', border_mode=border_mode, name=conv_name)(x) ...
# mixed 3: 17 x 17 x 768 branch3x3 = conv2d_bn(x, 384, 3, 3, subsample=(2, 2), border_mode='valid') branch3x3dbl = conv2d_bn(x, 64, 1, 1) branch3x3dbl = conv2d_bn(branch3x3dbl, 96, 3, 3) branch3x3dbl = conv2d_bn(branch3x3dbl, 96, 3, 3, subsample=(2, 2), border...
branch1x1 = conv2d_bn(x, 64, 1, 1) branch5x5 = conv2d_bn(x, 48, 1, 1) branch5x5 = conv2d_bn(branch5x5, 64, 5, 5) branch3x3dbl = conv2d_bn(x, 64, 1, 1) branch3x3dbl = conv2d_bn(branch3x3dbl, 96, 3, 3) branch3x3dbl = conv2d_bn(branch3x3dbl, 96, 3, 3) branch_pool...
conditional_block
custom.js
'height': width, '-webkit-transform' : 'scale(0)', '-moz-transform' : 'scale(0)', '-ms-transform' : 'scale(0)', '-o-transform' : 'scale(0)', 'transform' : 'scale(0)' }) setTimeout(function () { $('#bubble' + pob + ' .bubble').addClass('active') }, 100); setTimeout(function...
; $(document).on('click', '#showmenu', function() { $("#menu , #hidemenu").addClass("active"); $(this).removeClass("active"); $("#menu").offset({left: 0}); $("nav, #headertools").addClass("menu"); $('#topbar').append('<div id="dimmer"></div>'); $('html').css({'overflow':'hidden'}); $('body').append('<div...
{mobileModeEnd()}
conditional_block
custom.js
': width, '-webkit-transform' : 'scale(0)', '-moz-transform' : 'scale(0)', '-ms-transform' : 'scale(0)', '-o-transform' : 'scale(0)', 'transform' : 'scale(0)' }) setTimeout(function () { $('#bubble' + pob + ' .bubble').addClass('active') }, 100); setTimeout(function(){ /...
$( "#popularbazaar ul, #newbazaar ul" ).each(function(){ $(this).css({'width':'auto'}); }) } function filterbarMobile() { $('#filterbar button[
identifier_body
custom.js
(hash) { if (hash) { hash = hash }else{ hash = $('.director a[href^=#]').attr('href') } if (hash && hash.length> 1) { console.log(hash); $("a[href^=#]").removeClass('active'); $('a[href=' + hash + ']').addClass('active'); window.location.hash = hash; $('main > *.active').removeClass('active...
aHash
identifier_name
custom.js
filterbar button[name=list]').click(function(){ $('#filterbar button[name=grid]').removeClass('active'); $(this).addClass('active'); $('#ads .ad').removeClass('l-third').removeClass('m-half'); $('#ads .ad').addClass('l-full').addClass('m-full'); }) $('#filterbar button[name=grid]').click(function(){ $('#fil...
$(document).on('click', '.slider .handle li', function() {
random_line_split
register.rs
o_chain_types::Base16EncodedBytes>", try_from = "HashMap<NonMandatoryRegisterId, crate::chain::json::ergo_box::ConstantHolder>" ) )] pub struct NonMandatoryRegisters(Vec<RegisterValue>); impl NonMandatoryRegisters { /// Maximum number of non-mandatory registers pub const MAX_SIZE: usize = NonMandat...
impl TryFrom<HashMap<NonMandatoryRegisterId, crate::chain::json::ergo_box::ConstantHolder>> for NonMandatoryRegisters { type Error = NonMandatoryRegistersError; fn try_from( value: HashMap<NonMandatoryRegisterId, crate::chain::json::ergo_box::ConstantHolder>, ) -> Result<Self, Self::Error> { ...
} #[cfg(feature = "json")]
random_line_split
register.rs
_chain_types::Base16EncodedBytes>", try_from = "HashMap<NonMandatoryRegisterId, crate::chain::json::ergo_box::ConstantHolder>" ) )] pub struct NonMandatoryRegisters(Vec<RegisterValue>); impl NonMandatoryRegisters { /// Maximum number of non-mandatory registers pub const MAX_SIZE: usize = NonMandato...
/// Size of non-mandatory registers set pub fn len(&self) -> usize { self.0.len() } /// Return true if non-mandatory registers set is empty pub fn is_empty(&self) -> bool { self.0.is_empty() } /// Get register value (returns None, if there is no value for the given regist...
{ NonMandatoryRegisters::try_from( regs.into_iter() .map(|(k, v)| (k, v.into())) .collect::<HashMap<NonMandatoryRegisterId, RegisterValue>>(), ) }
identifier_body
register.rs
o_chain_types::Base16EncodedBytes>", try_from = "HashMap<NonMandatoryRegisterId, crate::chain::json::ergo_box::ConstantHolder>" ) )] pub struct NonMandatoryRegisters(Vec<RegisterValue>); impl NonMandatoryRegisters { /// Maximum number of non-mandatory registers pub const MAX_SIZE: usize = NonMandat...
(&self) -> bool { self.0.is_empty() } /// Get register value (returns None, if there is no value for the given register id) pub fn get(&self, reg_id: NonMandatoryRegisterId) -> Option<&RegisterValue> { self.0.get(reg_id as usize) } /// Get register value as a Constant /// retur...
is_empty
identifier_name
mooseleague_ts.ts
let data = sheet.data[0]; if (!data || !data.rowData) { continue; } let startUserRows = false; for (let row of data.rowData) { if (!row.values || !row.values.length) { continue; } if (!startUserRows) { if (row.values[0]?.formattedValue == 'Event') { raceName = ro...
this.events = await this.google.listEvents(); this.events = _.orderBy(this.events, e => e.date); return this.events; } async get(eventName: string): Promise<MEvent> { let events = await this.list(); return events.find(x => x.name.replace(/\s+/g, '').toLowerCase() == eventName.replace(/\s+/g, '...
{ return this.events; }
conditional_block
mooseleague_ts.ts
.division, note: 'DNS' })) }) } } } // then merge user results into the events for (let user of this.Users) { for (let result of user.results) { let evt = this.Events.find(e => e.name.toLowerCase() == result.event.toLowerCase()); if (ev...
random_line_split
mooseleague_ts.ts
, public $q: angular.IQService, public google: GoogleSvc) { } async list(): Promise<Array<MEvent>> { if (this.events && this.events.length) { return this.events; } this.events = await this.google.listEvents(); this.events = _.orderBy(this.events, e => e.date); return thi...
{ let ap = this.shouldAutoplay(); return this.$sce.trustAsResourceUrl(`https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/460111206&amp;auto_play=${ap}&amp;hide_related=false&amp;show_comments=true&amp;show_user=true&amp;show_reposts=false&amp;visual=true`); }
identifier_body
mooseleague_ts.ts
() { let users: MUser[] = []; let COL = this.USER_COLUMNS; for (let sheet of this.spreadsheet.sheets) { let eventName = sheet.properties.title; let raceName: string; let data = sheet.data[0]; if (!data || !data.rowData) { continue; } let startUserRows = false; for (let ro...
buildUsers
identifier_name
mod.rs
// TODO: Should this be handled by the `windows` module? (false, KeyCode::Esc) => if self.try_change_session(0) { return ; }, (false, KeyCode::F1) => if self.try_change_session(1) { return ; }, (false, KeyCode::F2) => if self.try_change_session(2) { return ; }, (false, KeyCode::F3) => if self.try_change_se...
{ self.0.fetch_or(1, Ordering::Relaxed); }
identifier_body
mod.rs
Channel { const fn new() -> InputChannel { InputChannel { shift_held: ModKeyPair::new(), ctrl_held: ModKeyPair::new(), alt_held: ModKeyPair::new(), //altgr: ModKeyPair::new(), cursor: MouseCursor::new(), last_key_pressed: AtomicU8::new(KeyCode::None as u8), double_click_info: Mutex::new(Mou...
KeyCode::Semicolon => shift!(self
KeyCode::SquareClose => shift!(self: "[", "{"), KeyCode::Backslash => shift!(self: "\\","|"),
random_line_split
mod.rs
{ const fn new() -> InputChannel { InputChannel { shift_held: ModKeyPair::new(), ctrl_held: ModKeyPair::new(), alt_held: ModKeyPair::new(), //altgr: ModKeyPair::new(), cursor: MouseCursor::new(), last_key_pressed: AtomicU8::new(KeyCode::None as u8), double_click_info: Mutex::new(MouseClick...
(&self) -> bool { self.shift_held.get() } fn upper(&self) -> bool { self.shift() } fn get_input_string(&self, keycode: KeyCode) -> &str { macro_rules! shift { ($s:ident: $lower:expr, $upper:expr) => { if $s.shift() { $upper } else {$lower} }; } macro_rules! alpha { ($s:ident: $lower:expr, $upper:expr) =>...
shift
identifier_name
shipper.go
JSON file. // If uploadCompacted is enabled, it also uploads compacted blocks which are already in filesystem. func New( logger log.Logger, r prometheus.Registerer, dir string, bucket objstore.Bucket, lbls func() labels.Labels, source metadata.SourceType, uploadCompactedFunc func() bool, allowOutOfOrderUploads...
(ctx context.Context) (uploaded int, err error) { meta, err := ReadMetaFile(s.dir) if err != nil { // If we encounter any error, proceed with an empty meta file and overwrite it later. // The meta file is only used to avoid unnecessary bucket.Exists call, // which are properly handled by the system if their occ...
Sync
identifier_name
shipper.go
(ctx context.Context) (uploaded int, err error) { meta, err := ReadMetaFile(s.dir) if err != nil { // If we encounter any error, proceed with an empty meta file and overwrite it later. // The meta file is only used to avoid unnecessary bucket.Exists call, // which are properly handled by the system if their occ...
{ // Make any changes to the file appear atomic. path := filepath.Join(dir, MetaFilename) tmp := path + ".tmp" f, err := os.Create(tmp) if err != nil { return err } enc := json.NewEncoder(f) enc.SetIndent("", "\t") if err := enc.Encode(meta); err != nil { runutil.CloseWithLogOnErr(logger, f, "write meta...
identifier_body
shipper.go
existing blocks from the remote bucket for check", "id", newMeta.ULID.String()) if err := c.sync(ctx); err != nil { return err } } // TODO(bwplotka) so confusing! we need to sort it first. Add comment to TSDB code. metas := append([]tsdb.BlockMeta{newMeta}, c.metas...) sort.Slice(metas, func(i, j int) bool...
random_line_split
shipper.go
JSON file. // If uploadCompacted is enabled, it also uploads compacted blocks which are already in filesystem. func New( logger log.Logger, r prometheus.Registerer, dir string, bucket objstore.Bucket, lbls func() labels.Labels, source metadata.SourceType, uploadCompactedFunc func() bool, allowOutOfOrderUploads...
// No error returned, just log line. This is because we want other blocks to be uploaded even // though this one failed. It will be retried on second Sync iteration. level.Error(s.logger).Log("msg", "shipping failed", "block", m.ULID, "err", err) uploadErrs++ continue } meta.Uploaded = append(meta....
{ return 0, errors.Wrapf(err, "upload %v", m.ULID) }
conditional_block
devcontrol.py
IGHUP, gracefulexit) def gracefulexit(signalnumber, frame): """Close the database, broker and client, and exit the program.""" sys.exit(0) # resources will be closed on their corresponding finally blocks # Main routines # ------------------------------------------------------------------------------ def proces...
# respond with a list of unverified devices, using the format ('<displayname>' )* # note that every guest is connected (otherwise it would just be removed from the list) "info": (1, info_handler), # info <displayname> # retrieve device profile # respond with the list of device properties in the profile...
# and a negative sign '-' if it is not "guestlist": (0, guestlist_handler), # guestlist # retrieve the guestlist
random_line_split
devcontrol.py
more information on each operation def timed_handler(userdata, *args): """Accomodate the input for a non-recurrent event.""" fuzzy = False if args[3] == "exact": fuzzy = False elif args[3] == "fuzzy": fuzzy = True else: raise FormatError("Expected 'fuzzy' or 'exact' but found '" + args[3] + "'...
"""Main MQTT/REST API event loop.""" userdata = {"done": False, "database": db, "cursor": cursor, "configuration": configuration, "client": None, "guestlist": guestlist} client = None try: client = mqtt.Client(userdata=userdata) client.username_pw_set(configuration["superuser"], configuration[...
identifier_body
devcontrol.py
), # askstatus <displayname> # ask the device for its current status "cmd": (2, device.execute), # cmd <displayname> <operation> # send immediate command to device; # arguments to the operation should be within the operation argument, e.g. 'dimmer 126' # the operation must be valid (and have valid a...
main()
conditional_block
devcontrol.py
IGHUP, gracefulexit) def gracefulexit(signalnumber, frame): """Close the database, broker and client, and exit the program.""" sys.exit(0) # resources will be closed on their corresponding finally blocks # Main routines # ------------------------------------------------------------------------------ def
(userdata, line): """Read a line from stdin and execute the corresponding command.""" def processcmd(command, args, expected_nargs, delegate): """Validate the number of arguments and call a delegate handler.""" if len(args) != expected_nargs: raise FormatError("Wrong number of arguments for '" + command +...
processline
identifier_name
lt_common.py
and not reset_db: self.load() def _init_ltgroup(self, ltg_alg): if ltg_alg == "shiso": import lt_shiso ltgroup = lt_shiso.LTGroupSHISO(self.table, ngram_length = self.conf.getint( "log_template_shiso", "ltgroup_ngram_length"),...
return "".join(l_w) else: return "".join([s + w for w, s in zip(l_w + [""], self.lts)]) def count(self): self.cnt += 1 return self.cnt def replace(self, l_w, l_s = None, count = None): self.ltw = l_w if l_s is not None: self.lts =...
def __init__(self, ltid, ltgid, ltw, lts, count, sym): self.ltid = ltid self.ltgid = ltgid self.ltw = ltw self.lts = lts self.cnt = count self.sym = sym def __str__(self): return self.restore_message(self.ltw) def var(self, l_w): return [w_org fo...
identifier_body
lt_common.py
and not reset_db: self.load() def _init_ltgroup(self, ltg_alg): if ltg_alg == "shiso": import lt_shiso ltgroup = lt_shiso.LTGroupSHISO(self.table, ngram_length = self.conf.getint( "log_template_shiso", "ltgroup_ngram_length"),...
if point.wild is None: point.wild = self._new_node(point, w) point = point.wild else: if not point.windex.has_key(w): point.windex[w] = self._new_node(point, w) point = point.windex[w] else: ...
point = self.root for w in ltwords: if w == self.sym:
random_line_split
lt_common.py
and not reset_db: self.load() def _init_ltgroup(self, ltg_alg): if ltg_alg == "shiso": import lt_shiso ltgroup = lt_shiso.LTGroupSHISO(self.table, ngram_length = self.conf.getint( "log_template_shiso", "ltgroup_ngram_length"),...
else: return "".join([s + w for w, s in zip(l_w + [""], self.lts)]) def count(self): self.cnt += 1 return self.cnt def replace(self, l_w, l_s = None, count = None): self.ltw = l_w if l_s is not None: self.lts = l_s if count is not No...
return "".join(l_w)
conditional_block
lt_common.py
and not reset_db: self.load() def _init_ltgroup(self, ltg_alg): if ltg_alg == "shiso": import lt_shiso ltgroup = lt_shiso.LTGroupSHISO(self.table, ngram_length = self.conf.getint( "log_template_shiso", "ltgroup_ngram_length"),...
(self, ltid): self.table.remove_lt(ltid) self.db.remove_lt(ltid) def remake_ltg(self): self.db.reset_ltg() self.ltgroup.init_dict() temp_table = self.table self.ltgroup.table = LTTable(self.sym) for ltline in temp_table: ltgid = self.ltgroup.add(...
remove_lt
identifier_name
lib.rs
Primary exported Tessel object with access to module ports, LEDs, and a button. /// # Example /// ``` /// use tessel::Tessel; /// /// # #[allow(dead_code)] /// # fn example() { /// let t = Tessel::new(); /// // Tessel 2 has four LEDs available. /// assert_eq!(t.led.len(), 4); /// // Tessel 2 has two ports labelled a a...
else { sock.write_command(Command::GpioLow(self.index as u8)) } } } impl Port { pub fn new(path: &str) -> Port { let mut pins = HashMap::new(); for i in 0..8 { pins.insert(i, Mutex::new(())); } // Create and return the port struct Port {...
{ sock.write_command(Command::GpioHigh(self.index as u8)) }
conditional_block
lib.rs
exported Tessel object with access to module ports, LEDs, and a button. /// # Example /// ``` /// use tessel::Tessel; /// /// # #[allow(dead_code)] /// # fn example() { /// let t = Tessel::new(); /// // Tessel 2 has four LEDs available. /// assert_eq!(t.led.len(), 4); /// // Tessel 2 has two ports labelled a and b ///...
fn tx(&self, sock: &mut MutexGuard<PortSocket>, address: u8, write_buf: &[u8]) { sock.write_command(Command::Start(address<<1)).unwrap(); // Write the command and data sock.write_command(Command::Tx(write_buf)).unwrap(); } fn rx(&self, sock: &mut MutexGuard<PortSocket>, address: u...
{ let mut sock = self.socket.lock().unwrap(); sock.write_command(Command::EnableI2C{ baud: baud }).unwrap(); }
identifier_body
lib.rs
>, } impl Tessel { // new() returns a Tessel struct conforming to the Tessel 2's functionality. pub fn new() -> Tessel { // Create a port group with two ports, one on each domain socket path. let ports = PortGroup { a: Port::new(PORT_A_UDS_PATH), b: Port::new(PORT_B_UDS_...
toggle
identifier_name
lib.rs
Primary exported Tessel object with access to module ports, LEDs, and a button. /// # Example /// ``` /// use tessel::Tessel; /// /// # #[allow(dead_code)] /// # fn example() { /// let t = Tessel::new(); /// // Tessel 2 has four LEDs available. /// assert_eq!(t.led.len(), 4); /// // Tessel 2 has two ports labelled a a...
pub port: PortGroup, // An array of LED structs. pub led: Vec<LED>, } impl Tessel { // new() returns a Tessel struct conforming to the Tessel 2's functionality. pub fn new() -> Tessel { // Create a port group with two ports, one on each domain socket path. let ports = PortGroup { ...
pub struct Tessel { // A group of module ports.
random_line_split
watch.rs
fn path_match(watched_paths: &HashSet<PathBuf>, event_path: &Path) -> bool { let event_parent = event_path.parent(); let matches = |watched: &Path| { if event_path == watched { debug!( "event path directly matches watched path"; "event_path" => event_path.to...
let nix = PathBuf::from("/nix/store/njlavpa90laywf22b1myif5101qhln8r-hello-2.10"); match super::Watch::extend_filter(nix.clone()) { Ok(path) => assert!(false, "{:?} should be filtered!", path), Err(super::FilteredOut { path, reason }) => { drop(reason); ...
identifier_body
watch.rs
(EventError::EventHasNoFilePath(event))) } else { let notify::Event { paths, kind, .. } = event; let interesting_paths: Vec<PathBuf> = paths .into_iter() .filter(|p| self.path_is_interesting(p, &kind)) ...
false }; watched_paths.iter().any(|watched| { if matches(watched) { return true; } if let Ok(canonicalized_watch) = watched.canonicalize() { if matches(&canonicalized_watch) { return true; } } false }) } ...
if parent == watched { debug!( "event path parent matches watched path"; "event_path" => event_path.to_str(), "parent_path" => parent.to_str()); return true; } }
conditional_block
watch.rs
is a symlink forest that is used to keep track of // channels and nix will uconditionally update the metadata of each // link in this forest. See https://github.com/NixOS/nix/blob/629b9b0049363e091b76b7f60a8357d9f94733cc/src/libstore/local-store.cc#L74-L80 // for the unc...
random_line_split
watch.rs
Error::EventHasNoFilePath(event))) } else { let notify::Event { paths, kind, .. } = event; let interesting_paths: Vec<PathBuf> = paths .into_iter() .filter(|p| self.path_is_interesting(p, &kind)) ...
ath: PathBuf) -> Result<PathBuf, FilteredOut<'static>> { if path.starts_with(Path::new("/nix/store")) { Err(FilteredOut { path, reason: "starts with /nix/store", }) } else { Ok(path) } } fn log_event(&self, event: &noti...
tend_filter(p
identifier_name
transformer.py
A wrapper that defines a key for the inference cache. """ def __init__(self, cache_key, fn): super().__init__() self.cache_key = cache_key self.fn = fn def forward(self, x, *, cache=None, **kwargs): return self.fn(x, cache=cache, cache_key=self.cache_key, **kwargs) # h...
elif attn_type == 'conv_like': attn_class = partial(SparseConvCausalAttention, seq_len = seq_len, image_size = image_fmap_size, stable = stable) else: raise ValueError(f'attention type "{attn_type}" is not valid') attn, reused_attn_type = shared_attn...
attn_class = partial(SparseAxialCausalAttention, seq_len = seq_len, axis = 1, image_size = image_fmap_size, stable = stable)
conditional_block
transformer.py
""" A wrapper that defines a key for the inference cache. """ def __init__(self, cache_key, fn): super().__init__() self.cache_key = cache_key self.fn = fn def forward(self, x, *, cache=None, **kwargs): return self.fn(x, cache=cache, cache_key=self.cache_key, **kwargs)...
# layer norm class PreNorm(nn.Module): def __init__(self, dim, fn, sandwich = False): super().__init__() self.norm = nn.LayerNorm(dim) self.norm_out = nn.LayerNorm(dim) if sandwich else nn.Identity() self.fn = fn def forward(self, x, **kwargs): x = self.norm(x) ...
def __init__(self, dim, depth, fn): super().__init__() if depth <= 18: init_eps = 0.1 elif depth > 18 and depth <= 24: init_eps = 1e-5 else: init_eps = 1e-6 scale = torch.zeros(1, 1, dim).fill_(init_eps) self.scale = nn.Parameter(scale...
identifier_body
transformer.py
A wrapper that defines a key for the inference cache. """ def __init__(self, cache_key, fn): super().__init__() self.cache_key = cache_key self.fn = fn def forward(self, x, *, cache=None, **kwargs): return self.fn(x, cache=cache, cache_key=self.cache_key, **kwargs) # h...
(nn.Module): def forward(self, x): x, gates = x.chunk(2, dim = -1) return x * F.gelu(gates) class FeedForward(nn.Module): def __init__(self, dim, dropout = 0., mult = 4.): super().__init__() self.net = nn.Sequential( nn.Linear(dim, dim * mult * 2), GEGLU(...
GEGLU
identifier_name
transformer.py
""" A wrapper that defines a key for the inference cache. """ def __init__(self, cache_key, fn): super().__init__() self.cache_key = cache_key self.fn = fn
# https://arxiv.org/abs/2103.17239 class LayerScale(nn.Module): def __init__(self, dim, depth, fn): super().__init__() if depth <= 18: init_eps = 0.1 elif depth > 18 and depth <= 24: init_eps = 1e-5 else: init_eps = 1e-6 scale = torch.zer...
def forward(self, x, *, cache=None, **kwargs): return self.fn(x, cache=cache, cache_key=self.cache_key, **kwargs)
random_line_split
lib.rs
used with passphrases that were provided by (or generated for) a human. //! - For compatibility with existing SSH keys, enable the `ssh` feature flag, and use //! [`ssh::Recipient`] and [`ssh::Identity`]. //! //! Age-encrypted files are binary and non-malleable. To encode them as text, use the //! wrapping readers a...
//! let passphrase = "this is not a good passphrase"; //! //! // Encrypt the plaintext to a ciphertext using the passphrase... //! # fn encrypt(passphrase: &str, plaintext: &[u8]) -> Result<Vec<u8>, age::EncryptError> { //! let encrypted = { //! let encryptor = age::Encryptor::with_user_passphrase(Secret::new(passp...
//! let plaintext = b"Hello world!";
random_line_split
lib.rs
new(pubkey)]) //! .expect("we provided a recipient"); //! //! let mut encrypted = vec![]; //! let mut writer = encryptor.wrap_output(&mut encrypted)?; //! writer.write_all(plaintext)?; //! writer.finish()?; //! //! encrypted //! }; //! # Ok(encrypted) //! # } //! //! // ... and decrypt the o...
fuzz_header
identifier_name
lib.rs
encrypted) //! # } //! //! // ... and decrypt the obtained ciphertext to the plaintext again. //! # fn decrypt(key: age::x25519::Identity, encrypted: Vec<u8>) -> Result<Vec<u8>, age::DecryptError> { //! let decrypted = { //! let decryptor = match age::Decryptor::new(&encrypted[..])? { //! age::Decryptor::Re...
{ let mut buf = Vec::with_capacity(data.len()); header.write(&mut buf).expect("can write header"); assert_eq!(&buf[..], &data[..buf.len()]); }
conditional_block
lib.rs
) //! # } //! //! // ... and decrypt the obtained ciphertext to the plaintext again. //! # fn decrypt(key: age::x25519::Identity, encrypted: Vec<u8>) -> Result<Vec<u8>, age::DecryptError> { //! let decrypted = { //! let decryptor = match age::Decryptor::new(&encrypted[..])? { //! age::Decryptor::Recipients(...
{ if let Ok(header) = format::Header::read(data) { let mut buf = Vec::with_capacity(data.len()); header.write(&mut buf).expect("can write header"); assert_eq!(&buf[..], &data[..buf.len()]); } }
identifier_body
api.go
}, }, Action: func(ctx *cli.Context) error { var query = ctx.String("query") return list(func(entryc chan<- interface{}, errc chan<- error, done <-chan struct{}) { c.client.SearchAPIsRaw(query, entryc, errc, done) }, func(table *TableFormatter) { table.Header("ID", "Name", "Version", "Description",...
if err := c.client.ChangeAPIStatus(id, wso2am.APIActionDeprecate); err != nil { errs = multierror.Append(errs, err) fmt.Println(err) return } if err := c.client.ChangeAPIStatus(id, wso2am.APIActionRetire); err != nil { errs = multierror.Append(errs, err) fmt.Println(...
{ return cli.Command{ Name: "delete", Aliases: []string{"del", "rm"}, Usage: "Delete the API", Flags: []cli.Flag{ cli.BoolFlag{ Name: "all,a", }, cli.BoolFlag{ Name: "force,f", }, }, ArgsUsage: "ID...", Action: func(ctx *cli.Context) error { // define rm func var errs error...
identifier_body
api.go
- %s `, wso2am.APIActionPublish, wso2am.APIActionDeployAsPrototype, wso2am.APIActionDemoteToCreated, wso2am.APIActionDemoteToPrototyped, wso2am.APIActionBlock, wso2am.APIActionDeprecate, wso2am.APIActionRePublish, wso2am.APIActionRetire), ArgsUsage: "ID ACTION", Action: func(ctx *cli.Context) error { if ctx.NAr...
{ api.Version = ctx.String("version") }
conditional_block