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 |
|---|---|---|---|---|
project.py | #!/usr/bin/env python
# Import modules
import numpy as np
import sklearn
from sklearn.preprocessing import LabelEncoder
import pickle
from sensor_stick.srv import GetNormals
from sensor_stick.features import compute_color_histograms
from sensor_stick.features import compute_normal_histograms
from visualization_msgs.ms... | (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 | import os
import seaborn as sns
import torch
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import sklearn.metrics as metrics
from sklearn.manifold import TSNE
from torch.nn import ReLU
GENDER_ENUM = np.vectorize(lambda t: 'male' if t == 0 else 'female')
class GuidedBackprop:
""... |
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 | import os
import seaborn as sns
import torch
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import sklearn.metrics as metrics
from sklearn.manifold import TSNE
from torch.nn import ReLU
GENDER_ENUM = np.vectorize(lambda t: 'male' if t == 0 else 'female')
class GuidedBackprop:
""... | (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 | import os
import seaborn as sns
import torch
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import sklearn.metrics as metrics
from sklearn.manifold import TSNE
from torch.nn import ReLU
GENDER_ENUM = np.vectorize(lambda t: 'male' if t == 0 else 'female')
class GuidedBackprop:
""... |
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 | import os
import seaborn as sns
import torch
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import sklearn.metrics as metrics
from sklearn.manifold import TSNE
from torch.nn import ReLU
GENDER_ENUM = np.vectorize(lambda t: 'male' if t == 0 else 'female')
class GuidedBackprop:
""... | 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 | #![no_std]
#![allow(clippy::declare_interior_mutable_const)]
#![allow(clippy::cast_ptr_alignment)]
#![allow(clippy::needless_lifetimes)]
extern crate alloc;
mod const_init;
mod imp_static_array;
mod neighbors;
mod size_classes;
use const_init::ConstInit;
use core::alloc::{GlobalAlloc, Layout};
use core::cell::Cell;
... | // 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 | #![no_std]
#![allow(clippy::declare_interior_mutable_const)]
#![allow(clippy::cast_ptr_alignment)]
#![allow(clippy::needless_lifetimes)]
extern crate alloc;
mod const_init;
mod imp_static_array;
mod neighbors;
mod size_classes;
use const_init::ConstInit;
use core::alloc::{GlobalAlloc, Layout};
use core::cell::Cell;
... | (&self, ptr: *mut u8, layout: Layout) {
ALLOC_BYTES_LEFT.fetch_add(layout.size() as i32, Ordering::SeqCst);
ALLOC_BYTES_USED.fetch_sub(layout.size() as i32, Ordering::SeqCst);
if let Some(ptr) = NonNull::new(ptr) {
self.dealloc_impl(ptr, layout);
}
}
}
| dealloc | identifier_name |
lib.rs | #![no_std]
#![allow(clippy::declare_interior_mutable_const)]
#![allow(clippy::cast_ptr_alignment)]
#![allow(clippy::needless_lifetimes)]
extern crate alloc;
mod const_init;
mod imp_static_array;
mod neighbors;
mod size_classes;
use const_init::ConstInit;
use core::alloc::{GlobalAlloc, Layout};
use core::cell::Cell;
... |
unsafe fn alloc_impl(&self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
let size = Bytes(layout.size());
let align = if layout.align() == 0 {
Bytes(1)
} else {
Bytes(layout.align())
};
if size.0 == 0 {
// Ensure that our made up p... | {
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 | package bip32
import (
"encoding/hex"
"testing"
"github.com/stretchr/testify/assert"
)
type testMasterKey struct {
seed string
children []testChildKey
privKey string
pubKey string
}
type testChildKey struct {
pathFragment uint32
privKey string
pubKey string
hexPubKey string
}
func T... | pathFragment: 2147483646 + hStart,
privKey: "xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc",
pubKey: "xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL",
},
{
... | privKey: "xprv9zFnWC6h2cLgpmSA46vutJzBcfJ8yaJGg8cX1e5StJh45BBciYTRXSd25UEPVuesF9yog62tGAQtHjXajPPdbRCHuWS6T8XA2ECKADdw4Ef",
pubKey: "xpub6DF8uhdarytz3FWdA8TvFSvvAh8dP3283MY7p2V4SeE2wyWmG5mg5EwVvmdMVCQcoNJxGoWaU9DCWh89LojfZ537wTfunKau47EL2dhHKon",
},
{ | random_line_split |
bip32_test.go | package bip32
import (
"encoding/hex"
"testing"
"github.com/stretchr/testify/assert"
)
type testMasterKey struct {
seed string
children []testChildKey
privKey string
pubKey string
}
type testChildKey struct {
pathFragment uint32
privKey string
pubKey string
hexPubKey string
}
func T... | (t *testing.T) {
tests := []struct {
seed []byte
base58 string
}{
{[]byte{}, "xprv9s21ZrQH143K4YUcKrp6cVxQaX59ZFkN6MFdeZjt8CHVYNs55xxQSvZpHWfojWMv6zgjmzopCyWPSFAnV4RU33J4pwCcnhsB4R4mPEnTsMC"},
{[]byte{1}, "xprv9s21ZrQH143K3YSbAXLMPCzJso5QAarQksAGc5rQCyZCBfw4Rj2PqVLFNgezSBhktYkiL3Ta2stLPDF9yZtLMaxk6Spiqh3DNF... | TestB58SerializeUnserialize | identifier_name |
bip32_test.go | package bip32
import (
"encoding/hex"
"testing"
"github.com/stretchr/testify/assert"
)
type testMasterKey struct {
seed string
children []testChildKey
privKey string
pubKey string
}
type testChildKey struct {
pathFragment uint32
privKey string
pubKey string
hexPubKey string
}
func T... |
func testVectorKeyPairs(t *testing.T, vector testMasterKey) {
// Decode master seed into hex
seed, _ := hex.DecodeString(vector.seed)
// Generate a master private and public key
privKey, err := NewMasterKey(seed)
assert.NoError(t, err)
pubKey := privKey.PublicKey()
assert.Equal(t, vector.privKey, privKey.St... | {
hStart := FirstHardenedChild
vector1 := testMasterKey{
seed: "000102030405060708090a0b0c0d0e0f",
privKey: "xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi",
pubKey: "xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Ru... | identifier_body |
bip32_test.go | package bip32
import (
"encoding/hex"
"testing"
"github.com/stretchr/testify/assert"
)
type testMasterKey struct {
seed string
children []testChildKey
privKey string
pubKey string
}
type testChildKey struct {
pathFragment uint32
privKey string
pubKey string
hexPubKey string
}
func T... |
}
func TestPublicParentPublicChildDerivation(t *testing.T) {
// Generated using https://iancoleman.github.io/bip39/
// Root key:
// xprv9s21ZrQH143K2Cfj4mDZBcEecBmJmawReGwwoAou2zZzG45bM6cFPJSvobVTCB55L6Ld2y8RzC61CpvadeAnhws3CHsMFhNjozBKGNgucYm
// Derivation Path m/44'/60'/0'/0:
// xprv9zy5o7z1GMmYdaeQdmabWFhUf52... | {
// 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 | use gam::FONT_TOTAL_LEN;
use ticktimer_server::Ticktimer;
use utralib::generated::*;
use crate::api::*;
use core::num::NonZeroUsize;
use num_traits::*;
use gam::modal::{Modal, Slider};
use crate::bcrypt::*;
use crate::api::PasswordType;
use core::convert::TryInto;
use ed25519_dalek::{Keypair, Signature, Signer};
use... | (&self) {
self.debug_print_key(KeyRomLocs::FPGA_KEY as usize, 256, "FPGA key: ");
self.debug_print_key(KeyRomLocs::SELFSIGN_PRIVKEY as usize, 256, "Self private key: ");
self.debug_print_key(KeyRomLocs::SELFSIGN_PUBKEY as usize, 256, "Self public key: ");
self.debug_print_key(KeyRomLocs:... | debug_staging | identifier_name |
implementation.rs | use gam::FONT_TOTAL_LEN;
use ticktimer_server::Ticktimer;
use utralib::generated::*;
use crate::api::*;
use core::num::NonZeroUsize;
use num_traits::*;
use gam::modal::{Modal, Slider};
use crate::bcrypt::*;
use crate::api::PasswordType;
use core::convert::TryInto;
use ed25519_dalek::{Keypair, Signature, Signer};
use... |
}
if false { // this path is for debugging the loader hash. It spoils the loader signature in the process.
let digest = hasher.finalize();
log::info!("len: {}", loader_len);
log::info!("{:x?}", digest);
// fake hasher for now
let mut hasher = ... | {
// read until we get a buffer that's not fully filled
break;
} | conditional_block |
implementation.rs | use gam::FONT_TOTAL_LEN;
use ticktimer_server::Ticktimer;
use utralib::generated::*;
use crate::api::*;
use core::num::NonZeroUsize;
use num_traits::*;
use gam::modal::{Modal, Slider};
use crate::bcrypt::*;
use crate::api::PasswordType;
use core::convert::TryInto;
use ed25519_dalek::{Keypair, Signature, Signer};
use... |
// generate and store a root key (aka boot key), this is what is unlocked by the "boot password"
// ironically, it's a "lower security" key because it just acts as a gatekeeper to further
// keys that would have a stronger password applied to them, based upon the importance of the secret
... |
update_progress(10, progress_modal, progress_action); | random_line_split |
implementation.rs | use gam::FONT_TOTAL_LEN;
use ticktimer_server::Ticktimer;
use utralib::generated::*;
use crate::api::*;
use core::num::NonZeroUsize;
use num_traits::*;
use gam::modal::{Modal, Slider};
use crate::bcrypt::*;
use crate::api::PasswordType;
use core::convert::TryInto;
use ed25519_dalek::{Keypair, Signature, Signer};
use... |
/// 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 | """这里把slide read的时候的dimention换成了mask的dimention,为了防止大小不一样"""
from openslide import open_slide, __library_version__ as openslide_lib_version, __version__ as openslide_version
import numpy as np
import random, os, glob, time
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize
from skimage.color import... | 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 | """这里把slide read的时候的dimention换成了mask的dimention,为了防止大小不一样"""
from openslide import open_slide, __library_version__ as openslide_lib_version, __version__ as openslide_version
import numpy as np
import random, os, glob, time
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize
from skimage.color import... | 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 | """这里把slide read的时候的dimention换成了mask的dimention,为了防止大小不一样"""
from openslide import open_slide, __library_version__ as openslide_lib_version, __version__ as openslide_version
import numpy as np
import random, os, glob, time
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize
from skimage.color import... | cting normal patches------')
#logging.info('extracting normal patches')
# print()
# get a random sample of healthy pixels
random_sample = min(len(list(zip(mask_lev_4_health[1], mask_lev_4_health[0])))-1, num_random_sample)
sample_health = random.sample(list(zip(mask_lev_4_health[1], mask_lev_4_heal... | # extract HEALTHY patches
# repeat the above for the healthy pixels
print('extra | conditional_block |
extract_patches2.py | """这里把slide read的时候的dimention换成了mask的dimention,为了防止大小不一样"""
from openslide import open_slide, __library_version__ as openslide_lib_version, __version__ as openslide_version
import numpy as np
import random, os, glob, time
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize
from skimage.color import... | - 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 | // Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// Logs an error message if the passed in `result` is an error.
#[macro_export]
macro_rules! log_if_err {
($result:expr, $log_prefix:expr) => {
... |
/// 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 | // Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// Logs an error message if the passed in `result` is an error.
#[macro_export]
macro_rules! log_if_err {
($result:expr, $log_prefix:expr) => {
... | // verify the bucketing logic
hist.add_data(50);
hist.add_data(65);
hist.add_data(75);
hist.add_data(79);
// Verify the values were counted and bucketed properly
assert_eq!(hist.count(), 4);
assert_eq!(
hist.get_data(),
vec![
... |
// Add some arbitrary values, making sure some do not land on the bucket boundary to further | random_line_split |
utils.rs | // Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// Logs an error message if the passed in `result` is an error.
#[macro_export]
macro_rules! log_if_err {
($result:expr, $log_prefix:expr) => {
... | (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 | package utility
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/gin-gonic/gin"
)
const (
keyLimit int = 50 // maximum number of characters allowed for a key
)
type StoreVal struct {
Value string `json:"value"`
CausalMetadata []int `json:"causal... | //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 | package utility
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/gin-gonic/gin"
)
const (
keyLimit int = 50 // maximum number of characters allowed for a key
)
type StoreVal struct {
Value string `json:"value"`
CausalMetadata []int `json:"causal... |
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 | package utility
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/gin-gonic/gin"
)
const (
keyLimit int = 50 // maximum number of characters allowed for a key
)
type StoreVal struct {
Value string `json:"value"`
CausalMetadata []int `json:"causal... | (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 | package utility
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/gin-gonic/gin"
)
const (
keyLimit int = 50 // maximum number of characters allowed for a key
)
type StoreVal struct {
Value string `json:"value"`
CausalMetadata []int `json:"causal... |
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 | /// Prints to [`stdout`][crate::stdout].
///
/// Equivalent to the [`println!`] macro except that a newline is not printed at
/// the end of the message.
///
/// Note that stdout is frequently line-buffered by default so it may be
/// necessary to use [`std::io::Write::flush()`] to ensure the output is emitted
/// imme... | /// 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 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# 認証認可サーバー
#
import os
import uuid
import json
import hashlib
import requests
import time
import base64
import auth_config as cf
# Flaskフレームワーク関連
from flask import Flask,render_template,make_response,request,send_from_directory,redirect,send_file
from flask_restful impor... | app.logger.debug('Unknown client ' + clientId)
return {'error': 'invalid_client'}, 401
# client_secret パスワードの一致チェック
if check_client_secret(clientId,clientSecret) == False:
app.logger.debug('Mismatched client secret')
return {'error': 'invalid_client'}, 401
app.logger.debug(... | clientId = request.form['client_id']
clientSecret = request.form['client_secret']
# client_id の存在と一致のチェック
if check_client_id(clientId) == False: | random_line_split |
app.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# 認証認可サーバー
#
import os
import uuid
import json
import hashlib
import requests
import time
import base64
import auth_config as cf
# Flaskフレームワーク関連
from flask import Flask,render_template,make_response,request,send_from_directory,redirect,send_file
from flask_restful impor... | turn response
#
# 認証の成功を受けて、
# access_token, id_token を発行してアプリへ提供する
#
@app.route('/token', methods=['POST', 'GET'])
@auth.login_required
def token():
app.logger.debug("/token")
app.logger.debug(request.headers)
app.logger.debug(request.form)
clientId = None
clientSecret = None
# authoriza... | pe': scope, #request.form['scope'],
'user': request.form['username'],
'client_id': query['client_id']
};
response = redirect(url, code=302)
re | conditional_block |
app.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# 認証認可サーバー
#
import os
import uuid
import json
import hashlib
import requests
import time
import base64
import auth_config as cf
# Flaskフレームワーク関連
from flask import Flask,render_template,make_response,request,send_from_directory,redirect,send_file
from flask_restful impor... |
#
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 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# 認証認可サーバー
#
import os
import uuid
import json
import hashlib
import requests
import time
import base64
import auth_config as cf
# Flaskフレームワーク関連
from flask import Flask,render_template,make_response,request,send_from_directory,redirect,send_file
from flask_restful impor... | st' }
url = query['redirect_uri'] + "?" + urllib.parse.urlencode(resp)
response = redirect(url, code=302)
return response
app.logger.debug(query_recv)
app.logger.debug("client_id = " + query['client_id'])
app.logger.debug("username = " + request.form['username'])
app.lo... | # クライアント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 | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&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 | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
}
impl<'a> Drop for AsyncPipe<'a> {
fn drop(&mut self) {
match self.state {
State::Reading => {}
_ => return,
}
// If we have a pending read operation, then we have to make sure that
// it's *done* before we actually drop this type. The kernel requires... | while self.result()? && self.schedule_read()? {
// ...
}
Ok(()) | random_line_split |
pipe.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
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 | /*
Copyright 2019 The KubeSphere Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... | (rls *v1alpha1.HelmRelease) error {
if rls.Status.State != v1alpha1.HelmStatusDeleting {
rls.Status.State = v1alpha1.HelmStatusDeleting
rls.Status.LastUpdate = metav1.Now()
err := r.Status().Update(context.TODO(), rls)
if err != nil {
return err
}
}
clusterName := rls.GetRlsCluster()
var clusterConfi... | uninstallHelmRelease | identifier_name |
helm_release_controller.go | /*
Copyright 2019 The KubeSphere Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... |
func (r *ReconcileHelmRelease) uninstallHelmRelease(rls *v1alpha1.HelmRelease) error {
if rls.Status.State != v1alpha1.HelmStatusDeleting {
rls.Status.State = v1alpha1.HelmStatusDeleting
rls.Status.LastUpdate = metav1.Now()
err := r.Status().Update(context.TODO(), rls)
if err != nil {
return err
}
}
... | } | random_line_split |
helm_release_controller.go | /*
Copyright 2019 The KubeSphere Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... |
return nil
}
func (r *ReconcileHelmRelease) uninstallHelmRelease(rls *v1alpha1.HelmRelease) error {
if rls.Status.State != v1alpha1.HelmStatusDeleting {
rls.Status.State = v1alpha1.HelmStatusDeleting
rls.Status.LastUpdate = metav1.Now()
err := r.Status().Update(context.TODO(), rls)
if err != nil {
retur... | {
return errors.New(res.Message)
} | conditional_block |
helm_release_controller.go | /*
Copyright 2019 The KubeSphere Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... |
func (r *ReconcileHelmRelease) uninstallHelmRelease(rls *v1alpha1.HelmRelease) error {
if rls.Status.State != v1alpha1.HelmStatusDeleting {
rls.Status.State = v1alpha1.HelmStatusDeleting
rls.Status.LastUpdate = metav1.Now()
err := r.Status().Update(context.TODO(), rls)
if err != nil {
return err
}
}
... | {
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 | #!/usr/bin/env python
# Copyright (c) 2016, SafeBreach
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of cond... |
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 | #!/usr/bin/env python
# Copyright (c) 2016, SafeBreach
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of cond... |
bits.append(input_bit)
last_input_bit = input_bit
last_poll_interval = args.poll_interval - (sliding_delta + 1)
if len(bits) == args.read[0]:
break
else:
# Write, pop bit form the bits array
... | 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 | #!/usr/bin/env python
# Copyright (c) 2016, SafeBreach
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of cond... |
###############
# Entry Point #
###############
if __name__ == "__main__":
sys.exit(main(sys.argv))
| 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 | #!/usr/bin/env python
# Copyright (c) 2016, SafeBreach
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of cond... | (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 | #!/usr/bin/env python
# Copyright 2015-2016 Yelp Inc.
#
# 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 ... |
send_event(instance_config=instance_config, status=status, output=output)
def filter_healthy_marathon_instances_for_short_app_id(all_tasks, app_id):
tasks_for_app = [task for task in all_tasks if task.app_id.startswith('/%s' % app_id)]
one_minute_ago = datetime.now() - timedelta(minutes=1)
healthy_t... | 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 | #!/usr/bin/env python
# Copyright 2015-2016 Yelp Inc.
#
# 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 ... |
def main():
args = parse_args()
if args.verbose:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=logging.WARNING)
system_paasta_config = load_system_paasta_config()
cluster = system_paasta_config.get_cluster()
clients = marathon_tools.get_marathon_c... | rootdir = os.path.abspath(soa_dir)
return os.listdir(rootdir) | identifier_body |
check_marathon_services_replication.py | #!/usr/bin/env python
# Copyright 2015-2016 Yelp Inc.
#
# 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 ... | (
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 | #!/usr/bin/env python
# Copyright 2015-2016 Yelp Inc.
#
# 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 ... |
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 | import time
import sys
import getopt
import partitionGUI
import random
import math
import bisect
import numpy as np
import Tkinter as tk
import networkx as nx
import matplotlib.pyplot as plt
from operator import itemgetter
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk... |
if __name__ == "__main__":
main(sys.argv[1:]) | random_line_split | |
partitionA3.py | import time
import sys
import getopt
import partitionGUI
import random
import math
import bisect
import numpy as np
import Tkinter as tk
import networkx as nx
import matplotlib.pyplot as plt
from operator import itemgetter
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk... |
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 | import time
import sys
import getopt
import partitionGUI
import random
import math
import bisect
import numpy as np
import Tkinter as tk
import networkx as nx
import matplotlib.pyplot as plt
from operator import itemgetter
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk... |
def updatePlot(self,cost):
""" Cost plot gets updated on every new cost value """
timer = time.clock() - self.start_timer
# Add new values to plot data set
self.lines.set_xdata(np.append(self.lines.get_xdata(), timer))
self.lines.set_ydata(np.append(self.... | """ Draw circuit Connections and Cell Tags """
self.delConns()
self.delTags()
self.drawConns()
self.drawTags() | identifier_body |
partitionA3.py | import time
import sys
import getopt
import partitionGUI
import random
import math
import bisect
import numpy as np
import Tkinter as tk
import networkx as nx
import matplotlib.pyplot as plt
from operator import itemgetter
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk... | (argv):
#==============Initialize Graphics============#
root = tk.Tk()
#=================Options=================#
# Default Values
inputfile = None
quietMode = False
seed = 30
try:
opts, args = getopt.getopt(argv, "hqs:t:i:", ["ifile="])
except getop... | main | identifier_name |
band.go | package commands
// import (
// "errors"
// "fmt"
// "os"
// "persephone/database"
// "persephone/fm"
// "persephone/lib"
// "strconv"
// "strings"
// "github.com/andersfylling/disgord"
// "github.com/cavaliercoder/grab"
// "github.com/fogleman/gg"
// "github.com/nfnt/resize"
// "github.com/pazuzu156/atl... | // var albums = []fm.TopAlbum{}
// // add first batch of albums for artist into slice
// for _, album := range alist.Albums {
// if album.Artist.Name == artist.Name {
// albums = append(albums, album)
// }
// }
// // if more pages than 1, run another sweep
// if alist.TotalPages > 1 {
// for i := 1; i ... | random_line_split | |
fine_tune_Inception.py | # Taken from: https://github.com/flyyufelix/cnn_finetune/blob/master/vgg16.py
# based on: https://gist.github.com/baraldilorenzo/07d7802847aaad0a35d3
# -*- coding: utf-8 -*-
import keras
import itertools
import sys
from sklearn.metrics import confusion_matrix
import numpy as np
import matplotlib
import matp... | def lr_schedule(epoch): # function that takes an epoch index as input and returns a new learning rate as output
return lr*(0.1**int(epoch/10))
if __name__ == '__main__':
img_rows, img_cols = 299, 299 # Resolution of inputs
channel = 3
num_classes = 43
# batch_size = 10 # 20
nb_epoch ... | random_line_split | |
fine_tune_Inception.py |
# Taken from: https://github.com/flyyufelix/cnn_finetune/blob/master/vgg16.py
# based on: https://gist.github.com/baraldilorenzo/07d7802847aaad0a35d3
# -*- coding: utf-8 -*-
import keras
import itertools
import sys
from sklearn.metrics import confusion_matrix
import numpy as np
import matplotlib
import ma... | (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 |
# Taken from: https://github.com/flyyufelix/cnn_finetune/blob/master/vgg16.py
# based on: https://gist.github.com/baraldilorenzo/07d7802847aaad0a35d3
# -*- coding: utf-8 -*-
import keras
import itertools
import sys
from sklearn.metrics import confusion_matrix
import numpy as np
import matplotlib
import ma... |
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 |
# Taken from: https://github.com/flyyufelix/cnn_finetune/blob/master/vgg16.py
# based on: https://gist.github.com/baraldilorenzo/07d7802847aaad0a35d3
# -*- coding: utf-8 -*-
import keras
import itertools
import sys
from sklearn.metrics import confusion_matrix
import numpy as np
import matplotlib
import ma... |
# 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 |
//////////////////////////////////////////////////////////////////////////////////
$(document).ready(function(){
//IE
isIE = /*@cc_on!@*/false || !!document.documentMode;
if (isIE) {
$( 'header, footer, main, aside' ).each(function(){
$(this).replaceWith( '<div class="ie-' + $(this).prop("tagName").toLowerCase... | ;
$(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 |
//////////////////////////////////////////////////////////////////////////////////
$(document).ready(function(){
//IE
isIE = /*@cc_on!@*/false || !!document.documentMode;
if (isIE) {
$( 'header, footer, main, aside' ).each(function(){
$(this).replaceWith( '<div class="ie-' + $(this).prop("tagName").toLowerCase... | name=grid]').removeClass('active');
$('#filterbar button[name=list]').addClass('active');
$('#ads .ad').removeClass('l-third').removeClass('m-half');
$('#ads .ad').addClass('l-full').addClass('m-full');
}
function filterbarNormal() {
$('#filterbar button[name=list]').removeClass('active');
$('#filterbar button[nam... | $( "#popularbazaar ul, #newbazaar ul" ).each(function(){
$(this).css({'width':'auto'});
})
}
function filterbarMobile() {
$('#filterbar button[ | identifier_body |
custom.js |
//////////////////////////////////////////////////////////////////////////////////
$(document).ready(function(){
//IE
isIE = /*@cc_on!@*/false || !!document.documentMode;
if (isIE) {
$( 'header, footer, main, aside' ).each(function(){
$(this).replaceWith( '<div class="ie-' + $(this).prop("tagName").toLowerCase... | (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 | //////////////////////////////////////////////////////////////////////////////////
$(document).ready(function(){
//IE
isIE = /*@cc_on!@*/false || !!document.documentMode;
if (isIE) {
$( 'header, footer, main, aside' ).each(function(){
$(this).replaceWith( '<div class="ie-' + $(this).prop("tagName").toLowerCase(... | clearTimeout(timer);
ThisSlide = parseInt($(this).attr('class').split("sl")[1])
$('.slider .handle li').removeClass('active');
$(this).addClass('active');
sliderRoll(ThisSlide)
})
//scroll to element
function scrollToElement(element ,gap) {
if (menu) {
gap = gap + 48
}
var distance = $(element).offset().top -... | $(document).on('click', '.slider .handle li', function() { | random_line_split |
register.rs | //! Box registers
use crate::mir::constant::Constant;
use crate::mir::expr::Expr;
use crate::serialization::sigma_byte_reader::SigmaByteRead;
use crate::serialization::sigma_byte_writer::SigmaByteWrite;
use crate::serialization::SigmaParsingError;
use crate::serialization::SigmaSerializable;
use crate::serialization::... | 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 | //! Box registers
use crate::mir::constant::Constant;
use crate::mir::expr::Expr;
use crate::serialization::sigma_byte_reader::SigmaByteRead;
use crate::serialization::sigma_byte_writer::SigmaByteWrite;
use crate::serialization::SigmaParsingError;
use crate::serialization::SigmaSerializable;
use crate::serialization::... |
/// 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 | //! Box registers
use crate::mir::constant::Constant;
use crate::mir::expr::Expr;
use crate::serialization::sigma_byte_reader::SigmaByteRead;
use crate::serialization::sigma_byte_writer::SigmaByteWrite;
use crate::serialization::SigmaParsingError;
use crate::serialization::SigmaSerializable;
use crate::serialization::... | (&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 |
// to prevent this loading twice in dev - hacky hacky whatever shut your face
// if (!window['apploaded']) {
// window['apploaded'] = true;
// throw "Already loaded";
// }
declare var byx;
declare var lmw;
interface MEvent {
name: string;
url: string;
date: string|Date|moment.Moment;
state: string;
e... |
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 | // to prevent this loading twice in dev - hacky hacky whatever shut your face
// if (!window['apploaded']) {
// window['apploaded'] = true;
// throw "Already loaded";
// }
declare var byx;
declare var lmw;
interface MEvent {
name: string;
url: string;
date: string|Date|moment.Moment;
state: string;
eve... | } else {
this.$timeout(() => this.countdown(), 500);
}
}
getBreadcrumbs() {
if (this.$state.current.name === this.lastState) {
return this.crumbs;
}
this.lastState = this.$state.current.name;
this.crumbs = [];
if (this.lastState !== 'Calendar') {
this.crumbs = [
... | random_line_split | |
mooseleague_ts.ts |
// to prevent this loading twice in dev - hacky hacky whatever shut your face
// if (!window['apploaded']) {
// window['apploaded'] = true;
// throw "Already loaded";
// }
declare var byx;
declare var lmw;
interface MEvent {
name: string;
url: string;
date: string|Date|moment.Moment;
state: string;
e... |
}
/**
* Individual event controller for event results pages
*/
class EventController {
tab: string = 'results';
hasRelay: boolean = false;
event: MEvent;
static $inject = ['$http', '$state', '$timeout', '$location', '$anchorScroll',
'$stateParams', 'Events', 'Results'];
constructor(p... | {
let ap = this.shouldAutoplay();
return this.$sce.trustAsResourceUrl(`https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/460111206&auto_play=${ap}&hide_related=false&show_comments=true&show_user=true&show_reposts=false&visual=true`);
} | identifier_body |
mooseleague_ts.ts |
// to prevent this loading twice in dev - hacky hacky whatever shut your face
// if (!window['apploaded']) {
// window['apploaded'] = true;
// throw "Already loaded";
// }
declare var byx;
declare var lmw;
interface MEvent {
name: string;
url: string;
date: string|Date|moment.Moment;
state: string;
e... | () {
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 | // "Tifflin" Kernel
// - By John Hodge (thePowersGang)
//
// Core/gui/input/mod.rs
//! GUI input managment
#[allow(unused_imports)]
use kernel::prelude::*;
use self::keyboard::KeyCode;
use core::sync::atomic::{Ordering,AtomicUsize,AtomicU8};
use kernel::sync::Mutex;
pub mod keyboard;
pub mod mouse;
#[derive(Debug)]
p... |
fn set_r(&self) { self.0.fetch_or(2, Ordering::Relaxed); }
fn clear_l(&self) { self.0.fetch_and(!1, Ordering::Relaxed); }
fn clear_r(&self) { self.0.fetch_and(!2, Ordering::Relaxed); }
fn get(&self) -> bool {
self.0.load(Ordering::Relaxed) != 0
}
}
impl MouseCursor {
const fn new() -> MouseCursor {
MouseCurs... | { self.0.fetch_or(1, Ordering::Relaxed); } | identifier_body |
mod.rs | // "Tifflin" Kernel
// - By John Hodge (thePowersGang)
//
// Core/gui/input/mod.rs
//! GUI input managment
#[allow(unused_imports)]
use kernel::prelude::*;
use self::keyboard::KeyCode;
use core::sync::atomic::{Ordering,AtomicUsize,AtomicU8};
use kernel::sync::Mutex;
pub mod keyboard;
pub mod mouse;
#[derive(Debug)]
p... | KeyCode::Semicolon => shift!(self: ";", ":"),
KeyCode::Quote => shift!(self: "'", "\""),
KeyCode::Comma => shift!(self: ",", "<"),
KeyCode::Period => shift!(self: ".", ">"),
KeyCode::Slash => shift!(self: "/", "?"),
KeyCode::Kb1 => shift!(self: "1", "!"),
KeyCode::Kb2 => shift!(self: "2", "@"),
K... | KeyCode::SquareClose => shift!(self: "[", "{"),
KeyCode::Backslash => shift!(self: "\\","|"), | random_line_split |
mod.rs | // "Tifflin" Kernel
// - By John Hodge (thePowersGang)
//
// Core/gui/input/mod.rs
//! GUI input managment
#[allow(unused_imports)]
use kernel::prelude::*;
use self::keyboard::KeyCode;
use core::sync::atomic::{Ordering,AtomicUsize,AtomicU8};
use kernel::sync::Mutex;
pub mod keyboard;
pub mod mouse;
#[derive(Debug)]
p... | (&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 | // Copyright (c) The Thanos Authors.
// Licensed under the Apache License 2.0.
// Package shipper detects directories on the local file system and uploads
// them to a block storage.
package shipper
import (
"context"
"encoding/json"
"math"
"os"
"path"
"path/filepath"
"sort"
"sync"
"github.com/go-kit/log"
... | (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 | // Copyright (c) The Thanos Authors.
// Licensed under the Apache License 2.0.
// Package shipper detects directories on the local file system and uploads
// them to a block storage.
package shipper
import (
"context"
"encoding/json"
"math"
"os"
"path"
"path/filepath"
"sort"
"sync"
"github.com/go-kit/log"
... |
// ReadMetaFile reads the given meta from <dir>/thanos.shipper.json.
func ReadMetaFile(dir string) (*Meta, error) {
fpath := filepath.Join(dir, filepath.Clean(MetaFilename))
b, err := os.ReadFile(fpath)
if err != nil {
return nil, errors.Wrapf(err, "failed to read %s", fpath)
}
var m Meta
if err := json.Unma... | {
// 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 | // Copyright (c) The Thanos Authors.
// Licensed under the Apache License 2.0.
// Package shipper detects directories on the local file system and uploads
// them to a block storage.
package shipper
import (
"context"
"encoding/json"
"math"
"os"
"path"
"path/filepath"
"sort"
"sync"
"github.com/go-kit/log"
... | return nil
}
// Meta defines the format thanos.shipper.json file that the shipper places in the data directory.
type Meta struct {
Version int `json:"version"`
Uploaded []ulid.ULID `json:"uploaded"`
}
const (
// MetaFilename is the known JSON filename for meta information.
MetaFilename = "thanos.shipper... | random_line_split | |
shipper.go | // Copyright (c) The Thanos Authors.
// Licensed under the Apache License 2.0.
// Package shipper detects directories on the local file system and uploads
// them to a block storage.
package shipper
import (
"context"
"encoding/json"
"math"
"os"
"path"
"path/filepath"
"sort"
"sync"
"github.com/go-kit/log"
... |
// 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 | # devcontrol.py
# Home automation device control service
#
# Part of AutoHome
#
# Copyright (c) 2017, Diego Guerrero
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of so... | # 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 | # devcontrol.py
# Home automation device control service
#
# Part of AutoHome
#
# Copyright (c) 2017, Diego Guerrero
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of so... |
def main():
"""Program entry point."""
setsignals()
configuration = None
guestlist = set()
configfilename = sys.argv[1] if len(sys.argv) > 1 else "configuration.json"
guestlist.add("pipe")
scriptdir = os.path.dirname(os.path.realpath(__file__))
try:
with open(configfilename) as configfile:
... | """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 | # devcontrol.py
# Home automation device control service
#
# Part of AutoHome
#
# Copyright (c) 2017, Diego Guerrero
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of so... | main() | conditional_block | |
devcontrol.py | # devcontrol.py
# Home automation device control service
#
# Part of AutoHome
#
# Copyright (c) 2017, Diego Guerrero
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of so... | (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 | #!/usr/bin/env python
# coding: utf-8
import os
import cPickle as pickle
class LTManager(object):
# adding lt to db (ltgen do not add)
def __init__(self, conf, db, table, reset_db, ltg_alg):
self.reset_db = reset_db
self.conf = conf
self.sym = conf.get("log_template", "variable_symbo... |
class LTGroup(object):
# usually used as super class of other ltgroup
# If used directly, this class will work as a dummy
# (ltgid is always same as ltid)
def __init__(self):
self.init_dict()
def init_dict(self):
self.d_group = {} # key : groupid, val : [ltline, ...]
se... | 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 | #!/usr/bin/env python
# coding: utf-8
import os
import cPickle as pickle
class LTManager(object):
# adding lt to db (ltgen do not add)
def __init__(self, conf, db, table, reset_db, ltg_alg):
self.reset_db = reset_db
self.conf = conf
self.sym = conf.get("log_template", "variable_symbo... | 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 | #!/usr/bin/env python
# coding: utf-8
import os
import cPickle as pickle
class LTManager(object):
# adding lt to db (ltgen do not add)
def __init__(self, conf, db, table, reset_db, ltg_alg):
self.reset_db = reset_db
self.conf = conf
self.sym = conf.get("log_template", "variable_symbo... |
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 | #!/usr/bin/env python
# coding: utf-8
import os
import cPickle as pickle
class LTManager(object):
# adding lt to db (ltgen do not add)
def __init__(self, conf, db, table, reset_db, ltg_alg):
self.reset_db = reset_db
self.conf = conf
self.sym = conf.get("log_template", "variable_symbo... | (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 | extern crate unix_socket;
pub mod protocol;
use protocol::{Command, reply, PortSocket};
use std::collections::HashMap;
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::sync::Arc;
use std::sync::{Mutex, MutexGuard, TryLockError};
use std::u8;
// TODO Corking reduces latency, as spid adds overhead for... | 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 | extern crate unix_socket;
pub mod protocol;
use protocol::{Command, reply, PortSocket};
use std::collections::HashMap;
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::sync::Arc;
use std::sync::{Mutex, MutexGuard, TryLockError};
use std::u8;
// TODO Corking reduces latency, as spid adds overhead for... |
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 | extern crate unix_socket;
pub mod protocol;
use protocol::{Command, reply, PortSocket};
use std::collections::HashMap;
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::sync::Arc;
use std::sync::{Mutex, MutexGuard, TryLockError};
use std::u8;
// TODO Corking reduces latency, as spid adds overhead for... | (&mut self) -> Result<(), io::Error> {
let new_value = !self.value;
self.write(new_value)
}
// Returns the current state of the LED.
pub fn read(&self) -> bool {
self.value
}
// Helper function to write new state to LED filepath.
fn write(&mut self, new_value: bool) -> ... | toggle | identifier_name |
lib.rs | extern crate unix_socket;
pub mod protocol;
use protocol::{Command, reply, PortSocket};
use std::collections::HashMap;
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::sync::Arc;
use std::sync::{Mutex, MutexGuard, TryLockError};
use std::u8;
// TODO Corking reduces latency, as spid adds overhead for... | 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 | //! Recursively watch paths for changes, in an extensible and
//! cross-platform way.
use crate::NixFile;
use crossbeam_channel as chan;
use notify::event::ModifyKind;
use notify::{EventKind, RecommendedWatcher, RecursiveMode, Watcher};
use slog_scope::{debug, info};
use std::collections::HashSet;
use std::path::{Path... | 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 | //! Recursively watch paths for changes, in an extensible and
//! cross-platform way.
use crate::NixFile;
use crossbeam_channel as chan;
use notify::event::ModifyKind;
use notify::{EventKind, RecommendedWatcher, RecursiveMode, Watcher};
use slog_scope::{debug, info};
use std::collections::HashSet;
use std::path::{Path... | 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 | //! Recursively watch paths for changes, in an extensible and
//! cross-platform way.
use crate::NixFile;
use crossbeam_channel as chan;
use notify::event::ModifyKind;
use notify::{EventKind, RecommendedWatcher, RecursiveMode, Watcher};
use slog_scope::{debug, info};
use std::collections::HashSet;
use std::path::{Path... | macos_eat_late_notifications(&mut watcher);
// bar is not watched, expect error
expect_bash(r#"echo 1 > "$1/bar""#, &[temp.path().as_os_str()]);
sleep(upper_watcher_timeout());
assert!(no_changes(&watcher));
// Rename bar to foo, expect a notification
expect_bas... | random_line_split | |
watch.rs | //! Recursively watch paths for changes, in an extensible and
//! cross-platform way.
use crate::NixFile;
use crossbeam_channel as chan;
use notify::event::ModifyKind;
use notify::{EventKind, RecommendedWatcher, RecursiveMode, Watcher};
use slog_scope::{debug, info};
use std::collections::HashSet;
use std::path::{Path... | 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: ¬i... | tend_filter(p | identifier_name |
transformer.py | from collections import deque
from collections.abc import Iterable
from functools import partial
from itertools import islice, cycle
import torch
from torch import nn, einsum
import torch.nn.functional as F
from einops import rearrange
from dalle_pytorch.reversible import ReversibleSequence, SequentialSequence
from d... |
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 | from collections import deque
from collections.abc import Iterable
from functools import partial
from itertools import islice, cycle
import torch
from torch import nn, einsum
import torch.nn.functional as F
from einops import rearrange
from dalle_pytorch.reversible import ReversibleSequence, SequentialSequence
from d... |
# 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 | from collections import deque
from collections.abc import Iterable
from functools import partial
from itertools import islice, cycle
import torch
from torch import nn, einsum
import torch.nn.functional as F
from einops import rearrange
from dalle_pytorch.reversible import ReversibleSequence, SequentialSequence
from d... | (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 | from collections import deque
from collections.abc import Iterable
from functools import partial
from itertools import islice, cycle
import torch
from torch import nn, einsum
import torch.nn.functional as F
from einops import rearrange
from dalle_pytorch.reversible import ReversibleSequence, SequentialSequence
from d... |
# 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 | //! *Library for encrypting and decrypting age files*
//!
//! This crate implements file encryption according to the [age-encryption.org/v1]
//! specification. It generates and consumes encrypted files that are compatible with the
//! [rage] CLI tool, as well as the reference [Go] implementation.
//!
//! The encryption... | //! 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 | //! *Library for encrypting and decrypting age files*
//!
//! This crate implements file encryption according to the [age-encryption.org/v1]
//! specification. It generates and consumes encrypted files that are compatible with the
//! [rage] CLI tool, as well as the reference [Go] implementation.
//!
//! The encryption... | (data: &[u8]) {
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()]);
}
}
| fuzz_header | identifier_name |
lib.rs | //! *Library for encrypting and decrypting age files*
//!
//! This crate implements file encryption according to the [age-encryption.org/v1]
//! specification. It generates and consumes encrypted files that are compatible with the
//! [rage] CLI tool, as well as the reference [Go] implementation.
//!
//! The encryption... |
}
| {
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 | //! *Library for encrypting and decrypting age files*
//!
//! This crate implements file encryption according to the [age-encryption.org/v1]
//! specification. It generates and consumes encrypted files that are compatible with the
//! [rage] CLI tool, as well as the reference [Go] implementation.
//!
//! The encryption... | {
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 | package cli
import (
"errors"
"fmt"
"os"
"strings"
multierror "github.com/hashicorp/go-multierror"
wso2am "github.com/uphy/go-wso2am"
"github.com/urfave/cli"
)
func (c *CLI) api() cli.Command {
return cli.Command{
Name: "api",
Aliases: []string{"a"},
Usage: "API management command",
Subcommands:... |
func (c *CLI) apiInspect() cli.Command {
return cli.Command{
Name: "inspect",
Aliases: []string{"show", "cat"},
Usage: "Inspect the API",
ArgsUsage: "ID",
Action: func(ctx *cli.Context) error {
if ctx.NArg() != 1 {
return errors.New("ID is required")
}
id := ctx.Args().Get(0)
api... | {
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 | package cli
import (
"errors"
"fmt"
"os"
"strings"
multierror "github.com/hashicorp/go-multierror"
wso2am "github.com/uphy/go-wso2am"
"github.com/urfave/cli"
)
func (c *CLI) api() cli.Command {
return cli.Command{
Name: "api",
Aliases: []string{"a"},
Usage: "API management command",
Subcommands:... |
if ctx.IsSet("gateway-env") {
api.GatewayEnvironments = ctx.String("gateway-env")
}
if ctx.IsSet("provider") {
api.Provider = ctx.String("provider")
}
if ctx.IsSet("visible-role") {
api.Visibility = wso2am.APIVisibilityRestricted
api.VisibleRoles = ctx.StringSlice("visible-role")
}
... | {
api.Version = ctx.String("version")
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.