code stringlengths 31 2.05k | label_name stringclasses 5
values | label int64 0 4 |
|---|---|---|
func (ar *AnswerActivityRepo) sendCancelAcceptAnswerNotification(
ctx context.Context, op *schema.AcceptAnswerOperationInfo) {
for _, act := range op.Activities {
msg := &schema.NotificationMsg{
ReceiverUserID: act.ActivityUserID,
Type: schema.NotificationTypeAchievement,
ObjectID: op.Answe... | Base | 1 |
func Satitize(data *imagedata.ImageData) (*imagedata.ImageData, error) {
r := bytes.NewReader(data.Data)
l := xml.NewLexer(parse.NewInput(r))
buf, cancel := imagedata.BorrowBuffer()
ignoreTag := 0
for {
tt, tdata := l.Next()
if ignoreTag > 0 {
switch tt {
case xml.ErrorToken:
cancel()
return ... | Base | 1 |
func (hs *HTTPServer) GetPluginMarkdown(c *models.ReqContext) response.Response {
pluginID := web.Params(c.Req)[":pluginId"]
name := web.Params(c.Req)[":name"]
content, err := hs.pluginMarkdown(c.Req.Context(), pluginID, name)
if err != nil {
var notFound plugins.NotFoundError
if errors.As(err, ¬Found) {
... | Base | 1 |
func NewHandler() *Handler {
return &Handler{
clusterService: cluster.NewService(),
userService: user.NewService(),
roleService: role.NewService(),
rolebindingService: rolebinding.NewService(),
ldapService: ldap.NewService(),
jwtSigner: jwt.NewSigner(jwt.HS256, JwtSigKey, ... | Base | 1 |
func ReadConfig(c *config.Config, path ...string) error {
v := viper.New()
v.SetConfigName("app")
v.SetConfigType("yaml")
for i := range path {
configFilePaths = append(configFilePaths, path[i])
}
for i := range configFilePaths {
realDir := file.ReplaceHomeDir(configFilePaths[i])
if exists := fileutil.Ex... | Base | 1 |
func AddV1Route(app iris.Party) {
v1Party := app.Party("/v1")
v1Party.Use(langHandler())
v1Party.Use(pageHandler())
session.Install(v1Party)
mfa.Install(v1Party)
authParty := v1Party.Party("")
authParty.Use(WarpedJwtHandler())
authParty.Use(authHandler())
authParty.Use(resourceExtractHandler())
authParty.Us... | Class | 2 |
func Serve(ctx context.Context, artifactPath string, addr string, port string) context.CancelFunc {
serverContext, cancel := context.WithCancel(ctx)
logger := common.Logger(serverContext)
if artifactPath == "" {
return cancel
}
router := httprouter.New()
logger.Debugf("Artifacts base path '%s'", artifactPath... | Base | 1 |
func (fsys MkdirFsImpl) OpenAtEnd(name string) (fs.File, error) {
file, err := os.OpenFile(fsys.dir+"/"+name, os.O_CREATE|os.O_RDWR, 0644)
if err != nil {
return nil, err
}
_, err = file.Seek(0, os.SEEK_END)
if err != nil {
return nil, err
}
return file, nil
} | Base | 1 |
func (fsys MkdirFsImpl) MkdirAll(path string, perm fs.FileMode) error {
return os.MkdirAll(fsys.dir+"/"+path, perm)
} | Base | 1 |
func uploads(router *httprouter.Router, fsys MkdirFS) {
router.POST("/_apis/pipelines/workflows/:runId/artifacts", func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
runID := params.ByName("runId")
json, err := json.Marshal(FileContainerResourceURL{
FileContainerResourceURL: fmt.Sprintf... | Base | 1 |
err := fs.WalkDir(fsys, dirPath, func(path string, entry fs.DirEntry, err error) error {
if !entry.IsDir() {
rel, err := filepath.Rel(dirPath, path)
if err != nil {
panic(err)
}
// if it was upload as gzip
rel = strings.TrimSuffix(rel, gzipExtension)
files = append(files, ContainerIt... | Base | 1 |
func (fsys MkdirFsImpl) Open(name string) (fs.File, error) {
return os.OpenFile(fsys.dir+"/"+name, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0644)
} | Base | 1 |
func TestListArtifactContainer(t *testing.T) {
assert := assert.New(t)
var memfs = fstest.MapFS(map[string]*fstest.MapFile{
"1/some/file": {
Data: []byte(""),
},
})
router := httprouter.New()
downloads(router, memfs)
req, _ := http.NewRequest("GET", "http://localhost/download/1?itemPath=some/file", nil)... | Base | 1 |
func TestDownloadArtifactFile(t *testing.T) {
assert := assert.New(t)
var memfs = fstest.MapFS(map[string]*fstest.MapFile{
"1/some/file": {
Data: []byte("content"),
},
})
router := httprouter.New()
downloads(router, memfs)
req, _ := http.NewRequest("GET", "http://localhost/artifact/1/some/file", nil)
r... | Base | 1 |
func (fsys MapFsImpl) MkdirAll(path string, perm fs.FileMode) error {
// mocked no-op
return nil
} | Base | 1 |
func TestListArtifacts(t *testing.T) {
assert := assert.New(t)
var memfs = fstest.MapFS(map[string]*fstest.MapFile{
"1/file.txt": {
Data: []byte(""),
},
})
router := httprouter.New()
downloads(router, memfs)
req, _ := http.NewRequest("GET", "http://localhost/_apis/pipelines/workflows/1/artifacts", nil)
... | Base | 1 |
func TestFinalizeArtifactUpload(t *testing.T) {
assert := assert.New(t)
var memfs = fstest.MapFS(map[string]*fstest.MapFile{})
router := httprouter.New()
uploads(router, MapFsImpl{memfs})
req, _ := http.NewRequest("PATCH", "http://localhost/_apis/pipelines/workflows/1/artifacts", nil)
rr := httptest.NewRecorde... | Base | 1 |
func (file WritableFile) Write(data []byte) (int, error) {
file.fsys[file.path].Data = data
return len(data), nil
} | Base | 1 |
func (fsys MapFsImpl) Open(path string) (fs.File, error) {
var file = fstest.MapFile{
Data: []byte("content2"),
}
fsys.MapFS[path] = &file
result, err := fsys.MapFS.Open(path)
return WritableFile{result, fsys.MapFS, path}, err
} | Base | 1 |
func (fsys MapFsImpl) OpenAtEnd(path string) (fs.File, error) {
var file = fstest.MapFile{
Data: []byte("content2"),
}
fsys.MapFS[path] = &file
result, err := fsys.MapFS.Open(path)
return WritableFile{result, fsys.MapFS, path}, err
} | Base | 1 |
func TestArtifactUploadBlob(t *testing.T) {
assert := assert.New(t)
var memfs = fstest.MapFS(map[string]*fstest.MapFile{})
router := httprouter.New()
uploads(router, MapFsImpl{memfs})
req, _ := http.NewRequest("PUT", "http://localhost/upload/1?itemPath=some/file", strings.NewReader("content"))
rr := httptest.N... | Base | 1 |
func TestNewArtifactUploadPrepare(t *testing.T) {
assert := assert.New(t)
var memfs = fstest.MapFS(map[string]*fstest.MapFile{})
router := httprouter.New()
uploads(router, MapFsImpl{memfs})
req, _ := http.NewRequest("POST", "http://localhost/_apis/pipelines/workflows/1/artifacts", nil)
rr := httptest.NewRecord... | Base | 1 |
func FromBytes(size int, bits []byte) Bitfield {
bf := NewBitfield(size)
start := len(bf) - len(bits)
if start < 0 {
panic("bitfield too small")
}
copy(bf[start:], bits)
return bf
} | Base | 1 |
func NewBitfield(size int) Bitfield {
if size%8 != 0 {
panic("Bitfield size must be a multiple of 8")
}
return make([]byte, size/8)
} | Base | 1 |
func BenchmarkBitfield(t *testing.B) {
bf := NewBitfield(benchmarkSize)
t.ResetTimer()
for i := 0; i < t.N; i++ {
if bf.Bit(i % benchmarkSize) {
t.Fatal("bad", i)
}
bf.SetBit(i % benchmarkSize)
bf.UnsetBit(i % benchmarkSize)
bf.SetBit(i % benchmarkSize)
bf.UnsetBit(i % benchmarkSize)
bf.SetBit(i % b... | Base | 1 |
func TestExhaustive24(t *testing.T) {
bf := NewBitfield(24)
max := 1 << 24
bint := new(big.Int)
bts := make([]byte, 4)
for j := 0; j < max; j++ {
binary.BigEndian.PutUint32(bts, uint32(j))
bint.SetBytes(bts[1:])
bf.SetBytes(nil)
for i := 0; i < 24; i++ {
if bf.Bit(i) {
t.Fatalf("bit %d should have... | Base | 1 |
func TestBitfield(t *testing.T) {
bf := NewBitfield(128)
if bf.OnesBefore(20) != 0 {
t.Fatal("expected no bits set")
}
bf.SetBit(10)
if bf.OnesBefore(20) != 1 {
t.Fatal("expected 1 bit set")
}
bf.SetBit(12)
if bf.OnesBefore(20) != 2 {
t.Fatal("expected 2 bit set")
}
bf.SetBit(30)
if bf.OnesBefore(20) !... | Base | 1 |
func BenchmarkOnes(t *testing.B) {
bf := NewBitfield(benchmarkSize)
t.ResetTimer()
for i := 0; i < t.N; i++ {
for j := 0; j*4 < benchmarkSize; j++ {
if bf.Ones() != j {
t.Fatal("bad", i)
}
bf.SetBit(j * 4)
}
for j := 0; j*4 < benchmarkSize; j++ {
bf.UnsetBit(j * 4)
}
}
} | Base | 1 |
func BenchmarkBytes(t *testing.B) {
bfa := NewBitfield(211)
bfb := NewBitfield(211)
for j := 0; j*4 < 211; j++ {
bfa.SetBit(j * 4)
}
t.ResetTimer()
for i := 0; i < t.N; i++ {
bfb.SetBytes(bfa.Bytes())
}
} | Base | 1 |
func NewUnixFSHAMTShard(ctx context.Context, substrate dagpb.PBNode, data data.UnixFSData, lsys *ipld.LinkSystem) (ipld.Node, error) {
if err := validateHAMTData(data); err != nil {
return nil, err
}
shardCache := make(map[ipld.Link]*_UnixFSHAMTShard, substrate.FieldLinks().Length())
bf := bitField(data)
return ... | Class | 2 |
func bitField(nd data.UnixFSData) bitfield.Bitfield {
bf := bitfield.NewBitfield(int(nd.FieldFanout().Must().Int()))
bf.SetBytes(nd.FieldData().Must().Bytes())
return bf
} | Class | 2 |
func (s *shard) serialize(ls *ipld.LinkSystem) (ipld.Link, uint64, error) {
ufd, err := BuildUnixFS(func(b *Builder) {
DataType(b, data.Data_HAMTShard)
HashType(b, s.hasher)
Data(b, s.bitmap())
Fanout(b, uint64(s.size))
})
if err != nil {
return nil, 0, err
}
pbb := dagpb.Type.PBNode.NewBuilder()
pbm, e... | Class | 2 |
func (s *shard) bitmap() []byte {
bm := bitfield.NewBitfield(s.size)
for i := 0; i < s.size; i++ {
if _, ok := s.children[i]; ok {
bm.SetBit(i)
}
}
return bm.Bytes()
} | Class | 2 |
func makeDirWidth(ds format.DAGService, size, width int) ([]string, *legacy.Shard, error) {
ctx := context.Background()
s, _ := legacy.NewShard(ds, width)
var dirs []string
for i := 0; i < size; i++ {
dirs = append(dirs, fmt.Sprintf("DIRNAME%d", i))
}
shuffle(time.Now().UnixNano(), dirs)
for i := 0; i < le... | Class | 2 |
func TestBasicSet(t *testing.T) {
ds, lsys := mockDag()
for _, w := range []int{128, 256, 512, 1024, 2048, 4096} {
t.Run(fmt.Sprintf("BasicSet%d", w), func(t *testing.T) {
names, s, err := makeDirWidth(ds, 1000, w)
require.NoError(t, err)
ctx := context.Background()
legacyNode, err := s.Node()
requir... | Class | 2 |
func bitField(nd data.UnixFSData) (bitfield.Bitfield, error) {
fanout := int(nd.FieldFanout().Must().Int())
if fanout > maximumHamtWidth {
return nil, fmt.Errorf("hamt witdh (%d) exceed maximum allowed (%d)", fanout, maximumHamtWidth)
}
bf := bitfield.NewBitfield(fanout)
bf.SetBytes(nd.FieldData().Must().Bytes()... | Class | 2 |
func NewHandler(appLister applisters.ApplicationLister, namespace string, enabledNamespaces []string, db db.ArgoDB, enf *rbac.Enforcer, cache *servercache.Cache,
appResourceTree AppResourceTreeFn, allowedShells []string) *terminalHandler {
return &terminalHandler{
appLister: appLister,
db: ... | Base | 1 |
func newTerminalSession(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (*terminalSession, error) {
conn, err := upgrader.Upgrade(w, r, responseHeader)
if err != nil {
return nil, err
}
session := &terminalSession{
wsConn: conn,
tty: true,
sizeChan: make(chan remotecommand.Termina... | Base | 1 |
func Test_nativeHelmChart_ExtractChart(t *testing.T) {
client := NewClient("https://argoproj.github.io/argo-helm", Creds{}, false, "")
path, closer, err := client.ExtractChart("argo-cd", "0.7.1", false)
assert.NoError(t, err)
defer io.Close(closer)
info, err := os.Stat(path)
assert.NoError(t, err)
assert.True(t,... | Class | 2 |
func Test_nativeHelmChart_ExtractChart_insecure(t *testing.T) {
client := NewClient("https://argoproj.github.io/argo-helm", Creds{InsecureSkipVerify: true}, false, "")
path, closer, err := client.ExtractChart("argo-cd", "0.7.1", false)
assert.NoError(t, err)
defer io.Close(closer)
info, err := os.Stat(path)
asser... | Class | 2 |
func safeAddr(ctx context.Context, resolver *net.Resolver, hostport string, opts ...Option) (string, error) {
c := basicConfig()
for _, opt := range opts {
opt(c)
}
host, port, err := net.SplitHostPort(hostport)
if err != nil {
return "", err
}
ip := net.ParseIP(host)
if ip != nil {
if ip.To4() != nil &&... | Base | 1 |
func (fs *Filesystem) Writefile(p string, r io.Reader) error {
cleaned, err := fs.SafePath(p)
if err != nil {
return err
}
var currentSize int64
// If the file does not exist on the system already go ahead and create the pathway
// to it and an empty file. We'll then write to it later on after this completes.
... | Base | 1 |
func (e *Engine) PeerDisconnected(p peer.ID) {
e.lock.Lock()
defer e.lock.Unlock()
ledger, ok := e.ledgerMap[p]
if ok {
ledger.lk.RLock()
entries := ledger.Entries()
ledger.lk.RUnlock()
for _, entry := range entries {
e.peerLedger.CancelWant(p, entry.Cid)
}
}
delete(e.ledgerMap, p)
e.scoreLedger.... | Base | 1 |
func (e *Engine) findOrCreate(p peer.ID) *ledger {
// Take a read lock (as it's less expensive) to check if we have a ledger
// for the peer
e.lock.RLock()
l, ok := e.ledgerMap[p]
e.lock.RUnlock()
if ok {
return l
}
// There's no ledger, so take a write lock, then check again and create the
// ledger if nec... | Base | 1 |
func (e *Engine) MessageSent(p peer.ID, m bsmsg.BitSwapMessage) {
l := e.findOrCreate(p)
l.lk.Lock()
defer l.lk.Unlock()
// Remove sent blocks from the want list for the peer
for _, block := range m.Blocks() {
e.scoreLedger.AddToSentBytes(l.Partner, len(block.RawData()))
l.wantList.RemoveType(block.Cid(), pb.... | Base | 1 |
func (e *Engine) Peers() []peer.ID {
e.lock.RLock()
defer e.lock.RUnlock()
response := make([]peer.ID, 0, len(e.ledgerMap))
for _, ledger := range e.ledgerMap {
response = append(response, ledger.Partner)
}
return response
} | Base | 1 |
func (e *Engine) PeerConnected(p peer.ID) {
e.lock.Lock()
defer e.lock.Unlock()
_, ok := e.ledgerMap[p]
if !ok {
e.ledgerMap[p] = newLedger(p)
}
e.scoreLedger.PeerConnected(p)
} | Base | 1 |
func (e *Engine) WantlistForPeer(p peer.ID) []wl.Entry {
partner := e.findOrCreate(p)
partner.lk.Lock()
entries := partner.wantList.Entries()
partner.lk.Unlock()
return entries
} | Base | 1 |
func (e *Engine) ReceivedBlocks(from peer.ID, blks []blocks.Block) {
if len(blks) == 0 {
return
}
l := e.findOrCreate(from)
// Record how many bytes were received in the ledger
l.lk.Lock()
defer l.lk.Unlock()
for _, blk := range blks {
log.Debugw("Bitswap engine <- block", "local", e.self, "from", from, "c... | Base | 1 |
func TestPeerIsAddedToPeersWhenMessageReceivedOrSent(t *testing.T) {
test.Flaky(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
sanfrancisco := newTestEngine(ctx, "sf")
seattle := newTestEngine(ctx, "sea")
m := message.New(true)
sanfrancisco.Engine.MessageSent(seattle.Peer, m)
seatt... | Base | 1 |
func (l *peerLedger) Wants(p peer.ID, k cid.Cid) {
m, ok := l.cids[k]
if !ok {
m = make(map[peer.ID]struct{})
l.cids[k] = m
}
m[p] = struct{}{}
} | Base | 1 |
func (l *peerLedger) Peers(k cid.Cid) []peer.ID {
m, ok := l.cids[k]
if !ok {
return nil
}
peers := make([]peer.ID, 0, len(m))
for p := range m {
peers = append(peers, p)
}
return peers
} | Base | 1 |
func newPeerLedger() *peerLedger {
return &peerLedger{cids: make(map[cid.Cid]map[peer.ID]struct{})}
} | Base | 1 |
func (l *peerLedger) CancelWant(p peer.ID, k cid.Cid) {
m, ok := l.cids[k]
if !ok {
return
}
delete(m, p)
if len(m) == 0 {
delete(l.cids, k)
}
} | Base | 1 |
func (t *Teler) checkCommonWebAttack(r *http.Request) error {
// Decode the URL-encoded request URI of the URL
uri := toURLDecode(r.URL.RequestURI())
// Declare byte slice for request body.
var body string
// Initialize buffer to hold request body.
buf := &bytes.Buffer{}
// Use io.Copy to copy the request bod... | Base | 1 |
func (ea *ExternalAuth) AuthPlain(username, password string) ([]string, error) {
accountName, ok := auth.CheckDomainAuth(username, ea.perDomain, ea.domains)
if !ok {
return nil, module.ErrUnknownCredentials
}
// TODO: Extend process protocol to support multiple authorization identities.
return []string{username... | Class | 2 |
func (a *Auth) AuthPlain(username, password string) ([]string, error) {
if a.useHelper {
if err := external.AuthUsingHelper(a.helperPath, username, password); err != nil {
return nil, err
}
}
err := runPAMAuth(username, password)
if err != nil {
return nil, err
}
return []string{username}, nil
} | Class | 2 |
func (a *Auth) AuthPlain(username, password string) ([]string, error) {
key, err := precis.UsernameCaseMapped.CompareKey(username)
if err != nil {
return nil, err
}
identities := make([]string, 0, 1)
if len(a.userTbls) != 0 {
for _, tbl := range a.userTbls {
repl, ok, err := tbl.Lookup(key)
if err != ni... | Class | 2 |
func TestPlainSplit_NoUser(t *testing.T) {
a := Auth{
passwd: []module.PlainAuth{
mockAuth{
db: map[string][]string{
"user1": []string{"user1a", "user1b"},
},
},
},
}
ids, err := a.AuthPlain("user1", "aaa")
if err != nil {
t.Fatal("Unexpected error:", err)
}
if !reflect.DeepEqual(ids, []... | Class | 2 |
func TestPlainSplit_NoUser_MultiPass(t *testing.T) {
a := Auth{
passwd: []module.PlainAuth{
mockAuth{
db: map[string][]string{
"user2": []string{"user2a", "user2b"},
},
},
mockAuth{
db: map[string][]string{
"user1": []string{"user1a", "user1b"},
},
},
},
}
ids, err := a.Aut... | Class | 2 |
func TestPlainSplit_MultiUser_Pass(t *testing.T) {
a := Auth{
userTbls: []module.Table{
mockTable{
db: map[string]string{
"userWH": "user1",
},
},
mockTable{
db: map[string]string{
"user1": "user2",
},
},
},
passwd: []module.PlainAuth{
mockAuth{
db: map[string][]strin... | Class | 2 |
func (m mockAuth) AuthPlain(username, _ string) ([]string, error) {
ids, ok := m.db[username]
if !ok {
return nil, errors.New("invalid creds")
}
return ids, nil
} | Class | 2 |
func TestPlainSplit_UserPass(t *testing.T) {
a := Auth{
userTbls: []module.Table{
mockTable{
db: map[string]string{
"user1": "user2",
},
},
},
passwd: []module.PlainAuth{
mockAuth{
db: map[string][]string{
"user2": []string{"user2a", "user2b"},
},
},
mockAuth{
db: map... | Class | 2 |
func filterIdentity(accounts []string, identity string) ([]string, error) {
if identity == "" {
return accounts, nil
}
matchFound := false
for _, acc := range accounts {
if precis.UsernameCaseMapped.Compare(acc, identity) {
accounts = []string{identity}
matchFound = true
break
}
}
if !matchFound {... | Class | 2 |
return sasl.NewLoginServer(func(username, password string) error {
accounts, err := s.AuthPlain(username, password)
if err != nil {
s.Log.Error("authentication failed", err, "username", username, "src_ip", remoteAddr)
return errors.New("auth: invalid credentials")
}
return successCb(accounts)
}... | Class | 2 |
func (s *SASLAuth) AuthPlain(username, password string) ([]string, error) {
if len(s.Plain) == 0 {
return nil, ErrUnsupportedMech
}
var lastErr error
accounts := make([]string, 0, 1)
for _, p := range s.Plain {
pAccs, err := p.AuthPlain(username, password)
if err != nil {
lastErr = err
continue
}
... | Class | 2 |
srv := a.CreateSASL("XWHATEVER", &net.TCPAddr{}, func([]string) error { return nil }) | Class | 2 |
srv := a.CreateSASL("PLAIN", &net.TCPAddr{}, func(passed []string) error {
ids = passed
return nil
}) | Class | 2 |
func (m mockAuth) AuthPlain(username, _ string) ([]string, error) {
ids, ok := m.db[username]
if !ok {
return nil, errors.New("invalid creds")
}
return ids, nil
} | Class | 2 |
func (mockAuth) SASLMechanisms() []string {
return []string{sasl.Plain, sasl.Login}
} | Class | 2 |
func (a *Auth) AuthPlain(username, password string) ([]string, error) {
if a.useHelper {
return []string{username}, external.AuthUsingHelper(a.helperPath, username, password)
}
ent, err := Lookup(username)
if err != nil {
return nil, err
}
if !ent.IsAccountValid() {
return nil, fmt.Errorf("shadow: account... | Class | 2 |
func SASLAuthDirective(m *config.Map, node *config.Node) (interface{}, error) { | Class | 2 |
func (d *Dummy) AuthPlain(username, _ string) ([]string, error) {
return []string{username}, nil
} | Class | 2 |
func (d *Dummy) SASLMechanisms() []string {
return []string{sasl.Plain, sasl.Login}
} | Class | 2 |
func (store *Storage) AuthPlain(username, password string) ([]string, error) {
// TODO: Pass session context there.
defer trace.StartRegion(context.Background(), "sql/AuthPlain").End()
accountName, err := prepareUsername(username)
if err != nil {
return nil, err
}
password, err = precis.OpaqueString.CompareKe... | Class | 2 |
func Create(filePath string) (*os.File, error) {
if exist, err := IsPathExist(filePath); err != nil {
return nil, err
} else if exist {
return os.Create(filePath)
}
if err := os.MkdirAll(filepath.Dir(filePath), os.ModePerm); err != nil {
return nil, err
}
return os.Create(filePath)
} | Base | 1 |
func RemoveFile(path string) error {
err := os.Remove(path)
return err
} | Base | 1 |
func IsPathExist(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
} | Base | 1 |
func BytesToFile(filePath string, data []byte) error {
exist, _ := IsPathExist(filePath)
if !exist {
if err := CreateFile(filePath); err != nil {
return err
}
}
return ioutil.WriteFile(filePath, data, 0644)
} | Base | 1 |
func unzipFile(file *zip.File, dstDir string) error {
// create the directory of file
filePath := path.Join(dstDir, file.Name)
if file.FileInfo().IsDir() {
if err := os.MkdirAll(filePath, os.ModePerm); err != nil {
return err
}
return nil
}
if err := os.MkdirAll(filepath.Dir(filePath), os.ModePerm); err !... | Base | 1 |
corsHandler := gh.CORS(gh.AllowCredentials(), gh.AllowedHeaders([]string{"x-requested-with", "content-type"}), gh.AllowedMethods([]string{"GET", "POST", "HEAD", "DELETE"}), gh.AllowedOriginValidator(func(origin string) bool {
if strings.Contains(origin, "localhost") ||
strings.HasSuffix(origin, "play-with-docker.... | Base | 1 |
func NewIdpAuthnRequest(idp *IdentityProvider, r *http.Request) (*IdpAuthnRequest, error) {
req := &IdpAuthnRequest{
IDP: idp,
HTTPRequest: r,
Now: TimeNow(),
}
switch r.Method {
case "GET":
compressedRequest, err := base64.StdEncoding.DecodeString(r.URL.Query().Get("SAMLRequest"))
if err... | Base | 1 |
func (sp *ServiceProvider) ValidateLogoutResponseRedirect(queryParameterData string) error {
retErr := &InvalidResponseError{
Now: TimeNow(),
}
rawResponseBuf, err := base64.StdEncoding.DecodeString(queryParameterData)
if err != nil {
retErr.PrivateErr = fmt.Errorf("unable to parse base64: %s", err)
return r... | Base | 1 |
func authentication(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authenticationHandler(w, r)
next.ServeHTTP(w, r)
})
} | Class | 2 |
func authenticationWithStore(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
store := helpers.Store(r)
db.StoreSession(store, r.URL.String(), func() {
authenticationHandler(w, r)
})
next.ServeHTTP(w, r)
})
} | Class | 2 |
func getSystemInfo(w http.ResponseWriter, r *http.Request) {
//updateAvailable, err := util.CheckUpdate()
//if err != nil {
// helpers.WriteError(w, err)
// return
//}
body := map[string]interface{}{
"version": util.Version,
//"update": updateAvailable,
"ansible": util.AnsibleVersion(),
"demo": util... | Class | 2 |
func (v *V002Entry) Unmarshal(pe models.ProposedEntry) error {
it, ok := pe.(*models.Intoto)
if !ok {
return errors.New("cannot unmarshal non Intoto v0.0.2 type")
}
var err error
if err := types.DecodeEntry(it.Spec, &v.IntotoObj); err != nil {
return err
}
// field validation
if err := v.IntotoObj.Validat... | Base | 1 |
func (v V002Entry) Verifier() (pki.PublicKey, error) {
if v.IntotoObj.Content == nil || v.IntotoObj.Content.Envelope == nil {
return nil, errors.New("intoto v0.0.2 entry not initialized")
}
sigs := v.IntotoObj.Content.Envelope.Signatures
if len(sigs) == 0 {
return nil, errors.New("no signatures found on intoto... | Base | 1 |
func (v V002Entry) Insertable() (bool, error) {
if v.IntotoObj.Content == nil {
return false, errors.New("missing content property")
}
if v.IntotoObj.Content.Envelope == nil {
return false, errors.New("missing envelope property")
}
if len(v.IntotoObj.Content.Envelope.Payload) == 0 {
return false, errors.New(... | Base | 1 |
func createRekorEnvelope(dsseEnv *dsse.Envelope, pub [][]byte) *models.IntotoV002SchemaContentEnvelope {
env := &models.IntotoV002SchemaContentEnvelope{}
b64 := strfmt.Base64([]byte(dsseEnv.Payload))
env.Payload = b64
env.PayloadType = &dsseEnv.PayloadType
for i, sig := range dsseEnv.Signatures {
env.Signatures... | Base | 1 |
func (*FailedEventsManagerT) SaveFailedRecordIDs(taskRunIDFailedEventsMap map[string][]*FailedEventRowT, txn *sql.Tx) {
if !failedKeysEnabled {
return
}
for taskRunID, failedEvents := range taskRunIDFailedEventsMap {
table := fmt.Sprintf(`%s_%s`, failedKeysTablePrefix, taskRunID)
sqlStatement := fmt.Sprintf(`... | Base | 1 |
func (fem *FailedEventsManagerT) FetchFailedRecordIDs(taskRunID string) []*FailedEventRowT {
if !failedKeysEnabled {
return []*FailedEventRowT{}
}
failedEvents := make([]*FailedEventRowT, 0)
var rows *sql.Rows
var err error
table := fmt.Sprintf(`%s_%s`, failedKeysTablePrefix, taskRunID)
sqlStatement := fmt.S... | Base | 1 |
func handle() {
// startReaper()
fluid.LogVersion()
if pprofAddr != "" {
newPprofServer(pprofAddr)
}
mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
Scheme: scheme,
MetricsBindAddress: metricsAddr,
Port: 9443,
})
if err != nil {
panic(fmt.Sprintf("csi: unab... | Class | 2 |
func NewDriver(nodeID, endpoint string, client client.Client, apiReader client.Reader) *driver {
glog.Infof("Driver: %v version: %v", driverName, version)
proto, addr := utils.SplitSchemaAddr(endpoint)
glog.Infof("protocol: %v addr: %v", proto, addr)
if !strings.HasPrefix(addr, "/") {
addr = fmt.Sprintf("/%s", ... | Class | 2 |
func (d *driver) newNodeServer() *nodeServer {
return &nodeServer{
nodeId: d.nodeId,
DefaultNodeServer: csicommon.NewDefaultNodeServer(d.csiDriver),
client: d.client,
apiReader: d.apiReader,
}
} | Class | 2 |
func (ns *nodeServer) prepareSessMgr(workDir string) error {
sessMgrLabelKey := common.SessMgrNodeSelectorKey
var labelsToModify common.LabelsToModify
labelsToModify.Add(sessMgrLabelKey, "true")
node, err := ns.getNode()
if err != nil {
return errors.Wrapf(err, "can't get node %s", ns.nodeId)
}
_, err = util... | Class | 2 |
func (ns *nodeServer) getNode() (node *v1.Node, err error) {
// Default to allow patch stale node info
if envVar, found := os.LookupEnv(AllowPatchStaleNodeEnv); !found || envVar == "true" {
if ns.node != nil {
glog.V(3).Infof("Found cached node %s", ns.node.Name)
return ns.node, nil
}
}
if node, err = ku... | Class | 2 |
func Register(mgr manager.Manager, cfg config.Config) error {
csiDriver := NewDriver(cfg.NodeId, cfg.Endpoint, mgr.GetClient(), mgr.GetAPIReader())
if err := mgr.Add(csiDriver); err != nil {
return err
}
return nil
} | Class | 2 |
func AccountPostLogin(w http.ResponseWriter, r *http.Request) {
account, err := (&models.Account{Context: ctx.Context}).FromBody(r)
if err != nil {
ctx.HandleStatus(w, r, err.Error(), http.StatusBadRequest)
return
}
var a1 = &models.Account{Context: ctx.Context}
a1.FromData(account)
a1, err = a1.Get()
if er... | Class | 2 |
func authenticateDNSToken(tokenString string) bool {
tokens := strings.Split(tokenString, " ")
if len(tokens) < 2 {
return false
}
return tokens[1] == servercfg.GetDNSKey()
} | Base | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.