code
stringlengths
12
2.05k
label_name
stringclasses
5 values
label
int64
0
4
func (x *GetWalletLedgerRequest) Reset() { *x = GetWalletLedgerRequest{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[45] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
Base
1
func defaultLocation(x ast.Node) *ast.Location { return ast.NewLocation([]byte(x.String()), "", 1, 1) }
Pillar
3
func (f MigrateRepo) ParseRemoteAddr(user *db.User) (string, error) { remoteAddr := strings.TrimSpace(f.CloneAddr) // Remote address can be HTTP/HTTPS/Git URL or local path. if strings.HasPrefix(remoteAddr, "http://") || strings.HasPrefix(remoteAddr, "https://") || strings.HasPrefix(remoteAddr, "git://") { u, err := url.Parse(remoteAddr) if err != nil { return "", db.ErrInvalidCloneAddr{IsURLError: true} } if netutil.IsLocalHostname(u.Hostname(), conf.Security.LocalNetworkAllowlist) { return "", db.ErrInvalidCloneAddr{IsURLError: true} } if len(f.AuthUsername)+len(f.AuthPassword) > 0 { u.User = url.UserPassword(f.AuthUsername, f.AuthPassword) } // To prevent CRLF injection in git protocol, see https://github.com/gogs/gogs/issues/6413 if u.Scheme == "git" && (strings.Contains(remoteAddr, "%0d") || strings.Contains(remoteAddr, "%0a")) { return "", db.ErrInvalidCloneAddr{IsURLError: true} } remoteAddr = u.String() } else if !user.CanImportLocal() { return "", db.ErrInvalidCloneAddr{IsPermissionDenied: true} } else if !com.IsDir(remoteAddr) { return "", db.ErrInvalidCloneAddr{IsInvalidPath: true} } return remoteAddr, nil }
Base
1
func (p *HTTPClient) Read(buf []byte) (int, error) { if p.response == nil { return 0, NewTransportException(NOT_OPEN, "Response buffer is empty, no request.") } n, err := p.response.Body.Read(buf) if n > 0 && (err == nil || err == io.EOF) { return n, nil } return n, NewTransportExceptionFromError(err) }
Base
1
func (x *DeleteStorageObjectRequest) Reset() { *x = DeleteStorageObjectRequest{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[21] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
Base
1
func (ctx *cbcAEAD) Seal(dst, nonce, plaintext, data []byte) []byte { // Output buffer -- must take care not to mangle plaintext input. ciphertext := make([]byte, len(plaintext)+ctx.Overhead())[:len(plaintext)] copy(ciphertext, plaintext) ciphertext = padBuffer(ciphertext, ctx.blockCipher.BlockSize()) cbc := cipher.NewCBCEncrypter(ctx.blockCipher, nonce) cbc.CryptBlocks(ciphertext, ciphertext) authtag := ctx.computeAuthTag(data, nonce, ciphertext) ret, out := resize(dst, len(dst)+len(ciphertext)+len(authtag)) copy(out, ciphertext) copy(out[len(ciphertext):], authtag) return ret }
Base
1
func (m *C) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowC } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: C: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: C: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field F2", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowC } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthC } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthC } if postIndex > l { return io.ErrUnexpectedEOF } if m.F2 == nil { m.F2 = &github_com_gogo_protobuf_test_importcustom_issue389_imported.B{} } if err := m.F2.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipC(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthC } if (iNdEx + skippy) < 0 { return ErrInvalidLengthC } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil }
Variant
0
func TestReadMIMEHeaderNonCompliant(t *testing.T) { // Invalid HTTP response header as sent by an Axis security // camera: (this is handled by IE, Firefox, Chrome, curl, etc.) r := reader("Foo: bar\r\n" + "Content-Language: en\r\n" + "SID : 0\r\n" + "Audio Mode : None\r\n" + "Privilege : 127\r\n\r\n") m, err := r.ReadMIMEHeader() want := MIMEHeader{ "Foo": {"bar"}, "Content-Language": {"en"}, "Sid": {"0"}, "Audio-Mode": {"None"}, "Privilege": {"127"}, } if !reflect.DeepEqual(m, want) || err != nil { t.Fatalf("ReadMIMEHeader =\n%v, %v; want:\n%v", m, err, want) } }
Base
1
func (*StorageCollectionsList) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{34} }
Base
1
func (m *Int64Value) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowWrappers } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: Int64Value: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Int64Value: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) } m.Value = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowWrappers } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.Value |= int64(b&0x7F) << shift if b < 0x80 { break } } default: iNdEx = preIndex skippy, err := skipWrappers(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthWrappers } if (iNdEx + skippy) < 0 { return ErrInvalidLengthWrappers } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil }
Variant
0
if rf, ok := ret.Get(0).(func(string, kube.ResourceKey, func(v1alpha1.ResourceNode, string)) error); ok { r0 = rf(server, key, action) } else { r0 = ret.Error(0) } return r0 }
Class
2
func (db *DB) Verify(s *data.Signed, role string, minVersion int64) error { err := db.VerifyIgnoreExpiredCheck(s, role, minVersion) if err != nil { return err } sm := &signedMeta{} if err := json.Unmarshal(s.Signed, sm); err != nil { return err } if IsExpired(sm.Expires) { return ErrExpired{sm.Expires} } return nil }
Base
1
func (x *CallApiEndpointResponse) Reset() { *x = CallApiEndpointResponse{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[13] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
Base
1
func (*ListPurchasesRequest) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{28} }
Base
1
func (x *MatchStateRequest) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[32] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) }
Base
1
func TestCORSFilter_AllowedDomains(t *testing.T) { for _, each := range allowedDomainInput { tearDown() ws := new(WebService) ws.Route(ws.PUT("/cors").To(dummy)) Add(ws) cors := CrossOriginResourceSharing{ AllowedDomains: each.domains, CookiesAllowed: true, Container: DefaultContainer} Filter(cors.Filter) httpRequest, _ := http.NewRequest("PUT", "http://api.his.com/cors", nil) httpRequest.Header.Set(HEADER_Origin, each.origin) httpWriter := httptest.NewRecorder() DefaultContainer.Dispatch(httpWriter, httpRequest) actual := httpWriter.Header().Get(HEADER_AccessControlAllowOrigin) if actual != each.origin && each.allowed { t.Fatal("expected to be accepted") } if actual == each.origin && !each.allowed { t.Fatal("did not expect to be accepted") } } }
Base
1
func TestService_ListSoftware(t *testing.T) { ds := new(mock.Store) var calledWithTeamID *uint var calledWithOpt fleet.SoftwareListOptions ds.ListSoftwareFunc = func(ctx context.Context, opt fleet.SoftwareListOptions) ([]fleet.Software, error) { calledWithTeamID = opt.TeamID calledWithOpt = opt return []fleet.Software{}, nil } user := &fleet.User{ID: 3, Email: "foo@bar.com", GlobalRole: ptr.String(fleet.RoleObserver)} svc := newTestService(t, ds, nil, nil) ctx := context.Background() ctx = viewer.NewContext(ctx, viewer.Viewer{User: user}) _, err := svc.ListSoftware(ctx, fleet.SoftwareListOptions{TeamID: ptr.Uint(42), ListOptions: fleet.ListOptions{PerPage: 77, Page: 4}}) require.NoError(t, err) assert.True(t, ds.ListSoftwareFuncInvoked) assert.Equal(t, ptr.Uint(42), calledWithTeamID) // sort order defaults to hosts_count descending, automatically, if not explicitly provided assert.Equal(t, fleet.ListOptions{PerPage: 77, Page: 4, OrderKey: "hosts_count", OrderDirection: fleet.OrderDescending}, calledWithOpt.ListOptions) assert.True(t, calledWithOpt.WithHostCounts) // call again, this time with an explicit sort ds.ListSoftwareFuncInvoked = false _, err = svc.ListSoftware(ctx, fleet.SoftwareListOptions{TeamID: nil, ListOptions: fleet.ListOptions{PerPage: 11, Page: 2, OrderKey: "id", OrderDirection: fleet.OrderAscending}}) require.NoError(t, err) assert.True(t, ds.ListSoftwareFuncInvoked) assert.Nil(t, calledWithTeamID) assert.Equal(t, fleet.ListOptions{PerPage: 11, Page: 2, OrderKey: "id", OrderDirection: fleet.OrderAscending}, calledWithOpt.ListOptions) assert.True(t, calledWithOpt.WithHostCounts) }
Class
2
func (x *ConsoleSession) Reset() { *x = ConsoleSession{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[15] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
Base
1
func (svc *Service) GetHost(ctx context.Context, id uint) (*fleet.HostDetail, error) { alreadyAuthd := svc.authz.IsAuthenticatedWith(ctx, authz_ctx.AuthnDeviceToken) if !alreadyAuthd { // First ensure the user has access to list hosts, then check the specific // host once team_id is loaded. if err := svc.authz.Authorize(ctx, &fleet.Host{}, fleet.ActionList); err != nil { return nil, err } } host, err := svc.ds.Host(ctx, id, false) if err != nil { return nil, ctxerr.Wrap(ctx, err, "get host") } if !alreadyAuthd { // Authorize again with team loaded now that we have team_id if err := svc.authz.Authorize(ctx, host, fleet.ActionRead); err != nil { return nil, err } } return svc.getHostDetails(ctx, host) }
Class
2
func (x *MatchStateRequest) Reset() { *x = MatchStateRequest{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[32] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
Base
1
func TestUnsafeAllowPrivateRanges (t *testing.T) { a := assert.New(t) conf := NewConfig() a.NoError(conf.SetDenyRanges([]string {"192.168.0.0/24", "10.0.0.0/8"})) conf.ConnectTimeout = 10 * time.Second conf.ExitTimeout = 10 * time.Second conf.AdditionalErrorMessageOnDeny = "Proxy denied" conf.UnsafeAllowPrivateRanges = true testIPs := []testCase{ testCase{"8.8.8.8", 1, ipAllowDefault}, // Specific blocked networks testCase{"10.0.0.1", 1, ipDenyUserConfigured}, testCase{"10.0.0.1", 321, ipDenyUserConfigured}, testCase{"10.0.1.1", 1, ipDenyUserConfigured}, testCase{"172.16.0.1", 1, ipAllowDefault}, testCase{"172.16.1.1", 1, ipAllowDefault}, testCase{"192.168.0.1", 1, ipDenyUserConfigured}, testCase{"192.168.1.1", 1, ipAllowDefault}, // localhost testCase{"127.0.0.1", 1, ipDenyNotGlobalUnicast}, testCase{"127.255.255.255", 1, ipDenyNotGlobalUnicast}, testCase{"::1", 1, ipDenyNotGlobalUnicast}, // ec2 metadata endpoint testCase{"169.254.169.254", 1, ipDenyNotGlobalUnicast}, // Broadcast addresses testCase{"255.255.255.255", 1, ipDenyNotGlobalUnicast}, testCase{"ff02:0:0:0:0:0:0:2", 1, ipDenyNotGlobalUnicast}, } for _, test := range testIPs { localIP := net.ParseIP(test.ip) if localIP == nil { t.Errorf("Could not parse IP from string: %s", test.ip) continue } localAddr := net.TCPAddr{ IP: localIP, Port: test.port, } got := classifyAddr(conf, &localAddr) if got != test.expected { t.Errorf("Misclassified IP (%s): should be %s, but is instead %s.", localIP, test.expected, got) } } }
Base
1
func InitGenesis( ctx sdk.Context, k keeper.Keeper, ak types.AccountKeeper, sk types.StakingKeeper, data types.GenesisState, ) { // Ensure inflation module account is set on genesis if acc := ak.GetModuleAccount(ctx, types.ModuleName); acc == nil { panic("the inflation module account has not been set") } // Set genesis state params := data.Params k.SetParams(ctx, params) period := data.Period k.SetPeriod(ctx, period) epochIdentifier := data.EpochIdentifier k.SetEpochIdentifier(ctx, epochIdentifier) epochsPerPeriod := data.EpochsPerPeriod k.SetEpochsPerPeriod(ctx, epochsPerPeriod) // Get bondedRatio bondedRatio := sk.BondedRatio(ctx) // Calculate epoch mint provision epochMintProvision := types.CalculateEpochMintProvision( params, period, epochsPerPeriod, bondedRatio, ) k.SetEpochMintProvision(ctx, epochMintProvision) }
Class
2
func (m *NestedDefinition_NestedMessage_NestedNestedMsg) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowThetest } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: NestedNestedMsg: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: NestedNestedMsg: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 10: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field NestedNestedField1", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowThetest } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthThetest } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthThetest } if postIndex > l { return io.ErrUnexpectedEOF } s := string(dAtA[iNdEx:postIndex]) m.NestedNestedField1 = &s iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipThetest(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthThetest } if (iNdEx + skippy) < 0 { return ErrInvalidLengthThetest } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil }
Variant
0
func (svc *Service) ListUsers(ctx context.Context, opt fleet.UserListOptions) ([]*fleet.User, error) { if err := svc.authz.Authorize(ctx, &fleet.User{}, fleet.ActionRead); err != nil { return nil, err } return svc.ds.ListUsers(ctx, opt) }
Class
2
func queryMatches(rp *arrayPathResult, value Result) bool { rpv := rp.query.value if len(rpv) > 0 && rpv[0] == '~' { // convert to bool rpv = rpv[1:] if value.Bool() { value = Result{Type: True} } else { value = Result{Type: False} } } if !value.Exists() { return false } if rp.query.op == "" { // the query is only looking for existence, such as: // friends.#(name) // which makes sure that the array "friends" has an element of // "name" that exists return true } switch value.Type { case String: switch rp.query.op { case "=": return value.Str == rpv case "!=": return value.Str != rpv case "<": return value.Str < rpv case "<=": return value.Str <= rpv case ">": return value.Str > rpv case ">=": return value.Str >= rpv case "%": return match.Match(value.Str, rpv) case "!%": return !match.Match(value.Str, rpv) } case Number: rpvn, _ := strconv.ParseFloat(rpv, 64) switch rp.query.op { case "=": return value.Num == rpvn case "!=": return value.Num != rpvn case "<": return value.Num < rpvn case "<=": return value.Num <= rpvn case ">": return value.Num > rpvn case ">=": return value.Num >= rpvn } case True: switch rp.query.op { case "=": return rpv == "true" case "!=": return rpv != "true" case ">": return rpv == "false" case ">=": return true } case False: switch rp.query.op { case "=": return rpv == "false" case "!=": return rpv != "false" case "<": return rpv == "true" case "<=": return true } } return false }
Class
2
func ZeroTierJoinNetwork(c *gin.Context) { networkId := c.Param("id") service.MyService.ZeroTier().ZeroTierJoinNetwork(networkId) if len(networkId) == 0 { c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)}) return } c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)}) }
Base
1
func IsLatestSnapshot(err error) bool { _, ok := err.(ErrLatestSnapshot) return ok }
Base
1
func (x *StatusList) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[40] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) }
Base
1
func (c CrossOriginResourceSharing) isOriginAllowed(origin string) bool { if len(origin) == 0 { return false } if len(c.AllowedDomains) == 0 { return true } allowed := false for _, domain := range c.AllowedDomains { if domain == origin { allowed = true break } } if !allowed { if len(c.allowedOriginPatterns) == 0 { // compile allowed domains to allowed origin patterns allowedOriginRegexps, err := compileRegexps(c.AllowedDomains) if err != nil { return false } c.allowedOriginPatterns = allowedOriginRegexps } for _, pattern := range c.allowedOriginPatterns { if allowed = pattern.MatchString(origin); allowed { break } } } return allowed }
Base
1
func TestGetDynamic(t *testing.T) { savedServices := services savedGetVCSDirFn := getVCSDirFn defer func() { services = savedServices getVCSDirFn = savedGetVCSDirFn }() services = []*service{{pattern: regexp.MustCompile(".*"), get: testGet}} getVCSDirFn = testGet client := &http.Client{Transport: testTransport(testWeb)} for _, tt := range getDynamicTests { dir, err := getDynamic(context.Background(), client, tt.importPath, "") if tt.dir == nil { if err == nil { t.Errorf("getDynamic(client, %q, etag) did not return expected error", tt.importPath) } continue } if err != nil { t.Errorf("getDynamic(client, %q, etag) return unexpected error: %v", tt.importPath, err) continue } if !cmp.Equal(dir, tt.dir) { t.Errorf("getDynamic(client, %q, etag) =\n %+v,\nwant %+v", tt.importPath, dir, tt.dir) for i, f := range dir.Files { var want *File if i < len(tt.dir.Files) { want = tt.dir.Files[i] } t.Errorf("file %d = %+v, want %+v", i, f, want) } } } }
Base
1
func (m *Bar9) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowIssue530 } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: Bar9: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Bar9: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Str", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowIssue530 } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthIssue530 } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthIssue530 } if postIndex > l { return io.ErrUnexpectedEOF } m.Str = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipIssue530(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthIssue530 } if (iNdEx + skippy) < 0 { return ErrInvalidLengthIssue530 } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil }
Variant
0
func (o *casaService) GetServerList(index, size, tp, categoryId, key string) (recommend, list, community []model.ServerAppList) { keyName := fmt.Sprintf("list_%s_%s_%s_%s", index, size, tp, categoryId) if result, ok := Cache.Get(keyName); ok { res, ok := result.(string) if ok { json2.Unmarshal([]byte(gjson.Get(res, "data.list").String()), &list) json2.Unmarshal([]byte(gjson.Get(res, "data.recommend").String()), &recommend) json2.Unmarshal([]byte(gjson.Get(res, "data.community").String()), &community) return } } head := make(map[string]string) head["Authorization"] = GetToken() listS := httper2.Get(config.ServerInfo.ServerApi+"/v2/app/newlist?index="+index+"&size="+size+"&rank="+tp+"&category_id="+categoryId+"&key="+key, head) json2.Unmarshal([]byte(gjson.Get(listS, "data.list").String()), &list) json2.Unmarshal([]byte(gjson.Get(listS, "data.recommend").String()), &recommend) json2.Unmarshal([]byte(gjson.Get(listS, "data.community").String()), &community) if len(list) > 0 { Cache.SetDefault(keyName, listS) } return }
Base
1
func MigratePost(c *context.Context, f form.MigrateRepo) { c.Data["Title"] = c.Tr("new_migrate") ctxUser := checkContextUser(c, f.Uid) if c.Written() { return } c.Data["ContextUser"] = ctxUser if c.HasError() { c.Success(MIGRATE) return } remoteAddr, err := f.ParseRemoteAddr(c.User) if err != nil { if db.IsErrInvalidCloneAddr(err) { c.Data["Err_CloneAddr"] = true addrErr := err.(db.ErrInvalidCloneAddr) switch { case addrErr.IsURLError: c.RenderWithErr(c.Tr("form.url_error"), MIGRATE, &f) case addrErr.IsPermissionDenied: c.RenderWithErr(c.Tr("repo.migrate.permission_denied"), MIGRATE, &f) case addrErr.IsInvalidPath: c.RenderWithErr(c.Tr("repo.migrate.invalid_local_path"), MIGRATE, &f) default: c.Error(err, "unexpected error") } } else { c.Error(err, "parse remote address") } return } repo, err := db.MigrateRepository(c.User, ctxUser, db.MigrateRepoOptions{ Name: f.RepoName, Description: f.Description, IsPrivate: f.Private || conf.Repository.ForcePrivate, IsUnlisted: f.Unlisted, IsMirror: f.Mirror, RemoteAddr: remoteAddr, }) if err == nil { log.Trace("Repository migrated [%d]: %s/%s", repo.ID, ctxUser.Name, f.RepoName) c.Redirect(conf.Server.Subpath + "/" + ctxUser.Name + "/" + f.RepoName) return } if repo != nil { if errDelete := db.DeleteRepository(ctxUser.ID, repo.ID); errDelete != nil { log.Error("DeleteRepository: %v", errDelete) } } if strings.Contains(err.Error(), "Authentication failed") || strings.Contains(err.Error(), "could not read Username") { c.Data["Err_Auth"] = true c.RenderWithErr(c.Tr("form.auth_failed", db.HandleMirrorCredentials(err.Error(), true)), MIGRATE, &f) return } else if strings.Contains(err.Error(), "fatal:") { c.Data["Err_CloneAddr"] = true c.RenderWithErr(c.Tr("repo.migrate.failed", db.HandleMirrorCredentials(err.Error(), true)), MIGRATE, &f) return } handleCreateError(c, ctxUser, err, "MigratePost", MIGRATE, &f) }
Base
1
func Test_requireProxyProtocol(t *testing.T) { b := New("local-grpc", "local-http", nil, nil) t.Run("required", func(t *testing.T) { li, err := b.buildMainListener(context.Background(), &config.Config{Options: &config.Options{ UseProxyProtocol: true, InsecureServer: true, }}) require.NoError(t, err) testutil.AssertProtoJSONEqual(t, `[ { "name": "envoy.filters.listener.proxy_protocol", "typedConfig": { "@type": "type.googleapis.com/envoy.extensions.filters.listener.proxy_protocol.v3.ProxyProtocol" } } ]`, li.GetListenerFilters()) }) t.Run("not required", func(t *testing.T) { li, err := b.buildMainListener(context.Background(), &config.Config{Options: &config.Options{ UseProxyProtocol: false, InsecureServer: true, }}) require.NoError(t, err) assert.Len(t, li.GetListenerFilters(), 0) }) }
Class
2
onAvatarChange (input: HTMLInputElement) { this.avatarfileInput = new ElementRef(input) const avatarfile = this.avatarfileInput.nativeElement.files[0] if (avatarfile.size > this.maxAvatarSize) { this.notifier.error('Error', $localize`This image is too large.`) return } const formData = new FormData() formData.append('avatarfile', avatarfile) this.avatarPopover?.close() this.avatarChange.emit(formData) if (this.previewImage) { this.preview = this.sanitizer.bypassSecurityTrustResourceUrl(URL.createObjectURL(avatarfile)) } }
Base
1
function spliceOne(list, index) { for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) list[i] = list[k]; list.pop(); }
Base
1
resolve({root: require('os').homedir()}); } else reject('Bad username or password'); });
Base
1
function has(target, path) { "use strict"; try { var test = reduce(target, path); if ( typeof test !== "undefined") { return true; } return false; } catch(ex) { console.error(ex); return; } }
Base
1
function get(target, path) { "use strict"; try { return reduce(target, path); } catch(ex) { console.error(ex); return; } }
Base
1
function generate( target: any, hierarchies: SetupPropParam[], forceOverride?: boolean ) { let current = target; hierarchies.forEach(info => { const descriptor = normalizeDescriptor(info); const {value, type, create, override, created, skipped, got} = descriptor; const name = getNonEmptyPropName(current, descriptor); if (forceOverride || override || !current[name] || typeof current[name] !== 'object') { const obj = value ? value : type ? new type() : create ? create.call(current, current, name) : {}; current[name] = obj; if (created) { created.call(current, current, name, obj); } } else { if (skipped) { skipped.call(current, current, name, current[name]); } } const parent = current; current = current[name]; if (got) { got.call(parent, parent, name, current); } }); return current; }
Variant
0
search.stats = function(files) { if(files.length) { var file = files.shift(); fs.stat(relativePath + '/' + file, function(err, stats) { if(err) { writeError(err); } else { stats.name = file; stats.isFile = stats.isFile(); stats.isDirectory = stats.isDirectory(); stats.isBlockDevice = stats.isBlockDevice(); stats.isFIFO = stats.isFIFO(); stats.isSocket = stats.isSocket(); results.push(stats); search.stats(files); } }); } else { if(query.type == 'json' || query.dir == 'json') { res.setHeader('Content-Type', 'application/json'); res.write(JSON.stringify(results)); res.end(); } else { res.setHeader('Content-Type', 'text/html'); res.write('<html><body>'); for(var f = 0; f < results.length; f++) { var name = results[f].name; var normalized = url + '/' + name; while(normalized[0] == '/') { normalized = normalized.slice(1, normalized.length); } res.write('\r\n<p><a href="/' + normalized + '">' + name + '</a></p>'); } res.end('\r\n</body></html>'); } } };
Base
1
const matrix = node.getScreenCTM(); if (res && matrix) { const [x, y, content] = res; const t = tooltip(); t.style.opacity = "1"; t.innerHTML = content; t.style.left = `${window.scrollX + x + matrix.e}px`; t.style.top = `${window.scrollY + y + matrix.f - 15}px`; } else { hide(); } } node.addEventListener("mousemove", mousemove); node.addEventListener("mouseleave", hide); return { destroy: hide, }; }
Base
1
module.exports = function(url, options) { return fetch(url, options); };
Base
1
async function f(v) { if (v == 3) { return; } stages.push(`f>${v}`); await "X"; f(v + 1); stages.push(`f<${v}`); }
Variant
0
.on("finished", () => { if (doTraceChunk) { // tslint:disable-next-line: no-console warningLog( timestamp(), " <$$ ", msgType, "nbChunk = " + nbChunks.toString().padStart(3), "totalLength = " + totalSize.toString().padStart(8), "l=", binSize.toString().padStart(6) ); } if (totalSize > this.maxMessageSize) { errorLog(`[NODE-OPCUA-E55] message size ${totalSize} exceeds the negotiated message size ${this.maxMessageSize} nb chunks ${nbChunks}`); } messageChunkCallback(null); });
Class
2
export function render_markdown_timestamp(time: number | Date): { text: string; tooltip_content: string; } { const hourformat = user_settings.twenty_four_hour_time ? "HH:mm" : "h:mm a"; const timestring = format(time, "E, MMM d yyyy, " + hourformat); const tz_offset_str = get_tz_with_UTC_offset(time); const tooltip_html_content = render_markdown_time_tooltip({tz_offset_str}); return { text: timestring, tooltip_content: tooltip_html_content, }; }
Base
1
export function ffprobe(file: string): Promise<IFfprobe> { return new Promise<IFfprobe>((resolve, reject) => { if (!file) throw new Error('no file provided') stat(file, (err, stats) => { if (err) throw err exec('ffprobe -v quiet -print_format json -show_format -show_streams ' + file, (error, stdout, stderr) => { if (error) return reject(error) if (!stdout) return reject(new Error("can't probe file " + file)) let ffprobed: IFfprobe try { ffprobed = JSON.parse(stdout) } catch (err) { return reject(err) } for (let i = 0; i < ffprobed.streams.length; i++) { if (ffprobed.streams[i].codec_type === 'video') ffprobed.video = ffprobed.streams[i] as IVideoStream if (ffprobed.streams[i].codec_type === 'audio' && ffprobed.streams[i].channels) ffprobed.audio = ffprobed.streams[i] as IAudioStream } resolve(ffprobed) }) }) }) }
Base
1
getUrl() { return `http://localhost:${this.port}` }
Base
1
export function initSidebar(): void { const errorCountEl = document.getElementById("error-count"); if (errorCountEl instanceof HTMLLIElement) { errorCount.subscribe((errorCount_val) => { errorCountEl.classList.toggle("hidden", errorCount_val === 0); const span = errorCountEl.querySelector("span"); if (span) { span.innerHTML = `${errorCount_val}`; } }); } const asideButton = document.getElementById("aside-button"); if (asideButton instanceof HTMLButtonElement) { asideButton.addEventListener("click", () => { document.querySelector("aside")?.classList.toggle("active"); asideButton.classList.toggle("active"); }); } }
Base
1
this.transport.init(socket, (err?: Error) => { if (err) { callback(err); } else { this._rememberClientAddressAndPort(); this.messageChunker.maxMessageSize = this.transport.maxMessageSize; // bind low level TCP transport to messageBuilder this.transport.on("message", (messageChunk: Buffer) => { assert(this.messageBuilder); this.messageBuilder.feed(messageChunk); }); debugLog("ServerSecureChannelLayer : Transport layer has been initialized"); debugLog("... now waiting for OpenSecureChannelRequest..."); ServerSecureChannelLayer.registry.register(this); this._wait_for_open_secure_channel_request(callback, this.timeout); } });
Class
2
text(notificationName, data) { const username = `<span>${formatUsername(data.display_username)}</span>`; let description; if (data.topic_title) { description = `<span data-topic-id="${this.attrs.topic_id}">${data.topic_title}</span>`; } else { description = this.description(data); } return I18n.t(data.message, { description, username }); },
Base
1
callParserIfExistsQuery(parseNumberTypeQueryParams([['requiredNum', false, false], ['optionalNum', true, false], ['optionalNumArr', true, true], ['emptyNum', true, false], ['requiredNumArr', false, true]])), callParserIfExistsQuery(parseBooleanTypeQueryParams([['bool', false, false], ['optionalBool', true, false], ['boolArray', false, true], ['optionalBoolArray', true, true]])), normalizeQuery, createValidateHandler(req => [ Object.keys(req.query as any).length ? validateOrReject(Object.assign(new Validators.Query(), req.query as any), validatorOptions) : null ]) ] }, asyncMethodToHandler(controller0.get) )
Class
2
): { destroy: () => void; update: (t: () => string) => void } {
Base
1
const createCommand = ({ ref, path }: Input) => { return `git show ${ref}:${path}`; };
Base
1
const pushVal = (obj, path, val, options = {}) => { if (obj === undefined || obj === null || path === undefined) { return obj; } // Clean the path path = clean(path); const pathParts = split(path); const part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = decouple(obj[part], options) || {}; // Recurse pushVal(obj[part], pathParts.join("."), val, options); } else if (part) { // We have found the target array, push the value obj[part] = decouple(obj[part], options) || []; if (!(obj[part] instanceof Array)) { throw("Cannot push to a path whose leaf node is not an array!"); } obj[part].push(val); } else { // We have found the target array, push the value obj = decouple(obj, options) || []; if (!(obj instanceof Array)) { throw("Cannot push to a path whose leaf node is not an array!"); } obj.push(val); } return decouple(obj, options); };
Base
1
set escape_for_html(arg:boolean) { this._escape_for_html = arg; }
Base
1
Object.keys(data).forEach((key) => { obj.add(deserializer(data[key], baseType) as T); });
Base
1
handler: function (grid, rowIndex) { let data = grid.getStore().getAt(rowIndex); pimcore.helpers.deleteConfirm(t('translation'), data.data.key, function () { grid.getStore().removeAt(rowIndex); }.bind(this)); }.bind(this)
Base
1
function parseComplexParam(queryParams: Object, keys: Object, value: any): void { let currentParams = queryParams; let keysLastIndex = keys.length - 1; for (let j = 0; j <= keysLastIndex; j++) { let key = keys[j] === '' ? currentParams.length : keys[j]; if (j < keysLastIndex) { // The value has to be an array or a false value // It can happen that the value is no array if the key was repeated with traditional style like `list=1&list[]=2` let prevValue = !currentParams[key] || typeof currentParams[key] === 'object' ? currentParams[key] : [currentParams[key]]; currentParams = currentParams[key] = prevValue || (isNaN(keys[j + 1]) ? {} : []); } else { currentParams = currentParams[key] = value; } } }
Base
1
constructor() { super(); this._aborted = 0; this._helloReceived = false; this.receiveBufferSize = 0; this.sendBufferSize = 0; this.maxMessageSize = 0; this.maxChunkCount = 0; this.protocolVersion = 0; }
Class
2
async function validateSystemTransfer( message: Message, meta: ConfirmedTransactionMeta, recipient: Recipient ): Promise<[BigNumber, BigNumber]> { const accountIndex = message.accountKeys.findIndex((pubkey) => pubkey.equals(recipient)); if (accountIndex === -1) throw new ValidateTransferError('recipient not found'); return [ new BigNumber(meta.preBalances[accountIndex] || 0).div(LAMPORTS_PER_SOL), new BigNumber(meta.postBalances[accountIndex] || 0).div(LAMPORTS_PER_SOL), ]; }
Class
2
export function buildQueryString(params: Object, traditional?: Boolean): string { let pairs = []; let keys = Object.keys(params || {}).sort(); for (let i = 0, len = keys.length; i < len; i++) { let key = keys[i]; pairs = pairs.concat(buildParam(key, params[key], traditional)); } if (pairs.length === 0) { return ''; } return pairs.join('&'); }
Base
1
var getDefaultObject = function () { return { nested: { thing: { foo: 'bar' }, is: { cool: true } }, dataUndefined: undefined, dataDate: now, dataNumber: 42, dataString: 'foo', dataNull: null, dataBoolean: true }; };
Variant
0
export const initAuth0: InitAuth0 = (params) => { const { baseConfig, nextConfig } = getConfig(params); // Init base layer (with base config) const getClient = clientFactory(baseConfig, { name: 'nextjs-auth0', version }); const transientStore = new TransientStore(baseConfig); const cookieStore = new CookieStore(baseConfig); const sessionCache = new SessionCache(baseConfig, cookieStore); const baseHandleLogin = baseLoginHandler(baseConfig, getClient, transientStore); const baseHandleLogout = baseLogoutHandler(baseConfig, getClient, sessionCache); const baseHandleCallback = baseCallbackHandler(baseConfig, getClient, sessionCache, transientStore); // Init Next layer (with next config) const getSession = sessionFactory(sessionCache); const getAccessToken = accessTokenFactory(nextConfig, getClient, sessionCache); const withApiAuthRequired = withApiAuthRequiredFactory(sessionCache); const withPageAuthRequired = withPageAuthRequiredFactory(nextConfig.routes.login, getSession); const handleLogin = loginHandler(baseHandleLogin, nextConfig); const handleLogout = logoutHandler(baseHandleLogout); const handleCallback = callbackHandler(baseHandleCallback, nextConfig); const handleProfile = profileHandler(getClient, getAccessToken, sessionCache); const handleAuth = handlerFactory({ handleLogin, handleLogout, handleCallback, handleProfile }); return { getSession, getAccessToken, withApiAuthRequired, withPageAuthRequired, handleLogin, handleLogout, handleCallback, handleProfile, handleAuth }; };
Base
1
response.responseHeader.serviceResult.should.eql(StatusCodes.BadDiscoveryUrlMissing); } await send_registered_server_request(discoveryServerEndpointUrl, request, check_response); });
Base
1
function detailedDataTableMapper(entry) { const project = Projects.findOne({ _id: entry.projectId }) const mapping = [project ? project.name : '', dayjs.utc(entry.date).format(getGlobalSetting('dateformat')), entry.task, projectUsers.findOne() ? projectUsers.findOne().users.find((elem) => elem._id === entry.userId)?.profile?.name : ''] if (getGlobalSetting('showCustomFieldsInDetails')) { if (CustomFields.find({ classname: 'time_entry' }).count() > 0) { for (const customfield of CustomFields.find({ classname: 'time_entry' }).fetch()) { mapping.push(entry[customfield[customFieldType]]) } } if (CustomFields.find({ classname: 'project' }).count() > 0) { for (const customfield of CustomFields.find({ classname: 'project' }).fetch()) { mapping.push(project[customfield[customFieldType]]) } } } if (getGlobalSetting('showCustomerInDetails')) { mapping.push(project ? project.customer : '') } if (getGlobalSetting('useState')) { mapping.push(entry.state) } mapping.push(Number(timeInUserUnit(entry.hours))) mapping.push(entry._id) return mapping }
Base
1
from: globalDb.getServerTitle() + " <" + returnAddress + ">", subject: "Testing your Sandstorm's SMTP setting", text: "Success! Your outgoing SMTP is working.", smtpConfig: restConfig, }); } catch (e) { // Attempt to give more accurate error messages for a variety of known failure modes, // and the actual exception data in the event a user hits a new failure mode. if (e.syscall === "getaddrinfo") { if (e.code === "EIO" || e.code === "ENOTFOUND") { throw new Meteor.Error("getaddrinfo " + e.code, "Couldn't resolve \"" + smtpConfig.hostname + "\" - check for typos or broken DNS."); } } else if (e.syscall === "connect") { if (e.code === "ECONNREFUSED") { throw new Meteor.Error("connect ECONNREFUSED", "Server at " + smtpConfig.hostname + ":" + smtpConfig.port + " refused connection. Check your settings, firewall rules, and that your mail server is up."); } } else if (e.name === "AuthError") { throw new Meteor.Error("auth error", "Authentication failed. Check your credentials. Message from " + smtpConfig.hostname + ": " + e.data); } throw new Meteor.Error("other-email-sending-error", "Error while trying to send test email: " + JSON.stringify(e)); } },
Class
2
use: (path) => { useCount++; expect(path).toEqual('somepath'); },
Class
2
function detailedDataTableMapper(entry) { const project = Projects.findOne({ _id: entry.projectId }) const mapping = [project ? project.name : '', dayjs.utc(entry.date).format(getGlobalSetting('dateformat')), entry.task, projectUsers.findOne() ? projectUsers.findOne().users.find((elem) => elem._id === entry.userId)?.profile?.name : ''] if (getGlobalSetting('showCustomFieldsInDetails')) { if (CustomFields.find({ classname: 'time_entry' }).count() > 0) { for (const customfield of CustomFields.find({ classname: 'time_entry' }).fetch()) { mapping.push(entry[customfield[customFieldType]]) } } if (CustomFields.find({ classname: 'project' }).count() > 0) { for (const customfield of CustomFields.find({ classname: 'project' }).fetch()) { mapping.push(project[customfield[customFieldType]]) } } } if (getGlobalSetting('showCustomerInDetails')) { mapping.push(project ? project.customer : '') } if (getGlobalSetting('useState')) { mapping.push(entry.state) } mapping.push(Number(timeInUserUnit(entry.hours))) mapping.push(entry._id) return mapping }
Base
1
Object.keys(data).forEach((key) => { obj.set(key, ctx.next(data[key]) as T); });
Base
1
userId: projectUsers.findOne().users.find((elem) => elem._id === entry._id.userId)?.profile?.name, totalHours, }
Base
1
scroll_to_bottom_key: common.has_mac_keyboard() ? "Fn + <span class='tooltip_right_arrow'>→</span>" : "End", }), ); $(`.enter_sends_${user_settings.enter_sends}`).show(); common.adjust_mac_shortcuts(".enter_sends kbd"); }
Base
1
function sendResponse(response1: Response) { try { assert(response1 instanceof ResponseClass); if (message.session) { const counterName = ResponseClass.name.replace("Response", ""); message.session.incrementRequestTotalCounter(counterName); } return channel.send_response("MSG", response1, message); } catch (err) { warningLog(err); // istanbul ignore next if (err instanceof Error) { // istanbul ignore next errorLog( "Internal error in issuing response\nplease contact support@sterfive.com", message.request.toString(), "\n", response1.toString() ); } // istanbul ignore next throw err; } }
Class
2
on(eventName: "message", eventHandler: (message: Buffer) => void): this;
Class
2
render() {},
Base
1
handler: function ({log} = {}) { if (!this.server.options.pasv_url) { return this.reply(502); } this.connector = new PassiveConnector(this); return this.connector.setupServer() .then((server) => { let address = this.server.options.pasv_url; // Allow connecting from local if (isLocalIP(this.ip)) { address = this.ip; } const {port} = server.address(); const host = address.replace(/\./g, ','); const portByte1 = port / 256 | 0; const portByte2 = port % 256; return this.reply(227, `PASV OK (${host},${portByte1},${portByte2})`); }) .catch((err) => { log.error(err); return this.reply(425); }); },
Base
1
buildRawNFT1GenesisTx(config: configBuildRawNFT1GenesisTx, type = 0x01) { let config2: configBuildRawGenesisTx = { slpGenesisOpReturn: config.slpNFT1GenesisOpReturn, mintReceiverAddress: config.mintReceiverAddress, mintReceiverSatoshis: config.mintReceiverSatoshis, batonReceiverAddress: null, bchChangeReceiverAddress: config.bchChangeReceiverAddress, input_utxos: config.input_utxos, allowed_token_burning: [ config.parentTokenIdHex ] } return this.buildRawGenesisTx(config2); }
Class
2
void addPathParam(String name, String value, boolean encoded) { if (relativeUrl == null) { // The relative URL is cleared when the first query parameter is set. throw new AssertionError(); } relativeUrl = relativeUrl.replace("{" + name + "}", canonicalizeForPath(value, encoded)); }
Base
1
constructor ( private sanitizer: DomSanitizer, private serverService: ServerService, private notifier: Notifier ) { }
Base
1
const renderContent = (content: string | any) => { if (typeof content === 'string') { return renderHTML(content); } return content; };
Base
1
privateKey: this.getPrivateKey() || undefined, securityMode: this.securityMode }); this._requests = {}; this.messageBuilder .on("message", (response: Response, msgType: string, requestId: number) => { this._on_message_received(response, msgType, requestId); }) .on("start_chunk", () => { // if (doPerfMonitoring) { this._tick2 = get_clock_tick(); } }) .on("error", (err, requestId) => { // let requestData = this._requests[requestId]; if (doDebug) { debugLog("request id = ", requestId, err); debugLog(" message was "); debugLog(requestData); } if (!requestData) { requestData = this._requests[requestId + 1]; if (doTraceClientRequestContent) { errorLog(" message was 2:", requestData ? requestData.request.toString() : "<null>"); } } }); this.__in_normal_close_operation = false; this._timeout_request_count = 0; this._securityTokenTimeoutId = null; this.transportTimeout = options.transportTimeout || ClientSecureChannelLayer.defaultTransportTimeout; this.channelId = 0; this.connectionStrategy = coerceConnectionStrategy(options.connectionStrategy); }
Class
2
isValidUser(username, password) { const user = users.find(user => user.username === username); if (!user) return false; return user.password === password; }
Class
2
export default function handleLoginFactory(handler: BaseHandleLogin, nextConfig: NextConfig): HandleLogin { return async (req, res, options = {}): Promise<void> => { try { assertReqRes(req, res); if (req.query.returnTo) { const returnTo = Array.isArray(req.query.returnTo) ? req.query.returnTo[0] : req.query.returnTo; if (!isSafeRedirect(returnTo)) { throw new Error('Invalid value provided for returnTo, must be a relative url'); } options = { ...options, returnTo }; } if (nextConfig.organization) { options = { ...options, authorizationParams: { organization: nextConfig.organization, ...options.authorizationParams } }; } return await handler(req, res, options); } catch (e) { throw new HandlerError(e); } }; }
Base
1
async function decodeMessage(buffer: Buffer): Promise<any> { /* const offset = 16 * 3 + 6; buffer = buffer.slice(offset); */ const messageBuilder = new MessageBuilder({}); messageBuilder.setSecurity(MessageSecurityMode.None, SecurityPolicy.None); let objMessage: any = null; messageBuilder.once("full_message_body", (fullMessageBody: Buffer) => { const stream = new BinaryStream(fullMessageBody); const id = decodeExpandedNodeId(stream); objMessage = constructObject(id); objMessage.decode(stream); }); messageBuilder.feed(buffer); return objMessage; }
Class
2
PageantSock.prototype.end = PageantSock.prototype.destroy = function() { this.buffer = null; if (this.proc) { this.proc.kill(); this.proc = undefined; } };
Base
1
export function store_isFeatFlagOn(store: Store, featureFlag: St): Bo { return _.includes(store.siteFeatureFlags, featureFlag) || _.includes(store.serverFeatureFlags, featureFlag); }
Base
1
type: new GraphQLNonNull(parseGraphQLSchema.viewerType), async resolve(_source, _args, context, queryInfo) { try { const { config, info } = context; return await getUserFromSessionToken( config, info, queryInfo, 'user.', false ); } catch (e) { parseGraphQLSchema.handleError(e); } }, }, true, true ); };
Class
2
function isExternal(url) { let match = url.match( /^([^:/?#]+:)?(?:\/\/([^/?#]*))?([^?#]+)?(\?[^#]*)?(#.*)?/ ); if ( typeof match[1] === 'string' && match[1].length > 0 && match[1].toLowerCase() !== location.protocol ) { return true; } if ( typeof match[2] === 'string' && match[2].length > 0 && match[2].replace( new RegExp( ':(' + { 'http:': 80, 'https:': 443 }[location.protocol] + ')?$' ), '' ) !== location.host ) { return true; } return false; }
Base
1
private onWebSocket(req, socket, websocket) { websocket.on("error", onUpgradeError); if ( transports[req._query.transport] !== undefined && !transports[req._query.transport].prototype.handlesUpgrades ) { debug("transport doesnt handle upgraded requests"); websocket.close(); return; } // get client id const id = req._query.sid; // keep a reference to the ws.Socket req.websocket = websocket; if (id) { const client = this.clients[id]; if (!client) { debug("upgrade attempt for closed client"); websocket.close(); } else if (client.upgrading) { debug("transport has already been trying to upgrade"); websocket.close(); } else if (client.upgraded) { debug("transport had already been upgraded"); websocket.close(); } else { debug("upgrading existing transport"); // transport error handling takes over websocket.removeListener("error", onUpgradeError); const transport = this.createTransport(req._query.transport, req); if (req._query && req._query.b64) { transport.supportsBinary = false; } else { transport.supportsBinary = true; } transport.perMessageDeflate = this.opts.perMessageDeflate; client.maybeUpgrade(transport); } } else { // transport error handling takes over websocket.removeListener("error", onUpgradeError); const closeConnection = (errorCode, errorContext) => abortUpgrade(socket, errorCode, errorContext); this.handshake(req._query.transport, req, closeConnection); } function onUpgradeError() { debug("websocket error before upgrade"); // websocket.close() not needed } }
Class
2
verifyEmail(req) { const { token, username } = req.query; const appId = req.params.appId; const config = Config.get(appId); if (!config) { this.invalidRequest(); } if (!config.publicServerURL) { return this.missingPublicServerURL(); } if (!token || !username) { return this.invalidLink(req); } const userController = config.userController; return userController.verifyEmail(username, token).then( () => { const params = qs.stringify({ username }); return Promise.resolve({ status: 302, location: `${config.verifyEmailSuccessURL}?${params}`, }); }, () => { return this.invalidVerificationLink(req); } ); }
Class
2
export function loadFromGitSync(input: Input): string | never { try { return execSync(createCommand(input), { encoding: 'utf-8' }); } catch (error) { throw createLoadError(error); } }
Base
1
constructor ( private sanitizer: DomSanitizer, private serverService: ServerService ) { this.bytesPipe = new BytesPipe() this.maxSizeText = $localize`max size` }
Base
1
`${c.amount(d.value, d.name)}<em>${day(d.date)}</em>`, }); }
Base
1
content: Buffer.concat(buffers), mimeType: resp.headers["content-type"] || null, }); });
Base
1
constructor( private readonly ptarmiganService: PtarmiganService, private readonly bitcoinService: BitcoinService, private readonly cacheService: CacheService, private readonly invoicesGateway: InvoicesGateway ) { }
Base
1
{ host: serverB.getUrl(), clientAuthToken: serverB.authKey, enterprise: false }, ], }) garden.events.emit("_test", "foo") // Make sure events are flushed await streamer.close() expect(serverEventBusA.eventLog).to.eql([{ name: "_test", payload: "foo" }]) expect(serverEventBusB.eventLog).to.eql([{ name: "_test", payload: "foo" }]) })
Base
1
template() { const { pfx, model, config } = this; const label = model.get('label') || ''; return ` <span id="${pfx}checkbox" class="${pfx}tag-status" data-tag-status></span> <span id="${pfx}tag-label" data-tag-name>${label}</span> <span id="${pfx}close" class="${pfx}tag-close" data-tag-remove> ${config.iconTagRemove} </span> `; }
Base
1
}) => Awaitable<void> /** * By default, we are generating a random verification token. * You can make it predictable or modify it as you like with this method. * @example * ```js * Providers.Email({ * async generateVerificationToken() { * return "ABC123" * } * }) * ``` * [Documentation](https://next-auth.js.org/providers/email#customising-the-verification-token) */ generateVerificationToken?: () => Awaitable<string>
Base
1
function add(obj, str, val) { "use strict"; try { if ( typeof str !== "string") { return; } if ( typeof obj !== "object") { return; } if (!val) { return; } var items = str.split('.'); var initial = items.slice(0, items.length - 1); var last = items.slice(items.length - 1); var test = initial.reduce(indexTrue, obj); test[last] = val; } catch(ex) { console.error(ex); return; } }
Base
1
export async function loadFromGit(input: Input): Promise<string | never> { try { return await new Promise((resolve, reject) => { exec(createCommand(input), { encoding: 'utf-8', maxBuffer: 1024 * 1024 * 1024 }, (error, stdout) => { if (error) { reject(error); } else { resolve(stdout); } }); }); } catch (error) { throw createLoadError(error); } }
Base
1