text
stringlengths
20
812k
id
stringlengths
40
40
metadata
dict
from google import google num_page = 1 search_results = google.search("what is your name?", num_page) print search_results[1].description
d83bc9053c048a9b82f5859f640223a7efe9c1d8
{ "blob_id": "d83bc9053c048a9b82f5859f640223a7efe9c1d8", "branch_name": "refs/heads/master", "committer_date": "2018-11-13T10:52:03", "content_id": "79cb37176f6f81dc71473dd0cb35957ed77d32f4", "detected_licenses": [ "Unlicense" ], "directory_id": "fa6bded4e422d5f5f52cf670cc378eec56123ada", "extension": "py", "filename": "b.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 108415648, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 140, "license": "Unlicense", "license_type": "permissive", "path": "/python/fbpi/b.py", "provenance": "stack-edu-0054.json.gz:725049", "repo_name": "hqnghi88/rpiBot", "revision_date": "2018-11-13T10:52:03", "revision_id": "33d28ffa2f5a050f172ba84fc8ccbbf3aa796891", "snapshot_id": "487a4da5d6e4eb95fe7a86bd3bce7e17444d4e26", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/hqnghi88/rpiBot/33d28ffa2f5a050f172ba84fc8ccbbf3aa796891/python/fbpi/b.py", "visit_date": "2021-04-25T18:26:18.221850", "added": "2024-11-19T00:40:30.958522+00:00", "created": "2018-11-13T10:52:03", "int_score": 3, "score": 2.515625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0072.json.gz" }
package com.nevergetme.autumn.bytedance.solution02; import java.util.Scanner; public class Main{ public static void main(String args[]) throws Exception { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int k = scanner.nextInt(); String secret = scanner.next(); char[] result = new char[n]; result[0] = secret.charAt(0); for (int i = 1; i < k; i++) { result[i] = xor(secret.charAt(i), secret.charAt(i - 1)); } for (int i = k; i < n; i++) { result[i] = xor(xor(secret.charAt(i), secret.charAt(i - 1)), result[i - k]); } System.out.println(new String(result)); throw new Exception(""); } private static char xor(char a, char b) { return a == b ? '0' : '1'; } } //import java.util.Scanner; // //public class Main { // public static void main(String[] args) { // Scanner scanner = new Scanner(System.in); // String line = scanner.nextLine(); // String S = scanner.nextLine(); // String[] t = line.split(" "); // int N = Integer.parseInt(t[0]); // int K = Integer.parseInt(t[1]); // getB(S, N, K); // } // // public static void getB(String s, int N, int K) { // char[] temp = s.toCharArray(); // int[] output = new int[N]; // for (int i = 0; i < N; i++) { // output[i] = temp[i] - '0'; // if(i>0)output[i]^=temp[i-1] - '0'; // // for(int j=i-1;j>=0&&j>i-K;j--){ // output[i]^=output[j]; // } // } // for(int k:output){ // System.out.print(k); // } // System.out.println(); // } //}
95ea1a567fb3b66fbc3fa230886dbb18165e42ce
{ "blob_id": "95ea1a567fb3b66fbc3fa230886dbb18165e42ce", "branch_name": "refs/heads/master", "committer_date": "2019-09-20T14:03:06", "content_id": "d4a8f6465fc9ce1665f48a71c97e9acb9c8a65ce", "detected_licenses": [ "Apache-2.0" ], "directory_id": "63681b76f02c44c939cd7d16f138d80ae8ce1887", "extension": "java", "filename": "Main.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 154286267, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1729, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/com/nevergetme/autumn/bytedance/solution02/Main.java", "provenance": "stack-edu-0023.json.gz:703594", "repo_name": "hTangle/AlgorithmPractice", "revision_date": "2019-09-20T14:03:06", "revision_id": "64ce6de1041c855719d9ba153f57245ef726e35b", "snapshot_id": "c336e68541f21f1737d3b8fdba134bbfcc73a77d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/hTangle/AlgorithmPractice/64ce6de1041c855719d9ba153f57245ef726e35b/src/com/nevergetme/autumn/bytedance/solution02/Main.java", "visit_date": "2020-04-02T09:18:08.175072", "added": "2024-11-18T22:02:30.626572+00:00", "created": "2019-09-20T14:03:06", "int_score": 3, "score": 3.4375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0041.json.gz" }
#ifndef BUFFER_H_ #define BUFFER_H_ #include <stdint.h> #include "oo.h" #define SEEK_BEGIN 0 #define SEEK_END ((size_t)-1) DeclareClass(Buffer, Object) uint8_t *m_buf; size_t m_length; size_t m_pos; EndDeclareClass(Buffer, Object) DeclareClassFunctions(Buffer, Object) DeclareFunction(Buffer, void, enlarge, size_t) DeclareFunction(Buffer, void, seek, size_t) DeclareFunction(Buffer, size_t, tell) DeclareFunction(Buffer, void, write_u8, uint8_t) DeclareFunction(Buffer, void, write_u16, uint16_t) DeclareFunction(Buffer, void, write_u32, uint32_t) DeclareFunction(Buffer, void, write_number, int) DeclareFunction(Buffer, void, write_string, const char *) DeclareFunction(Buffer, void, write_bytes, const uint8_t *, size_t) DeclareFunction(Buffer, uint8_t, read_u8) DeclareFunction(Buffer, uint16_t, read_u16) DeclareFunction(Buffer, uint32_t, read_u32) DeclareFunction(Buffer, int, read_number) DeclareFunction(Buffer, char *, read_string) DeclareFunction(Buffer, size_t, read_bytes, uint8_t *, size_t) // create or parse ASCII-safe version of buffer DeclareFunction(Buffer, uint16_t, checksum) DeclareFunction(Buffer, int, dearmor, const char *) DeclareFunction(Buffer, char *, armor) EndDeclareClassFunctions(Buffer) #endif
4cc1067b5ee1dc42f51f71a12e38b06043820b01
{ "blob_id": "4cc1067b5ee1dc42f51f71a12e38b06043820b01", "branch_name": "refs/heads/master", "committer_date": "2022-12-27T15:47:54", "content_id": "3f58c2b25fa30e553349f15b1ac0ce8325073f6e", "detected_licenses": [ "MIT" ], "directory_id": "59864cbd213b5da6f50d6255b0a021564b3d5bd4", "extension": "h", "filename": "Buffer.h", "fork_events_count": 133, "gha_created_at": "2015-08-31T17:04:31", "gha_event_created_at": "2023-06-29T02:47:13", "gha_language": "C", "gha_license_id": "MIT", "github_id": 41688943, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1323, "license": "MIT", "license_type": "permissive", "path": "/disabled-challenges/adventure_game/src/Buffer.h", "provenance": "stack-edu-0000.json.gz:504925", "repo_name": "trailofbits/cb-multios", "revision_date": "2022-12-27T15:47:54", "revision_id": "810d7b24b1f62f56ef49b148fe155b0d0629cad2", "snapshot_id": "8af96a4fbc3b34644367faa135347f88e0e0d0a3", "src_encoding": "UTF-8", "star_events_count": 522, "url": "https://raw.githubusercontent.com/trailofbits/cb-multios/810d7b24b1f62f56ef49b148fe155b0d0629cad2/disabled-challenges/adventure_game/src/Buffer.h", "visit_date": "2023-09-05T03:56:20.229403", "added": "2024-11-18T22:49:21.474639+00:00", "created": "2022-12-27T15:47:54", "int_score": 2, "score": 2.171875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0018.json.gz" }
package com.aldimbilet.activityservice; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.aldimbilet.activityservice.model.Activity; import com.aldimbilet.activityservice.repo.ActivityRepository; @SpringBootApplication public class AldimbiletActivityServicesApplication { public static void main(String[] args) { SpringApplication.run(AldimbiletActivityServicesApplication.class, args); } @Autowired ActivityRepository activityRepo; @PostConstruct private void createDummyActivities() { if (activityRepo.getCount() == 0) { // Yes i am too lazy to create a controller and a feign client and a thymeleaf page and and mvc operation in the mvc app Activity activity = new Activity(); activity.setName("Activity 1"); activity.setNumberOfSeats(5); activityRepo.save(activity); activity = new Activity(); activity.setName("Activity 2"); activity.setNumberOfSeats(3); activityRepo.save(activity); activity = new Activity(); activity.setName("Activity 3"); activity.setNumberOfSeats(3); activityRepo.save(activity); } } }
33ae6013f5fefcaedc38ad226f6a9946ff2d7c80
{ "blob_id": "33ae6013f5fefcaedc38ad226f6a9946ff2d7c80", "branch_name": "refs/heads/main", "committer_date": "2021-02-02T11:26:59", "content_id": "3456161498c9f9d9618db8a02307074275d6d45a", "detected_licenses": [ "MIT" ], "directory_id": "4465694d5f507ba09ebb8b0e721b106691145150", "extension": "java", "filename": "AldimbiletActivityServicesApplication.java", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 320810320, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1256, "license": "MIT", "license_type": "permissive", "path": "/ab - activityservice/src/main/java/com/aldimbilet/activityservice/AldimbiletActivityServicesApplication.java", "provenance": "stack-edu-0019.json.gz:168088", "repo_name": "numankaraaslan/Microservices-Saga", "revision_date": "2021-02-02T11:26:59", "revision_id": "3c628800399fa628e2652d1fce41f519ab51a2b4", "snapshot_id": "c48dd1d6feac6f050510e566787501d1c966eba0", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/numankaraaslan/Microservices-Saga/3c628800399fa628e2652d1fce41f519ab51a2b4/ab - activityservice/src/main/java/com/aldimbilet/activityservice/AldimbiletActivityServicesApplication.java", "visit_date": "2023-02-26T15:01:02.367222", "added": "2024-11-19T01:21:47.089896+00:00", "created": "2021-02-02T11:26:59", "int_score": 2, "score": 2.34375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0037.json.gz" }
import pytest from googleform.questions.duration import DurationQuestion @pytest.fixture(scope="module") def duration_paths(fixture_path): return [ fixture_path("duration.html"), ] @pytest.fixture(scope="module") def not_duration_paths(fixture_path): return [ fixture_path("checkbox.html"), fixture_path("date_time.html"), fixture_path("date_year_time.html"), fixture_path("date_year.html"), fixture_path("date.html"), fixture_path("dropdown.html"), fixture_path("long_text.html"), fixture_path("other_checkbox.html"), fixture_path("other_radio_list.html"), fixture_path("radio_list.html"), fixture_path("radio_scale.html"), fixture_path("required_dropdown.html"), fixture_path("required_radio_list.html"), fixture_path("short_text.html"), fixture_path("time.html"), ] @pytest.fixture(scope="module") def duration_questions(get_question, duration_paths): return list(map(get_question, duration_paths)) @pytest.fixture(scope="module") def not_duration_questions(get_question, not_duration_paths): return list(map(get_question, not_duration_paths)) def test_distinguish_duration(duration_questions, not_duration_questions): for question in duration_questions: assert DurationQuestion.is_this_question(question["tree"]) is True for question in not_duration_questions: assert DurationQuestion.is_this_question(question["tree"]) is False
fe183d0e6d134162b4234712bbe0d11423a75473
{ "blob_id": "fe183d0e6d134162b4234712bbe0d11423a75473", "branch_name": "refs/heads/master", "committer_date": "2019-02-15T03:48:59", "content_id": "4aaca3ddf55fcea1f8c1775ced904bac7e665ec5", "detected_licenses": [ "MIT" ], "directory_id": "43aeb4ec28ddca29f950474534dd0a813f1ecf05", "extension": "py", "filename": "test_duration.py", "fork_events_count": 0, "gha_created_at": "2020-05-22T06:12:03", "gha_event_created_at": "2020-05-22T06:12:04", "gha_language": null, "gha_license_id": "MIT", "github_id": 266032714, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1521, "license": "MIT", "license_type": "permissive", "path": "/tests/unit_tests/questions/test_duration.py", "provenance": "stack-edu-0055.json.gz:356103", "repo_name": "fruch/google-form-python", "revision_date": "2019-02-15T03:48:59", "revision_id": "e0de991bd7d18832fde36fc3aca972064e1a77b6", "snapshot_id": "fb753041fac5edb7eda85bc985bd41bc5984ed5e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/fruch/google-form-python/e0de991bd7d18832fde36fc3aca972064e1a77b6/tests/unit_tests/questions/test_duration.py", "visit_date": "2022-09-15T20:19:47.077159", "added": "2024-11-18T20:31:13.138909+00:00", "created": "2019-02-15T03:48:59", "int_score": 2, "score": 2.390625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0073.json.gz" }
/* $Id$ */ #ifndef HTTP_BUFFERING_H #define HTTP_BUFFERING_H #include "memfile.h" typedef enum { INITIAL, /* HEADER */ HEADER_FIRST_LINE, HEADER_PARSING, HEADER_PARSING_CONTENT_LENGTH, HEADER_PARSING_TRANSFER_ENCODING, CONTENT_LENGTH, /* CHUNK */ CHUNK_HEX, CHUNK_DATA, CHUNK_CRLF, CHUNK_READ_ENT_HEADER, CHUNK_LAST, MULTIPART_BYTERANGE, UNTIL_CLOSE, PARSING_COMPLETE } http_parsing_state; typedef struct { unsigned char invalidFlag; long flushed_content_len; long content_buf_offset; long parsed_data_size; long flushed_data_size; long wanted_data_size; http_parsing_state state; } http_parsing_t; typedef struct { http_parsing_t *parsing_status; memfile *recvbuffer; } http_buffering_t; /* By Pattern */ char* http_buffering_getUntil(http_buffering_t *handle, char **buf, char *pattern); int http_buffering_fill_memfile_Until(http_buffering_t *handle, memfile *buf, char *pattern); /* By Bytes */ int http_buffering_getNByte(http_buffering_t *handle, void **buf, int size); int http_buffering_fill_memfile_NByte(http_buffering_t *handle, memfile *mfile, int size); /* By Connection Close */ int http_buffering_fill_memfile_UntilClose(http_buffering_t *handle, memfile *mfile, char *connClosedFlag); #endif //HTTP_BUFFERING_H
1fda87d86ae8b9ff12f2a72e9af79fa60fe62f72
{ "blob_id": "1fda87d86ae8b9ff12f2a72e9af79fa60fe62f72", "branch_name": "refs/heads/master", "committer_date": "2014-05-13T07:05:07", "content_id": "34620c7bce0fc8ca3b241db7d9733c46a8b1253c", "detected_licenses": [ "MIT" ], "directory_id": "f8ca09031c44bdf552380b2bc082f81468676c3c", "extension": "h", "filename": "http_buffering.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1289, "license": "MIT", "license_type": "permissive", "path": "/modules/mod_http_client/http_buffering.h", "provenance": "stack-edu-0000.json.gz:85641", "repo_name": "aragorn/wisebot", "revision_date": "2014-05-13T07:05:07", "revision_id": "fff0b4db3a14fb4f03642e3a7bb70434465265a5", "snapshot_id": "ac50b211092b4300008d5b4b299828fc2363ab31", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/aragorn/wisebot/fff0b4db3a14fb4f03642e3a7bb70434465265a5/modules/mod_http_client/http_buffering.h", "visit_date": "2016-09-06T02:58:35.912406", "added": "2024-11-18T23:05:58.132919+00:00", "created": "2014-05-13T07:05:07", "int_score": 2, "score": 2.09375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0018.json.gz" }
// Code generated by the Pulumi SDK Generator DO NOT EDIT. // *** WARNING: Do not edit by hand unless you're certain you know what you are doing! *** package v2 import ( "context" "reflect" "github.com/pulumi/pulumi-google-native/sdk/go/google/internal" "github.com/pulumi/pulumi/sdk/v3/go/pulumi" ) // Retrieve an inbound SAML configuration for an Identity Toolkit project. func LookupInboundSamlConfig(ctx *pulumi.Context, args *LookupInboundSamlConfigArgs, opts ...pulumi.InvokeOption) (*LookupInboundSamlConfigResult, error) { opts = internal.PkgInvokeDefaultOpts(opts) var rv LookupInboundSamlConfigResult err := ctx.Invoke("google-native:identitytoolkit/v2:getInboundSamlConfig", args, &rv, opts...) if err != nil { return nil, err } return &rv, nil } type LookupInboundSamlConfigArgs struct { InboundSamlConfigId string `pulumi:"inboundSamlConfigId"` Project *string `pulumi:"project"` TenantId string `pulumi:"tenantId"` } type LookupInboundSamlConfigResult struct { // The config's display name set by developers. DisplayName string `pulumi:"displayName"` // True if allows the user to sign in with the provider. Enabled bool `pulumi:"enabled"` // The SAML IdP (Identity Provider) configuration when the project acts as the relying party. IdpConfig GoogleCloudIdentitytoolkitAdminV2IdpConfigResponse `pulumi:"idpConfig"` // The name of the InboundSamlConfig resource, for example: 'projects/my-awesome-project/inboundSamlConfigs/my-config-id'. Ignored during create requests. Name string `pulumi:"name"` // The SAML SP (Service Provider) configuration when the project acts as the relying party to receive and accept an authentication assertion issued by a SAML identity provider. SpConfig GoogleCloudIdentitytoolkitAdminV2SpConfigResponse `pulumi:"spConfig"` } func LookupInboundSamlConfigOutput(ctx *pulumi.Context, args LookupInboundSamlConfigOutputArgs, opts ...pulumi.InvokeOption) LookupInboundSamlConfigResultOutput { return pulumi.ToOutputWithContext(context.Background(), args). ApplyT(func(v interface{}) (LookupInboundSamlConfigResult, error) { args := v.(LookupInboundSamlConfigArgs) r, err := LookupInboundSamlConfig(ctx, &args, opts...) var s LookupInboundSamlConfigResult if r != nil { s = *r } return s, err }).(LookupInboundSamlConfigResultOutput) } type LookupInboundSamlConfigOutputArgs struct { InboundSamlConfigId pulumi.StringInput `pulumi:"inboundSamlConfigId"` Project pulumi.StringPtrInput `pulumi:"project"` TenantId pulumi.StringInput `pulumi:"tenantId"` } func (LookupInboundSamlConfigOutputArgs) ElementType() reflect.Type { return reflect.TypeOf((*LookupInboundSamlConfigArgs)(nil)).Elem() } type LookupInboundSamlConfigResultOutput struct{ *pulumi.OutputState } func (LookupInboundSamlConfigResultOutput) ElementType() reflect.Type { return reflect.TypeOf((*LookupInboundSamlConfigResult)(nil)).Elem() } func (o LookupInboundSamlConfigResultOutput) ToLookupInboundSamlConfigResultOutput() LookupInboundSamlConfigResultOutput { return o } func (o LookupInboundSamlConfigResultOutput) ToLookupInboundSamlConfigResultOutputWithContext(ctx context.Context) LookupInboundSamlConfigResultOutput { return o } // The config's display name set by developers. func (o LookupInboundSamlConfigResultOutput) DisplayName() pulumi.StringOutput { return o.ApplyT(func(v LookupInboundSamlConfigResult) string { return v.DisplayName }).(pulumi.StringOutput) } // True if allows the user to sign in with the provider. func (o LookupInboundSamlConfigResultOutput) Enabled() pulumi.BoolOutput { return o.ApplyT(func(v LookupInboundSamlConfigResult) bool { return v.Enabled }).(pulumi.BoolOutput) } // The SAML IdP (Identity Provider) configuration when the project acts as the relying party. func (o LookupInboundSamlConfigResultOutput) IdpConfig() GoogleCloudIdentitytoolkitAdminV2IdpConfigResponseOutput { return o.ApplyT(func(v LookupInboundSamlConfigResult) GoogleCloudIdentitytoolkitAdminV2IdpConfigResponse { return v.IdpConfig }).(GoogleCloudIdentitytoolkitAdminV2IdpConfigResponseOutput) } // The name of the InboundSamlConfig resource, for example: 'projects/my-awesome-project/inboundSamlConfigs/my-config-id'. Ignored during create requests. func (o LookupInboundSamlConfigResultOutput) Name() pulumi.StringOutput { return o.ApplyT(func(v LookupInboundSamlConfigResult) string { return v.Name }).(pulumi.StringOutput) } // The SAML SP (Service Provider) configuration when the project acts as the relying party to receive and accept an authentication assertion issued by a SAML identity provider. func (o LookupInboundSamlConfigResultOutput) SpConfig() GoogleCloudIdentitytoolkitAdminV2SpConfigResponseOutput { return o.ApplyT(func(v LookupInboundSamlConfigResult) GoogleCloudIdentitytoolkitAdminV2SpConfigResponse { return v.SpConfig }).(GoogleCloudIdentitytoolkitAdminV2SpConfigResponseOutput) } func init() { pulumi.RegisterOutputType(LookupInboundSamlConfigResultOutput{}) }
da5e9c906f9875d7b81687e4ebe27e6fe7dded52
{ "blob_id": "da5e9c906f9875d7b81687e4ebe27e6fe7dded52", "branch_name": "refs/heads/master", "committer_date": "2023-07-20T04:25:48", "content_id": "00fae03e6229d8b2785a9a0557f154bf4c18eafc", "detected_licenses": [ "BSD-3-Clause", "Apache-2.0" ], "directory_id": "ba694353a3cb1cfd02a6773b40f693386d0dba39", "extension": "go", "filename": "getInboundSamlConfig.go", "fork_events_count": 16, "gha_created_at": "2020-12-22T16:39:01", "gha_event_created_at": "2023-09-13T00:28:04", "gha_language": "Python", "gha_license_id": "Apache-2.0", "github_id": 323680373, "is_generated": true, "is_vendor": false, "language": "Go", "length_bytes": 5053, "license": "BSD-3-Clause,Apache-2.0", "license_type": "permissive", "path": "/sdk/go/google/identitytoolkit/v2/getInboundSamlConfig.go", "provenance": "stack-edu-0016.json.gz:243449", "repo_name": "pulumi/pulumi-google-native", "revision_date": "2023-07-20T04:25:48", "revision_id": "124d255e5b7f5440d1ef63c9a71e4cc1d661cd10", "snapshot_id": "cc57af8bd3d1d6b76f1f48333ed1f1b31d56f92b", "src_encoding": "UTF-8", "star_events_count": 69, "url": "https://raw.githubusercontent.com/pulumi/pulumi-google-native/124d255e5b7f5440d1ef63c9a71e4cc1d661cd10/sdk/go/google/identitytoolkit/v2/getInboundSamlConfig.go", "visit_date": "2023-08-25T00:18:00.300230", "added": "2024-11-18T21:59:12.562421+00:00", "created": "2023-07-20T04:25:48", "int_score": 2, "score": 2.03125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0034.json.gz" }
package com.hqb.patshop.config.shiro; import com.hqb.patshop.common.api.CommonResult; import com.hqb.patshop.common.api.IErrorCode; import org.apache.shiro.ShiroException; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; import javax.servlet.http.HttpServletRequest; @RestControllerAdvice public class ExceptionController { // 捕捉shiro的异常 @ResponseStatus(HttpStatus.UNAUTHORIZED) @ExceptionHandler(ShiroException.class) public CommonResult handle401(ShiroException e) { return CommonResult.forbidden(null); } // 捕捉UnauthorizedException @ResponseStatus(HttpStatus.UNAUTHORIZED) @ExceptionHandler(UnauthorizedException.class) public CommonResult handle401() { return CommonResult.forbidden(null); } // 捕捉其他所有异常 @ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public CommonResult globalException(HttpServletRequest request, Throwable ex) { return CommonResult.failed(new IErrorCode() { @Override public long getCode() { return getStatus(request).value(); } @Override public String getMessage() { return ex.getMessage() + " —————— " + ex.getCause(); } }); } private HttpStatus getStatus(HttpServletRequest request) { Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); if (statusCode == null) { return HttpStatus.INTERNAL_SERVER_ERROR; } return HttpStatus.valueOf(statusCode); } }
cdd0b5c880ab06f8ef9f15ad09b89b8d03275260
{ "blob_id": "cdd0b5c880ab06f8ef9f15ad09b89b8d03275260", "branch_name": "refs/heads/master", "committer_date": "2021-10-16T15:23:58", "content_id": "a28503b9788cd23ac548d417b58935b80e70515f", "detected_licenses": [ "Apache-2.0" ], "directory_id": "a7c7278ba5ac0f2f4f4ac9f14674ffc6c6ea67d9", "extension": "java", "filename": "ExceptionController.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1828, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/main/java/com/hqb/patshop/config/shiro/ExceptionController.java", "provenance": "stack-edu-0028.json.gz:214279", "repo_name": "huangqiubin/Patshop", "revision_date": "2021-10-16T15:23:58", "revision_id": "1c003ac759b1c2bef07ee297ab86119b53156d9a", "snapshot_id": "a1698c4dd6891297f48061b61efa57ace317b0e1", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/huangqiubin/Patshop/1c003ac759b1c2bef07ee297ab86119b53156d9a/src/main/java/com/hqb/patshop/config/shiro/ExceptionController.java", "visit_date": "2023-08-16T17:06:39.251178", "added": "2024-11-18T23:43:35.427848+00:00", "created": "2021-10-16T15:23:58", "int_score": 2, "score": 2.203125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0046.json.gz" }
import { PolymerElement, html } from "../../node_modules/@polymer/polymer/polymer-element.js"; import "../../node_modules/@polymer/iron-component-page/iron-component-page.js"; /* Extend the base PolymerElement class */ class Docs extends PolymerElement { /* Define a template for the new element */ static get template() { return html` <style> iron-component-page { --iron-component-page-header-color: #1A9FFF; } </style> <iron-component-page></iron-component-page> `; } } /* Register the new element with the browser */ window.customElements.define('docs-app', Docs);
13b0ea82ad3e78eb3af4086cdeecf7657d10e6eb
{ "blob_id": "13b0ea82ad3e78eb3af4086cdeecf7657d10e6eb", "branch_name": "refs/heads/master", "committer_date": "2020-06-22T09:47:04", "content_id": "fda4f0c86e037eed06ad5912ba7514b8ac7adf50", "detected_licenses": [ "Apache-2.0", "MIT", "BSD-3-Clause" ], "directory_id": "a274079b19a1234737ad0c380f6e13018691e2d9", "extension": "js", "filename": "docs.js", "fork_events_count": 73, "gha_created_at": "2015-11-02T16:21:20", "gha_event_created_at": "2021-01-04T15:30:53", "gha_language": "JavaScript", "gha_license_id": "NOASSERTION", "github_id": 45406296, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 645, "license": "Apache-2.0,MIT,BSD-3-Clause", "license_type": "permissive", "path": "/build/docs/src/demo-app/docs.js", "provenance": "stack-edu-0037.json.gz:91180", "repo_name": "MyScript/myscript-math-web", "revision_date": "2020-06-22T09:47:04", "revision_id": "09825dab372a31eeb4ba6c1827f61469d69417a3", "snapshot_id": "b84644087c9bc3a47650233c0fb78081f23f5402", "src_encoding": "UTF-8", "star_events_count": 259, "url": "https://raw.githubusercontent.com/MyScript/myscript-math-web/09825dab372a31eeb4ba6c1827f61469d69417a3/build/docs/src/demo-app/docs.js", "visit_date": "2021-01-17T06:06:04.734374", "added": "2024-11-18T19:14:15.304160+00:00", "created": "2020-06-22T09:47:04", "int_score": 2, "score": 2.0625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0055.json.gz" }
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Json extends CI_Controller { public function __construct() { parent::__construct(); $this->load->helper(array('general', 'path', 'url')); $beo = $this->security->xss_clean($this->input->post('beo')); if(empty($beo) && $beo!='038') { echo json_encode( array( 'ok' => 0, 'msg' => 'No auth found' ) ); exit(); } } public function view(/*$id_marker = null*/) { /*if($id_marker != null) { $all = $this->db->where('id_marker', $id_marker); }*/ $all = $this->db->order_by('id_marker', 'asc')->get('beo_bengkel'); foreach ($all->result() as $v) { $profile = json_decode($v->profile); $latlng = json_decode($v->latlng); $v->name = $profile->name; $key = $v->id_marker; $result[] = array( "id" => $v->id, "id_marker" => $v->id_marker, "name" => $profile->name, "company" => $profile->company, "contact" => $profile->contact, "email" => $profile->email, "location" => $profile->location, "price" => $profile->price, "lat" => $latlng->lat, "lng" => $latlng->lng, "created" => $v->created, "updated" => $v->updated, ); } $output["ok"] = 1; $output["result"] = $result; pretty_json($output); } public function list_item() { $page = intval($this->uri->segment(3)); $per_page = 10; $offset = $page == 0 ? $page : $page * $per_page - $per_page; $data = $this->db->order_by('created', 'desc') ->limit($per_page, $offset) ->get('beo_bengkel'); $total = $this->db->get('beo_bengkel') ->num_rows(); foreach ($data->result() as $v) { $profile = json_decode($v->profile); $latlng = json_decode($v->latlng); $v->name = $profile->name; $key = $v->id_marker; $result[] = array( "id" => $v->id, "id_marker" => $v->id_marker, "name" => $profile->name, "company" => $profile->company, "contact" => $profile->contact, "email" => $profile->email, "location" => $profile->location, "price" => $profile->price, "lat" => $latlng->lat, "lng" => $latlng->lng, "created" => $v->created, "updated" => $v->updated, ); } $output['ok'] = 1; $output['result'] = array( 'list' => $result, 'per_page' => $per_page, 'total_data' => $total, 'total_page' => ceil($total/$per_page) ); pretty_json($output); } }
6e1c123115ae231407fc7b863dc4d2594d0c21c7
{ "blob_id": "6e1c123115ae231407fc7b863dc4d2594d0c21c7", "branch_name": "refs/heads/master", "committer_date": "2019-03-16T01:59:10", "content_id": "b30640f8a18b1b4c3bdb35e10cb6211efb161332", "detected_licenses": [ "MIT" ], "directory_id": "e975026aac8b7081a90e5a143178c275f77e895d", "extension": "php", "filename": "Json.php", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 46739571, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2824, "license": "MIT", "license_type": "permissive", "path": "/application/controllers/Json.php", "provenance": "stack-edu-0049.json.gz:316306", "repo_name": "utqinadhif/onbeng", "revision_date": "2019-03-16T01:59:10", "revision_id": "340c4af245a79de8b0ed60805efd7fa53bdf4ad2", "snapshot_id": "e3aaa32e66c5a88aa79bd99ecc529425c90a5031", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/utqinadhif/onbeng/340c4af245a79de8b0ed60805efd7fa53bdf4ad2/application/controllers/Json.php", "visit_date": "2021-01-09T21:58:04.968060", "added": "2024-11-18T18:30:50.092650+00:00", "created": "2019-03-16T01:59:10", "int_score": 2, "score": 2.1875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0067.json.gz" }
#!/bin/bash # Script used to clear the results and mesh from the model and reset the # variables; this should be run before dockerRun.sh is run # Philip Cardiff, UCD # Feb-21 docker run -it --mount src=$(PWD),target=/home/app/model,type=bind \ philippic/foam-extend-4.0-ubuntu18.04:latest bash -c \ 'source /home/app/foam/foam-extend-4.0/etc/bashrc > /dev/null \ && cd model && \rm -rf 0.* [1-9]* probes case.foam \ && \cp 0/org/U 0/ && \cp constant/org/transportProperties constant'
f387eba14c43c9fe675d957ab9cf9dbb81c9e601
{ "blob_id": "f387eba14c43c9fe675d957ab9cf9dbb81c9e601", "branch_name": "refs/heads/master", "committer_date": "2021-02-17T20:30:21", "content_id": "68ea1e0d5fcc59b9403bd3c53d62ce7b25915704", "detected_licenses": [ "MIT" ], "directory_id": "da641f9112b278d0cac1070c758dde80f6c95a48", "extension": "sh", "filename": "dockerClean.sh", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 280244863, "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 514, "license": "MIT", "license_type": "permissive", "path": "/simulator/elbowFlow2d/dockerClean.sh", "provenance": "stack-edu-0069.json.gz:585537", "repo_name": "andrewcparnell/intro_emulators", "revision_date": "2021-02-17T20:30:21", "revision_id": "c7befe58cf7f9c384003fe4ff85d03967dee50ec", "snapshot_id": "74fafa611997b9f6fc92803f5bce296c5931390d", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/andrewcparnell/intro_emulators/c7befe58cf7f9c384003fe4ff85d03967dee50ec/simulator/elbowFlow2d/dockerClean.sh", "visit_date": "2023-03-10T16:33:06.551902", "added": "2024-11-19T00:18:48.193443+00:00", "created": "2021-02-17T20:30:21", "int_score": 3, "score": 2.671875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0087.json.gz" }
package edu.isi.karma.rdf; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CommandLineArgumentParser { private static Logger logger = LoggerFactory.getLogger(CommandLineArgumentParser.class); private CommandLineArgumentParser() { } public static CommandLine parse(String args[], Options options, String commandName) { CommandLineParser parser = new BasicParser(); CommandLine cl = null; try { /** * PARSE THE COMMAND LINE ARGUMENTS * */ cl = parser.parse(options, args); if (cl == null || cl.getOptions().length == 0 || cl.hasOption("help")) { HelpFormatter hf = new HelpFormatter(); hf.printHelp(commandName, options); return null; } } catch (Exception e) { logger.error("Error occured while parsing arguments!", e); return cl; } return cl; } }
7a3b0ad4f34453aecf90e2087be7dc99f327d8dd
{ "blob_id": "7a3b0ad4f34453aecf90e2087be7dc99f327d8dd", "branch_name": "refs/heads/master", "committer_date": "2023-08-31T16:40:28", "content_id": "b722a432a0efab6b392db2e66a851ee3e323fcc8", "detected_licenses": [ "Apache-2.0" ], "directory_id": "3999c1034a70935846d7208ff0b69fe537814a40", "extension": "java", "filename": "CommandLineArgumentParser.java", "fork_events_count": 187, "gha_created_at": "2011-09-23T06:58:53", "gha_event_created_at": "2023-09-06T23:14:09", "gha_language": "Java", "gha_license_id": "Apache-2.0", "github_id": 2442452, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1087, "license": "Apache-2.0", "license_type": "permissive", "path": "/karma-offline/src/main/java/edu/isi/karma/rdf/CommandLineArgumentParser.java", "provenance": "stack-edu-0020.json.gz:80927", "repo_name": "usc-isi-i2/Web-Karma", "revision_date": "2023-08-31T16:40:28", "revision_id": "05392615086538e95322278e705f76f9bbf2ed71", "snapshot_id": "2f15b7759ce3338702f3da3a06fbee8ba118de8e", "src_encoding": "UTF-8", "star_events_count": 526, "url": "https://raw.githubusercontent.com/usc-isi-i2/Web-Karma/05392615086538e95322278e705f76f9bbf2ed71/karma-offline/src/main/java/edu/isi/karma/rdf/CommandLineArgumentParser.java", "visit_date": "2023-09-02T05:18:12.455691", "added": "2024-11-19T02:48:51.704484+00:00", "created": "2023-08-31T16:40:28", "int_score": 2, "score": 2.375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0038.json.gz" }
import { run, runWithoutIncludes } from "../interpreter"; import { TRUE, FALSE, NIL } from "../parser"; import { debug } from "../debug"; let testsRun = 0; let testsOK = 0; let testsFail = 0; let IN_SUITE = false; export function runSuite(suite: () => void) { let outerSuite = !IN_SUITE; let start; if (outerSuite) { console.log(''); console.log('Running tests...'); start = new Date().getTime(); IN_SUITE = true; } suite(); if (outerSuite) { let end = new Date().getTime(); IN_SUITE = true; console.log(`Tests run: ${testsRun}. OK: ${testsOK}. Fail: ${testsFail} (${end - start} milliseconds)`); console.log(''); IN_SUITE = false; } } export function assertRun(program: string, result: any, runWithIncludes = true) { debug("Starting test: -----------------\n" + program + '\n--------------------------------\n'); testsRun++; let ret; try { if (runWithIncludes) { ret = run(program); } else { ret = runWithoutIncludes(program); } } catch (ex) { testsFail++; console.log("Exception running program " + program); console.log("Exception message: " + ex + '\n\n'); return; } if (ret != result) { testsFail++; console.log("Error running program " + program); console.log(`Expected: ${result}. Got '${JSON.stringify(ret)}' instead\n\n`); return; } debug("\nFinishing test--------------------\n\n"); testsOK++; } export function assertRunError(program: string, errorMsg: string) { debug("Starting test: -----------------\n" + program + '\n--------------------------------\n'); testsRun++; try { run(program); } catch (ex) { if (("" + ex).indexOf(errorMsg) >= 0) { testsOK++; debug("\nFinishing test--------------------\n\n"); } else { console.log("Error running program " + program); console.log("Expected exception containing '" + errorMsg + "', but exception was '" + ex + "'\n\n"); testsFail++; } return; } console.log("Error running program " + program); console.log("Expected exception containing '" + errorMsg + "', but no exception was thrown"); testsFail++; } function assert(condition: boolean, msg?: string) { if (condition) return; throw "Assertion failed: " + msg; } export function assertEquals(test: () => any, result: any, name: string = "(anon test)") { debug("Starting test: -----------------\n" + name + '\n--------------------------------\n'); testsRun++; let ret; try { ret = test(); } catch (ex) { testsFail++; console.log("Exception running test" + name); console.log("Exception message: " + ex + '\n\n'); return; } if (ret != result) { testsFail++; console.log("Error running program " + name) ; console.log(`Expected: ${result}. Got '${JSON.stringify(ret)}' instead\n\n`); return; } debug("\nFinishing test--------------------\n\n"); testsOK++; } export function assertError(body: () => any, errorMsg: string, name: string) { debug("Starting test: -----------------\n" + name + '\n--------------------------------\n'); testsRun++; try { body(); } catch (ex) { if (ex.indexOf(errorMsg) < 0) { console.log("Error running test " + name) ; console.log(`Expected: ${errorMsg}. Got '${ex}' instead\n\n`); testsFail++; return; } } testsOK++; debug("\nFinishing test--------------------\n\n"); }
aab0cbf72c57cee966737cb2eb6ad2bb01e787e1
{ "blob_id": "aab0cbf72c57cee966737cb2eb6ad2bb01e787e1", "branch_name": "refs/heads/master", "committer_date": "2020-06-20T20:57:59", "content_id": "d34f1777cc10c446c87d1183c8ced528a8470537", "detected_licenses": [ "Apache-2.0" ], "directory_id": "6ad5288a38a9e1d46b8eef7013eea6199279f1bb", "extension": "ts", "filename": "testing.ts", "fork_events_count": 3, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 115457317, "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3718, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/tests/testing.ts", "provenance": "stack-edu-0074.json.gz:736526", "repo_name": "pedroabelleira/jlisp", "revision_date": "2020-06-20T20:57:59", "revision_id": "49aaaeb837116c0889caa865c728c1519ef974c5", "snapshot_id": "e923cfd32e1dc5de89d68b79962a5e191aed0ca2", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/pedroabelleira/jlisp/49aaaeb837116c0889caa865c728c1519ef974c5/src/tests/testing.ts", "visit_date": "2022-11-07T16:00:46.375910", "added": "2024-11-18T22:19:58.473664+00:00", "created": "2020-06-20T20:57:59", "int_score": 3, "score": 2.71875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0092.json.gz" }
/** * Created by NLFSoftware on 07/04/16. */ 'use strict'; angular.module('NFRiaCowboy.boot', ['ngRoute']) .config(['$routeProvider', function ($routeProvider) { $routeProvider.when('/boot', { templateUrl: 'boot/boot.html', controller: 'BootController' }); }]) .controller('BootController', ['$scope', function ($scope) { var voice = { amplitude: 100, wordgap: 1, pitch: 105, speed: 160, variant: 'f2' }; meSpeak.loadConfig("components/meSpeak/mespeak_config.json"); meSpeak.loadVoice("components/meSpeak/voices/en/en.json"); //meSpeak.speak("Welcome to NFRiaCowboy's Playground.", voice); var nfriacowboyBoot = new ElizaBot(); $scope.conversation = []; $scope.humanText = ""; $scope.elizaReset = function() { nfriacowboyBoot.reset(); elizaStep(); }; $scope.handleNewInput = function() { var nfriacowboyOutput = ""; if (nfriacowboyBoot.quit) { $scope.humanText = ''; if (confirm("This session is over.\nStart over?")) elizaReset(); return; } else if ($scope.humanText != '') { $scope.conversation.push({ id: new Date().getTime(), msg: '<div class="bubble human">' + $scope.humanText + '</div>'}); nfriacowboyOutput =nfriacowboyBoot.transform($scope.humanText); } else if ($scope.conversation.length == 0) { nfriacowboyOutput = nfriacowboyBoot.getInitial(); } meSpeak.speak(nfriacowboyOutput, voice); $scope.conversation.push({ id: new Date().getTime(), msg: '<div class="imgCarmen"></div><div class="bubble carmen">' + nfriacowboyOutput + '</div>'}); $scope.humanText = ''; }; $scope.handleNewInput(); $('#humanTextInput').keyup(function(e){ var code = (e.keyCode ? e.keyCode : e.which); if(code == 13 && $scope.humanText != '') { //Enter keycode $scope.handleNewInput(); $scope.$apply(); } }); }]);
d11450ffab427d3d9a655a51f7bed9f3868edc39
{ "blob_id": "d11450ffab427d3d9a655a51f7bed9f3868edc39", "branch_name": "refs/heads/master", "committer_date": "2016-04-09T09:20:01", "content_id": "f986f83e4ffceebe60aa7c5265355ac8944e1b1e", "detected_licenses": [ "MIT" ], "directory_id": "e5293c7f497956e7d0a29b34ca55930cedd01c47", "extension": "js", "filename": "boot.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 55763453, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2332, "license": "MIT", "license_type": "permissive", "path": "/app/boot/boot.js", "provenance": "stack-edu-0037.json.gz:436251", "repo_name": "nfriacowboy/NFRiacowboy.com", "revision_date": "2016-04-09T09:20:01", "revision_id": "8340b5af9a733c226b459e7b39571009f7c1980e", "snapshot_id": "b5d1157c439c9bbb152fdb79e8e826f086bad5d8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/nfriacowboy/NFRiacowboy.com/8340b5af9a733c226b459e7b39571009f7c1980e/app/boot/boot.js", "visit_date": "2021-01-10T07:04:49.838611", "added": "2024-11-18T19:43:01.935022+00:00", "created": "2016-04-09T09:20:01", "int_score": 2, "score": 2.328125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0055.json.gz" }
<?php use dmitrybukhonov\adyammy\widgets\factory\CustomBanner; /** * @var CustomBanner $banner */ ?> <?php if ($banner->getImageUrl()) : ?> <div class="module"> <div class="bns <?= $banner->getImageClass() ?> banner-position-<?= $banner->getPositionId() ?>"> <a href="<?= $banner->getBannerUrl() ?>" target="_blank"> <img src="<?= $banner->getImageUrl() ?>" alt="<?= $banner->getTitle() ?>"> </a> </div> </div> <?php endif; ?>
1b1328d7e89fcb80abd8447182dfad43298c0a8a
{ "blob_id": "1b1328d7e89fcb80abd8447182dfad43298c0a8a", "branch_name": "refs/heads/master", "committer_date": "2023-05-01T17:41:23", "content_id": "d58d2e8e602b7ef7629da7a2d5b664cd7d83931f", "detected_licenses": [ "MIT" ], "directory_id": "80b196f05372495d0ce9a3722cc7ea3d75c5eb6b", "extension": "php", "filename": "custom-banner.php", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 634965110, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 495, "license": "MIT", "license_type": "permissive", "path": "/src/widgets/views/custom-banner.php", "provenance": "stack-edu-0048.json.gz:244575", "repo_name": "dmitrybukhonov/yii2-ad-yammy", "revision_date": "2023-05-01T17:41:23", "revision_id": "0492300a9436b33439026703a9216dc49d52ccc2", "snapshot_id": "7ee46c1c8f47645b2e7aab26ccc2b0c969b629b1", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/dmitrybukhonov/yii2-ad-yammy/0492300a9436b33439026703a9216dc49d52ccc2/src/widgets/views/custom-banner.php", "visit_date": "2023-08-11T14:27:23.150278", "added": "2024-11-19T02:55:31.522546+00:00", "created": "2023-05-01T17:41:23", "int_score": 2, "score": 2.1875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0066.json.gz" }
import { IRssFilter, IRssFeed, IRssUpdate } from "./types"; /** * Parse an array of raw uTorrent RSS updates into the new format */ export function rssUpdates (updates: Array<any>) { let result: Array<IRssUpdate> = []; for (let update of updates) { result.push({ name : update[0], name_full : update[1], url : update[2], quality : update[3], codec : update[4], timestamp : update[5], season : update[6], episode : update[7], episode_to: update[8], feed_id : update[9], repack : update[10], in_history: update[11] }); } return result; } /** * Parse an array of raw uTorrent RSS feeds into the new format */ export function rssFeeds (feeds: Array<any>) { let result: Array<IRssFeed> = []; for (let feed of feeds) { result.push({ id : feeds[0], enabled : feeds[1], use_feed_title: feeds[2], user_selected : feeds[3], programmed : feeds[4], download_state: feeds[5], url : feeds[6], next_update : feeds[7], history : rssUpdates(feeds[8]) }); } return result; } /** * Parse an array of raw uTorrent RSS feeds into the new format */ export function rssFilters (filters: Array<any>) { let result: Array<IRssFilter> = []; for (let filter of filters) { result.push({ id : filters[0], flags : filters[1], name : filters[2], filter : filters[3], not_filter : filters[4], directory : filters[5], feed : filters[6], quality : filters[7], label : filters[8], postpone_mode : filters[9], last_match : filters[10], smart_ep_filter : filters[11], repack_ep_filter : filters[12], episode_filter_str : filters[13], episode_filter : filters[14], resolving_candidate: filters[15] }); } return result; } // /** // * Parse an array of raw uTorrent torrents into the new format // */ // export function torrents (torrents: Array<any>) { // let result: Array<ITorrent> = []; // for (let torrent of torrents) { // result.push({ // hash : torrent[0], // status : torrent[1], // name : torrent[2], // size : torrent[3], // progress : torrent[4] / 1000, // downloaded : torrent[5], // uploaded : torrent[6], // up_down_ratio : torrent[7] / 1000, // upload_speed : torrent[8], // download_speed : torrent[9], // time_remaining : torrent[10], // label : torrent[11], // peers_connected: torrent[12], // peers_in_swarm : torrent[13], // seeds_connected: torrent[14], // seeds_in_swarm : torrent[15], // availability : torrent[16], // queue_order : torrent[18], // download_url : torrent[19], // rss_feed_url : torrent[20], // status_message : torrent[21], // stream_id : torrent[22], // date_added : new Date(torrent[23] * 1000), // date_completed : torrent[24] ? new Date(torrent[24] * 1000) : null, // app_update_url : torrent[25] // }); // } // return result; // }
f72a197123b7985a515b031d337fed9d8b135d3a
{ "blob_id": "f72a197123b7985a515b031d337fed9d8b135d3a", "branch_name": "refs/heads/master", "committer_date": "2019-04-25T23:24:55", "content_id": "b7686b364535ed363cfb19b6f0e9885c9ff9ab48", "detected_licenses": [ "MIT" ], "directory_id": "6bc42ea55fdccafb2f56f64d4e7e5e3d5402ec95", "extension": "ts", "filename": "parse.ts", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3150, "license": "MIT", "license_type": "permissive", "path": "/src/parse.ts", "provenance": "stack-edu-0072.json.gz:371582", "repo_name": "trungkien006/utorrent-web-api", "revision_date": "2019-04-25T23:24:55", "revision_id": "b59f1d91e109464c9089eac6dfcb6e8aedeef547", "snapshot_id": "2812e819cc0947cd80536bbbbb9b2cc91673031b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/trungkien006/utorrent-web-api/b59f1d91e109464c9089eac6dfcb6e8aedeef547/src/parse.ts", "visit_date": "2022-01-11T20:47:15.540774", "added": "2024-11-19T02:09:31.970247+00:00", "created": "2019-04-25T23:24:55", "int_score": 2, "score": 2.3125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0090.json.gz" }
using System; using System.Collections.ObjectModel; using System.Linq; using TcOpen.Inxton.Security; using TcOpen.Inxton.Input; using System.Windows; namespace TcOpen.Inxton.Local.Security.Wpf { public class AllUsersViewModel : BaseUserViewModel { public ObservableCollection<UserData> AllUsersFiltered { get; set; } public ObservableCollection<String> AllRolesFiltered { get; set; } private UserData _selectedUser; void UpateCommands() { AvailableToCurrentRoleCommand.RaiseCanExecuteChanged(); CurrentToAvailableRoleCommand.RaiseCanExecuteChanged(); AddMultipleRolesCommand .RaiseCanExecuteChanged(); StarEditUserCommand .RaiseCanExecuteChanged(); DeleteUserCommand .RaiseCanExecuteChanged(); AddRoleCommand .RaiseCanExecuteChanged(); RemoveRoleCommand.RaiseCanExecuteChanged(); } public UserData SelectedUser { get => _selectedUser; set { _selectedUser = value; SetProperty(ref _selectedUser, value); FilterRoles(); UpateCommands(); } } private string _allUsersFilterQuery; public string AllUsersFilterQuery { get => _allUsersFilterQuery; set { _allUsersFilterQuery = value; FilterUserList(); } } public RelayCommand AvailableToCurrentRoleCommand { get; private set; } public RelayCommand CurrentToAvailableRoleCommand { get; private set; } public RelayCommand AddMultipleRolesCommand { get; private set; } public RelayCommand StarEditUserCommand { get; private set; } public RelayCommand DeleteUserCommand { get; private set; } public RelayCommand AddRoleCommand { get; private set; } public RelayCommand RemoveRoleCommand { get; private set; } public RelayCommand RequestTokenChangeCommand { get; private set; } public AllUsersViewModel() : base() { AllUsersFiltered = new ObservableCollection<UserData>(); AllRolesFiltered = new ObservableCollection<string>(); AvailableToCurrentRoleCommand = new RelayCommand(role => AddRole(role as String) , p => true); CurrentToAvailableRoleCommand = new RelayCommand(role => RemoveRole(role as String) , p => true); AddMultipleRolesCommand = new RelayCommand(group => AddGroup(group as string) , x => SelectedUser != null); StarEditUserCommand = new RelayCommand(pswd => UpdateUser(pswd as Pwds) , p => true); DeleteUserCommand = new RelayCommand(pswd => DeleteUser() , p => SelectedUser != null); AddRoleCommand = new RelayCommand(roles => AddRole(roles) , p => SelectedUser != null); RemoveRoleCommand = new RelayCommand(roles => RemoveRole(roles) , p => SelectedUser != null); Populate(); BaseUserViewModel.OnNewUserAdded += Refresh; } private void AddRole(object roles) => (roles as ObservableCollection<object>) .OfType<String>() .ToList() .ForEach(AddRole); private void RemoveRole(object roles) => (roles as ObservableCollection<object>) .OfType<String>() .ToList() .ForEach(RemoveRole); private void Refresh(object sender, EventArgs e) => Populate(); private void DeleteUser() { if (_messageBoxService.ShowMessage(Properties.strings.AreYouSure,Properties.strings.Delete, MessageType.YesNo)) { UserRepository.Delete(this.SelectedUser.Username); TcoAppDomain.Current.Logger.Information($"User '{this.SelectedUser.Username}' deleted. {{@sender}}", new { UserName = this.SelectedUser.Username }); UsersChanged(); Populate(); } } private void UpdateUser(Pwds pwds) { try { if (this.SelectedUser != null) { if (!(String.IsNullOrEmpty(pwds.Pb1.Password) && String.IsNullOrEmpty(pwds.Pb2.Password))) SelectedUser.SetPlainTextPassword(pwds.Pb1.Password); if (pwds.Pb1.Password != pwds.Pb2.Password) throw new Exception("Passwords do not match"); UserRepository.Update(this.SelectedUser.Username, SelectedUser); TcoAppDomain.Current.Logger.Information($"User '{this.SelectedUser.Username}' updated. {{@sender}}", new { UserName = this.SelectedUser.Username, Roles = this.SelectedUser.Roles }); pwds.Pb1.Clear(); pwds.Pb2.Clear(); UsersChanged(); Populate(); } } catch (Exception ex) { MessageBox.Show($"Error updating new user: '{ex.Message}'", "Failed to create user", MessageBoxButton.OK, MessageBoxImage.Error); } } private void AddRole(string v) { if (!SelectedUser.Roles.Contains(v)) { SelectedUser.Roles.Add(v); FilterRoles(); } else { SelectedUser.Roles.Remove(v); FilterRoles(); } } private void RemoveRole(string v) { SelectedUser.Roles.Remove(v); FilterRoles(); } private void AddGroup(string group) => AllRoles.Where(role => role.DefaultGroup == group) .Select( role => role.Name) .ToList() .ForEach( role => AddRole(role)); public void Populate() { AllUsersFiltered.Clear(); AllUsers.ToList().ForEach(AllUsersFiltered.Add); } private readonly IMessageBoxService _messageBoxService = new WPFMessageBoxService(); #region List filtering private void FilterUserList() { AllUsersFiltered.Clear(); if (AllUsersFilterQuery == null) { Populate(); } else { AllUsers .Where(u => UserFilter(u)) .ToList() .ForEach(AllUsersFiltered.Add); } } private bool UserFilter(UserData u) => u.Username.ToLower().Contains(AllUsersFilterQuery.ToLower()); private void FilterRoles() { if (SelectedUser != null) { AllRolesFiltered.Clear(); AllRoles .Select(x => x.Name) .Except(SelectedUser.Roles) .ToList() .ForEach(AllRolesFiltered.Add); } } #endregion List filtering } }
e87ed45631304413d22648d5460ea4fada456e85
{ "blob_id": "e87ed45631304413d22648d5460ea4fada456e85", "branch_name": "refs/heads/dev", "committer_date": "2023-09-04T14:57:15", "content_id": "b69144aa0988ab3dc852692db6d5dd14d1b8f230", "detected_licenses": [ "MIT" ], "directory_id": "d5c9910d8e76f1f308f87b4c0abd6fc40cc52440", "extension": "cs", "filename": "AllUsersViewModel.cs", "fork_events_count": 57, "gha_created_at": "2020-10-27T17:19:48", "gha_event_created_at": "2023-09-13T14:54:24", "gha_language": "C#", "gha_license_id": "MIT", "github_id": 307775598, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7264, "license": "MIT", "license_type": "permissive", "path": "/src/TcOpen.Inxton/src/Security.Wpf/UserManagement/AllUsersViewModel.cs", "provenance": "stack-edu-0013.json.gz:563829", "repo_name": "TcOpenGroup/TcOpen", "revision_date": "2023-09-04T14:57:15", "revision_id": "74725205a05f475c629490cecdb8125e9ddc20d4", "snapshot_id": "c3fad6cd9329bd347cf3d26b941a89362ac2e3b1", "src_encoding": "UTF-8", "star_events_count": 238, "url": "https://raw.githubusercontent.com/TcOpenGroup/TcOpen/74725205a05f475c629490cecdb8125e9ddc20d4/src/TcOpen.Inxton/src/Security.Wpf/UserManagement/AllUsersViewModel.cs", "visit_date": "2023-09-05T22:07:43.691440", "added": "2024-11-18T23:35:48.855779+00:00", "created": "2023-09-04T14:57:15", "int_score": 2, "score": 2.3125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0031.json.gz" }
from telegram.ext import Updater, CommanHandler def start (update, context): update.message.replytext('Hola, humano!') if __name__=='__main__': updater = Updater(token='2083176106:AAHRL2aUHoiXVnZC8u-T6bDMnLAxF-Oxvcs', use_context=True) dp=updater.dispatcher dp.add_handler(CommandHandler('start', start)) updater.start_polling() updater.idle()
1988a5bf062b760f4ac7066b2acf2a159019e2fa
{ "blob_id": "1988a5bf062b760f4ac7066b2acf2a159019e2fa", "branch_name": "refs/heads/main", "committer_date": "2021-11-04T17:40:52", "content_id": "8c7fd4555dc009e7746a4c93766ae06d6c34db29", "detected_licenses": [ "MIT" ], "directory_id": "536b39bfecf52f814e4247756609d6cbaa272ff8", "extension": "py", "filename": "DarkWolf.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 424681912, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 387, "license": "MIT", "license_type": "permissive", "path": "/Code/DarkWolf.py", "provenance": "stack-edu-0059.json.gz:291652", "repo_name": "rec02/DarkWolfBot", "revision_date": "2021-11-04T17:40:52", "revision_id": "9dc03e26036f5ee74e1b56570ce0eab35ced0e00", "snapshot_id": "d6ffc1eeff4be5f1b160c7e20580ff99a9cdb47e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/rec02/DarkWolfBot/9dc03e26036f5ee74e1b56570ce0eab35ced0e00/Code/DarkWolf.py", "visit_date": "2023-09-05T18:01:43.657120", "added": "2024-11-19T02:30:33.564823+00:00", "created": "2021-11-04T17:40:52", "int_score": 2, "score": 2.1875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0077.json.gz" }
# Copyright European Organization for Nuclear Research (CERN) # # 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 # # Authors: # - Martin Barisits, <[email protected]>, 2014 # - Andrew Lister, <[email protected]>, 2019 # - Eli Chadwick, <[email protected]>, 2020 # # PY3K COMPATIBLE import logging from rucio.common.types import InternalScope from rucio.common.utils import api_update_return_dict from rucio.core import lock from rucio.core.rse import get_rse_id LOGGER = logging.getLogger('lock') LOGGER.setLevel(logging.DEBUG) def get_dataset_locks(scope, name, vo='def'): """ Get the dataset locks of a dataset. :param scope: Scope of the dataset. :param name: Name of the dataset. :param vo: The VO to act on. :return: List of dicts {'rse_id': ..., 'state': ...} """ scope = InternalScope(scope, vo=vo) locks = lock.get_dataset_locks(scope=scope, name=name) for l in locks: yield api_update_return_dict(l) def get_dataset_locks_by_rse(rse, vo='def'): """ Get the dataset locks of an RSE. :param rse: RSE name. :param vo: The VO to act on. :return: List of dicts {'rse_id': ..., 'state': ...} """ rse_id = get_rse_id(rse=rse, vo=vo) locks = lock.get_dataset_locks_by_rse_id(rse_id=rse_id) for l in locks: yield api_update_return_dict(l) def get_replica_locks_for_rule_id(rule_id, vo='def'): """ Get the replica locks for a rule_id. :param rule_id: Rule ID. :param vo: The VO to act on. :return: List of dicts. """ locks = lock.get_replica_locks_for_rule_id(rule_id=rule_id) for l in locks: if l['scope'].vo != vo: # rule is on a different VO, so don't return any locks LOGGER.debug('rule id %s is not present on VO %s' % (rule_id, vo)) break yield api_update_return_dict(l)
13ce900ab47e78af7f6b5af1aa1d1f098704e8ff
{ "blob_id": "13ce900ab47e78af7f6b5af1aa1d1f098704e8ff", "branch_name": "refs/heads/master", "committer_date": "2021-01-27T12:58:21", "content_id": "ab0fd260e9e921b28e7507553933aff6cf50fa6c", "detected_licenses": [ "Apache-2.0" ], "directory_id": "9d023ac016b56130dd69ffcea30122ccda181345", "extension": "py", "filename": "lock.py", "fork_events_count": 0, "gha_created_at": "2019-03-15T19:24:25", "gha_event_created_at": "2019-03-15T19:24:25", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 175879086, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2154, "license": "Apache-2.0", "license_type": "permissive", "path": "/lib/rucio/api/lock.py", "provenance": "stack-edu-0062.json.gz:185259", "repo_name": "viveknigam3003/rucio", "revision_date": "2021-01-27T12:58:21", "revision_id": "bf33d9441d3b4ff160a392eed56724f635a03fe6", "snapshot_id": "5996c6b650caf9ddb49daf14cfb152187be2239b", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/viveknigam3003/rucio/bf33d9441d3b4ff160a392eed56724f635a03fe6/lib/rucio/api/lock.py", "visit_date": "2021-06-21T12:37:12.755105", "added": "2024-11-18T20:30:02.330187+00:00", "created": "2021-01-27T12:58:21", "int_score": 2, "score": 2.140625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0080.json.gz" }
import React, { useState, useRef, useEffect, useContext } from "react"; import { Table, Form } from "antd"; const EditableTable = (props) => { const { /* 数据源 */ dataSource, /* 数据格式 */ columns, /* 其他熟悉 */ ...restProps } = props; const EditableContext = React.createContext(); const EditableRow = ({ index, ...props }) => { const [form] = Form.useForm(); return ( <Form form={form} component={false}> <EditableContext.Provider value={form}> <tr {...props} /> </EditableContext.Provider> </Form> ); }; const EditableCell = ({ title, editable, children, dataIndex, record, rules, handleSave, inputRender, ...restProps }) => { const [editing, setEditing] = useState(false); const inputRef = useRef(); const form = useContext(EditableContext); useEffect(() => { if (editing) { inputRef.current.focus(); } }, [editing]); const toggleEdit = () => { setEditing(!editing); form.setFieldsValue({ [dataIndex]: record[dataIndex], }); }; const save = async (e) => { try { const values = await form.validateFields(); toggleEdit(); handleSave({ ...record, ...values }); } catch (errInfo) { console.log("Save failed:", errInfo); } }; let childNode = children; if (editable) { childNode = editing ? ( <Form.Item style={{ margin: 0, }} name={dataIndex} rules={rules} > {inputRender({ ref: inputRef, onBlur: save, })} </Form.Item> ) : ( <div className='editable-cell-value-wrap' onClick={toggleEdit}> {children} </div> ); } return <td {...restProps}>{childNode}</td>; }; const components = { body: { row: EditableRow, cell: EditableCell, }, }; const getColumn = (col) => { if (col.children) { let children = col.children.map((item) => { return getColumn(item); }); col.children = children; return col; } else { if (!col.editable) { return col; } return { ...col, onCell: (record) => ({ record, editable: col.editable, dataIndex: col.dataIndex, title: col.title, rules: col.rules, handleSave: col.handleSave, inputRender: col.inputRender, }), }; } }; const wrapColumns = columns.map((col) => { return getColumn(col); }); return ( <Table rowClassName={() => "editable-row"} dataSource={dataSource} components={components} columns={wrapColumns} {...restProps} ></Table> ); }; export default EditableTable;
3e2474aeb9c297ac239a654c9b8e4cf6c1b99c1a
{ "blob_id": "3e2474aeb9c297ac239a654c9b8e4cf6c1b99c1a", "branch_name": "refs/heads/master", "committer_date": "2020-09-04T09:12:58", "content_id": "f24e3129ea6a60e516658ef6ed7d7449e8fd9549", "detected_licenses": [ "MIT" ], "directory_id": "83f6967dbc057d5b737a50bf2aaa54d57ad45331", "extension": "jsx", "filename": "index.jsx", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 291597444, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2906, "license": "MIT", "license_type": "permissive", "path": "/src/components/EditableTable/index.jsx", "provenance": "stack-edu-0043.json.gz:245707", "repo_name": "Jevirs/stock-system-front-end", "revision_date": "2020-09-04T09:12:58", "revision_id": "50bdd685391f3490757171a6a35a7ff71136653f", "snapshot_id": "bb68687c7954f8fdc1e1d1d170e49c8c3932b5b9", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Jevirs/stock-system-front-end/50bdd685391f3490757171a6a35a7ff71136653f/src/components/EditableTable/index.jsx", "visit_date": "2022-12-13T20:29:53.453630", "added": "2024-11-19T01:21:33.319904+00:00", "created": "2020-09-04T09:12:58", "int_score": 3, "score": 2.5625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0061.json.gz" }
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_MEDIA_ROUTER_PRESENTATION_SESSION_MESSAGES_OBSERVER_H_ #define CHROME_BROWSER_MEDIA_ROUTER_PRESENTATION_SESSION_MESSAGES_OBSERVER_H_ #include "base/macros.h" #include "base/memory/scoped_vector.h" #include "chrome/browser/media/router/media_route.h" #include "content/public/browser/presentation_service_delegate.h" #include "content/public/browser/presentation_session.h" namespace media_router { class MediaRouter; // Observes messages originating from the MediaSink connected to a MediaRoute // that represents a presentation. // Messages are received from MediaRouter via |OnMessagesReceived|, where // |message_cb_| will be invoked. class PresentationSessionMessagesObserver { public: // |message_cb|: The callback to invoke whenever messages are received. // |route_id|: ID of MediaRoute to listen for messages. PresentationSessionMessagesObserver( const content::PresentationSessionMessageCallback& message_cb, const MediaRoute::Id& route_id, MediaRouter* router); ~PresentationSessionMessagesObserver(); // Invoked by |router_| whenever messages are received. Invokes |message_cb_| // with |messages|. // |messages| is guaranteed to be non-empty. // If |pass_ownership| is true, then this observer may reuse buffers from the // contents of |messages| without copying. void OnMessagesReceived( const ScopedVector<content::PresentationSessionMessage>& messages, bool pass_ownership); const MediaRoute::Id& route_id() const { return route_id_; } private: content::PresentationSessionMessageCallback message_cb_; const MediaRoute::Id route_id_; MediaRouter* const router_; DISALLOW_COPY_AND_ASSIGN(PresentationSessionMessagesObserver); }; } // namespace media_router #endif // CHROME_BROWSER_MEDIA_ROUTER_PRESENTATION_SESSION_MESSAGES_OBSERVER_H_
2df073d9dccc275b08263de867aa2cfd4ee27181
{ "blob_id": "2df073d9dccc275b08263de867aa2cfd4ee27181", "branch_name": "refs/heads/webosce", "committer_date": "2018-09-20T14:25:18", "content_id": "62c95127fb058f23f69c66283cc9cd6b4842550c", "detected_licenses": [ "BSD-3-Clause", "Apache-2.0" ], "directory_id": "3b9b4049a8e7d38b49e07bb752780b2f1d792851", "extension": "h", "filename": "presentation_session_messages_observer.h", "fork_events_count": 2, "gha_created_at": "2018-08-21T05:52:31", "gha_event_created_at": "2019-08-21T22:44:55", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 145513343, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2014, "license": "BSD-3-Clause,Apache-2.0", "license_type": "permissive", "path": "/src/chrome/browser/media/router/presentation_session_messages_observer.h", "provenance": "stack-edu-0006.json.gz:225617", "repo_name": "webosce/chromium53", "revision_date": "2018-08-23T08:35:17", "revision_id": "9171447efcf0bb393d41d1dc877c7c13c46d8e38", "snapshot_id": "f8e745e91363586aee9620c609aacf15b3261540", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/webosce/chromium53/9171447efcf0bb393d41d1dc877c7c13c46d8e38/src/chrome/browser/media/router/presentation_session_messages_observer.h", "visit_date": "2020-03-26T23:08:14.416858", "added": "2024-11-18T22:07:38.865861+00:00", "created": "2018-08-23T08:35:17", "int_score": 2, "score": 2.09375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0024.json.gz" }
// // Aspir // Copyright(c) 2013 Matt Hernandez <[email protected]> // MIT Licensed // var util = require('util'); // // Get the value of the specified path on the specified object. // function get(obj, path) { var props = []; if (util.isArray(path)) { props = path; } else { props = path.split('.'); } while(props.length && obj) { var prop = props.shift() , match = /(.+)\[([0-9]*)\]/.exec(prop); if (match && match.length === 3) { var name = match[1] , index = match[2]; if (typeof obj[name] !== 'undefined') { obj = obj[name][index]; } else { obj = null; } } else { obj = obj[prop]; } } return obj || null; } // // Check for the existence of the specified path on the specified object. // exports.exists = function exists(obj, path) { if (typeof path === 'string') path = path.split('.'); if (!util.isArray(path) || path.length === 0) return false; if (typeof obj !== 'object' || !obj) return false; var key = path.shift(); if (/\[[0-9]\]/g.test(key)) return get(obj, key) !== null; if (path.length === 0) return Object.hasOwnProperty.apply(obj, [key]); return exists(obj[key], path); }; // // Expose the get function. // exports.get = get;
87abd6ccc255a4c5b3e83399845fe4e9abb86cf9
{ "blob_id": "87abd6ccc255a4c5b3e83399845fe4e9abb86cf9", "branch_name": "refs/heads/master", "committer_date": "2014-02-17T16:51:57", "content_id": "6f978058ba50981dfb04c69110d1227a90f67c95", "detected_licenses": [ "MIT" ], "directory_id": "9d0816ab1e940aac9216053e02f943512c8e2827", "extension": "js", "filename": "index.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1280, "license": "MIT", "license_type": "permissive", "path": "/index.js", "provenance": "stack-edu-0045.json.gz:750220", "repo_name": "InconceivableDuck/aspir", "revision_date": "2014-02-17T16:51:57", "revision_id": "d2946ba459a11e04e1836b4aff2167bd3016f20c", "snapshot_id": "b9c71e8cfb2a992b8bff5f096297bb32d7e69c90", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/InconceivableDuck/aspir/d2946ba459a11e04e1836b4aff2167bd3016f20c/index.js", "visit_date": "2020-12-11T01:42:28.780327", "added": "2024-11-19T02:00:20.044932+00:00", "created": "2014-02-17T16:51:57", "int_score": 3, "score": 2.984375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0063.json.gz" }
#include <stdio.h> #include "../include/error.h" #include "../include/defs.h" /** * Prints out the relevant error messages * * @param errorId */ int ErrorMsgs(int errorId, int printFlag) { if (printFlag == OK) { printf("<ERROR %d>: ", errorId); switch (errorId) { case RELNOEXIST: printf("Relation does not exist! Please check the name and try again.\n"); break; case ATTRNOEXIST: printf("The attribute with given name is not present in the relation.\n"); break; case RELNUM_OUT_OF_BOUND: printf("Out of bound relation number encountered\n"); break; case NULL_POINTER_EXCEPTION: printf("Null pointer exception!\n"); break; case INVALID_ATTR_TYPE: printf("Invalid attribute type! Attribute type should be i, f or s.\n"); break; case INVALID_COMP_OP: printf("Invalid comparison operator!\n"); break; case FILE_SEEK_ERROR: printf("Error while seeking in file!\n"); break; case NULL_ARGUMENT_RECEIVED: printf("A NULL argument was received where non-NULL was required!\n"); break; case WRITE_DISK_ERROR: printf("Error occurred while writing data to disk!\n"); break; case READ_DISK_ERROR: printf("Error occurred while reading data from disk!\n"); break; case NO_ATTRS_FOUND: printf("No attributes found for the relation!\n"); break; case NO_CATALOG_FOUND: printf("No catalog found in the database!\n"); break; case CAT_FILE_ALREADY_EXIST: printf("Catalog file(s) already exist in the database!\n"); break; case DB_ALREADY_EXISTS: printf("A DB with the given name already exists! \ Please provide a different name and try again\n"); break; case ARGC_INSUFFICIENT: printf("Argument(s) missing! The number of arguments received is \ less than required number of arguments!\n"); break; case FILE_SYSTEM_ERROR: printf("Error occurred while trying to create file/directory. \ Please check file system permissions and try again.\n"); break; case DBNAME_INVALID: printf("Database not found with given name! Please check the database name.\n"); break; case REL_ALREADY_EXISTS: printf("A relation with given name already exists! Please try again with a \ different name.\n"); break; case INVALID_ATTR_NAME: printf("An attribute or relation name is invalid! Names should start with alphabet \ and can be at most 20 characters long.\n"); break; case DB_NOT_OPEN: printf("Please call opendb <DBNAME> to open a database first.\n"); break; case DB_NOT_CLOSED: printf("Database not closed! Please call CloseDB() before open/create a db \n"); break; case NO_ATTRIBUTES_TO_INSERT: printf("Insert has no attribute-value pairs to be inserted into the relation!\n"); break; case ATTR_NOT_IN_REL: printf("Attribute with the given name is not found in relation! Please check\ if all attributes are named correctly.\n"); break; case DUPLICATE_TUPLE: printf("Tuple already exists in this relation! All tuples must be unique.\n"); break; case METADATA_SECURITY: printf("Permission denied! Meta data tables cannot be modified directly.\n"); break; case INTEGER_EXPECTED: printf("Integer value was expected but got string instead.\n"); break; case FLOAT_EXPECTED: printf("Float value was expected but got string instead.\n"); break; case MAX_STRING_EXCEEDED: printf("Exceeded the maximum allowed string size of %d\n",MAX_STRING_SIZE); break; case PID_OUT_OF_BOUND: printf("Trying to read a page which is greater than the number of \ pages in the relation.\n"); break; case DBNAME_EXCEED_LIMIT: printf("Database Name exceeded the limit! Enter name within 20 characters.\n"); break; case TYPE_MISMATCH: printf("Type Mismatch while performing Join! Please try similar attributes.\n"); break; case REL_NOT_EMPTY: printf("Relation is not empty! One can load only on to empty relations.\n"); break; case INVALID_FILE: printf("Cannot open file! Please check the path given and try again.\n"); break; case PAGE_OVERFLOW: printf("MINIREL cannot handle a record of size > %d. Please try again with \ lesser number of attributes or arguments with smaller size.\n", MAXRECORD); break; case INSUFFICIENT_ATTRS: printf("Number of attributes mismatch! Please pass all the attributes present and \ its values to insert a new record. Use \n\t select into <some_name> from attrcat where (relName = \ \"<RELNAME>\");\n to find the attributes for a relation\n"); break; case ATTR_REPEATED: printf("Attribute repeated! Please check the insert query and remove the \ duplicate entry.\n"); break; default: printf("Congratulations! You just won 500 million GBP! Please send your \ bank details to developer to claim the price. :)\n"); break; } } return NOTOK; }
fe739019ee44cb080381e9d406e200f1e0b0b1e7
{ "blob_id": "fe739019ee44cb080381e9d406e200f1e0b0b1e7", "branch_name": "refs/heads/master", "committer_date": "2014-11-28T16:08:18", "content_id": "608b0b8ad05f47ad56710e854a00ec8c95ddc498", "detected_licenses": [ "MIT" ], "directory_id": "eb17e5788dbf46f2ef397f3464f79fad2619a62c", "extension": "c", "filename": "error.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6174, "license": "MIT", "license_type": "permissive", "path": "/physical/error.c", "provenance": "stack-edu-0000.json.gz:47071", "repo_name": "Sakshipushkar/minirel", "revision_date": "2014-11-28T16:08:18", "revision_id": "aaffbb69a912c9dabb8863cf959d67208a1418e5", "snapshot_id": "b15a24d44e9c87a803d28d4052d6a5555807f1f6", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Sakshipushkar/minirel/aaffbb69a912c9dabb8863cf959d67208a1418e5/physical/error.c", "visit_date": "2020-03-21T22:25:34.928002", "added": "2024-11-18T22:23:58.157247+00:00", "created": "2014-11-28T16:08:18", "int_score": 3, "score": 2.765625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0018.json.gz" }
import glob import os import shutil import numpy class File(object): """ File is a utility class for I/O operations on files and directories. """ @staticmethod def read(filename, mode="r", encoding="utf-8", errors='ignore'): """Load a text file.""" with open(filename, mode=mode, encoding=encoding, errors=errors) as f: return f.read() @staticmethod def get_files_count(directory: str): return len([name for name in os.listdir(directory) if os.path.isfile(name)]) @staticmethod def create_directory(directory: str): if not File.directory_exists(directory): os.makedirs(directory) @staticmethod def create_file(filename: str): file = open(filename, 'a') file.close() @staticmethod def write_file(filename: str, content, mode: str = "w"): if not File.file_exists(filename): File.create_file(filename) file = open(filename, mode) file.write(content) file.close() @staticmethod def delete_file(filename: str): os.remove(filename) @staticmethod def empty_directory(directory: str, sub_dirs: bool = False): for the_file in os.listdir(directory): file_path = os.path.join(directory, the_file) try: if os.path.isfile(file_path): os.unlink(file_path) elif os.path.isdir(file_path) and sub_dirs: shutil.rmtree(file_path) except Exception as e: print(e) @staticmethod def directory_exists(directory): return os.path.exists(directory) @staticmethod def file_exists(filename): return os.path.exists(filename) @staticmethod def is_file(path): return os.path.isfile(path) @staticmethod def is_dir(path): return os.path.isdir(path) @staticmethod def get_files_count(path): return sum([len(files) for r, d, files in os.walk(path)]) @staticmethod def length(file_name): return sum(1 for line in open(file_name) if line.rstrip()) @staticmethod def get_dir_iterator(directory, extension='*', recursive=True): File.directory_exists(directory) return glob.iglob(directory + f"{'/**' if recursive else None}/{extension}", recursive=recursive) @staticmethod def get_dir_files_recursive(directory, extension='*') -> []: File.directory_exists(directory) return [y for x in os.walk(directory) for y in glob.glob(os.path.join(x[0], f"*.{extension}"))] @staticmethod def get_randomized_files_list(path): f_list = File.get_dir_files_recursive(path) numpy.random.shuffle(f_list) return f_list
981c07c60ac8c9c7dab36a902cd8f89f4492e580
{ "blob_id": "981c07c60ac8c9c7dab36a902cd8f89f4492e580", "branch_name": "refs/heads/master", "committer_date": "2019-07-08T09:51:25", "content_id": "9f78677c011f449899fda7d3019666b01df5fd13", "detected_licenses": [ "Apache-2.0" ], "directory_id": "248735628d8fb05b8be738d2c09acbf69810e826", "extension": "py", "filename": "File.py", "fork_events_count": 0, "gha_created_at": "2018-11-28T05:11:10", "gha_event_created_at": "2019-07-07T23:58:30", "gha_language": "Python", "gha_license_id": "Apache-2.0", "github_id": 159447094, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2783, "license": "Apache-2.0", "license_type": "permissive", "path": "/Utils/File.py", "provenance": "stack-edu-0057.json.gz:631022", "repo_name": "StefanoFrazzetto/CrimeDetector", "revision_date": "2019-07-08T09:51:25", "revision_id": "a5d39a3b44e8732502b9f6b41d44c8244940ebe6", "snapshot_id": "9fda2484fd57c926a0c8596b662e9e879c7d4332", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/StefanoFrazzetto/CrimeDetector/a5d39a3b44e8732502b9f6b41d44c8244940ebe6/Utils/File.py", "visit_date": "2020-04-08T14:40:33.776980", "added": "2024-11-19T02:28:41.972475+00:00", "created": "2019-07-08T09:51:25", "int_score": 3, "score": 3.078125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0075.json.gz" }
<?php namespace Eulogix\Cool\Bundle\CoreBundle\Model\Core\om; use \Criteria; use \Exception; use \ModelCriteria; use \PDO; use \Propel; use \PropelException; use \PropelObjectCollection; use \PropelPDO; use Eulogix\Cool\Bundle\CoreBundle\Model\Core\PgListenerHook; use Eulogix\Cool\Bundle\CoreBundle\Model\Core\PgListenerHookPeer; use Eulogix\Cool\Bundle\CoreBundle\Model\Core\PgListenerHookQuery; /** * @method PgListenerHookQuery orderByPgListenerHookId($order = Criteria::ASC) Order by the pg_listener_hook_id column * @method PgListenerHookQuery orderByName($order = Criteria::ASC) Order by the name column * @method PgListenerHookQuery orderByChannelsRegex($order = Criteria::ASC) Order by the channels_regex column * @method PgListenerHookQuery orderByDescription($order = Criteria::ASC) Order by the description column * @method PgListenerHookQuery orderByExecSqlStatements($order = Criteria::ASC) Order by the exec_sql_statements column * @method PgListenerHookQuery orderByExecSfCommand($order = Criteria::ASC) Order by the exec_sf_command column * @method PgListenerHookQuery orderByExecShellCommand($order = Criteria::ASC) Order by the exec_shell_command column * @method PgListenerHookQuery orderByExecPhpCode($order = Criteria::ASC) Order by the exec_php_code column * * @method PgListenerHookQuery groupByPgListenerHookId() Group by the pg_listener_hook_id column * @method PgListenerHookQuery groupByName() Group by the name column * @method PgListenerHookQuery groupByChannelsRegex() Group by the channels_regex column * @method PgListenerHookQuery groupByDescription() Group by the description column * @method PgListenerHookQuery groupByExecSqlStatements() Group by the exec_sql_statements column * @method PgListenerHookQuery groupByExecSfCommand() Group by the exec_sf_command column * @method PgListenerHookQuery groupByExecShellCommand() Group by the exec_shell_command column * @method PgListenerHookQuery groupByExecPhpCode() Group by the exec_php_code column * * @method PgListenerHookQuery leftJoin($relation) Adds a LEFT JOIN clause to the query * @method PgListenerHookQuery rightJoin($relation) Adds a RIGHT JOIN clause to the query * @method PgListenerHookQuery innerJoin($relation) Adds a INNER JOIN clause to the query * * @method PgListenerHook findOne(PropelPDO $con = null) Return the first PgListenerHook matching the query * @method PgListenerHook findOneOrCreate(PropelPDO $con = null) Return the first PgListenerHook matching the query, or a new PgListenerHook object populated from the query conditions when no match is found * * @method PgListenerHook findOneByName(string $name) Return the first PgListenerHook filtered by the name column * @method PgListenerHook findOneByChannelsRegex(string $channels_regex) Return the first PgListenerHook filtered by the channels_regex column * @method PgListenerHook findOneByDescription(string $description) Return the first PgListenerHook filtered by the description column * @method PgListenerHook findOneByExecSqlStatements(string $exec_sql_statements) Return the first PgListenerHook filtered by the exec_sql_statements column * @method PgListenerHook findOneByExecSfCommand(string $exec_sf_command) Return the first PgListenerHook filtered by the exec_sf_command column * @method PgListenerHook findOneByExecShellCommand(string $exec_shell_command) Return the first PgListenerHook filtered by the exec_shell_command column * @method PgListenerHook findOneByExecPhpCode(string $exec_php_code) Return the first PgListenerHook filtered by the exec_php_code column * * @method array findByPgListenerHookId(int $pg_listener_hook_id) Return PgListenerHook objects filtered by the pg_listener_hook_id column * @method array findByName(string $name) Return PgListenerHook objects filtered by the name column * @method array findByChannelsRegex(string $channels_regex) Return PgListenerHook objects filtered by the channels_regex column * @method array findByDescription(string $description) Return PgListenerHook objects filtered by the description column * @method array findByExecSqlStatements(string $exec_sql_statements) Return PgListenerHook objects filtered by the exec_sql_statements column * @method array findByExecSfCommand(string $exec_sf_command) Return PgListenerHook objects filtered by the exec_sf_command column * @method array findByExecShellCommand(string $exec_shell_command) Return PgListenerHook objects filtered by the exec_shell_command column * @method array findByExecPhpCode(string $exec_php_code) Return PgListenerHook objects filtered by the exec_php_code column */ abstract class BasePgListenerHookQuery extends ModelCriteria { /** * Initializes internal state of BasePgListenerHookQuery object. * * @param string $dbName The dabase name * @param string $modelName The phpName of a model, e.g. 'Book' * @param string $modelAlias The alias for the model in this query, e.g. 'b' */ public function __construct($dbName = null, $modelName = null, $modelAlias = null) { if (null === $dbName) { $dbName = 'cool_db'; } if (null === $modelName) { $modelName = 'Eulogix\\Cool\\Bundle\\CoreBundle\\Model\\Core\\PgListenerHook'; } parent::__construct($dbName, $modelName, $modelAlias); } /** * Returns a new PgListenerHookQuery object. * * @param string $modelAlias The alias of a model in the query * @param PgListenerHookQuery|Criteria $criteria Optional Criteria to build the query from * * @return PgListenerHookQuery */ public static function create($modelAlias = null, $criteria = null) { if ($criteria instanceof PgListenerHookQuery) { return $criteria; } $query = new PgListenerHookQuery(null, null, $modelAlias); if ($criteria instanceof Criteria) { $query->mergeWith($criteria); } return $query; } /** * Find object by primary key. * Propel uses the instance pool to skip the database if the object exists. * Go fast if the query is untouched. * * <code> * $obj = $c->findPk(12, $con); * </code> * * @param mixed $key Primary key to use for the query * @param PropelPDO $con an optional connection object * * @return PgListenerHook|PgListenerHook[]|mixed the result, formatted by the current formatter */ public function findPk($key, $con = null) { if ($key === null) { return null; } if ((null !== ($obj = PgListenerHookPeer::getInstanceFromPool((string) $key))) && !$this->formatter) { // the object is already in the instance pool return $obj; } if ($con === null) { $con = Propel::getConnection(PgListenerHookPeer::DATABASE_NAME, Propel::CONNECTION_READ); } $this->basePreSelect($con); if ($this->formatter || $this->modelAlias || $this->with || $this->select || $this->selectColumns || $this->asColumns || $this->selectModifiers || $this->map || $this->having || $this->joins) { return $this->findPkComplex($key, $con); } else { return $this->findPkSimple($key, $con); } } /** * Alias of findPk to use instance pooling * * @param mixed $key Primary key to use for the query * @param PropelPDO $con A connection object * * @return PgListenerHook A model object, or null if the key is not found * @throws PropelException */ public function findOneByPgListenerHookId($key, $con = null) { return $this->findPk($key, $con); } /** * Find object by primary key using raw SQL to go fast. * Bypass doSelect() and the object formatter by using generated code. * * @param mixed $key Primary key to use for the query * @param PropelPDO $con A connection object * * @return PgListenerHook A model object, or null if the key is not found * @throws PropelException */ protected function findPkSimple($key, $con) { $sql = 'SELECT pg_listener_hook_id, name, channels_regex, description, exec_sql_statements, exec_sf_command, exec_shell_command, exec_php_code FROM core.pg_listener_hook WHERE pg_listener_hook_id = :p0'; try { $stmt = $con->prepare($sql); $stmt->bindValue(':p0', $key, PDO::PARAM_INT); $stmt->execute(); } catch (Exception $e) { Propel::log($e->getMessage(), Propel::LOG_ERR); throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), $e); } $obj = null; if ($row = $stmt->fetch(PDO::FETCH_NUM)) { $obj = new PgListenerHook(); $obj->hydrate($row); PgListenerHookPeer::addInstanceToPool($obj, (string) $key); } $stmt->closeCursor(); return $obj; } /** * Find object by primary key. * * @param mixed $key Primary key to use for the query * @param PropelPDO $con A connection object * * @return PgListenerHook|PgListenerHook[]|mixed the result, formatted by the current formatter */ protected function findPkComplex($key, $con) { // As the query uses a PK condition, no limit(1) is necessary. $criteria = $this->isKeepQuery() ? clone $this : $this; $stmt = $criteria ->filterByPrimaryKey($key) ->doSelect($con); return $criteria->getFormatter()->init($criteria)->formatOne($stmt); } /** * Find objects by primary key * <code> * $objs = $c->findPks(array(12, 56, 832), $con); * </code> * @param array $keys Primary keys to use for the query * @param PropelPDO $con an optional connection object * * @return PropelObjectCollection|PgListenerHook[]|mixed the list of results, formatted by the current formatter */ public function findPks($keys, $con = null) { if ($con === null) { $con = Propel::getConnection($this->getDbName(), Propel::CONNECTION_READ); } $this->basePreSelect($con); $criteria = $this->isKeepQuery() ? clone $this : $this; $stmt = $criteria ->filterByPrimaryKeys($keys) ->doSelect($con); return $criteria->getFormatter()->init($criteria)->format($stmt); } /** * Find objects by primary key while maintaining the original sort order of the keys * <code> * $objs = $c->findPksKeepingKeyOrder(array(12, 56, 832), $con); * </code> * @param array $keys Primary keys to use for the query * @param PropelPDO $con an optional connection object * * @return PgListenerHook[] */ public function findPksKeepingKeyOrder($keys, $con = null) { if ($con === null) { $con = Propel::getConnection($this->getDbName(), Propel::CONNECTION_READ); } $ret = array(); foreach($keys as $key) $ret[ $key ] = $this->findPk($key, $con); return $ret; } /** * Filter the query by primary key * * @param mixed $key Primary key to use for the query * * @return PgListenerHookQuery The current query, for fluid interface */ public function filterByPrimaryKey($key) { return $this->addUsingAlias(PgListenerHookPeer::PG_LISTENER_HOOK_ID, $key, Criteria::EQUAL); } /** * Filter the query by a list of primary keys * * @param array $keys The list of primary key to use for the query * * @return PgListenerHookQuery The current query, for fluid interface */ public function filterByPrimaryKeys($keys) { return $this->addUsingAlias(PgListenerHookPeer::PG_LISTENER_HOOK_ID, $keys, Criteria::IN); } /** * Filter the query on the pg_listener_hook_id column * * Example usage: * <code> * $query->filterByPgListenerHookId(1234); // WHERE pg_listener_hook_id = 1234 * $query->filterByPgListenerHookId(array(12, 34)); // WHERE pg_listener_hook_id IN (12, 34) * $query->filterByPgListenerHookId(array('min' => 12)); // WHERE pg_listener_hook_id >= 12 * $query->filterByPgListenerHookId(array('max' => 12)); // WHERE pg_listener_hook_id <= 12 * </code> * * @param mixed $pgListenerHookId The value to use as filter. * Use scalar values for equality. * Use array values for in_array() equivalent. * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return PgListenerHookQuery The current query, for fluid interface */ public function filterByPgListenerHookId($pgListenerHookId = null, $comparison = null) { if (is_array($pgListenerHookId)) { $useMinMax = false; if (isset($pgListenerHookId['min'])) { $this->addUsingAlias(PgListenerHookPeer::PG_LISTENER_HOOK_ID, $pgListenerHookId['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($pgListenerHookId['max'])) { $this->addUsingAlias(PgListenerHookPeer::PG_LISTENER_HOOK_ID, $pgListenerHookId['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(PgListenerHookPeer::PG_LISTENER_HOOK_ID, $pgListenerHookId, $comparison); } /** * Filter the query on the name column * * Example usage: * <code> * $query->filterByName('fooValue'); // WHERE name = 'fooValue' * $query->filterByName('%fooValue%'); // WHERE name LIKE '%fooValue%' * </code> * * @param string $name The value to use as filter. * Accepts wildcards (* and % trigger a LIKE) * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return PgListenerHookQuery The current query, for fluid interface */ public function filterByName($name = null, $comparison = null) { if (null === $comparison) { if (is_array($name)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $name)) { $name = str_replace('*', '%', $name); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(PgListenerHookPeer::NAME, $name, $comparison); } /** * Filter the query on the channels_regex column * * Example usage: * <code> * $query->filterByChannelsRegex('fooValue'); // WHERE channels_regex = 'fooValue' * $query->filterByChannelsRegex('%fooValue%'); // WHERE channels_regex LIKE '%fooValue%' * </code> * * @param string $channelsRegex The value to use as filter. * Accepts wildcards (* and % trigger a LIKE) * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return PgListenerHookQuery The current query, for fluid interface */ public function filterByChannelsRegex($channelsRegex = null, $comparison = null) { if (null === $comparison) { if (is_array($channelsRegex)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $channelsRegex)) { $channelsRegex = str_replace('*', '%', $channelsRegex); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(PgListenerHookPeer::CHANNELS_REGEX, $channelsRegex, $comparison); } /** * Filter the query on the description column * * Example usage: * <code> * $query->filterByDescription('fooValue'); // WHERE description = 'fooValue' * $query->filterByDescription('%fooValue%'); // WHERE description LIKE '%fooValue%' * </code> * * @param string $description The value to use as filter. * Accepts wildcards (* and % trigger a LIKE) * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return PgListenerHookQuery The current query, for fluid interface */ public function filterByDescription($description = null, $comparison = null) { if (null === $comparison) { if (is_array($description)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $description)) { $description = str_replace('*', '%', $description); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(PgListenerHookPeer::DESCRIPTION, $description, $comparison); } /** * Filter the query on the exec_sql_statements column * * Example usage: * <code> * $query->filterByExecSqlStatements('fooValue'); // WHERE exec_sql_statements = 'fooValue' * $query->filterByExecSqlStatements('%fooValue%'); // WHERE exec_sql_statements LIKE '%fooValue%' * </code> * * @param string $execSqlStatements The value to use as filter. * Accepts wildcards (* and % trigger a LIKE) * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return PgListenerHookQuery The current query, for fluid interface */ public function filterByExecSqlStatements($execSqlStatements = null, $comparison = null) { if (null === $comparison) { if (is_array($execSqlStatements)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $execSqlStatements)) { $execSqlStatements = str_replace('*', '%', $execSqlStatements); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(PgListenerHookPeer::EXEC_SQL_STATEMENTS, $execSqlStatements, $comparison); } /** * Filter the query on the exec_sf_command column * * Example usage: * <code> * $query->filterByExecSfCommand('fooValue'); // WHERE exec_sf_command = 'fooValue' * $query->filterByExecSfCommand('%fooValue%'); // WHERE exec_sf_command LIKE '%fooValue%' * </code> * * @param string $execSfCommand The value to use as filter. * Accepts wildcards (* and % trigger a LIKE) * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return PgListenerHookQuery The current query, for fluid interface */ public function filterByExecSfCommand($execSfCommand = null, $comparison = null) { if (null === $comparison) { if (is_array($execSfCommand)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $execSfCommand)) { $execSfCommand = str_replace('*', '%', $execSfCommand); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(PgListenerHookPeer::EXEC_SF_COMMAND, $execSfCommand, $comparison); } /** * Filter the query on the exec_shell_command column * * Example usage: * <code> * $query->filterByExecShellCommand('fooValue'); // WHERE exec_shell_command = 'fooValue' * $query->filterByExecShellCommand('%fooValue%'); // WHERE exec_shell_command LIKE '%fooValue%' * </code> * * @param string $execShellCommand The value to use as filter. * Accepts wildcards (* and % trigger a LIKE) * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return PgListenerHookQuery The current query, for fluid interface */ public function filterByExecShellCommand($execShellCommand = null, $comparison = null) { if (null === $comparison) { if (is_array($execShellCommand)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $execShellCommand)) { $execShellCommand = str_replace('*', '%', $execShellCommand); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(PgListenerHookPeer::EXEC_SHELL_COMMAND, $execShellCommand, $comparison); } /** * Filter the query on the exec_php_code column * * Example usage: * <code> * $query->filterByExecPhpCode('fooValue'); // WHERE exec_php_code = 'fooValue' * $query->filterByExecPhpCode('%fooValue%'); // WHERE exec_php_code LIKE '%fooValue%' * </code> * * @param string $execPhpCode The value to use as filter. * Accepts wildcards (* and % trigger a LIKE) * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return PgListenerHookQuery The current query, for fluid interface */ public function filterByExecPhpCode($execPhpCode = null, $comparison = null) { if (null === $comparison) { if (is_array($execPhpCode)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $execPhpCode)) { $execPhpCode = str_replace('*', '%', $execPhpCode); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(PgListenerHookPeer::EXEC_PHP_CODE, $execPhpCode, $comparison); } /** * Exclude object from result * * @param PgListenerHook $pgListenerHook Object to remove from the list of results * * @return PgListenerHookQuery The current query, for fluid interface */ public function prune($pgListenerHook = null) { if ($pgListenerHook) { $this->addUsingAlias(PgListenerHookPeer::PG_LISTENER_HOOK_ID, $pgListenerHook->getPgListenerHookId(), Criteria::NOT_EQUAL); } return $this; } }
180c1a3ede23039ec764fea507d630286533524b
{ "blob_id": "180c1a3ede23039ec764fea507d630286533524b", "branch_name": "refs/heads/master", "committer_date": "2019-04-26T12:27:11", "content_id": "c94222ee8387354cf2438666200c37db88f8a260", "detected_licenses": [ "MIT" ], "directory_id": "8895a14c7af5eeae4597aa21dc5ebd9839c33d1d", "extension": "php", "filename": "BasePgListenerHookQuery.php", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 90288429, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 22546, "license": "MIT", "license_type": "permissive", "path": "/Bundle/CoreBundle/Model/Core/om/BasePgListenerHookQuery.php", "provenance": "stack-edu-0053.json.gz:701818", "repo_name": "eulogix/cool-core-bundle", "revision_date": "2019-04-26T12:27:11", "revision_id": "5a78c1135226f2367f47a736fa89f23e3c19006f", "snapshot_id": "5b72c046b1a04aae1108c1565979bd15e568dbaf", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/eulogix/cool-core-bundle/5a78c1135226f2367f47a736fa89f23e3c19006f/Bundle/CoreBundle/Model/Core/om/BasePgListenerHookQuery.php", "visit_date": "2021-01-20T09:49:01.030250", "added": "2024-11-18T21:00:23.047102+00:00", "created": "2019-04-26T12:27:11", "int_score": 2, "score": 2.171875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0071.json.gz" }
test("basic functionality", () => { expect(WeakSet.prototype.delete).toHaveLength(1); var original = [{ a: 1 }, { a: 2 }, { a: 3 }, Symbol("foo")]; const weakSet = new WeakSet(original); expect(weakSet.delete(original[0])).toBeTrue(); expect(weakSet.delete(original[0])).toBeFalse(); expect(weakSet.delete(original[3])).toBeTrue(); expect(weakSet.delete(original[3])).toBeFalse(); expect(weakSet.delete(null)).toBeFalse(); });
2a22cc92ebb33472a05e6f28ee944eb7e241e703
{ "blob_id": "2a22cc92ebb33472a05e6f28ee944eb7e241e703", "branch_name": "refs/heads/master", "committer_date": "2023-09-01T10:45:38", "content_id": "c40a75bf78dce308dfa9ece124cebe78518def59", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "eda03521b87da8bdbef6339b5b252472a5be8d23", "extension": "js", "filename": "WeakSet.prototype.delete.js", "fork_events_count": 3929, "gha_created_at": "2018-12-02T19:28:41", "gha_event_created_at": "2023-09-14T21:00:04", "gha_language": "C++", "gha_license_id": "BSD-2-Clause", "github_id": 160083795, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 460, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/Userland/Libraries/LibJS/Tests/builtins/WeakSet/WeakSet.prototype.delete.js", "provenance": "stack-edu-0042.json.gz:379217", "repo_name": "SerenityOS/serenity", "revision_date": "2023-09-01T08:06:28", "revision_id": "ef9b6c25fafcf4ef0b44a562ee07f6412aeb8561", "snapshot_id": "6ba3ffb242ed76c9f335bd2c3b9a928329cd7d98", "src_encoding": "UTF-8", "star_events_count": 27256, "url": "https://raw.githubusercontent.com/SerenityOS/serenity/ef9b6c25fafcf4ef0b44a562ee07f6412aeb8561/Userland/Libraries/LibJS/Tests/builtins/WeakSet/WeakSet.prototype.delete.js", "visit_date": "2023-09-01T13:04:30.262106", "added": "2024-11-19T01:01:44.653621+00:00", "created": "2023-09-01T08:06:28", "int_score": 3, "score": 2.734375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0060.json.gz" }
var app = angular.module('nbaRoutes'); app.controller('homeCtrl', function($scope, homeService, teamsArray){ for(var i = 0; i < teamsArray.length; i++) { teamsArray[i].then(function(data) { console.log(data); }) } });
7f31f620999588a09c19a0502bc405ad67c8a3ea
{ "blob_id": "7f31f620999588a09c19a0502bc405ad67c8a3ea", "branch_name": "refs/heads/master", "committer_date": "2015-02-25T03:09:02", "content_id": "2c478f4a99f02614ab3e4bae39f2f2609c7aa9af", "detected_licenses": [ "MIT" ], "directory_id": "1539a4dff92e6643c8c19f7e1abb2792591af52f", "extension": "js", "filename": "homeCtrl.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 31134401, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 230, "license": "MIT", "license_type": "permissive", "path": "/js/home/homeCtrl.js", "provenance": "stack-edu-0045.json.gz:657937", "repo_name": "stevenroper/nbaRoutes", "revision_date": "2015-02-25T03:09:02", "revision_id": "5f73a98d9d0cf8671e94025a247cf303ae2bb9a8", "snapshot_id": "9eb16a4e7b327d85f05264e4282ee841787d735e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/stevenroper/nbaRoutes/5f73a98d9d0cf8671e94025a247cf303ae2bb9a8/js/home/homeCtrl.js", "visit_date": "2016-09-01T18:17:06.321206", "added": "2024-11-19T01:41:44.797407+00:00", "created": "2015-02-25T03:09:02", "int_score": 2, "score": 2.125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0063.json.gz" }
/* WITH t_batch AS ( SELECT * FROM sch_chameleon.t_replica_batch WHERE b_started AND b_processed ORDER BY ts_created LIMIT 1 ), t_events AS ( SELECT log.v_table_name, log.v_schema_name, log.v_binlog_event, log.jsb_event_data, tab.v_table_pkey as v_table_pkeys, replace(array_to_string(tab.v_table_pkey,','),'"','') as v_table_pkey, array_length(tab.v_table_pkey,1) as i_pkeys FROM sch_chameleon.t_log_replica log INNER JOIN sch_chameleon.t_replica_tables tab ON tab.v_table_name=log.v_table_name AND tab.v_schema_name=log.v_schema_name INNER JOIN t_batch bat ON bat.i_id_batch=log.i_id_batch ORDER BY ts_event_datetime ), t_sub AS ( SELECT generate_subscripts(v_table_pkeys,1) sub FROM t_events ) SELECT v_table_name, v_schema_name, v_binlog_event, jsb_event_data, string_to_array(v_table_pkey,',') as t_keys, v_table_pkey, i_pkeys FROM t_events ; WITH t_jsb AS ( SELECT '{"id": 1379492, "data": "Hello", "data2": "friend", "date_test": "2016-09-02 11:30:46"}'::jsonb jsb_event_data, ARRAY['id','data'] v_table_pkey ), t_subscripts AS ( SELECT generate_subscripts(v_table_pkey,1) sub FROM t_jsb ) SELECT array_to_string(v_table_pkey,','), array_to_string(array_agg((jsb_event_data->>v_table_pkey[sub])::text),',') as pk_value FROM t_subscripts,t_jsb GROUP BY v_table_pkey ; */ SELECT array_to_string(array_agg(format('%I',t_field)),',') t_field, array_to_string(array_agg(format('%L',t_value)),',') t_value FROM ( SELECT unnest('{id,data,data2,date_test}'::text[]) t_field, unnest('{1379262,Hello," my friend","2016-09-02 11:30:46"}'::text[]) t_value ) t_val ( SELECT count(v_log_table) AS i_cnt_tables, v_log_table FROM sch_chameleon.t_replica_batch GROUP BY v_log_table UNION ALL SELECT 1 AS i_cnt_tables, 't_log_replica_1' AS i_cnt_tables ) ORDER BY 1 LIMIT 1 delete from sch_chameleon.t_replica_batch WITH t_created AS ( SELECT max(ts_created) AS ts_created FROM sch_chameleon.t_replica_batch WHERE NOT b_processed ) UPDATE sch_chameleon.t_replica_batch SET b_started=True FROM t_created WHERE t_replica_batch.ts_created=t_created.ts_created RETURNING i_id_batch, t_binlog_name, i_binlog_position, v_log_table select count(*) from sch_chameleon.t_log_replica select * from sch_chameleon.t_log_replica where enm_binlog_event='delete'; select * from sch_chameleon.t_log_replica where enm_binlog_event='insert' ; --delete from sch_chameleon.t_log_replica select * from sch_chameleon.t_replica_batch order by ts_Created set client_min_messages='debug' select sch_chameleon.fn_process_batch() select count(*) from sakila.test_table WITH t_batch AS ( SELECT i_id_batch FROM sch_chameleon.t_replica_batch WHERE b_started AND b_processed AND NOT b_replayed ORDER BY ts_created LIMIT 1 ), t_events AS ( SELECT bat.i_id_batch, log.v_table_name, log.v_schema_name, log.enm_binlog_event, log.jsb_event_data, replace(array_to_string(tab.v_table_pkey,','),'"','') as t_pkeys, array_length(tab.v_table_pkey,1) as i_pkeys FROM sch_chameleon.t_log_replica log INNER JOIN sch_chameleon.t_replica_tables tab ON tab.v_table_name=log.v_table_name AND tab.v_schema_name=log.v_schema_name INNER JOIN t_batch bat ON bat.i_id_batch=log.i_id_batch ORDER BY ts_event_datetime ) SELECT i_id_batch, v_table_name, v_schema_name, enm_binlog_event, jsb_event_data, string_to_array(t_pkeys,',') as v_table_pkey, t_pkeys, i_pkeys FROM t_events
f0eca3bc6de3ba85f8a3aa3c17e11e4bd91d95b4
{ "blob_id": "f0eca3bc6de3ba85f8a3aa3c17e11e4bd91d95b4", "branch_name": "refs/heads/master", "committer_date": "2017-06-22T06:25:22", "content_id": "90b94d5ac4c4cc8fcddcf52c9c7b614557702ef3", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause" ], "directory_id": "4324057af03cbc90ea60fbb964af67639b51fc92", "extension": "sql", "filename": "scratch.sql", "fork_events_count": 0, "gha_created_at": "2017-06-16T00:57:40", "gha_event_created_at": "2017-06-16T00:57:40", "gha_language": null, "gha_license_id": null, "github_id": 94490906, "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 3872, "license": "BSD-2-Clause,BSD-3-Clause", "license_type": "permissive", "path": "/sql/scratch.sql", "provenance": "stack-edu-0070.json.gz:440576", "repo_name": "WangYiPengPeter/pg_chameleon", "revision_date": "2017-06-22T06:25:22", "revision_id": "df795cc8296f245ca17f69d5c8ede4767e276c5a", "snapshot_id": "b83fd54a07948fb42c576abc96a8516c50171248", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/WangYiPengPeter/pg_chameleon/df795cc8296f245ca17f69d5c8ede4767e276c5a/sql/scratch.sql", "visit_date": "2020-09-17T05:43:09.823480", "added": "2024-11-19T01:26:32.842465+00:00", "created": "2017-06-22T06:25:22", "int_score": 4, "score": 3.796875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0088.json.gz" }
'use strict'; // From Ilya Podolko's webinar demo. /* Recomendations: Service module to describe services. Controller module to describe controllers. Directive module to describe directives. And entire app module. Adding routes(when). [route], {[template path for ng-view], [controller for this template]} otherwise Set default route. $routeParams.id - :id parameter. */ var servicesModule = angular.module('servicesModule',[]); var controllersModule = angular.module('controllersModule', []); var app = angular.module('app', ['ngRoute', 'ngCookies', 'ui.bootstrap', 'servicesModule', 'controllersModule']); app.config([ '$routeProvider', function( $routeProvider ) { $routeProvider.when( '/tasks', {templateUrl: 'partials/tasks.html'} ); $routeProvider.when( '/tasks/:id', {templateUrl: 'partials/task.html', controller: 'TaskCtrl'} ); $routeProvider.otherwise( {redirectTo: '/tasks'} ); }]); angular.element(document).ready(function () { $.get('config.json', function (data) { RESTWebApp = data; }, 'json'); });
6c00c5fa6f08433c27c70dfba09a2660e8cad988
{ "blob_id": "6c00c5fa6f08433c27c70dfba09a2660e8cad988", "branch_name": "refs/heads/master", "committer_date": "2018-04-11T22:35:36", "content_id": "6b4c723441d4d5d79a9b4a774810b514ee242f8b", "detected_licenses": [ "MIT" ], "directory_id": "7d8829b4ac09195f7c37372e0164ab162a81a48b", "extension": "js", "filename": "app.js", "fork_events_count": 0, "gha_created_at": "2018-04-11T19:55:53", "gha_event_created_at": "2018-04-11T19:55:53", "gha_language": null, "gha_license_id": "MIT", "github_id": 129146815, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1048, "license": "MIT", "license_type": "permissive", "path": "/workflow/js/app.js", "provenance": "stack-edu-0041.json.gz:477150", "repo_name": "daimor/EnsembleWorkflowUI", "revision_date": "2018-04-11T22:35:36", "revision_id": "3f3ac94d942d998e89f955127f3ad765799378bf", "snapshot_id": "1b930d35297bd6443bdd8074339cbbdf40d0342c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/daimor/EnsembleWorkflowUI/3f3ac94d942d998e89f955127f3ad765799378bf/workflow/js/app.js", "visit_date": "2020-03-10T02:48:57.363790", "added": "2024-11-19T01:27:44.237996+00:00", "created": "2018-04-11T22:35:36", "int_score": 2, "score": 2.03125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0059.json.gz" }
"""Integration tests for the User Blueprint. """ from unittest.mock import patch from factories.user_factory import UserFactoryFake from tests.base_test_case import BaseTestCase from app.utils.auth import PermissionRepo, UserRoleRepo from factories import ( UserFactory, RoleFactory, PermissionFactory, UserRoleFactory, LocationFactory, ) from .user_role import create_user_role class TestUserEndpoints(BaseTestCase): def setUp(self): self.BaseSetUp() def tearDown(self): self.BaseTearDown() # @patch.object(PermissionRepo, "get_unpaginated") # @patch.object(UserRoleRepo, "find_first") # def test_get_admin_user_endpoint_with_right_permission( # self, mock_user_role_repo_find_first, mock_permission_repo_get_unpaginated # ): # class MockUserRoleRep: # def __init__(self, role_id): # self.role_id = role_id # # class MockPermissionRepo: # def __init__(self, keyword): # self.keyword = keyword # # mock_user_role_repo = MockUserRoleRep(1) # mock_user_perms = MockPermissionRepo("create_user_roles") # # with self.app.app_context(): # mock_user_role_repo_find_first.return_value = mock_user_role_repo # mock_permission_repo_get_unpaginated.return_value = [mock_user_perms] # # response = self.client().get( # self.make_url("/users/admin"), headers=self.headers() # ) # response = response.get_json() # # assert response["msg"] == "OK" # assert response["payload"].get("adminUsers") == [] def test_list_users_endpoint(self): role = RoleFactory.create(name="admin") user_id = BaseTestCase.user_id() PermissionFactory.create(keyword="view_users", role=role) UserRoleFactory.create(user_id=user_id, role=role) # Create ten Dummy users UserFactory.create_batch(10) response = self.client().get(self.make_url("/users/"), headers=self.headers()) response_json = self.decode_from_json_string(response.data.decode("utf-8")) payload = response_json["payload"] self.assert200(response) self.assertEqual(len(payload["users"]), 11) self.assertJSONKeysPresent(payload["users"][0], "first_name", "last_name") def test_delete_user_endpoint_with_right_permission(self): role = RoleFactory.create(name="admin") user_id = BaseTestCase.user_id() permission = PermissionFactory.create(keyword="delete_user", role=role) permission.save() user_role = UserRoleFactory.create(user_id=user_id, role=role) user_role.save() user = UserFactory.create() user.save() response = self.client().delete( self.make_url(f"/users/{user.id}/"), headers=self.headers() ) response_json = self.decode_from_json_string(response.data.decode("utf-8")) payload = response_json["payload"] self.assert200(response) self.assertEqual(payload["status"], "success") self.assertEqual(response_json["msg"], "User deleted") def test_delete_already_deleted_user_with_right_permission(self): role = RoleFactory.create(name="admin") user_id = BaseTestCase.user_id() PermissionFactory.create(keyword="delete_user", role=role) UserRoleFactory.create(user_id=user_id, role=role) user = UserFactory.create(is_deleted=True) user.save() response = self.client().delete( self.make_url(f"/users/{user.id}/"), headers=self.headers() ) response_json = self.decode_from_json_string(response.data.decode("utf-8")) self.assert400(response) self.assertEqual(400, response.status_code) self.assertEqual(response_json["msg"], "User has already been deleted") def test_delete_vendor_endpoint_without_right_permission(self): role = RoleFactory.create(name="admin") user_id = BaseTestCase.user_id() PermissionFactory.create(keyword="wrong_permission", role_id=100) UserRoleFactory.create(user_id=user_id, role=role) user = UserFactory.create(is_deleted=True) user.save() response = self.client().delete( self.make_url(f"/users/{user.id}/"), headers=self.headers() ) response_json = self.decode_from_json_string(response.data.decode("utf-8")) self.assert401(response) self.assertEqual(response_json["msg"], "Access Error - No Permission Granted") def test_delete_user_endpoint_with_wrong_user_id(self): role = RoleFactory.create(name="admin") user_id = BaseTestCase.user_id() PermissionFactory.create(keyword="delete_user", role=role) user = UserFactory.create(is_deleted=True) user.save() UserRoleFactory.create(user_id=user_id, role_id=user.id) response = self.client().delete( self.make_url("/userrs/-576A/"), headers=self.headers() ) self.assert404(response) def test_create_user_endpoint_succeeds1(self): location = LocationFactory() create_user_role("create_user", "admin") user = UserFactoryFake.build() role1 = RoleFactory() user_data = dict( first_name=user.first_name, last_name=user.last_name, role_id=role1.id, email=user.email, gender=user.gender, date_of_birth=str(user.date_of_birth), location_id=location.id, password=user.password, ) headers = self.headers() headers.update({"X-Location": location.id}) response = self.client().post( self.make_url("/users/"), headers=headers, data=self.encode_to_json_string(user_data), ) response_json = self.decode_from_json_string(response.data.decode("utf-8")) self.assertEqual(response.status_code, 201) self.assertEqual(response_json["msg"], "OK") self.assertEqual( response_json["payload"]["user"]["first_name"], user.first_name ) self.assertEqual(response_json["payload"]["user"]["last_name"], user.last_name) def test_create_user_endpoint_succeeds2(self): location = LocationFactory.create() headers = self.headers() headers.update({"X-Location": location.id}) create_user_role("view_users", "admin") user = UserFactory() user.save() response = self.client().get( self.make_url(f"/users/user_profile/{user.id}"), headers=headers ) response_json = self.decode_from_json_string(response.data.decode("utf-8")) self.assertEqual(response.status_code, 200) self.assertEqual(response_json["msg"], "OK") self.assertEqual( response_json["payload"]["user"]["first_name"], user.first_name ) self.assertEqual(response_json["payload"]["user"]["last_name"], user.last_name) # Failing Test even though it should succeed # def test_update_user_endpoint_succeeds(self): # # create_user_role("update_user", "admin") # role = RoleFactory() # user = UserFactory.create(first_name="testng") # user.save() # user_role = UserRoleFactory(user_id=user.id, role=role) # user_role.save() # print("asfdasfd", user_role.id) # print("user being checked", user.id) # # user_data = dict(first_name="Andela", last_name="Eats", role_id=role.id) # # response = self.client().patch( # self.make_url(f"/users/{user.id}"), # headers=self.headers(), # data=self.encode_to_json_string(user_data), # ) # print(response) # response_json = self.decode_from_json_string(response.data.decode("utf-8")) # print(response) # self.assertEqual(response.status_code, 200) # self.assertEqual(response_json["msg"], "OK") # self.assertEqual(response_json["payload"]["user"]["first_name"], user.first_name) # self.assertEqual(response_json["payload"]["user"]["last_name"], user.last_name) def test_update_user_endpoint_with_invalid_role_fails(self): create_user_role("update_user", "admin") role = RoleFactory() user = UserFactory() user.save() UserRoleFactory(user_id=user.id, role=role) user_data = dict( first_name="Andela", last_name="Eats", role_id=100, gender="male", date_of_birth="2020-10-01", employment_date="2020-10-01", ) response = self.client().patch( self.make_url(f"/users/{user.id}"), headers=self.headers(), data=self.encode_to_json_string(user_data), ) response_json = self.decode_from_json_string(response.data.decode("utf-8")) self.assertEqual(response.status_code, 400) self.assertEqual(response_json["msg"], "Role with id 100 doesnot exist") def test_update_user_endpoint_for_non_existing_user_id_fails(self): create_user_role("update_user", "admin") user = UserFactory.create(id=600) user.save() user_data = dict( first_name="Andela", last_name="Eats", user_id=601, role_id=1, gender="male", date_of_birth="2020-10-01", employment_date="2020-10-01", ) response = self.client().put( self.make_url("/users/" + str(user.id + 1)), headers=self.headers(), data=self.encode_to_json_string(user_data), ) response_json = self.decode_from_json_string(response.data.decode("utf-8")) self.assertEqual(response.status_code, 404) self.assertEqual(response_json["msg"], "FAIL") self.assertEqual(response_json["payload"]["user"], "User not found") def test_update_user_endpoint_for_already_deleted_user_fails(self): create_user_role("update_user", "admin") user = UserFactory.create(is_deleted=True) user.save() user_data = dict( first_name="Andela", last_name="Eats", user_id=user.id, role_id=1, gender="male", date_of_birth="2020-10-01", employment_date="2020-10-01", ) response = self.client().put( self.make_url("/users/" + str(user.id)), headers=self.headers(), data=self.encode_to_json_string(user_data), ) response_json = self.decode_from_json_string(response.data.decode("utf-8")) self.assertEqual(response.status_code, 400) self.assertEqual(response_json["msg"], "FAIL") self.assertEqual(response_json["payload"]["user"], "User already deleted") def test_create_user_endpoint_succeeds(self): create_user_role("create_user", "admin") user = UserFactoryFake.build(id=500, is_deleted=True) role = RoleFactory(name="test_role") location = LocationFactory.create() headers = self.headers() headers.update({"X-Location": location.id}) user_data = dict( first_name=user.first_name, last_name=user.last_name, role_id=role.id, gender=user.gender, date_of_birth=str(user.date_of_birth), employment_date=str(user.employment_date), password=user.password, email=user.email, location_id=user.location_id, ) response = self.client().post( self.make_url("/users/"), headers=headers, data=self.encode_to_json_string(user_data), ) response_json = self.decode_from_json_string(response.data.decode("utf-8")) print(response_json) self.assertEqual(response.status_code, 201) self.assertEqual(response_json["msg"], "OK") self.assertEqual( response_json["payload"]["user"]["first_name"], user.first_name ) self.assertEqual(response_json["payload"]["user"]["last_name"], user.last_name) self.assertEqual( response_json["payload"]["user"]["user_roles"][0]["name"], role.name ) self.assertEqual( response_json["payload"]["user"]["user_roles"][0]["help"], role.help )
79daff1789c002007cd2c4eb339993127fbe4239
{ "blob_id": "79daff1789c002007cd2c4eb339993127fbe4239", "branch_name": "refs/heads/development", "committer_date": "2021-02-03T12:46:07", "content_id": "1a074c591f45cbd66c9d361ae1c06d00ceecced2", "detected_licenses": [ "MIT" ], "directory_id": "267c3a8cec5b3c265386195117f845670101129a", "extension": "py", "filename": "test_user_endpoints.py", "fork_events_count": 0, "gha_created_at": "2020-12-22T15:52:24", "gha_event_created_at": "2021-01-31T18:45:08", "gha_language": "Python", "gha_license_id": "MIT", "github_id": 323669431, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12569, "license": "MIT", "license_type": "permissive", "path": "/tests/integration/endpoints/test_user_endpoints.py", "provenance": "stack-edu-0061.json.gz:604436", "repo_name": "Maxcutex/pm_api", "revision_date": "2021-02-03T12:46:07", "revision_id": "de1e1a07feecd1be7bb86a87b4ffed012a05aec0", "snapshot_id": "a0dee8795d6457aaf88f868c5d4179f78ef18df3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Maxcutex/pm_api/de1e1a07feecd1be7bb86a87b4ffed012a05aec0/tests/integration/endpoints/test_user_endpoints.py", "visit_date": "2023-02-25T00:43:48.545547", "added": "2024-11-18T22:02:50.606610+00:00", "created": "2021-02-03T12:46:07", "int_score": 2, "score": 2.078125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0079.json.gz" }
// // LoginViewController.swift // FlockApp // // Created by Nathalie on 4/8/19. // import UIKit import FirebaseAuth class LoginViewController: UIViewController { @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! private var authservice = AppDelegate.authservice override func viewDidLoad() { super.viewDidLoad() authservice.authserviceExistingAccountDelegate = self emailTextField.delegate = self passwordTextField.delegate = self } @IBAction func loginButtonPressed(_ sender: UIButton) { guard let email = emailTextField.text, !email.isEmpty, let password = passwordTextField.text, !password.isEmpty else { return } authservice.signInExistingAccount(email: email, password: password) } } extension LoginViewController: AuthServiceExistingAccountDelegate { func didRecieveErrorSigningToExistingAccount(_ authservice: AuthService, error: Error) { showAlert(title: "Signin Error", message: error.localizedDescription) } func didSignInToExistingAccount(_ authservice: AuthService, user: User) { let mainTabBarController = TabBarController() mainTabBarController.modalPresentationStyle = .fullScreen present(mainTabBarController, animated: true) } } extension LoginViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
1158da6182d24654072ade6006705a03fc9dd961
{ "blob_id": "1158da6182d24654072ade6006705a03fc9dd961", "branch_name": "refs/heads/master", "committer_date": "2020-11-24T21:33:12", "content_id": "0279e40dbc96443c4dc159d577d52da134bef69e", "detected_licenses": [ "MIT" ], "directory_id": "06051ef9e6300453c0252a5003137c27d8826731", "extension": "swift", "filename": "LoginViewController.swift", "fork_events_count": 1, "gha_created_at": "2019-04-02T15:03:49", "gha_event_created_at": "2020-02-06T18:08:21", "gha_language": "Swift", "gha_license_id": "MIT", "github_id": 179102553, "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 1587, "license": "MIT", "license_type": "permissive", "path": "/FlockApp/FlockApp/Groups/Account Login/Account Login View Controllers/LoginViewController.swift", "provenance": "stack-edu-0071.json.gz:875450", "repo_name": "SLRAM/FlockApp", "revision_date": "2020-11-24T21:33:12", "revision_id": "fa2ad512e05693889ebc1d13228d0553d8139602", "snapshot_id": "1094b27f05396d37a3ab40e98f9693090d241c51", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/SLRAM/FlockApp/fa2ad512e05693889ebc1d13228d0553d8139602/FlockApp/FlockApp/Groups/Account Login/Account Login View Controllers/LoginViewController.swift", "visit_date": "2021-06-26T12:52:19.368404", "added": "2024-11-18T23:43:13.833460+00:00", "created": "2020-11-24T21:33:12", "int_score": 3, "score": 2.890625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0089.json.gz" }
<?php namespace app\models; use Yii; use yii\behaviors\TimestampBehavior; use yii\db\Expression; /** * This is the model class for table "pages". * * @property integer $id * @property string $title * */ class Question extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'questions'; } /** * @inheritdoc */ public function rules() { return [ [['title', 'answer', 'question', 'slug'], 'required'], [['category_id'], 'integer'], [['created', 'modified', 'is_public', 'is_show_answer', 'is_often', 'is_famous', 'like', 'dislike'], 'safe'], [['seo_description', 'seo_keyword', 'seo_title'], 'string'], [['slug'], 'unique'], ]; } public function behaviors() { return [ [ 'class' => TimestampBehavior::className(), 'value' => new Expression('NOW()'), 'createdAtAttribute' => 'created', 'updatedAtAttribute' => 'modified', ], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => Yii::t('app', 'ID'), 'title' => Yii::t('app', 'Заголовок'), 'category_id' => Yii::t('app', 'Категория'), 'slug' => Yii::t('app', 'Алиас url'), 'question' => Yii::t('app', 'Вопрос'), 'answer' => Yii::t('app', 'Ответ'), 'created' => Yii::t('app', 'Дата создания'), 'modified' => Yii::t('app', 'Дата обновления'), 'ref' => Yii::t('app', 'Ref'), 'seo_description' => Yii::t('app', 'Seo description'), 'seo_title' => Yii::t('app', 'Seo заголовок'), 'seo_keyword' => Yii::t('app', 'Seo ключевые слова'), 'is_public' => Yii::t('app', 'Опубликовать'), 'is_show_answer' => Yii::t('app', 'Показывать ответ бесплатно'), 'is_often' => Yii::t('app', 'Частовстречающийся'), 'is_famous' => Yii::t('app', 'Вопрос известной компании'), 'like' => Yii::t('app', 'За вопрос'), 'dislike' => Yii::t('app', 'Против вопроса'), ]; } public function getPrevSlug() { $model = Question::find()->where([ 'category_id' => $this->category_id, 'is_public' => true ])->andWhere('id < :id', [':id' => $this->id]) ->orderBy('id DESC')->one(); return $model->slug ?? ''; } public function getNextSlug() { $model = Question::find()->where([ 'category_id' => $this->category_id, 'is_public' => true ])->andWhere('id > :id', [':id' => $this->id]) ->orderBy('id ASC')->one(); return $model->slug ?? ''; } }
fb2550019b86aeb943cf541e36fef89221a55c48
{ "blob_id": "fb2550019b86aeb943cf541e36fef89221a55c48", "branch_name": "refs/heads/master", "committer_date": "2017-03-30T21:09:56", "content_id": "c5a2d595eccb97413b99ed6a7f97bff91d88d6e2", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "69d16ad1f5efb0e6e627d745547df70b5193fc38", "extension": "php", "filename": "Question.php", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 79272969, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 3232, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/models/Question.php", "provenance": "stack-edu-0053.json.gz:289212", "repo_name": "connorholt/yoffer", "revision_date": "2017-03-30T21:09:56", "revision_id": "998d81fe09d5f0d4463f713a9687978f6ebbea8f", "snapshot_id": "113829219794b7346ff1d86023852733ccc448cc", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/connorholt/yoffer/998d81fe09d5f0d4463f713a9687978f6ebbea8f/models/Question.php", "visit_date": "2021-01-11T21:13:20.604748", "added": "2024-11-18T23:23:20.091848+00:00", "created": "2017-03-30T21:09:56", "int_score": 3, "score": 2.515625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0071.json.gz" }
$(document).ready(function() { //Shows side navs $("#sideNavButton").click(() => { $("#mySidenav").css("width", "250px"); }); //hides side navs $(".closebtn").click(() => { $("#mySidenav").css("width", "0"); }); //On contact link button press, close side nav $("#mySidenav a:nth-child(8)").click(() => { $("#mySidenav").css("width", "0"); }); //AJAX QUERY SERVER $("#form").submit(function(e) { e.preventDefault(); let data = getFormData($(this)); $("#loading-gif").css("display", "inline-block"); $.post("/submit", data).done(data => { $("#loading-gif").css("display", "none"); $("#return").html(data); }); }); //prepares form data to be POSTED function getFormData($form) { let unindexed_array = $form.serializeArray(); let indexed_array = {}; $.map(unindexed_array, function(n, i) { indexed_array[n["name"]] = n["value"]; }); return indexed_array; } function parallax(scroll) { $("video").css("top", scroll * 0.75 + "px"); } $("#imagem1").parallax({ imageSrc: "/images/big/bigBarBig.jpg" }); $("#imagem2").parallax({ imageSrc: "/images/big/cocktailNiceBig.jpg" }); $("#imagem3").parallax({ imageSrc: "/images/big/aboutMain.jpg" }); $("#imagem4").parallax({ imageSrc: "/images/big/weddingBarBig.jpg" }); $("#imagem5").parallax({ imageSrc: "/images/big/mobileCocktailBig.jpg" }); $("#imagem6").parallax({ imageSrc: "/images/big/coffeeCocktailBig.jpg" }); $("#imagem7").parallax({ imageSrc: "/images/big/juAndBroBig.jpg" }); $("#imagem8").parallax({ imageSrc: "/images/big/jullBlinking.jpg" }); $("#imagem9").parallax({ imageSrc: "/images/big/cocktail5Big.jpg" }); $("#imagem10").parallax({ imageSrc: "/images/big/coffeeCocktailBig.jpg" }); var scrollLink = $(".scroll"); // Smooth scrolling scrollLink.click(function(e) { e.preventDefault(); $("body,html").animate( { scrollTop: $(this.hash).offset().top }, 1000 ); }); $("#logo").click(e => { $("body,html").animate( { scrollTop: 0 }, 1000 ); }); // Active link switching $(window).scroll(function() { let scroll = $(window).scrollTop(); parallax(scroll); let scrollbarLocation = $(this).scrollTop(); scrollLink.each(function() { let sectionOffset = $(this.hash).offset().top - 20; if (sectionOffset <= scrollbarLocation) { $(this) .parent() .addClass("active"); $(this) .parent() .siblings() .removeClass("active"); } }); }); });
50e3fe5e81fa5b987cc6549a9cd54b05b9dfd0f9
{ "blob_id": "50e3fe5e81fa5b987cc6549a9cd54b05b9dfd0f9", "branch_name": "refs/heads/master", "committer_date": "2019-02-13T21:42:24", "content_id": "cee16b471bd2dfcd8cbac4310bb1e5c68dc05132", "detected_licenses": [ "MIT" ], "directory_id": "b07854787fde877a27450a744ab1ee05eef9ecb5", "extension": "js", "filename": "scripts.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 161098371, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2626, "license": "MIT", "license_type": "permissive", "path": "/public/scripts/scripts.js", "provenance": "stack-edu-0035.json.gz:483815", "repo_name": "cadimas/StirWebsite", "revision_date": "2019-02-13T21:42:24", "revision_id": "effcb967aecf4ead8df2f7cdd8166dd427b009a9", "snapshot_id": "688c30bfd2ccce1a6d529bd8838e396c6d4c788d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/cadimas/StirWebsite/effcb967aecf4ead8df2f7cdd8166dd427b009a9/public/scripts/scripts.js", "visit_date": "2020-04-10T15:08:17.124661", "added": "2024-11-18T23:50:11.481613+00:00", "created": "2019-02-13T21:42:24", "int_score": 2, "score": 2.390625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0053.json.gz" }
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use App\Models\InitialScreening; use App\Models\FinalInterview; use App\Models\JobOrientation; use App\Models\Applicant; use App\Models\Test; use App\Models\User; use App\Models\InterviewHistory; use Session; class ApplicationsController extends Controller { public function __construct(){ $this->middleware('auth'); $this->middleware('checkrole:2')->only(['procedure','initial_screening','final-interview','job-orientation']); $this->middleware('checkrole:3')->only(['candidates','profile']); } public function procedure($applicant_id){ $applicant = Applicant::with('application_status','initial_screening','final_interview','job_orientation')->find($applicant_id); $tests = Test::all(); $interviewers = User::interviewers(); $init_view = ''; $fin_view = ''; $jo_view = ''; // this is for the view on the initial screening tab if($applicant->initial_screening()->exists()){ $init_view = 'application.initial_screen.show'; }else{ $init_view = 'application.initial_screen.new'; } // this is for the view on the final interview tab if(in_array($applicant->application_status_id,[1,2])) $fin_view = 'application.unavailable'; elseif($applicant->final_interview()->exists()){ $fin_view = 'application.final_interview.show'; }else{ $fin_view = 'application.final_interview.new'; } // this is for the job orientation view tab if(in_array($applicant->application_status_id,[1,2,3,4,5,11])) $jo_view = 'application.unavailable'; elseif($applicant->job_orientation()->exists()){ $jo_view = 'application.job_orientation.show'; }else{ $jo_view = 'application.job_orientation.new'; } return view('application.main',compact('applicant','tests','interviewers','init_view','fin_view','jo_view')); } public function candidates(){ $user = Auth::user(); $interviews = $user->final_interviews()->with(['applicant'])->where('is_done','=',0)->paginate(5); return view('application.candidate.candidate_list',compact('interviews')); } public function search(Request $request){ $user_id = Auth::id(); $candidates = FinalInterview::search($request->skey, $user_id); $skey = $request->skey; if($request->ajax()) return view('application.candidate.search-result',compact('candidates','skey')); return view('application.candidate.search-page',compact('candidates','skey')); } public function profile($applicant_id){ $applicant = Applicant::find($applicant_id); $info = $applicant->person()->with(['colleges','work_experiences'])->first(); $elem = $applicant->person->elem(); $high = $applicant->person->high(); $init = $applicant->initial_screening; $fin = $applicant->final_interview; return view('application.candidate.candidate_profile',compact('info','elem','high','init','fin')); } public function no_show($applicant_id, Request $request){ $fin_interview = Applicant::find($applicant_id)->final_interview; // update final interviews table $fin_interview->result = 'No Show'; $fin_interview->is_done = 1; if($fin_interview->save()){ // insert to history $info = Applicant::with(['person','final_interview'])->find($applicant_id); $history_data['interviewer_id'] = $info->final_interview->interviewer_id; $history_data['applicant_first_name'] = $info->person->first_name; $history_data['applicant_middle_name'] = $info->person->middle_name; $history_data['applicant_last_name'] = $info->person->last_name; $history_data['applicant_applied_for'] = $info->job->name; $history_data['applicant_applied_date'] = $info->applied_date(); $history_data['result'] = $info->final_interview->result; $history_data['remarks'] = $info->final_interview->remarks; InterviewHistory::create($history_data); // update application status $fin_interview->applicant()->update(['application_status_id'=>application_status('FINS')]); Session::flash('success',"{$info->person->name()} was tagged as no show"); }else{ Session::flash('error','Something went wrong'); } } }
4d7c1570af917a8233d375e7a09e3a160b620cc2
{ "blob_id": "4d7c1570af917a8233d375e7a09e3a160b620cc2", "branch_name": "refs/heads/master", "committer_date": "2020-11-05T19:12:00", "content_id": "6ffff530b01c67c65d521e8ebfa33801231a8271", "detected_licenses": [ "MIT" ], "directory_id": "ab83d757b76f961e31df4765dd9cce3ede8bf21e", "extension": "php", "filename": "ApplicationsController.php", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 227941430, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 4689, "license": "MIT", "license_type": "permissive", "path": "/app/Http/Controllers/ApplicationsController.php", "provenance": "stack-edu-0053.json.gz:614719", "repo_name": "Louknows-leadgen/recruitment", "revision_date": "2020-11-05T19:12:00", "revision_id": "675c682e4bb264959a4da0579440231065b07078", "snapshot_id": "5484a70cf5434b2f0f1be1c7a2ed5840a82c7c1b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Louknows-leadgen/recruitment/675c682e4bb264959a4da0579440231065b07078/app/Http/Controllers/ApplicationsController.php", "visit_date": "2020-11-24T03:17:07.838264", "added": "2024-11-19T00:38:32.802200+00:00", "created": "2020-11-05T19:12:00", "int_score": 2, "score": 2.15625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0071.json.gz" }
module Fastlane module Actions class UploadToPlayStoreInternalAppSharingAction < Action def self.run(params) require 'supply' # If no APK params were provided, try to fill in the values from lane context, preferring # the multiple APKs over the single APK if set. if params[:apk_paths].nil? && params[:apk].nil? all_apk_paths = Actions.lane_context[SharedValues::GRADLE_ALL_APK_OUTPUT_PATHS] || [] if all_apk_paths.size > 1 params[:apk_paths] = all_apk_paths else params[:apk] = Actions.lane_context[SharedValues::GRADLE_APK_OUTPUT_PATH] end end # If no AAB param was provided, try to fill in the value from lane context. # First GRADLE_ALL_AAB_OUTPUT_PATHS if only one # Else from GRADLE_AAB_OUTPUT_PATH if params[:aab].nil? all_aab_paths = Actions.lane_context[SharedValues::GRADLE_ALL_AAB_OUTPUT_PATHS] || [] if all_aab_paths.count == 1 params[:aab] = all_aab_paths.first else params[:aab] = Actions.lane_context[SharedValues::GRADLE_AAB_OUTPUT_PATH] end end Supply.config = params # we already have the finished config Supply::Uploader.new.perform_upload_to_internal_app_sharing end ##################################################### # @!group Documentation ##################################################### def self.description "Upload binaries to Google Play Internal App Sharing (via _supply_)" end def self.details "More information: https://docs.fastlane.tools/actions/upload_to_play_store_internal_app_sharing/" end def self.available_options require 'supply' require 'supply/options' options = Supply::Options.available_options.clone # remove all the unnecessary (for this action) options options_to_keep = [:package_name, :apk, :apk_paths, :aab, :aab_paths, :json_key, :json_key_data, :root_url, :timeout] options.delete_if { |option| options_to_keep.include?(option.key) == false } end def self.return_value "Returns a string containing the download URL for the uploaded APK/AAB (or array of strings if multiple were uploaded)." end def self.authors ["andrewhavens"] end def self.is_supported?(platform) platform == :android end def self.example_code ["upload_to_play_store_internal_app_sharing"] end def self.category :production end end end end
0a22bad57070709d0f238ce3e5276d7c588faef8
{ "blob_id": "0a22bad57070709d0f238ce3e5276d7c588faef8", "branch_name": "refs/heads/master", "committer_date": "2023-05-25T12:11:08", "content_id": "02114a5dc5ad265553c0bff69648b0bae124bf32", "detected_licenses": [ "MIT" ], "directory_id": "5049943cc2505e1bca3906dd2f466952ae21d73c", "extension": "rb", "filename": "upload_to_play_store_internal_app_sharing.rb", "fork_events_count": 1, "gha_created_at": "2017-11-22T10:54:29", "gha_event_created_at": "2023-09-11T16:49:25", "gha_language": "Ruby", "gha_license_id": "MIT", "github_id": 111672522, "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2647, "license": "MIT", "license_type": "permissive", "path": "/fastlane/lib/fastlane/actions/upload_to_play_store_internal_app_sharing.rb", "provenance": "stack-edu-0067.json.gz:664379", "repo_name": "BendingSpoons/fastlane", "revision_date": "2023-05-25T12:11:08", "revision_id": "e5c8218d2d9fb8444fba4e7bec5987344692a7ff", "snapshot_id": "f3c0903d3b47c7f33f5df03c249b114a6671d2ff", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/BendingSpoons/fastlane/e5c8218d2d9fb8444fba4e7bec5987344692a7ff/fastlane/lib/fastlane/actions/upload_to_play_store_internal_app_sharing.rb", "visit_date": "2023-06-08T15:20:52.639267", "added": "2024-11-18T19:08:37.148375+00:00", "created": "2023-05-25T12:11:08", "int_score": 2, "score": 2.140625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0085.json.gz" }
from __future__ import print_function import concurrent.futures import numba import numpy as np import time from collections import defaultdict from disc_learning import NoiseAwareModel from math import exp, log MIN_LR = 1e-6 class FMCT(NoiseAwareModel): """fastmulticontext""" def __init__(self, preprocess_function=None): self.fmct = None self.w = None self.X_train = None self.preprocess_f = preprocess_function def train(self, training_marginals, embed_matrices, **hyperparams): """ Train method for fastmulticontext training_marginals: marginal probabilities for training examples embed_matrices: list of matrices to embed hyperparams: fmct hyperparams, including raw_xs """ self.fmct = fastmulticontext(self.preprocess_f) self.fmct.train(training_marginals, embed_matrices, **hyperparams) def marginals(self, embed_matrices, raw_xs=None): return self.fmct.predict(embed_matrices, raw_xs) def get_matrix_keys(matrices): n, m = matrices[0].shape[0], len(matrices) embed_xs = [[[] for _ in xrange(m)] for _ in xrange(n)] for k, matrix in enumerate(matrices): matrix_coo = matrix.tocoo(copy=True) for i, j, ct in zip(matrix_coo.row, matrix_coo.col, matrix_coo.data): embed_xs[i][k].extend('FEATURE_{0}_{1}'.format(k, j) for _ in xrange(int(ct))) print("Processed {0} matrices".format(k)) return embed_xs @numba.jit(nopython=True, nogil=True) def fmct_activation(z, hidden_embed, wo, wo_raw, wi_sub, x_ct, x_type, x_raw): """ JIT function for computing activation for fmct """ n_classes, embed_size = wo.shape raw_size = wo_raw.shape[1] x_size, dim = wi_sub.shape # Embedded features for i in xrange(x_size): if x_ct[i] == 0: continue for j in xrange(dim): hidden_embed[j + x_type[i]*dim] += wi_sub[i][j] / x_ct[i] # Compute activations for k in xrange(n_classes): for j in xrange(embed_size): z[k] += wo[k][j] * hidden_embed[j] for r in xrange(raw_size): z[k] += wo_raw[k][r] * x_raw[r] @numba.jit(nopython=True, nogil=True) def fmct_update(wo, wo_raw, wi_sub, x_ct, x_type, x_raw, p, lr, lambda_n): """ JIT function for issuing SGD step of fmct """ n_classes, embed_size = wo.shape raw_size = wo_raw.shape[1] x_size, dim = wi_sub.shape # Get activations z = np.zeros(n_classes) hidden_embed = np.zeros(embed_size) fmct_activation(z, hidden_embed, wo, wo_raw, wi_sub, x_ct, x_type, x_raw) # Compute softmax mz = z[0] for i in xrange(n_classes): mz = max(mz, z[i]) s = 0 for k in xrange(n_classes): z[k] = exp(z[k] - mz) s += z[k] for k in xrange(n_classes): z[k] /= s # Update embedding gradient and linear layer grad = np.zeros(embed_size) for k in xrange(n_classes): # Noise-aware gradient calculation # g(x) = [(1-p)\hat{p} - p(1-\hat{p})]x alpha = lr * ((1.0-p[k])*z[k] - p[k]*(1.0-z[k])) # Updates for embedded features for j in xrange(embed_size): grad[j] += alpha * wo[k][j] # Apply regularization first wo[k][j] *= (1.0 - lr * lambda_n) wo[k][j] -= alpha * hidden_embed[j] # Updates for raw features for r in xrange(raw_size): # Apply regularization first wo_raw[k][r] *= (1.0 - lr * lambda_n) wo_raw[k][r] -= alpha * x_raw[r] # Update embeddings for i in xrange(x_size): for j in xrange(dim): if x_ct[i] == 0: continue # Apply regularization first wi_sub[i][j] *= (1.0 - lr * lambda_n) wi_sub[i][j] -= (grad[j + x_type[i]*dim] / x_ct[i]) # Return loss pmx, lmx = 0.0, None for k in xrange(n_classes): if p[k] > pmx: pmx, lmx = p[k], -log(z[k]) return lmx @numba.jit(nopython=True, nogil=True) def print_status(progress, loss, n_examples, lr): """ Print training progress and loss """ print('-------------------') print(100. * progress) print(loss / n_examples) print('-------------------') @numba.jit(nopython=True, nogil=True) def fmct_sgd_thread(thread_n, wo, wo_raw, wi, marginals, lambda_n, epoch, n, lr, raw_xs, n_print, feat_start, feat_end, f_cache, f_ct_cache, f_t_cache): loss, n_examples, lr_orig = 0, 0, lr ### Run SGD ### for kt in xrange(epoch * n): # Update status and learning rate k = kt % n n_examples += 1 progress = float(kt) / (epoch * n) lr = max(MIN_LR, lr_orig * (1.0 - progress)) # Retrieve features and probabilities feats = f_cache[feat_start[k] : feat_end[k]] feats_ct = f_ct_cache[feat_start[k] : feat_end[k]] feats_type = f_t_cache[feat_start[k] : feat_end[k]] raw_feats = raw_xs[k] if len(feats) + len(raw_feats) == 0: continue # Gradient step wi_sub = wi[feats] loss += fmct_update( wo, wo_raw, wi_sub, feats_ct, feats_type, raw_feats, marginals[k], lr, lambda_n, ) wi[feats, :] = wi_sub # Update learning rate and print status if thread_n == 0 and kt % n_print == 0: print_status(progress, loss, n_examples, lr) if thread_n == 0: print_status(1, loss, n_examples, lr) print('\n') def fmct_sgd(n_threads, *args): if n_threads == 1: fmct_sgd_thread(0, *args) else: threadpool = concurrent.futures.ThreadPoolExecutor(n_threads) threads = [ threadpool.submit(fmct_sgd_thread, i, *args) for i in xrange(n_threads) ] concurrent.futures.wait(threads) for thread in threads: if thread.exception() is not None: raise thread.exception() class fastmulticontext(object): def __init__(self, preprocess_function=get_matrix_keys): """ Initialize fastmulticontext model preprocess_function: function returning features for embedding sequence """ self.vocabs = [] self.n_classes = None self.n_embed = None self.vocab_slice = None self.wo = None self.wo_raw = None self.wi = None self.preprocess_f = preprocess_function def train(self, marginals, embed_xs, raw_xs=None, dim=50, lr=0.05, lambda_l2=1e-7, epoch=5, min_ct=1, n_print=10000, n_threads=16, seed=1701): """ Train FMCT model marginals: marginal probabilities for training examples (array) embed_xs: embedded features for training examples (passed to feat_f) raw_xs: raw features for training examples (2d numpy array) dim: dimensionality of embeddings lr: initial learning rate epoch: number of learning epochs min_ct: minimum feature count for modeling n_print: how frequently to print updates """ if seed is not None: np.random.seed(seed=seed) print("Processing data", end='\t\t') embed_xs = self.preprocess_f(embed_xs) if self.preprocess_f else embed_xs self.n_classes = 2 # Hardcode binary classification for now n = len(embed_xs) ### Init feature indices ### self.n_embed = len(embed_xs[0]) # If no raw features, add a bias term if raw_xs is None: raw_xs = np.ones((n, 1)) ### Build vocab ### print("Building vocab", end='\t\t') self._build_vocabs(embed_xs, min_ct) all_vocab_size = self.vocab_slice[-1] feat_cache = [] feat_ct_cache = [] feat_type_cache = [] feat_start, feat_end = np.zeros(n, dtype=int), np.zeros(n, dtype=int) s = 0 for k in xrange(n): feats, feats_ct, feats_type = self._get_vocab_index(embed_xs[k]) feat_cache.extend(feats) feat_ct_cache.extend(feats_ct) feat_type_cache.extend(feats_type) feat_start[k] = s feat_end[k] = s + len(feats) s += len(feats) feat_cache = np.ravel(feat_cache).astype(int) feat_ct_cache = np.ravel(feat_ct_cache) feat_type_cache = np.ravel(feat_type_cache).astype(int) ### Init model ### print("Training") self.wo = np.zeros((self.n_classes, dim * self.n_embed)) self.wo_raw = np.zeros((self.n_classes, raw_xs.shape[1])) self.wi = np.random.uniform(-1.0 / dim, 1.0 / dim, (all_vocab_size, dim)) marginals = np.array([[1.0 - float(p), float(p)] for p in marginals]) lambda_n = float(lambda_l2) / n s = time.time() fmct_sgd( n_threads, self.wo, self.wo_raw, self.wi, marginals, lambda_n, epoch, n, lr, raw_xs, n_print, feat_start, feat_end, feat_cache, feat_ct_cache, feat_type_cache, ) print("Training time: {0:.3f} seconds".format(time.time() - s)) def predict(self, embed_xs, raw_xs=None): """ Predict marginals for new examples embed_xs: embedded features raw_xs: raw features """ embed_xs = self.preprocess_f(embed_xs) if self.preprocess_f else embed_xs n = len(embed_xs) log_odds = np.zeros(n) n_skipped = 0 # If no raw features, add a bias term if raw_xs is None: raw_xs = np.ones((n, 1)) for k in xrange(n): x, x_raw = embed_xs[k], raw_xs[k, :] feats, feats_ct, feats_type = self._get_vocab_index(x) if len(feats) + np.sum(x_raw) == 0: n_skipped += 1 log_odds[k] = 0.0 continue wi_sub = self.wi[feats, :] z = np.zeros(self.n_classes) hidden_embed = np.zeros(self.wo.shape[1]) fmct_activation( z, hidden_embed, self.wo, self.wo_raw, wi_sub, feats_ct, feats_type, x_raw ) log_odds[k] = z[1] print("Skipped {0} because no feats".format(n_skipped)) return 1.0 / (1.0 + np.exp(-log_odds)) def _build_vocabs(self, embed_xs, min_ct): """ Build vocabulary embed_xs: features to embed min_ct: minimum count of feature to include in modeling """ if not hasattr(min_ct, '__iter__'): min_ct = [min_ct for _ in xrange(self.n_embed)] count_dicts = [defaultdict(int) for _ in xrange(self.n_embed)] # Count instances of feats in corpus for x in embed_xs: for d, feats in enumerate(x): for feat in feats: count_dicts[d][feat] += 1 # Build vocab from feats with sufficient counts self.vocabs = [{} for _ in xrange(self.n_embed)] for d, count_dict in enumerate(count_dicts): for feat, ct in count_dict.iteritems(): if ct >= min_ct[d]: self.vocabs[d][feat] = len(self.vocabs[d]) print("Built vocab {0} of length {1}".format(d, len(self.vocabs[d]))) self.vocab_slice = [0] for vocab in self.vocabs: self.vocab_slice.append(self.vocab_slice[-1] + len(vocab)) def _get_vocab_index(self, x): """ Retrieve feat indices of x x: feature to embed """ # Get feature indices in each vocab vocab_idxs = [] for d, feats in enumerate(x): indices = [] for feat in feats: if feat in self.vocabs[d]: indices.append(self.vocabs[d][feat]) vocab_idxs.append(np.ravel(sorted(indices))) # Aggregate to global index m, s = np.sum([len(vc) for vc in vocab_idxs]), 0 feat_idxs, feat_cts, feat_type = np.zeros(m), np.zeros(m), np.zeros(m) for i, vc in enumerate(vocab_idxs): feat_idxs[s : s+len(vc)] = (vc + self.vocab_slice[i]) feat_cts[s : s+len(vc)] = len(vc) feat_type[s : s+len(vc)] = i s += len(vc) return feat_idxs.astype(int), feat_cts.astype(int), feat_type.astype(int) def _print_status(self, progress, loss, n_examples, lr): """ Print training progress and loss """ sys.stdout.write("\rProgress: {0:06.3f}%\tLoss: {1:.6f}\tLR={2:.6f}".format( 100. * progress, loss / n_examples, lr )) sys.stdout.flush()
86ed0f863206413733a7d60c22d807c8c4fc162f
{ "blob_id": "86ed0f863206413733a7d60c22d807c8c4fc162f", "branch_name": "refs/heads/master", "committer_date": "2019-06-28T22:51:20", "content_id": "5561837eed64f5f828f1453fc7e98cfa7dfa586d", "detected_licenses": [ "Apache-2.0" ], "directory_id": "66835854d2fd1492d1ccb113b433966e9f40dc11", "extension": "py", "filename": "fastmulticontext.py", "fork_events_count": 0, "gha_created_at": "2019-04-24T20:16:37", "gha_event_created_at": "2019-04-24T20:16:37", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 183300539, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12715, "license": "Apache-2.0", "license_type": "permissive", "path": "/snorkel/contrib/disc_learning/fmc/fastmulticontext.py", "provenance": "stack-edu-0057.json.gz:409843", "repo_name": "nishamuktewar/snorkel", "revision_date": "2019-06-28T22:51:20", "revision_id": "049de8f8b4c8e3626de87cd1bce6f6cea746abbd", "snapshot_id": "b8c4cbca50482ae0f846cf7966bf51682234718d", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/nishamuktewar/snorkel/049de8f8b4c8e3626de87cd1bce6f6cea746abbd/snorkel/contrib/disc_learning/fmc/fastmulticontext.py", "visit_date": "2020-05-16T21:17:51.015968", "added": "2024-11-18T19:58:21.227450+00:00", "created": "2019-06-28T22:51:20", "int_score": 2, "score": 2.375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0075.json.gz" }
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os # Dependency imports import tensorflow as tf from slim.datasets import dataset_utils slim = tf.contrib.slim _FILE_PATTERN = 'lung_32_%s.tfrecord' _SPLITS_TO_SIZES = {'train': 10000, 'valid': 100, 'test': 1000, 'uint8': 900, 'float32': 900} _ITEMS_TO_DESCRIPTIONS = { 'real_image': 'A [32 x 32 x 1] RGB image.', 'virtual_image': 'A [32 x 32 x 1] RGB image.', 'label': 'A float32 vector of length 6', } def get_split(split_name, dataset_dir, file_pattern=None, reader=None): """Gets a dataset tuple with instructions for reading MNIST. Args: split_name: A train/test split name. dataset_dir: The base directory of the dataset sources. Returns: A `Dataset` namedtuple. Raises: ValueError: if `split_name` is not a valid train/test split. """ if split_name not in _SPLITS_TO_SIZES: raise ValueError('split name %s was not recognized.' % split_name) if not file_pattern: file_pattern = _FILE_PATTERN file_pattern = os.path.join(dataset_dir, file_pattern % split_name) # Allowing None in the signature so that dataset_factory can use the default. if reader is None: reader = tf.TFRecordReader keys_to_features = { 'real_image': tf.FixedLenFeature([], dtype=tf.string), 'images/format': tf.FixedLenFeature([], dtype=tf.string, default_value='raw'), 'virtual_image': tf.FixedLenFeature([], dtype=tf.string), 'label': tf.FixedLenFeature([], dtype=tf.string), } items_to_handlers = { 'real_image': slim.tfexample_decoder.Image( image_key='real_image', format_key='images/format', shape=[32, 32, 1], # required after my hack in # tensorflow/contrib/slim/python/slim/data/tfexample_decoder.py channels=1, # unused after above hack dtype=tf.float32), 'virtual_image': slim.tfexample_decoder.Image( image_key='virtual_image', format_key='images/format', shape=[32, 32, 1], channels=1, dtype=tf.float32), 'label': slim.tfexample_decoder.Image( image_key='label', format_key='images/format', shape=[6], # required channels=1, # unused dtype=tf.float32), } decoder = slim.tfexample_decoder.TFExampleDecoder( keys_to_features, items_to_handlers) labels_to_names = None if dataset_utils.has_labels(dataset_dir): labels_to_names = dataset_utils.read_label_file(dataset_dir) return slim.dataset.Dataset( data_sources=file_pattern, reader=reader, decoder=decoder, num_samples=_SPLITS_TO_SIZES[split_name], # num_classes=_NUM_CLASSES, items_to_descriptions=_ITEMS_TO_DESCRIPTIONS, labels_to_names=labels_to_names)
feb3d7b86545c1d864f8820bb8ef6c423c9a609c
{ "blob_id": "feb3d7b86545c1d864f8820bb8ef6c423c9a609c", "branch_name": "refs/heads/master", "committer_date": "2017-12-16T01:56:25", "content_id": "55ad034b01aa7661cf78d15600dba0b6a17fd92a", "detected_licenses": [ "Apache-2.0" ], "directory_id": "ea3115e481284ab0fed84b2bb09c6b1325320622", "extension": "py", "filename": "lung.py", "fork_events_count": 0, "gha_created_at": "2017-09-29T22:44:45", "gha_event_created_at": "2017-09-29T22:44:45", "gha_language": null, "gha_license_id": null, "github_id": 105323112, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2810, "license": "Apache-2.0", "license_type": "permissive", "path": "/research/domain_adaptation/datasets/lung.py", "provenance": "stack-edu-0062.json.gz:470568", "repo_name": "gnedivad/models", "revision_date": "2017-12-16T01:56:25", "revision_id": "59091c7b295a349434e21a24bda72b517c594140", "snapshot_id": "4e094e454ffa513b569ef362d2f1a6f4da7b1502", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/gnedivad/models/59091c7b295a349434e21a24bda72b517c594140/research/domain_adaptation/datasets/lung.py", "visit_date": "2021-08-30T04:29:47.852274", "added": "2024-11-18T20:26:54.645230+00:00", "created": "2017-12-16T01:56:25", "int_score": 2, "score": 2.390625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0080.json.gz" }
# PG PubSub A Publish/Subscribe implementation on top of [PostgreSQL NOTIFY/LISTEN](http://www.postgresql.org/docs/9.3/static/sql-notify.html) [![Build Status](https://travis-ci.org/voxpelli/node-pg-pubsub.svg?branch=master)](https://travis-ci.org/voxpelli/node-pg-pubsub) [![Coverage Status](https://coveralls.io/repos/voxpelli/node-pg-pubsub/badge.svg)](https://coveralls.io/r/voxpelli/node-pg-pubsub) [![dependencies Status](https://david-dm.org/voxpelli/node-pg-pubsub/status.svg)](https://david-dm.org/voxpelli/node-pg-pubsub) [![Known Vulnerabilities](https://snyk.io/test/github/voxpelli/node-pg-pubsub/badge.svg?targetFile=package.json)](https://snyk.io/test/github/voxpelli/node-pg-pubsub?targetFile=package.json) [![js-semistandard-style](https://img.shields.io/badge/code%20style-semistandard-brightgreen.svg?style=flat)](https://github.com/Flet/semistandard) ## Installation ```bash npm install pg-pubsub --save ``` ## Requirements Node.js >= 6.x ## Usage Simple: ```javascript var pubsubInstance = new PGPubsub('postgres://username@localhost/database'); pubsubInstance.addChannel('channelName', function (channelPayload) { // Process the payload – if it was JSON that JSON has been parsed into an object for you }); pubsubInstance.publish('channelName', { hello: "world" }); ``` The above sends `NOTIFY channelName, '{"hello":"world"}'` to PostgreSQL, which will trigger the above listener with the parsed JSON in `channelPayload`. More advanced variant: ```javascript var pubsubInstance = new PGPubsub('postgres://username@localhost/database'); pubsubInstance.addChannel('channelName'); // pubsubInstance is a full EventEmitter object that sends events on channel names pubsubInstance.once('channelName', function (channelPayload) { // Process the payload }); ``` ## new PGPubsub([conString], [options]) * **conString** – a connection string for the Postgres database. If none is picked, then the default is the same default as for [`pg.Client()`](https://github.com/brianc/node-postgres/wiki/Client) * **options.retryLimit** – may be set to a numeric value to limit the the number of retries that are made ## Methods * **addChannel(channelName[, eventListener])** – starts listening on a channel and optionally adds an event listener for that event. As `PGPubsub` inherits from `EventEmitter` one also add it oneself. * **removeChannel(channelName[, eventListener])** – either removes all event listeners and stops listeneing on the channel or removes the specified event listener and stops listening on the channel if that was the last listener attached. * **publish(channelName, data)** – publishes the specified data JSON-encoded to the specified channel. It may be better to do this by sending the `NOTIFY channelName, '{"hello":"world"}'` query yourself using your ordinary Postgres pool, rather than relying on the single connection of this module. Returns a Promise that will become rejected or resolved depending on the success of the Postgres call. * **close** – closes down the database connection and removes all listeners. Useful for graceful shutdowns. * All [EventEmitter methods](http://nodejs.org/api/events.html#events_class_events_eventemitter) are inherited from `EventEmitter` ## Description Creating a `PGPubsub` instance will not do much up front. It will prepare itself to start a Postgres connection once the first channel is added and then it will keep a connection open until its shut down, reconnecting it if it gets lost, so that it can constantly listen for new notifications. ## Lint / Test `npm test`
216433aacaea3a22b03778cdd19f508d88fa57ad
{ "blob_id": "216433aacaea3a22b03778cdd19f508d88fa57ad", "branch_name": "refs/heads/master", "committer_date": "2018-06-17T14:54:26", "content_id": "32597dcee44ebbbd0cd6add4717913a55c8660c7", "detected_licenses": [ "MIT" ], "directory_id": "081bac803ff71963a1436be8dc4dd52735750397", "extension": "md", "filename": "README.md", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3589, "license": "MIT", "license_type": "permissive", "path": "/README.md", "provenance": "stack-edu-markdown-0005.json.gz:43302", "repo_name": "darahayes/node-pg-pubsub", "revision_date": "2018-06-17T14:54:26", "revision_id": "726bcdf8fb6b1918e9b570fabd7d3794ae62d742", "snapshot_id": "f086a32ad4214ed841651bad7dea0d00049ce9db", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/darahayes/node-pg-pubsub/726bcdf8fb6b1918e9b570fabd7d3794ae62d742/README.md", "visit_date": "2020-03-23T16:11:29.970749", "added": "2024-11-19T02:44:56.835868+00:00", "created": "2018-06-17T14:54:26", "int_score": 4, "score": 3.890625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0005.json.gz" }
require "fipe2/version" module Fipe2 class VehicleType attr_accessor :pk, :name def initialize(pk, name) self.pk = pk self.name = name end end class TableReference attr_accessor :pk, :date, :vtype def initialize(pk, date, vtype) self.pk = pk self.date = date self.vtype = vtype end end class VehicleBrand attr_accessor :pk, :brand, :vdate def initialize(pk, brand, vdate) self.pk = pk self.brand = brand self.vdate = vdate end end class VehicleModel attr_accessor :pk, :model, :vbrand def initialize(pk, model, vbrand) self.pk = pk self.model = model self.vbrand = vbrand end end class VehicleYear attr_accessor :pk, :model, :vmodel def initialize(pk, model, vmodel) self.pk = pk self.model = model self.vmodel = vmodel end end class VehicleData attr_accessor :fipe_code, :reference, :average_value, :query_date, :vyear def initialize(fipe_code, reference, average_value, query_date, vyear) self.fipe_code = fipe_code self.reference = reference self.average_value = average_value self.query_date = query_date self.vyear = vyear end end TRANSLATE = {:lblReferencia => 'reference', :lblCodFipe => 'fipe_code', :lblValor => 'average_value', :lblData => 'query_date'} TRANSLATE_MONTH = { :Jan => 'January', :Fev => 'February', :Mar => 'March', :Abr => 'April', :Mai => 'May', :Jun => 'June', :Jul => 'July', :Ago => 'August', :Set => 'September', :Out => 'October', :Nov => 'November', :Dez => 'December' } #TODO: Handle errors, improve api class VehicleAPI BASE_URL = 'http://www.fipe.org.br/web/indices/veiculos/default.aspx' BASE_URL_HOST = 'http://www.fipe.org.br' BASE_URL_PATH = '/web/indices/veiculos/default.aspx' VEHICLE_CAR = 0 VEHICLE_MOTORBIKE =1 VEHICLE_TRUNK = 2 TYPE_DESCRIPTION = {VEHICLE_CAR: 'Cars', VEHICLE_MOTORBIKE: 'Motorbikes', VEHICLE_TRUNK: 'Trunks'} TYPE_PARAMS = {VEHICLE_CAR: {:p => 51}, VEHICLE_MOTORBIKE: {:p => 52, :v => 'm'}, VEHICLE_TRUNK: {:p => 53, :v => 'c'}} attr_accessor :_cache_request_data def initialize self._cache_request_data = {} end private def _get_vehicle_params(vehicle_type) TYPE_DESCRIPTION.each do |key, value| if (key == vehicle_type || value == vehicle_type) return TYPE_PARAMS[key] end end end def _update_cache_request_data(data) html_doc = Nokogiri::HTML(data) html_doc.css('#form1 input[type="hidden"]').each do |node| self._cache_request_data[node['name']] = node['value'] end end def app_params_to_base_path(params) url = BASE_URL_PATH + '?' params.each do |key, value| url += "#{key}=#{value}" end return url end def _request_data(vehicle_type, data) params = _get_vehicle_params(vehicle_type) unless params Raise 'vehicle type not found' end # TODO fix this line data = data.merge(_cache_request_data) retry_count = 0 begin uri = URI.parse(BASE_URL_HOST) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = false http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(app_params_to_base_path(params)) request.add_field('Content-Type', 'application/json') # request.body = data.to_json request.set_form_data(data) response = http.request(request) if (response.code.to_i != 200) raise "Request error" end rescue Exception => e sleep 5000 if retry_count < 3 retry_count +=1 retry else raise "Request error tried #{retry_count} times" end end data = response.body _update_cache_request_data(data) return data end def _css_select_from_data(selector, data, skip_match=nil) html_doc = Nokogiri::HTML(data) items = [] html_doc.css(selector).each do |node| self._cache_request_data[node['name']] = node['value'] if (skip_match && node.text.include?(skip_match)) next end items << node end items end public def clear_cache self._cache_request_data = {} end def get_vehicle_types return TYPE_DESCRIPTION end def get_table_reference(vehicle_type) request_data = {'ScriptManager1' => 'updAnoValor|ddlAnoValor', 'ddlTabelaReferencia' => ''} data = _request_data(vehicle_type, request_data) unless data return end items = _css_select_from_data('select[name="ddlTabelaReferencia"] option', data, skip_match='Selecione ') table_reference = [] items.each do |item| if item.text == "Atual" table_reference << TableReference.new(item['value'], Time.now.strftime("%Y / %B"), vehicle_type) else label = (item.text.split().last).to_sym year = item.text.split().first if TRANSLATE_MONTH.has_key?(label) tmp = "#{year} / #{TRANSLATE_MONTH[label]}" table_reference << TableReference.new(item['value'], tmp, vehicle_type) end end end table_reference end def get_vehicle_brands(date) request_data = {'ScriptManager1' => 'UdtMarca|ddlMarca', 'ddlTabelaReferencia' => date.pk} data = _request_data(date, request_data) unless data return end items = _css_select_from_data('select[name="ddlMarca"] option', data, skip_match='Selecione ') vehicle_brands = [] items.each do |item| vehicle_brands << VehicleBrand.new(item['value'], item.text, date) end vehicle_brands end def get_vehicle_models(brand) request_data = {'ScriptManager1' => 'UdtMarca|ddlMarca', 'ddlTabelaReferencia' => brand.vdate.pk, 'ddlMarca' => brand.pk} data = _request_data(brand.vdate.vtype, request_data) unless data return end items = _css_select_from_data('select[name="ddlModelo"] option', data, skip_match='Selecione') vehicle_models = [] items.each do |item| vehicle_models << VehicleModel.new(item['value'], item.text, brand) end vehicle_models end def get_vehicle_years(model) request_data = {'ScriptManager1' => 'updModelo|ddlModelo', 'ddlTabelaReferencia' => model.vbrand.vdate.pk, 'ddlMarca' => model.vbrand.pk, 'ddlModelo' => model.pk, } data = _request_data(model.vbrand.vdate.vtype, request_data) unless data return end items = _css_select_from_data('select[name="ddlAnoValor"] option', data, skip_match='Selecione ') vehicle_years = [] items.each do |item| vehicle_years << VehicleYear.new(item['value'], item.text, model) end vehicle_years end def get_vehicle_data(year) request_data = {'ScriptManager1' => 'updAnoValor|ddlAnoValor', 'ddlTabelaReferencia' => year.vmodel.vbrand.vdate.pk, 'ddlMarca' => year.vmodel.vbrand.pk, 'ddlModelo' => year.vmodel.pk, 'ddlAnoValor' => year.pk} data = _request_data(year.vmodel.vbrand.vdate.vtype, request_data) unless data return end items = _css_select_from_data('#pnlResultado table td span', data) tmp = {} items.each do |item| label = item['id'].to_sym if TRANSLATE.has_key?(label) tmp[TRANSLATE[label]] = item.text end end tmp['vyear'] = year return VehicleData.new(tmp['fipe_code'], tmp['reference'], tmp['average_value'], tmp['query_date'], tmp['vyear']) end end end
813e1c9e4047f55b2c80ea2bf7202800e097567e
{ "blob_id": "813e1c9e4047f55b2c80ea2bf7202800e097567e", "branch_name": "refs/heads/master", "committer_date": "2015-05-07T11:47:44", "content_id": "45e1bb2120c75882ee861e33ccab0e0ebc33f24b", "detected_licenses": [ "MIT" ], "directory_id": "2dea17d463ac9203b3aa0bb32f104ff2818dcbb0", "extension": "rb", "filename": "fipe2.rb", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 20323160, "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 7963, "license": "MIT", "license_type": "permissive", "path": "/lib/fipe2.rb", "provenance": "stack-edu-0066.json.gz:689656", "repo_name": "pinemodule/fipe2", "revision_date": "2015-05-07T11:47:44", "revision_id": "bec53f4b3c58f4b9c010a3068f52e7181204cec6", "snapshot_id": "fac6b61c8cec2c6c449dbf09ff1579e22ea0c564", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/pinemodule/fipe2/bec53f4b3c58f4b9c010a3068f52e7181204cec6/lib/fipe2.rb", "visit_date": "2020-05-17T09:06:13.903075", "added": "2024-11-18T18:14:21.336847+00:00", "created": "2015-05-07T11:47:44", "int_score": 2, "score": 2.28125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0084.json.gz" }
--- layout: post title: IITK NYC office Internship Day 13 --- Note : I will update the earlier blog entries once I've written/explained them properly ## Setting up Distributed-Frontera I am setting up Distributed-frontera on my machine to try it out and writing Dockerfiles for it simultaneously. * [Distributed Frontera tutorial](https://github.com/scrapinghub/frontera/blob/distributed/docs/source/topics/distributed-architecture.rst) * [Distributed Frontera Docs](http://distributed-frontera.readthedocs.io/en/latest/index.html) ### Scrapy * Install Scrapy on Ubuntu using ```bash $ sudo apt-get install python-dev python-pip libxml2-dev libxslt1-dev zlib1g-dev libffi-dev libssl-dev $ pip install Scrapy ``` * For other Operating systems refer to the [Installation guide](http://doc.scrapy.org/en/latest/intro/install.html). I couldn't find a good Docker image for scrapy so I will be writing one on my own. ### Setting up Kafka locally * Follow the [Kafka Tutorial](http://kafka.apache.org/documentation.html#quickstart) till step 6. * At step 2 ```bash $ bin/zookeeper-server-start.sh config/zookeeper.properties ``` This gave me an error about permission being denied. So I tried changing the owner of the folder using ```bash $ sudo chown -R $USER: kafka_2.11-<IP_ADDRESS> ``` But the downloaded files were on another partition which is automatically mounted on login by root. Hence I placed it in my home folder and voilaa!! * We have now ensured that Kafka is running and got some feel as to how it works. As for the next step in Frontera setup I have HBase already setup. After this point I started Kafka on docker image to try the message producer and listener there. ### Using Kafka docker image * Clone the Docker image GitHub repository using ```bash $ git clone https://github.com/wurstmeister/kafka-docker.git ``` and open the directory . * Follow steps from the [Tutorial](http://wurstmeister.github.io/kafka-docker/) for running the image. * Install docker-compose * Install command completion for the bash * Get docker host ip using ```bash $ ip addr show dev docker0 ``` * I'm stuck at the Kafka shell part as I'm unable to find the ZK_HOST.
87b0d8f6596e9f555be8bc794153056e0c9c2713
{ "blob_id": "87b0d8f6596e9f555be8bc794153056e0c9c2713", "branch_name": "refs/heads/master", "committer_date": "2016-05-28T22:54:09", "content_id": "eb29946b5869f8e2ee3d00d7fd3dfb2373a15152", "detected_licenses": [ "MIT" ], "directory_id": "771f25acf4e4336cfd11068873e95ee0bbcdd192", "extension": "md", "filename": "2016-5-28-Day-13.md", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2201, "license": "MIT", "license_type": "permissive", "path": "/_posts/2016-5-28-Day-13.md", "provenance": "stack-edu-markdown-0004.json.gz:330658", "repo_name": "LabhanshAgrawal/LabhanshAgrawal.github.io_old", "revision_date": "2016-05-28T22:54:09", "revision_id": "213a9656ddb8424ed0f0aaa718471f6c0c4c60b7", "snapshot_id": "eda397d4ff6091f98c9242cd58c96c5366009a0d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/LabhanshAgrawal/LabhanshAgrawal.github.io_old/213a9656ddb8424ed0f0aaa718471f6c0c4c60b7/_posts/2016-5-28-Day-13.md", "visit_date": "2021-05-31T17:30:38.442506", "added": "2024-11-18T23:18:17.312982+00:00", "created": "2016-05-28T22:54:09", "int_score": 3, "score": 3.21875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0004.json.gz" }
(function load() { $(document).ready(function () { refresh_toast_disappear_setting(); let toast_disappear_check = $('#toast_disappear_check'); let toast_disappear_check_test_btn = $('#toast_disappear_check_test'); if (toast_disappear_setting) { toast_disappear_check.prop('checked', toast_disappear_setting); } else { localStorage.setItem(TOAST_DISAPPEAR_KEY, 'false'); } toast_disappear_check.on('change', (event) => { let new_value = event.target.checked.toString(); localStorage.setItem(TOAST_DISAPPEAR_KEY, new_value); refresh_toast_disappear_setting(); }); toast_disappear_check_test_btn.on('click', () => { report_error('Test error:', 'error message'); }); }); })();
cf9825f11498129ddddfb835cb35e8e01987666e
{ "blob_id": "cf9825f11498129ddddfb835cb35e8e01987666e", "branch_name": "refs/heads/master", "committer_date": "2021-06-09T14:14:17", "content_id": "7a92fc8e8a653537936aedc8f91ce6e72767b682", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "d4aca1712c37303c9098d67ad56356e044ca8a09", "extension": "js", "filename": "settings.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 329059507, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 834, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/web/static/js/settings.js", "provenance": "stack-edu-0035.json.gz:349209", "repo_name": "Amjad50/Fyp", "revision_date": "2021-06-09T14:14:17", "revision_id": "6bd934ef42edf7e355ade6cf5d2a151f098f2352", "snapshot_id": "b7fce39401c2fbc7b82705e0fc74be29bd4c579c", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Amjad50/Fyp/6bd934ef42edf7e355ade6cf5d2a151f098f2352/web/static/js/settings.js", "visit_date": "2023-05-31T03:51:13.406033", "added": "2024-11-18T18:20:29.060922+00:00", "created": "2021-06-09T14:14:17", "int_score": 2, "score": 2.0625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0053.json.gz" }
<?php namespace Database\Seeders; use Illuminate\Database\Seeder; use Spatie\Permission\Models\Role; use Spatie\Permission\Models\Permission; class RolesAndPermissionsTableSeeder extends Seeder { private $permissions , $gerente_permissions ,$user_permissions; public function __construct() { /* set the default permissions */ $this->permissions = [ /* Usuarios */ 'VerUsuario', 'RegistrarUsuario', 'EditarUsuario', 'EliminarUsuario', /* Asignar permisos */ 'AsignarPermisos', 'VerPermisos', 'CrearPermisos', 'EditarPermisos', 'EliminarPermisos', /* Logins */ 'VerLogins', 'VerLogSistema', /* Roles */ 'VerRole', 'RegistrarRole', 'EditarRole', 'EliminarRole', /*Productos */ 'VerProducto', 'RegistraProducto', 'EditaProducto', 'EliminaProducto', /*Clientes */ 'VerCliente', 'RegistrarCliente', 'EditaCliente', 'EliminaCliente', /*Proveedors */ 'VerProveedor', 'RegistrarProveedor', 'EditaProveedor', 'EliminaProveedor', /*Empleados */ 'VerEmpleados', 'RegistrarEmpleados', 'EditaEmpleados', 'EliminarEmpleados', /*Caja */ 'AperturarCaja', 'CerrarCaja', /*Ventas */ 'VerVentas', 'RegistrarVentas', 'EditaVentas', 'EliminarVentas', /*Gastos */ 'VerGastos', 'RegistrarGastos', 'EditaGastos', 'EliminarGastos', /*Ganancias */ 'VerGanancias', /*Surcursales */ 'VerSucursales', 'RegistrarSucursales', 'EditaSucursales', 'EliminarSucursales', ]; /* set the permissions for the user role, by default role admin we will assign all the permissions */ $this->gerente_permissions = [ /*Productos */ 'VerProducto', 'RegistraProducto', 'EditaProducto', 'EliminaProducto', /*Clientes */ 'VerCliente', 'RegistrarCliente', 'EditaCliente', 'EliminaCliente', /*Proveedors */ 'VerProveedor', 'RegistrarProveedor', 'EditaProveedor', 'EliminaProveedor', /*Empleados */ 'VerEmpleados', 'RegistrarEmpleados', 'EditaEmpleados', 'EliminarEmpleados', /*Caja */ 'AperturarCaja', 'CerrarCaja', /*Ventas */ 'VerVentas', 'RegistrarVentas', 'EditaVentas', 'EliminarVentas', /*Gastos */ 'VerGastos', 'RegistrarGastos', 'EditaGastos', 'EliminarGastos', /*Ganancias */ 'VerGanancias', /*Surcursales */ 'VerSucursales', 'RegistrarSucursales', 'EditaSucursales', 'EliminarSucursales', ]; $this->user_permissions = [ 'VerProducto', /*Clientes */ 'VerCliente', 'RegistrarCliente', 'EditaCliente', 'EliminaCliente', /*Proveedors */ 'VerProveedor', 'RegistrarProveedor', 'EditaProveedor', 'EliminaProveedor', /*Caja */ 'AperturarCaja', /*Ventas */ 'VerVentas', 'RegistrarVentas', 'EditaVentas', 'EliminarVentas', ]; } public function run() { // Reset cached roles and permissions app()['cache']->forget('spatie.permission.cache'); // create permissions foreach ($this->permissions as $permission) { Permission::create(['name' => $permission]); } // create the admin role and set all default permissions $role = Role::create(['name' => 'Super Administrador']); $role->givePermissionTo($this->permissions); // create the user role and set all user permissions $role = Role::create(['name' => 'Gerente']); $role->givePermissionTo($this->gerente_permissions); // create the user role and set all user permissions $role = Role::create(['name' => 'Vendedor']); $role->givePermissionTo($this->user_permissions); } }
7302cf1c3e7b593fc34c2eda1e5e254a1eda578e
{ "blob_id": "7302cf1c3e7b593fc34c2eda1e5e254a1eda578e", "branch_name": "refs/heads/main", "committer_date": "2021-10-04T16:52:24", "content_id": "e0fa89ea395551300d31a94206bdcd58d448827a", "detected_licenses": [ "MIT" ], "directory_id": "2ddf6db1365697c3e216494e3ed3606520527017", "extension": "php", "filename": "RolesAndPermissionsTableSeeder.php", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 401439511, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 7920, "license": "MIT", "license_type": "permissive", "path": "/database/seeders/RolesAndPermissionsTableSeeder.php", "provenance": "stack-edu-0053.json.gz:375503", "repo_name": "theizerg/venta", "revision_date": "2021-10-04T16:52:24", "revision_id": "abfd39f9bb472cb2d30e415ec8b57e38d2d2ec29", "snapshot_id": "29e84023c214fea334d240524278bb9d1a8f43b0", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/theizerg/venta/abfd39f9bb472cb2d30e415ec8b57e38d2d2ec29/database/seeders/RolesAndPermissionsTableSeeder.php", "visit_date": "2023-08-11T12:49:21.530240", "added": "2024-11-19T03:21:22.985250+00:00", "created": "2021-10-04T16:52:24", "int_score": 3, "score": 2.515625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0071.json.gz" }
namespace Polly.Contrib.CachePolicy.Providers.Logging { /// <summary> /// Configuration option for <see cref="LoggingProvider"/>. /// </summary> public class LoggingProviderOptions { /// <summary> /// Metric name for cache get operation latencies. /// </summary> public string MetricNameCacheGetAsyncLatency { get; set; } /// <summary> /// Metric name for cache set operation latency. /// </summary> public string MetricNameCacheSetAsyncLatency { get; set; } /// <summary> /// Metric name for backend get operation latency. /// </summary> public string MetricNameBackendGetAsyncLatency { get; set; } /// <summary> /// Metric name for cache serialize operation latency. /// </summary> public string MetricNameCacheSerializeLatency { get; set; } /// <summary> /// Metric name for cache deserialize operation latency. /// </summary> public string MetricNameCacheDeserializeLatency { get; set; } /// <summary> /// Metric name for cache compress operation latency. /// </summary> public string MetricNameCacheCompressLatency { get; set; } /// <summary> /// Metric name for cache decompress operation latency. /// </summary> public string MetricNameCacheDecompressLatency { get; set; } /// <summary> /// Metric name for serialized size of a cache object. /// </summary> public string MetricNameCacheSerializedSize { get; set; } /// <summary> /// Metric name for compressed serialized size of a cache object. /// </summary> public string MetricNameCacheCompressedSerializedSize { get; set; } /// <summary> /// Dimension name for the cache scenario. /// </summary> public string DimensionNameOperationName { get; set; } /// <summary> /// Dimension name for operation states of CacheGetAsync, CacheSetAsync, BackendGetAsync events. /// </summary> public string DimensionNameIsSuccess { get; set; } /// <summary> /// Dimension name for cache get operation results (hit/miss). /// </summary> public string DimensionNameIsCacheHit { get; set; } /// <summary> /// Dimension name for freshness of cache get operation results (fresh/stale). /// </summary> public string DimensionNameIsCacheFresh { get; set; } /// <summary> /// Dimension name for falling back to cache operations. /// </summary> public string DimensionNameIsCacheFallback { get; set; } /// <summary> /// Dimension name for strategy used to serialize a cache object. /// </summary> public string DimensionNameSerializationStrategy { get; set; } /// <summary> /// Dimension name for strategy used to compress serialized cache objects. /// </summary> public string DimensionNameCompressionStrategy { get; set; } } }
babf2c1b5d0a1495ded60e669bdeffb4af2192f5
{ "blob_id": "babf2c1b5d0a1495ded60e669bdeffb4af2192f5", "branch_name": "refs/heads/master", "committer_date": "2022-05-23T13:18:36", "content_id": "99d2c03566b19a60a8d3f5b70620d973d7efe80c", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "a82053bf247d51f82b9d3a8f391234b25a9f944f", "extension": "cs", "filename": "LoggingProviderOptions.cs", "fork_events_count": 4, "gha_created_at": "2019-08-28T19:51:08", "gha_event_created_at": "2022-06-22T22:23:56", "gha_language": "C#", "gha_license_id": "NOASSERTION", "github_id": 205011590, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3119, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/Polly.Contrib.CachePolicy/Providers/Logging/LoggingProviderOptions.cs", "provenance": "stack-edu-0013.json.gz:109639", "repo_name": "Polly-Contrib/Polly.Contrib.CachePolicy", "revision_date": "2022-05-23T13:18:36", "revision_id": "4ef62c46ded99e14fc2f4547b31e489457be0e02", "snapshot_id": "5bf37058bc798de960d693d901557f6a797fa431", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/Polly-Contrib/Polly.Contrib.CachePolicy/4ef62c46ded99e14fc2f4547b31e489457be0e02/src/Polly.Contrib.CachePolicy/Providers/Logging/LoggingProviderOptions.cs", "visit_date": "2022-12-10T14:21:39.238223", "added": "2024-11-18T22:50:29.661692+00:00", "created": "2022-05-23T13:18:36", "int_score": 2, "score": 2.03125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0031.json.gz" }
using System; namespace Workflow.Business { public class DealerConversionWorkflow : IWorkflow { #region Private Fields - Instance Member private readonly EnrollmentForm form; private UserRole role; private WorkflowState state; #endregion #region Public Methods - Instance Member public DealerConversionWorkflow(IRoleManager roleManager, EnrollmentForm form) { ValidateParams(form); this.form = form; this.role = roleManager.GetRole(); this.state = WorkflowState.None; } public WorkflowStateResponse GetNextState() { if (IsApproved()) HandleApprovedForm(); else if (IsReturned()) HandleReturnedForm(); else if (IsRejected()) HandleRejectedForm(); return new WorkflowStateResponse { WorkflowState = state }; } #endregion #region Private Methods - Instance Member private void HandleReturnedForm() { if (IsProgramManager()) state = WorkflowState.PMReturned; else if (IsSalesManager()) state = WorkflowState.SMReturned; } private void HandleApprovedForm() { if (IsProgramManager()) state = WorkflowState.PMApproved; else if (IsSalesManager()) state = WorkflowState.SMApproved; else if (IsDistributor()) state = WorkflowState.DistributorSubmitted; } private void HandleRejectedForm() { if (IsProgramManager()) state = WorkflowState.PMRejected; else if (IsSalesManager()) state = WorkflowState.SMRejected; } private bool IsApproved() { return form.WorkflowAction == WorkflowAction.Approved; } private bool IsRejected() { return form.WorkflowAction == WorkflowAction.Rejected; } private bool IsReturned() { return form.WorkflowAction == WorkflowAction.Returned; } private void ValidateParams(params object[] args) { foreach (var arg in args) { if (null == arg) throw new ArgumentNullException(args.GetType().Name, "Workflow parameters are null"); } } private bool IsSalesManager() { return role == UserRole.SalesManager; } private bool IsProgramManager() { return role == UserRole.ProgramManager; } private bool IsDistributor() { return role == UserRole.Distributor; } #endregion } }
87d90ea3eb83c57553f386597a22956ad622cfb7
{ "blob_id": "87d90ea3eb83c57553f386597a22956ad622cfb7", "branch_name": "refs/heads/master", "committer_date": "2017-07-01T10:54:41", "content_id": "c23c45cb4fc878a58fa131df72c51ccc36faa746", "detected_licenses": [ "MIT" ], "directory_id": "b5c33945bbfdc54ede571faaeb146f6e05e9db80", "extension": "cs", "filename": "DealerConversionWorkflow.cs", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 62829784, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2861, "license": "MIT", "license_type": "permissive", "path": "/Src/TDD/WorkflowDemo_Completed/Workflow.Business/Workflow/DealerConversionWorkflow.cs", "provenance": "stack-edu-0010.json.gz:101737", "repo_name": "chan4lk/k-talk", "revision_date": "2017-07-01T10:54:41", "revision_id": "f557d91b48fc07e2824c71fa739d2f3a6cb20b8f", "snapshot_id": "969dba3e5f3e4f6fa2db8c665e70866cfdbc13dd", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/chan4lk/k-talk/f557d91b48fc07e2824c71fa739d2f3a6cb20b8f/Src/TDD/WorkflowDemo_Completed/Workflow.Business/Workflow/DealerConversionWorkflow.cs", "visit_date": "2021-01-20T21:12:37.646407", "added": "2024-11-18T22:57:24.092939+00:00", "created": "2017-07-01T10:54:41", "int_score": 3, "score": 2.65625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0028.json.gz" }
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Brand; use App\Models\Category; use App\Models\Product; use App\Handlers\ImageUploadHandler; use App\Http\Requests\BrandRequest; class BrandsController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $brands = Brand::paginate(16); $categories = Category::where('name', '=', 'root')->first(); return view('brands.index',compact('brands','categories')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create(Brand $brand) { $categories = Category::where('name', '=', 'root')->first(); return view('brands.create_and_edit',compact('brand','categories')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(BrandRequest $request, ImageUploadHandler $uploader, Brand $brand) { $brand->fill($request->all()); if($brand->logo){ $result = $uploader->save($request->logo, 'brand-logos', $brand->id); if($result){ $brand->logo = $result['path']; } } //dd($brand); $brand->save(); return redirect()->route('brands.show', $brand->id)->with('message', '品牌添加成功!'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show(Brand $brand) { $categories = Category::where('name', '=', 'root')->first(); $products = Product::where('brand_id', $brand->id)->get(); //dd($products); return view('brands.show', compact('brand','categories','products')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } }
380cf810df8d1346c11b2a7d4f9977213a2b55db
{ "blob_id": "380cf810df8d1346c11b2a7d4f9977213a2b55db", "branch_name": "refs/heads/main", "committer_date": "2020-11-04T12:29:43", "content_id": "32e88bb2ad69a74a3e1c650863794c2136c15d9e", "detected_licenses": [ "MIT" ], "directory_id": "bd54ddb96d51719f0aa3d5a05bd07bb77fe8b4f7", "extension": "php", "filename": "BrandsController.php", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 309905082, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2637, "license": "MIT", "license_type": "permissive", "path": "/app/Http/Controllers/BrandsController.php", "provenance": "stack-edu-0053.json.gz:621308", "repo_name": "fruitlau/jomay", "revision_date": "2020-11-04T12:29:43", "revision_id": "604bc433f3791106d15941b404aacefd24f88afa", "snapshot_id": "0e76f71aeafc9eb992767a26e90ccb067d1d6459", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/fruitlau/jomay/604bc433f3791106d15941b404aacefd24f88afa/app/Http/Controllers/BrandsController.php", "visit_date": "2023-01-05T16:33:12.933338", "added": "2024-11-19T02:33:01.084580+00:00", "created": "2020-11-04T12:29:43", "int_score": 2, "score": 2.34375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0071.json.gz" }
// // CacheWarmerService.swift // mservice-cachewarmer // // Copyright © 2018 Christopher Reitz. Licensed under the MIT license. // See LICENSE file in the project root for full license information. // import Vapor final class CacheWarmerService { // MARK: - Properties let log: Logger let httpClient: Client let runInformationService: RunInformationServiceType let nightWatchmanService: NightWatchmanServiceType let baseURL: String let fetchNumberOfThreads: Int let dispatchGroup = DispatchGroup() let queue = DispatchQueue(label: "CacheWarmerQueue", qos: .background) var jobIsRunning = false var startTime = DispatchTime.now() // MARK: - Initializers init(log: Logger, httpClient: Client, runInformationService: RunInformationServiceType, nightWatchmanService: NightWatchmanServiceType, baseURL: String, fetchNumberOfThreads: Int = 20 ) { self.log = log self.httpClient = httpClient self.runInformationService = runInformationService self.nightWatchmanService = nightWatchmanService self.baseURL = baseURL self.fetchNumberOfThreads = fetchNumberOfThreads log.info("CacheWarmerService initialized with baseUrl: \(baseURL)") } // MARK: - Public func run(didFinishBlock: ((Bool, Double?) -> Void)? = nil) { let startDate = Date() guard nightWatchmanService.entranceAllowed(on: startDate) else { log.info("🌝 Skipping run, it's night time") didFinishBlock?(false, nil) return } guard !jobIsRunning else { log.info("🏁 Skipping run, because previous did not finish yet") didFinishBlock?(false, nil) return } jobIsRunning = true startTime = DispatchTime.now() log.info("🚀 Starting new run - \(startDate)") for board in fetchBoards() { guard let boardId = board.id else { continue } perform { let threads = self.fetchThreads(boardId: boardId) self.perform { var i = 0 for thread in threads { i += 1; if i > self.fetchNumberOfThreads { break } self.fetchThread(boardId: boardId, threadId: thread.id) } } } } dispatchGroup.notify(queue: queue) { let endTime = DispatchTime.now() let nanoTime = endTime.uptimeNanoseconds - self.startTime.uptimeNanoseconds let duration = Double(nanoTime) / 1_000_000_000 didFinishBlock?(true, duration) self.runInformationService.update(duration: Int(duration)) self.log.info(""" \n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ✅ finished job in \(duration) seconds ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n """) self.jobIsRunning = false } } // MARK: - Private private func perform(block: @escaping () -> Void) { dispatchGroup.enter() queue.asyncAfter(deadline: .now() + .milliseconds(500)) { block() self.dispatchGroup.leave() } } private func fetch(_ route: String) throws -> EventLoopFuture<Response> { log.info("📦 fetching \(route)") return self.httpClient.get("\(baseURL)\(route)", headers: ["user-agent": "m!service-cachewarmer"]) } private func fetchBoards() -> Boards { do { return try fetch("/boards").flatMap(to: Boards.self, { response in return try response.content.decode(Boards.self) }).wait().filter { $0.id != nil } } catch { log.report(error: error, verbose: true) return Boards() } } private func fetchThreads(boardId: Int) -> Threads { do { return try fetch("/board/\(boardId)/threads").flatMap(to: Threads.self, { response in return try response.content.decode(Threads.self) }).wait() } catch { log.report(error: error, verbose: true) return Threads() } } private func fetchThread(boardId: Int, threadId: Int) { do { _ = try fetch("/board/\(boardId)/thread/\(threadId)").wait() } catch { log.report(error: error, verbose: true) } } }
29c49067e7ad612beaa4fd878431c9bd276d723c
{ "blob_id": "29c49067e7ad612beaa4fd878431c9bd276d723c", "branch_name": "refs/heads/master", "committer_date": "2018-11-27T13:18:29", "content_id": "7f27aacc6ae578a96412316e7062dea656fada2e", "detected_licenses": [ "MIT" ], "directory_id": "530f30da3b56ba8cf5defa5ea611fc7bcc5f9704", "extension": "swift", "filename": "CacheWarmerService.swift", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 158058070, "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 4519, "license": "MIT", "license_type": "permissive", "path": "/Sources/App/Services/CacheWarmerService.swift", "provenance": "stack-edu-0070.json.gz:617415", "repo_name": "Stitch7/mservice-cachewarmer", "revision_date": "2018-11-27T12:04:41", "revision_id": "cf57a31eb7f000f1bac26529b9e59aee74322ed4", "snapshot_id": "17ba12b4fa7136d25c321896dc9469ccb0b06c02", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Stitch7/mservice-cachewarmer/cf57a31eb7f000f1bac26529b9e59aee74322ed4/Sources/App/Services/CacheWarmerService.swift", "visit_date": "2020-04-07T04:28:19.867738", "added": "2024-11-19T00:21:18.970897+00:00", "created": "2018-11-27T12:04:41", "int_score": 2, "score": 2.46875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0088.json.gz" }
import {DOM} from 'aurelia-framework'; export class AuSelectCustomAttribute { static inject = [DOM.Element]; constructor(element) { element._updateItems = function() { const nodes = window.Polymer.dom(this).querySelectorAll(this.selectable || '*') .filter(this._bindFilterItem); this._setItems(nodes); }; } }
71d84fad159bb324a2ab04b54144898d0e602b68
{ "blob_id": "71d84fad159bb324a2ab04b54144898d0e602b68", "branch_name": "refs/heads/master", "committer_date": "2017-02-25T05:29:41", "content_id": "64710fa251eb3a67cd8c9960cafe6dc96747d093", "detected_licenses": [ "MIT" ], "directory_id": "9a264f7728cb078b5134446cf323db0b84d972b0", "extension": "js", "filename": "au-select-custom-attribute.js", "fork_events_count": 3, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 40501327, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 341, "license": "MIT", "license_type": "permissive", "path": "/src/au-select-custom-attribute.js", "provenance": "stack-edu-0043.json.gz:761781", "repo_name": "bnavetta/aurelia-polymer", "revision_date": "2017-02-25T05:29:41", "revision_id": "5b3fe76be1e190ece4f73c7b6209a3c5391ca0ca", "snapshot_id": "5de4f1dad10ed2bf6a1c1ea441aaa7e04f166a52", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/bnavetta/aurelia-polymer/5b3fe76be1e190ece4f73c7b6209a3c5391ca0ca/src/au-select-custom-attribute.js", "visit_date": "2021-06-15T18:00:38.895594", "added": "2024-11-19T01:05:13.638714+00:00", "created": "2017-02-25T05:29:41", "int_score": 2, "score": 2.09375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0061.json.gz" }
# CakePHP Pusher [![Build Status](https://secure.travis-ci.org/tanuck/cakephp-pusher.svg?branch=master)](http://travis-ci.org/tanuck/cakephp-pusher) [![License](https://poser.pugx.org/tanuck/pusher/license.svg)](https://packagist.org/packages/tanuck/pusher) [![Total Downloads](https://poser.pugx.org/tanuck/pusher/downloads.svg)](https://packagist.org/packages/tanuck/pusher) A CakePHP plugin for interaction with the Pusher API. ## Installation Include the following in your composer.json file: ``` { "require": { "tanuck/pusher": "dev-master" } } ``` Note: This plugin should install in your `Plugin` directory rather than the composer vendors directory. ## Configuration Firstly, you must load the plugin: ```php CakePlugin::load('CakePusher'); ``` Include the component in your controller: ```php class MyController extends AppController { public $components = array( 'CakePusher.Pusher' => array( 'auth_key' => 'PUSHER_APP_AUTH_KEY', 'secret' => 'PUSHER_APP_SECRET', 'app_id' => 'PUSHER_APP_ID', ), ); } ``` This is the most basic form taken by the Component constructor, for further configuration options see the Usage section below. Then access the Component like so: ```php $this->Pusher->trigger('my-channel', 'my-event', 'My Message'); ``` ## Usage If you wish to use just the one Pusher app in your CakePHP application, then the `$components` definition above will be enough. The options available mirror those passed to the Pusher API constructor (see [here](https://github.com/pusher/pusher-http-php) form more information). The plugin allows you to configure and use multiple Pusher apps with the Component. This can be done by nesting the configuration arrays in the component settings, the array index of each will become the internal alias to each Pusher app. For example: ```php class MyController extends AppController { public $components = array( 'CakePusher.Pusher' => array( 'main' => array( 'auth_key' => 'PUSHER_APP_AUTH_KEY', 'secret' => 'PUSHER_APP_SECRET', 'app_id' => 'PUSHER_APP_ID', ), 'otherApp' => array( 'auth_key' => 'PUSHER_APP_AUTH_KEY', 'secret' => 'PUSHER_APP_SECRET', 'app_id' => 'PUSHER_APP_ID', ), ), ); } ``` **NOTE: When using more than one Pusher instance you must specifiy a `main` app.** You can interact with the default `main` app using the methods directly on the component or you can specify an app to use with the `with` method: ```php $this->Pusher->trigger('my-channel', 'my-event', 'My Message'); $this->Pusher->socketAuth('my-channel', '1234.1234'); $this->Pusher->presenceAuth('my-channel', '1234.1234', 'user-12', true); $this->Pusher->get('/channels'); $this->Pusher->with('otherApp')->trigger('my-channel', 'my-event', 'My Message'); ``` You can get and set the name of the default Pusher app like so: ```php $this->Pusher->getDefault(); $this->Pusher->setDefault('otherApp'); ``` And you can add additional app configurations on the fly: ```php $this->Pusher->addAppConfig('myAppName', array( 'auth_key' => 'PUSHER_APP_AUTH_KEY', 'secret' => 'PUSHER_APP_SECRET', 'app_id' => 'PUSHER_APP_ID', )); ``` ## License cakephp-pusher is offered under an [MIT license](http://www.opensource.org/licenses/mit-license.php).
d8752666f6e2a86f25a9ffca93c43b7d1afe6774
{ "blob_id": "d8752666f6e2a86f25a9ffca93c43b7d1afe6774", "branch_name": "refs/heads/master", "committer_date": "2015-08-16T19:56:08", "content_id": "b7ce9afe51e2c0e55a4572d2285b612aa25b79ef", "detected_licenses": [ "MIT" ], "directory_id": "e2e6a3970db8bc940162e5c04fc83aadae5f24ca", "extension": "md", "filename": "README.md", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3268, "license": "MIT", "license_type": "permissive", "path": "/README.md", "provenance": "stack-edu-markdown-0010.json.gz:44429", "repo_name": "karime7gezly/cakephp-pusher", "revision_date": "2015-08-16T19:56:08", "revision_id": "38711b016be0b289a253ff7d10a74f752b677182", "snapshot_id": "4bcb5dad898d3a06c1743f920e8396891bf90b36", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/karime7gezly/cakephp-pusher/38711b016be0b289a253ff7d10a74f752b677182/README.md", "visit_date": "2020-12-28T21:52:12.061863", "added": "2024-11-19T03:08:29.339554+00:00", "created": "2015-08-16T19:56:08", "int_score": 4, "score": 3.84375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0010.json.gz" }
<?php namespace Anomaly\Streams\Platform\Addon\Module\Command; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Builder; /** * Class InstallModulesTableHandler * * @link http://pyrocms.com/ * @author PyroCMS, Inc. <[email protected]> * @author Ryan Thompson <[email protected]> */ class InstallModulesTableHandler { /** * The schema builder object. * * @var Builder */ protected $schema; /** * Create a new InstallModulesTableHandler instance. */ public function __construct() { $this->schema = app('db')->connection()->getSchemaBuilder(); } /** * Install the modules table. */ public function handle() { $this->schema->dropIfExists('addons_modules'); $this->schema->create( 'addons_modules', function (Blueprint $table) { $table->increments('id'); $table->string('slug'); $table->boolean('installed')->default(0); $table->boolean('enabled')->default(0); } ); } }
fc6b1233df816deaa2574098449552fed5430ab0
{ "blob_id": "fc6b1233df816deaa2574098449552fed5430ab0", "branch_name": "refs/heads/1.9", "committer_date": "2023-07-05T06:48:49", "content_id": "0a495b6add731584557bad1a5d8f3d793273175f", "detected_licenses": [ "MIT" ], "directory_id": "a0dcb04eb133197e2cea98b70432a380497df8cb", "extension": "php", "filename": "InstallModulesTableHandler.php", "fork_events_count": 2, "gha_created_at": "2020-01-29T14:56:16", "gha_event_created_at": "2023-07-05T22:04:02", "gha_language": "PHP", "gha_license_id": "NOASSERTION", "github_id": 237008308, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1118, "license": "MIT", "license_type": "permissive", "path": "/src/Addon/Module/Command/InstallModulesTableHandler.php", "provenance": "stack-edu-0047.json.gz:614141", "repo_name": "openclassify/streams-platform", "revision_date": "2023-07-05T06:48:49", "revision_id": "27c89d92cbdff2d5ca0fa5ea6276b63a554a3fd9", "snapshot_id": "a5421134b5783d5afe97fa1df81140aeb5cc78cd", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/openclassify/streams-platform/27c89d92cbdff2d5ca0fa5ea6276b63a554a3fd9/src/Addon/Module/Command/InstallModulesTableHandler.php", "visit_date": "2023-07-07T04:40:50.419963", "added": "2024-11-19T00:26:58.810965+00:00", "created": "2023-07-05T06:48:49", "int_score": 2, "score": 2.5, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0065.json.gz" }
<?php declare(strict_types=1); namespace ShlinkioTest\Shlink\Common\Factory; use Doctrine\Common\Cache\ApcuCache; use Doctrine\Common\Cache\ArrayCache; use Doctrine\Common\Cache\FilesystemCache; use Doctrine\Common\Cache\MemcachedCache; use Doctrine\Common\Cache\RedisCache; use PHPUnit\Framework\TestCase; use Shlinkio\Shlink\Common\Factory\CacheFactory; use Shlinkio\Shlink\Core\Options\AppOptions; use Zend\ServiceManager\ServiceManager; class CacheFactoryTest extends TestCase { /** * @var CacheFactory */ protected $factory; public function setUp() { $this->factory = new CacheFactory(); } public static function tearDownAfterClass() { putenv('APP_ENV'); } /** * @test */ public function productionReturnsApcAdapter() { putenv('APP_ENV=pro'); $instance = $this->factory->__invoke($this->createSM(), ''); $this->assertInstanceOf(ApcuCache::class, $instance); } /** * @test */ public function developmentReturnsArrayAdapter() { putenv('APP_ENV=dev'); $instance = $this->factory->__invoke($this->createSM(), ''); $this->assertInstanceOf(ArrayCache::class, $instance); } /** * @test */ public function adapterDefinedInConfigIgnoresEnvironment() { putenv('APP_ENV=pro'); $instance = $this->factory->__invoke($this->createSM(ArrayCache::class), ''); $this->assertInstanceOf(ArrayCache::class, $instance); } /** * @test */ public function invalidAdapterDefinedInConfigFallbacksToEnvironment() { putenv('APP_ENV=pro'); $instance = $this->factory->__invoke($this->createSM(RedisCache::class), ''); $this->assertInstanceOf(ApcuCache::class, $instance); } /** * @test */ public function filesystemCacheAdaptersReadDirOption() { $dir = realpath(sys_get_temp_dir()); /** @var FilesystemCache $instance */ $instance = $this->factory->__invoke($this->createSM(FilesystemCache::class, ['dir' => $dir]), ''); $this->assertInstanceOf(FilesystemCache::class, $instance); $this->assertEquals($dir, $instance->getDirectory()); } /** * @test */ public function memcachedCacheAdaptersReadServersOption() { $servers = [ [ 'host' => '1.2.3.4', 'port' => 123, ], [ 'host' => '4.3.2.1', 'port' => 321, ], ]; /** @var MemcachedCache $instance */ $instance = $this->factory->__invoke($this->createSM(MemcachedCache::class, ['servers' => $servers]), ''); $this->assertInstanceOf(MemcachedCache::class, $instance); $this->assertEquals(count($servers), count($instance->getMemcached()->getServerList())); } private function createSM($cacheAdapter = null, array $options = []) { return new ServiceManager(['services' => [ 'config' => isset($cacheAdapter) ? [ 'cache' => [ 'adapter' => $cacheAdapter, 'options' => $options, ], ] : [], AppOptions::class => new AppOptions(), ]]); } }
2c2763bfcb4c947dc498b86541e055e7944a2f44
{ "blob_id": "2c2763bfcb4c947dc498b86541e055e7944a2f44", "branch_name": "refs/heads/master", "committer_date": "2018-07-09T16:48:28", "content_id": "0da1b6948a01bbeeb1f10e231cfc4d05f45a1002", "detected_licenses": [ "MIT" ], "directory_id": "2008df4a6fcc1dff4f81f617a58b0b81f1c974df", "extension": "php", "filename": "CacheFactoryTest.php", "fork_events_count": 0, "gha_created_at": "2018-07-25T22:35:28", "gha_event_created_at": "2018-07-25T22:35:28", "gha_language": null, "gha_license_id": "MIT", "github_id": 142360531, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 3312, "license": "MIT", "license_type": "permissive", "path": "/module/Common/test/Factory/CacheFactoryTest.php", "provenance": "stack-edu-0053.json.gz:451404", "repo_name": "dgram/shlink", "revision_date": "2018-07-09T16:48:28", "revision_id": "975260f1263c95c148f925bb0665b07c4bc3ecdb", "snapshot_id": "06ba5ab889b258544c41761dd09dd1fc1c60154f", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/dgram/shlink/975260f1263c95c148f925bb0665b07c4bc3ecdb/module/Common/test/Factory/CacheFactoryTest.php", "visit_date": "2020-03-24T02:02:51.475025", "added": "2024-11-18T22:42:21.644091+00:00", "created": "2018-07-09T16:48:28", "int_score": 2, "score": 2.265625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0071.json.gz" }
// JavaScript Document function buttonSubmit(address){ $("#Form").action=address; $("#Form").submit(); } function num_del(){ if(document.getElementById("product_amount").value>1) { --document.getElementById("product_amount").value;} } function num_add(){ a=$("#kucun").text()*1; if(document.getElementById("product_amount").value<a){ ++document.getElementById("product_amount").value; }} function chooseSize(id){ $("#size").value=id.title; $(".size a").css("border","1px #dcdcdc solid"); $(id).css("border","1px #ff0000 solid"); $("#itemMessage").html("已选择:"+'“'+id.title+'”'); } function toLogin(){ alert("请先登录"); window.location.href="/shoe-shop/user/login"; } function checknumber(obj){ b=$("#kucun").text()*1; if(obj.value>b){ obj.value=b; } }
66928bc7a2bff006d792871e9bb602867046943e
{ "blob_id": "66928bc7a2bff006d792871e9bb602867046943e", "branch_name": "refs/heads/master", "committer_date": "2014-12-01T17:01:12", "content_id": "1a20fcb76795c1d447cb1da9f761b3655074a8c7", "detected_licenses": [ "MIT" ], "directory_id": "a1bd7d170d15329dd4fd32aac2738b0a798e83cf", "extension": "js", "filename": "single.js", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 27389477, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 794, "license": "MIT", "license_type": "permissive", "path": "/src/main/webapp/common/js/single.js", "provenance": "stack-edu-0036.json.gz:240671", "repo_name": "everjesse/StSneaker", "revision_date": "2014-12-01T17:01:12", "revision_id": "55f9161b062a3bb4be843a56be5cf77f9a7c2715", "snapshot_id": "2b6095363081c3e64a0d95369121ad8dbf37f4b6", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/everjesse/StSneaker/55f9161b062a3bb4be843a56be5cf77f9a7c2715/src/main/webapp/common/js/single.js", "visit_date": "2021-01-17T21:00:05.418798", "added": "2024-11-19T01:13:42.750607+00:00", "created": "2014-12-01T17:01:12", "int_score": 2, "score": 2.28125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0054.json.gz" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DirectOutput.FX { /// <summary> /// The EffectEventArgs class is used for events triggered by IEffect objects /// </summary> public class EffectEventArgs: EventArgs { /// <summary> /// IEffect object which has triggered the event. /// </summary> public IEffect Effect { get; set; } public EffectEventArgs() { } public EffectEventArgs(IEffect Effect) { this.Effect = Effect; } } /// <summary> /// EventArgs for the BeforeEffectNameChanged event /// </summary> public class BeforeEffectNameChangeAventArgs : EffectEventArgs { /// <summary> /// New name for the Effect /// </summary> public string NewName { get; set; } /// <summary> /// If CancelNameChanges is set to true, the Name of the Effect will not be changed and a exception is thrown. /// </summary> public bool CancelNameChange { get; set; } /// <summary> /// Initializes a new instance of the <see cref="BeforeEffectNameChangeAventArgs"/> class. /// </summary> public BeforeEffectNameChangeAventArgs() { } /// <summary> /// Initializes a new instance of the <see cref="BeforeEffectNameChangeAventArgs"/> class. /// </summary> /// <param name="Effect">The effect.</param> /// <param name="NewName">The new name.</param> public BeforeEffectNameChangeAventArgs(IEffect Effect, string NewName) : base(Effect) { this.NewName = NewName; } } }
0b7346dc7418adc4078ad7cf475fe96b00480e87
{ "blob_id": "0b7346dc7418adc4078ad7cf475fe96b00480e87", "branch_name": "refs/heads/master", "committer_date": "2023-07-06T18:33:45", "content_id": "161ac9450e5145767c6f667cf1f406d4150240c2", "detected_licenses": [ "MIT" ], "directory_id": "9291fdaf87f7720d2ab94fb974961fdc0c5f3569", "extension": "cs", "filename": "EffectEventArgs.cs", "fork_events_count": 18, "gha_created_at": "2016-09-29T03:49:36", "gha_event_created_at": "2023-07-06T18:33:47", "gha_language": "C#", "gha_license_id": "MIT", "github_id": 69528472, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1812, "license": "MIT", "license_type": "permissive", "path": "/DirectOutput/FX/EffectEventArgs.cs", "provenance": "stack-edu-0011.json.gz:850500", "repo_name": "mjrgh/DirectOutput", "revision_date": "2023-07-06T18:33:45", "revision_id": "47712355dc8537918d94b122fa25902f5b42e0c5", "snapshot_id": "e1133d321722836a5f503c118e4424d079412ddd", "src_encoding": "UTF-8", "star_events_count": 13, "url": "https://raw.githubusercontent.com/mjrgh/DirectOutput/47712355dc8537918d94b122fa25902f5b42e0c5/DirectOutput/FX/EffectEventArgs.cs", "visit_date": "2023-07-20T01:47:57.468805", "added": "2024-11-19T02:28:45.181866+00:00", "created": "2023-07-06T18:33:45", "int_score": 3, "score": 2.984375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0029.json.gz" }
<?php namespace Dvsa\Olcs\Cli\Service\Queue\Consumer\CompaniesHouse; use Dvsa\Olcs\Api\Domain\Command\CompaniesHouse\InitialLoad as Cmd; /** * Companies House Initial Data Load Queue Consumer * * @author Dan Eggleston <[email protected]> */ class InitialDataLoad extends AbstractConsumer { /** * @var string the command to handle processing */ protected $commandName = Cmd::class; }
d8c0b4ae3eb24cd629577346e34c6d06337d0172
{ "blob_id": "d8c0b4ae3eb24cd629577346e34c6d06337d0172", "branch_name": "refs/heads/master", "committer_date": "2023-03-01T14:08:31", "content_id": "47691b2e2a9296b6f9b569123188486b5421c218", "detected_licenses": [ "MIT" ], "directory_id": "9d6b8bc1c0dc7a0870435406aa10acf5c9bd0c9f", "extension": "php", "filename": "InitialDataLoad.php", "fork_events_count": 2, "gha_created_at": "2017-03-28T14:53:23", "gha_event_created_at": "2018-10-03T20:38:52", "gha_language": "PHP", "gha_license_id": "NOASSERTION", "github_id": 86472717, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 408, "license": "MIT", "license_type": "permissive", "path": "/module/Cli/src/Service/Queue/Consumer/CompaniesHouse/InitialDataLoad.php", "provenance": "stack-edu-0051.json.gz:852497", "repo_name": "dvsa/olcs-backend", "revision_date": "2023-03-01T14:08:31", "revision_id": "63791a6e45a5cd4efa2f8626804173beae182171", "snapshot_id": "750553f64141406418a6d7f37125baa590b59452", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/dvsa/olcs-backend/63791a6e45a5cd4efa2f8626804173beae182171/module/Cli/src/Service/Queue/Consumer/CompaniesHouse/InitialDataLoad.php", "visit_date": "2023-03-16T02:10:59.271508", "added": "2024-11-18T21:42:40.241443+00:00", "created": "2023-03-01T14:08:31", "int_score": 2, "score": 2.25, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0069.json.gz" }
# ActiveModelAttributes Changelog ## master ## 1.1.0 Changes: - [BUGFIX] Pass `options` argument to `ActiveModel::Type.lookup` in attribute writers @jughead ## 1.0.0 Update notes: - Breaking change: the attribute's setter now calls #cast method on type instead of #deserialize. If you have defined any custom type, just rename the method from #deserialize to #cast Changes: - [ENHANCEMENT] Use #cast method from types instead of #deserialize by @Azdaroth ## 0.1.0 Update notes: - None Changes: - [FEATURE] Basic implementation by @Azdaroth
43eb7e061d6e2072e730ed5d87a0df086261fea7
{ "blob_id": "43eb7e061d6e2072e730ed5d87a0df086261fea7", "branch_name": "refs/heads/master", "committer_date": "2017-04-23T09:22:18", "content_id": "23ce5c42489cbca70805d3decfa24de61cd09624", "detected_licenses": [ "MIT" ], "directory_id": "56ae36f8aff8087f5379823d28fe18f5c1c599d9", "extension": "md", "filename": "Changelog.md", "fork_events_count": 0, "gha_created_at": "2017-04-23T12:59:12", "gha_event_created_at": "2017-04-23T12:59:12", "gha_language": null, "gha_license_id": null, "github_id": 89142027, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 561, "license": "MIT", "license_type": "permissive", "path": "/Changelog.md", "provenance": "stack-edu-markdown-0009.json.gz:40953", "repo_name": "JulienItard/active_model_attributes", "revision_date": "2017-04-23T09:22:18", "revision_id": "88f3470c129a6b0547aa19ef484ce6bc4e5e3fc0", "snapshot_id": "5fb8cd8872c680d554b19d0493f82b4f71b24b8f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/JulienItard/active_model_attributes/88f3470c129a6b0547aa19ef484ce6bc4e5e3fc0/Changelog.md", "visit_date": "2021-01-20T00:29:32.071150", "added": "2024-11-19T01:54:44.151973+00:00", "created": "2017-04-23T09:22:18", "int_score": 2, "score": 2.296875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0009.json.gz" }
use na::{DVector, Point2}; use std::iter; use crate::bounding_volume::AABB; use crate::math::{Real, Vector}; use crate::shape::Segment; #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Clone, Debug)] /// A 2D heightfield. pub struct HeightField { heights: DVector<Real>, scale: Vector<Real>, removed: Vec<bool>, aabb: AABB, } impl HeightField { /// Creates a new 2D heightfield with the given heights and scale factor. pub fn new(heights: DVector<Real>, scale: Vector<Real>) -> Self { assert!( heights.len() > 1, "A heightfield heights must have at least 2 elements." ); let max = heights.max(); let min = heights.min(); let hscale = scale * na::convert::<_, Real>(0.5); let aabb = AABB::new( Point2::new(-hscale.x, min * scale.y), Point2::new(hscale.x, max * scale.y), ); HeightField { heights, scale, aabb, removed: Vec::new(), } } /// The number of cells of this heightfield. pub fn num_cells(&self) -> usize { self.heights.len() - 1 } /// The height at each cell endpoint. pub fn heights(&self) -> &DVector<Real> { &self.heights } /// The scale factor applied to this heightfield. pub fn scale(&self) -> &Vector<Real> { &self.scale } /// The AABB of this heightfield. pub fn root_aabb(&self) -> &AABB { &self.aabb } /// The width of a single cell of this heightfield. pub fn cell_width(&self) -> Real { self.unit_cell_width() * self.scale.x } /// The width of a single cell of this heightfield, without taking the scale factor into account. pub fn unit_cell_width(&self) -> Real { 1.0 / na::convert::<f64, Real>(self.heights.len() as f64 - 1.0) } /// The left-most x-coordinate of this heightfield. pub fn start_x(&self) -> Real { self.scale.x * na::convert::<f64, Real>(-0.5) } fn quantize_floor(&self, val: Real, seg_length: Real) -> usize { let _0_5: Real = na::convert::<f64, Real>(0.5); let i = na::clamp( ((val + _0_5) / seg_length).floor(), 0.0, na::convert::<f64, Real>((self.num_cells() - 1) as f64), ); na::convert_unchecked::<Real, f64>(i) as usize } fn quantize_ceil(&self, val: Real, seg_length: Real) -> usize { let _0_5: Real = na::convert::<f64, Real>(0.5); let i = na::clamp( ((val + _0_5) / seg_length).ceil(), 0.0, na::convert::<f64, Real>(self.num_cells() as f64), ); na::convert_unchecked::<Real, f64>(i) as usize } /// Index of the cell a point is on after vertical projection. pub fn cell_at_point(&self, pt: &Point2<Real>) -> Option<usize> { let _0_5: Real = na::convert::<f64, Real>(0.5); let scaled_pt = pt.coords.component_div(&self.scale); let seg_length = self.unit_cell_width(); if scaled_pt.x < -_0_5 || scaled_pt.x > _0_5 { // Outside of the heightfield bounds. None } else { Some(self.quantize_floor(scaled_pt.x, seg_length)) } } /// Iterator through all the segments of this heightfield. pub fn segments<'a>(&'a self) -> impl Iterator<Item = Segment> + 'a { // FIXME: this is not very efficient since this wil // recompute shared points twice. (0..self.num_cells()).filter_map(move |i| self.segment_at(i)) } /// The i-th segment of the heightfield if it has not been removed. pub fn segment_at(&self, i: usize) -> Option<Segment> { if i >= self.num_cells() || self.is_segment_removed(i) { return None; } let _0_5: Real = na::convert::<f64, Real>(0.5); let seg_length = 1.0 / na::convert::<f64, Real>(self.heights.len() as f64 - 1.0); let x0 = -_0_5 + seg_length * na::convert::<f64, Real>(i as f64); let x1 = x0 + seg_length; let y0 = self.heights[i + 0]; let y1 = self.heights[i + 1]; let mut p0 = Point2::new(x0, y0); let mut p1 = Point2::new(x1, y1); // Apply scales: p0.coords.component_mul_assign(&self.scale); p1.coords.component_mul_assign(&self.scale); Some(Segment::new(p0, p1)) } /// Mark the i-th segment of this heightfield as removed or not. pub fn set_segment_removed(&mut self, i: usize, removed: bool) { if self.removed.len() == 0 { self.removed = iter::repeat(false).take(self.num_cells()).collect() } self.removed[i] = removed } /// Checks if the i-th segment has been removed. pub fn is_segment_removed(&self, i: usize) -> bool { self.removed.len() != 0 && self.removed[i] } /// Applies `f` to each segment of this heightfield that intersects the given `aabb`. pub fn map_elements_in_local_aabb(&self, aabb: &AABB, f: &mut impl FnMut(u32, &Segment)) { let _0_5: Real = na::convert::<f64, Real>(0.5); let ref_mins = aabb.mins.coords.component_div(&self.scale); let ref_maxs = aabb.maxs.coords.component_div(&self.scale); let seg_length = 1.0 / na::convert::<f64, Real>(self.heights.len() as f64 - 1.0); if ref_maxs.x < -_0_5 || ref_mins.x > _0_5 { // Outside of the heightfield bounds. return; } let min_x = self.quantize_floor(ref_mins.x, seg_length); let max_x = self.quantize_ceil(ref_maxs.x, seg_length); // FIXME: find a way to avoid recomputing the same vertices // multiple times. for i in min_x..max_x { if self.is_segment_removed(i) { continue; } let x0 = -_0_5 + seg_length * na::convert::<f64, Real>(i as f64); let x1 = x0 + seg_length; let y0 = self.heights[i + 0]; let y1 = self.heights[i + 1]; if (y0 > ref_maxs.y && y1 > ref_maxs.y) || (y0 < ref_mins.y && y1 < ref_mins.y) { continue; } let mut p0 = Point2::new(x0, y0); let mut p1 = Point2::new(x1, y1); // Apply scales: p0.coords.component_mul_assign(&self.scale); p1.coords.component_mul_assign(&self.scale); // Build the segment. let seg = Segment::new(p0, p1); // Call the callback. f(i as u32, &seg); } } }
f74c390fb34edb6b482a94ce0c902b94e2338775
{ "blob_id": "f74c390fb34edb6b482a94ce0c902b94e2338775", "branch_name": "refs/heads/master", "committer_date": "2021-06-15T09:27:35", "content_id": "cfec4bdc631795fc5e1fa0a3bfae8eb390bd341f", "detected_licenses": [ "Apache-2.0" ], "directory_id": "eaa1a1e62d72e92be27d2f60ae5bec507578a5c9", "extension": "rs", "filename": "heightfield2.rs", "fork_events_count": 0, "gha_created_at": "2021-06-25T21:01:39", "gha_event_created_at": "2021-06-25T21:01:40", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 380353015, "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 6588, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/shape/heightfield2.rs", "provenance": "stack-edu-0067.json.gz:768675", "repo_name": "katharostech/parry", "revision_date": "2021-06-15T05:47:01", "revision_id": "91718edd7e93a63ace17c0d876f226fdf8de52ee", "snapshot_id": "1b6cf8f765eea0ff5f9dd2556fec6057761155de", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/katharostech/parry/91718edd7e93a63ace17c0d876f226fdf8de52ee/src/shape/heightfield2.rs", "visit_date": "2023-06-05T13:33:48.043033", "added": "2024-11-18T23:24:43.298852+00:00", "created": "2021-06-15T05:47:01", "int_score": 3, "score": 2.765625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0085.json.gz" }
''' Created on June 05, 2013 @author: Michael Kraus ([email protected]) ''' import sys import petsc4py petsc4py.init(sys.argv) import numpy as np from petsc4py import PETSc from vlasov.toolbox.VIDA import VIDA from vlasov.run.run_base_split import viVlasov1Dbasesplit class viVlasov1DbasesplitRK2(viVlasov1Dbasesplit): ''' PETSc/Python Vlasov Poisson Solver in 1D. ''' def __init__(self, cfgfile, runid=None, cfg=None): ''' Constructor ''' super().__init__(cfgfile, runid, cfg) # Runge-Kutta collocation points self.c1 = 0.5 # Runge-Kutta coefficients self.a11 = 0.5 # create solution and RHS vector self.b = self.da1.createGlobalVec() self.k1 = self.da1.createGlobalVec() self.kh = self.da1.createGlobalVec() # create substep vectors self.f1 = self.da1.createGlobalVec() self.n1 = self.dax.createGlobalVec() self.p1_int = self.dax.createGlobalVec() self.p1_ext = self.dax.createGlobalVec() self.h11 = self.da1.createGlobalVec() self.h21 = self.da1.createGlobalVec() self.p1_niter = 0 def calculate_moments2(self, potential=True, output=True): self.fh.copy(self.f1) self.f1.axpy(0.5 * self.grid.ht, self.k1) self.toolbox.compute_density(self.f1, self.n1) if potential: self.poisson_solver.formRHS(self.n1, self.pb) self.poisson_ksp.solve(self.pb, self.p1_int) self.p1_niter = self.poisson_ksp.getIterationNumber() self.toolbox.potential_to_hamiltonian(self.p1_int, self.h11) def calculate_external2(self, itime): current_time0 = self.grid.ht*itime current_time1 = self.grid.ht*(itime - 1 + self.c1) # calculate external field self.calculate_external(current_time0, self.pc_ext) self.calculate_external(current_time1, self.p1_ext) # copy to Hamiltonian self.toolbox.potential_to_hamiltonian(self.p1_ext, self.h21) def calculate_residual2(self): self.vlasov_solver.function_mult(self.k1, self.b) fnorm = self.b.norm() self.poisson_solver.function_mult(self.p1_int, self.n1, self.pb) p1norm = self.pb.norm() return fnorm + p1norm def initial_guess2(self): self.initial_guess_none() def initial_guess_none(self): self.k1.set(0.) self.fc.copy(self.f1) self.pc_int.copy(self.p1_int) # def initial_guess_symplectic2(self): # super().initial_guess_symplectic2() # self.copy_data_to_x() # # # def initial_guess_symplectic4(self): # super().initial_guess_symplectic4() # self.copy_data_to_x() # # # def initial_guess_rk4(self): # super().initial_guess_rk4() # self.copy_data_to_x() # # # def initial_guess_gear(self, itime): # super().initial_guess_gear() # self.copy_data_to_x()
ed619f11fe479fcfcce1d711c63eea3220886e0d
{ "blob_id": "ed619f11fe479fcfcce1d711c63eea3220886e0d", "branch_name": "refs/heads/master", "committer_date": "2018-01-10T20:05:04", "content_id": "e7f09a5f85d662b9819883ef84585825caf95189", "detected_licenses": [ "MIT" ], "directory_id": "c3d36ee056348cd0270c0a5149aa88c9e93cb7cb", "extension": "py", "filename": "run_base_split_rk2.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 117005066, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3250, "license": "MIT", "license_type": "permissive", "path": "/vlasov/run/run_base_split_rk2.py", "provenance": "stack-edu-0056.json.gz:136005", "repo_name": "DDMGNI/viVlasov1D", "revision_date": "2018-01-10T20:05:04", "revision_id": "901dd058711f6943eb6497b941bc115a64e822de", "snapshot_id": "8a458f26670eec6c0f97540f3822301eb4bfd5fa", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/DDMGNI/viVlasov1D/901dd058711f6943eb6497b941bc115a64e822de/vlasov/run/run_base_split_rk2.py", "visit_date": "2019-07-31T19:57:46.611459", "added": "2024-11-18T20:23:34.168239+00:00", "created": "2018-01-10T20:05:04", "int_score": 2, "score": 2.109375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0074.json.gz" }
#!/bin/bash DEVICE1='wlanfront' #'wlxc4e984e026ee' DEVICE2='wlanback' #'wlxa42bb0c0408d' cd "/home/pi/" #sleep 30 FOLDER="CHANNEL_SCAN" i=0 while [[ -d "$FOLDER-$i" ]] ; do let i++ done FOLDER="$FOLDER-$i" mkdir $FOLDER echo "Starting Drone Logger $FOLDER $MACFILTER" killall -9 telemetry-saver ~/DroneSDK/build/bin/telemetry-saver "UserConfig.txt" "$FOLDER/drone.log"& python drone_channel_strength.py "$FOLDER/channels.csv" &
0e6aecd9036ca6f07c68d626442254c60d4c5efa
{ "blob_id": "0e6aecd9036ca6f07c68d626442254c60d4c5efa", "branch_name": "refs/heads/master", "committer_date": "2019-06-21T19:09:03", "content_id": "3e8a0b6ac805b73775ce5b74d09739e56feccab6", "detected_licenses": [ "MIT" ], "directory_id": "16018f57e34792d3c923901341d7c8e6468298ce", "extension": "sh", "filename": "scan.sh", "fork_events_count": 2, "gha_created_at": "2018-12-07T00:31:02", "gha_event_created_at": "2018-12-07T00:31:02", "gha_language": null, "gha_license_id": null, "github_id": 160749584, "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 442, "license": "MIT", "license_type": "permissive", "path": "/plugins/db-loader-rssi/scan.sh", "provenance": "stack-edu-0069.json.gz:29032", "repo_name": "mikrasov/emergence", "revision_date": "2019-06-21T19:09:03", "revision_id": "ef091743a97261c8322cbea27749f63d641ac8c5", "snapshot_id": "3bcf4bc806a48fd987bd2902938142f4d85e7f93", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mikrasov/emergence/ef091743a97261c8322cbea27749f63d641ac8c5/plugins/db-loader-rssi/scan.sh", "visit_date": "2020-04-10T02:40:02.442721", "added": "2024-11-19T00:16:59.282812+00:00", "created": "2019-06-21T19:09:03", "int_score": 3, "score": 2.859375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0087.json.gz" }
import tensorflow as tf import numpy as np import selu import util import sys import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) conv3p_module = tf.load_op_library(BASE_DIR + '/tf_ops/conv3p/tf_conv3p.so') def conv3p(points_tensor, input_tensor, kernel_tensor, stride_tensor, voxel_size): return conv3p_module.conv3p(points_tensor, input_tensor, kernel_tensor, stride_tensor, voxel_size); @tf.RegisterGradient('Conv3p') def _conv3p_grad(op, grad_from_next_layer): """The derivatives for convolution. Args: op: the convolution op. grad_from_next_layer: the tensor representing the gradient w.r.t. the output Returns: the gradients w.r.t. the point tensor, input tensor, and the filter """ points = op.inputs[0] input = op.inputs[1] filter = op.inputs[2] stride = op.inputs[3] voxel_size = op.inputs[4] input_grad, filter_grad = conv3p_module.conv3p_grad(grad_from_next_layer, points, input, filter, stride, voxel_size) return [None, input_grad, filter_grad, None, None] def layer(idx, points_tensor, input_tensor, voxel_size, filter_shape, stride_shape, is_training=True): filter_tensor = tf.get_variable("filter{}".format(idx), filter_shape) stride_tensor = tf.constant(stride_shape) conv = conv3p(points_tensor, input_tensor, filter_tensor, stride_tensor, voxel_size); relu = selu.selu(conv) return relu class PointConvNet: def __init__(self, num_class): self.num_class = num_class def model(self, points_tensor, input_tensor, is_training=True): """ Arguments: points_tensor: [b, n, 3] point cloud input_tensor: [b, n, channels] extra data defined for each point """ in_channels = input_tensor.get_shape()[2].value voxel_size = tf.constant([0.1]) net1 = layer(1, points_tensor, input_tensor, voxel_size, [3, 3, 3, in_channels, 9], [1, 1, 1]) net2 = layer(2, points_tensor, net1, voxel_size, [3, 3, 3, 9, 9], [2, 2, 2]) net3 = layer(3, points_tensor, net2, voxel_size, [3, 3, 3, 9, 9], [3, 3, 3]) net4 = layer(4, points_tensor, net3, voxel_size, [3, 3, 3, 9, 9], [4, 4, 4]) concat = tf.concat([net1, net2, net3, net4], axis=2) net = layer(5, points_tensor, concat, voxel_size, [3, 3, 3, 36, self.num_class], [1, 1, 1]) return net def loss(self, logits, labels): """ Arguments: logits: prediction with shape [batch_size, num_class] labels: ground truth scalar labels with shape [batch_size] """ onehot_labels = tf.one_hot(labels, depth=self.num_class) e = tf.losses.softmax_cross_entropy(onehot_labels, logits) #e = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=labels) #e = tf.reduce_mean(e) return e
fde4b30ad5b2fb29fb2e8dc75d4c04f71e9dbf13
{ "blob_id": "fde4b30ad5b2fb29fb2e8dc75d4c04f71e9dbf13", "branch_name": "refs/heads/master", "committer_date": "2020-01-02T06:17:33", "content_id": "fc0ccac53657c8f64806a9b4a47e0dc48c6fa471", "detected_licenses": [ "MIT" ], "directory_id": "1c363586d0c33352ba232bfc1091c41f96baccd7", "extension": "py", "filename": "pointcnn_scene_seg_acsd.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2897, "license": "MIT", "license_type": "permissive", "path": "/scene_seg/pointcnn_scene_seg_acsd.py", "provenance": "stack-edu-0062.json.gz:468063", "repo_name": "hejiao610/pointwise", "revision_date": "2020-01-02T06:17:33", "revision_id": "8ce1eeb73c3bfbd26e5a14d5c47fcdae163d4ed4", "snapshot_id": "5597c1381eae5e0864e7f8aa1bcde22336246d20", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/hejiao610/pointwise/8ce1eeb73c3bfbd26e5a14d5c47fcdae163d4ed4/scene_seg/pointcnn_scene_seg_acsd.py", "visit_date": "2021-04-13T01:24:27.259900", "added": "2024-11-18T19:58:31.501484+00:00", "created": "2020-01-02T06:17:33", "int_score": 2, "score": 2.4375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0080.json.gz" }
#include "depthai-shared/datatype/DatatypeEnum.hpp" #include <functional> #include <type_traits> #include <unordered_map> #include <vector> namespace dai { const std::unordered_map<DatatypeEnum, std::vector<DatatypeEnum>> hierarchy = {{DatatypeEnum::Buffer, {DatatypeEnum::ImgFrame, DatatypeEnum::NNData, DatatypeEnum::ImageManipConfig, DatatypeEnum::CameraControl, DatatypeEnum::ImgDetections, DatatypeEnum::SpatialImgDetections, DatatypeEnum::SystemInformation, DatatypeEnum::SpatialLocationCalculatorConfig, DatatypeEnum::SpatialLocationCalculatorData, DatatypeEnum::EdgeDetectorConfig, DatatypeEnum::Tracklets, DatatypeEnum::IMUData, DatatypeEnum::StereoDepthConfig}}, {DatatypeEnum::ImgFrame, {}}, {DatatypeEnum::NNData, {}}, {DatatypeEnum::ImageManipConfig, {}}, {DatatypeEnum::CameraControl, {}}, {DatatypeEnum::ImgDetections, {DatatypeEnum::SpatialImgDetections}}, {DatatypeEnum::SpatialImgDetections, {}}, {DatatypeEnum::SystemInformation, {}}, {DatatypeEnum::SpatialLocationCalculatorConfig, {}}, {DatatypeEnum::SpatialLocationCalculatorData, {}}, {DatatypeEnum::EdgeDetectorConfig, {}}, {DatatypeEnum::Tracklets, {}}, {DatatypeEnum::IMUData, {}}, { DatatypeEnum::StereoDepthConfig, {}, }}; bool isDatatypeSubclassOf(DatatypeEnum parent, DatatypeEnum children) { for(const auto& d : hierarchy.at(parent)) { if(d == children) return true; if(isDatatypeSubclassOf(d, children)) return true; } return false; } } // namespace dai
e5f0f74f88143187ebc19c36edca5b405efde67e
{ "blob_id": "e5f0f74f88143187ebc19c36edca5b405efde67e", "branch_name": "refs/heads/main", "committer_date": "2021-07-05T23:40:27", "content_id": "8c32f6f0a400da90a70c26cfd71463665d0e3f96", "detected_licenses": [ "MIT" ], "directory_id": "59ed92a3cc571becfc0806eb889df5efa4de6bb1", "extension": "cpp", "filename": "DatatypeEnum.cpp", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3794, "license": "MIT", "license_type": "permissive", "path": "/src/datatype/DatatypeEnum.cpp", "provenance": "stack-edu-0002.json.gz:262409", "repo_name": "ashishd/depthai-shared", "revision_date": "2021-07-05T23:40:27", "revision_id": "9b5d920d354cc5dad0793b3f168159a9c62fcb09", "snapshot_id": "c0e81eb7e2492cf41be59ed6f0b5b6d1b8671c61", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ashishd/depthai-shared/9b5d920d354cc5dad0793b3f168159a9c62fcb09/src/datatype/DatatypeEnum.cpp", "visit_date": "2023-06-12T08:58:21.945003", "added": "2024-11-18T22:50:14.366660+00:00", "created": "2021-07-05T23:40:27", "int_score": 2, "score": 2.015625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0020.json.gz" }
// // NKStyle.swift // NKit // // Created by Nghia Nguyen on 8/30/16. // Copyright © 2016 Nghia Nguyen. All rights reserved. // import Foundation final class NKStyle<T: NKStylable> { var closure: (model: T) -> Void init(closure: (model: T) -> Void) { self.closure = closure } func execute(model: NKStylable) { guard let model = model as? T else { return } self.closure(model: model) } }
db9710322055ea77e29c262bf280a42a15b4022c
{ "blob_id": "db9710322055ea77e29c262bf280a42a15b4022c", "branch_name": "refs/heads/master", "committer_date": "2016-08-31T02:39:28", "content_id": "85d26e036e3cabfab8ec6545539b7451310525f4", "detected_licenses": [ "MIT" ], "directory_id": "e833e5ffb3d0896cd9cfa7276de32c96f322183b", "extension": "swift", "filename": "NKStyle.swift", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 66993082, "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 476, "license": "MIT", "license_type": "permissive", "path": "/NStyle/Source/NKStyle.swift", "provenance": "stack-edu-0072.json.gz:287490", "repo_name": "nghiaphunguyen/NStyle", "revision_date": "2016-08-31T02:39:28", "revision_id": "5eafd8d2008b7c20d22a289fe194bd566dbc2433", "snapshot_id": "fb93ace49ecd8f10c88ca86fb829886b3a1d7595", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/nghiaphunguyen/NStyle/5eafd8d2008b7c20d22a289fe194bd566dbc2433/NStyle/Source/NKStyle.swift", "visit_date": "2020-12-06T19:55:28.403826", "added": "2024-11-19T00:29:22.396014+00:00", "created": "2016-08-31T02:39:28", "int_score": 3, "score": 2.75, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0090.json.gz" }
var knex = require('./knex.js'); function Jokes() { return knex('jokes'); } function Setlists() { return knex('setlists'); } // *** joke queries *** // function getAllJokes() { return Jokes().select(); } function getSingleJoke(jokeID) { return Jokes().where('id', parseInt(jokeID)).first(); } function addJoke(joke) { return Jokes().insert(joke, 'id'); } function updateJoke(jokeID, updates) { return Jokes().where('id', parseInt(jokeID)).update(updates); } function deleteJoke(jokeID) { return Jokes().where('id', parseInt(jokeID)).del(); } // *** setlist queries *** // function getAllSetlists() { return Setlists().select(); } function getSingleSetlist(setlistID) { return Setlists().where('id', parseInt(setlistID)).first(); } function addSetlist(setlist) { return Setlists().insert(setlist, 'id'); } function updateSetlist(setlistID, updates) { return Setlists().where('id', parseInt(setlistID)).update(updates); } function deleteSetlist(setlistID) { return Setlists().where('id', parseInt(setlistID)).del(); } // *** users queries *** function getAllUsers() { return knex('users').select(); } module.exports = { getAllJokes, getSingleJoke, addJoke, updateJoke, deleteJoke, getAllSetlists, getSingleSetlist, addSetlist, updateSetlist, deleteSetlist, getAllUsers };
8bfb499c44dd9eb9fb539a8970933aea063ba2cd
{ "blob_id": "8bfb499c44dd9eb9fb539a8970933aea063ba2cd", "branch_name": "refs/heads/master", "committer_date": "2019-03-08T06:00:35", "content_id": "956147c51fdb27e342d14a4a6e4ea95208c70613", "detected_licenses": [], "directory_id": "4797c191b06a3cbd03218b784236a308e111ec16", "extension": "js", "filename": "queries.js", "fork_events_count": 0, "gha_created_at": "2018-04-23T19:40:32", "gha_event_created_at": "2019-03-08T06:00:36", "gha_language": "JavaScript", "gha_license_id": "MIT", "github_id": 130747707, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1335, "license": "", "license_type": "permissive", "path": "/db/queries.js", "provenance": "stack-edu-0042.json.gz:276755", "repo_name": "Elyott/Jokeboard", "revision_date": "2019-03-08T06:00:35", "revision_id": "79d8517e4b39711e600dcaece035421fa2377c20", "snapshot_id": "5f78ce7b4d7474375709366e6bb53940d111fc48", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Elyott/Jokeboard/79d8517e4b39711e600dcaece035421fa2377c20/db/queries.js", "visit_date": "2020-03-12T17:53:58.050792", "added": "2024-11-19T00:06:05.925860+00:00", "created": "2019-03-08T06:00:35", "int_score": 2, "score": 2.171875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0060.json.gz" }
function UrlCheck(url) { this.url = url; this.type = ActionParser.URL_CHECK; this.humanName = 'Sihtaadressi kontroll'; this.perform = function(webview) { let actionData = { url: this.url }; webview.get(0).send('url-check-playback', actionData); }; }
9d29e6f5de1b77b7e5f5c0a67af540c29f5caccd
{ "blob_id": "9d29e6f5de1b77b7e5f5c0a67af540c29f5caccd", "branch_name": "refs/heads/master", "committer_date": "2017-04-22T15:26:19", "content_id": "23d5718c3796e03eafcf525bbbf5c5a5a75f11c9", "detected_licenses": [ "MIT" ], "directory_id": "a679542001ff402c41add0d02354d43351df6bc3", "extension": "js", "filename": "url-check.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 81189237, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 261, "license": "MIT", "license_type": "permissive", "path": "/scripts/classes/url-check.js", "provenance": "stack-edu-0038.json.gz:615613", "repo_name": "kardoj/ui-tests", "revision_date": "2017-04-22T15:26:19", "revision_id": "0112a1b709fff0037cda7c1000570dea4238a5e4", "snapshot_id": "7a4bea91bb2bf6395802ebafaa583a0739702af4", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/kardoj/ui-tests/0112a1b709fff0037cda7c1000570dea4238a5e4/scripts/classes/url-check.js", "visit_date": "2021-01-13T11:32:15.962972", "added": "2024-11-18T19:57:54.412721+00:00", "created": "2017-04-22T15:26:19", "int_score": 2, "score": 2.140625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0056.json.gz" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TTracker.Models; using TTracker.DataAccess.TextHelper; namespace TTracker.DataAccess { public class TextConnector : IDataConnection { public void CreatePerson(PersonModel Model) { List<PersonModel> players = GlobalConfig.Playersfile.FullFilePath().LoadFile().ConverttoPlayerModel(); int currentId = 1; if (players.Count > 0) { currentId = players.OrderByDescending(x => x.Id).First().Id + 1; } Model.Id = currentId; players.Add(Model); players.SaveToPlayersFile(GlobalConfig.Playersfile); } // TODO -- public void CreatePrize(PrizeModel Model) { List<PrizeModel> prizes= GlobalConfig.Prizesfile.FullFilePath().LoadFile().ConverttoPrizeModel(); int currentId = 1; if (prizes.Count > 0) { currentId = prizes.OrderByDescending(x => x.Id).First().Id + 1; } Model.Id = currentId; prizes.Add(Model); prizes.SaveToPrizeFile(GlobalConfig.Prizesfile); } public void CreateTeam(TeamModel Model) { List<TeamModel> Teams = GlobalConfig.Teamsfile.FullFilePath().LoadFile().CoverttoTeamModel(GlobalConfig.Playersfile); int currentId = 1; if (Teams.Count > 0) { currentId = Teams.OrderByDescending(x => x.Id).First().Id + 1; } Model.Id = currentId; Teams.Add(Model); Teams.Savetoteamfile(GlobalConfig.Teamsfile); } public void CreateTournamentModel(TournamentModel model) { List < TournamentModel > tournaments = GlobalConfig.Tournamentsfile.FullFilePath().LoadFile().ConvertToTournamentModel(GlobalConfig.Teamsfile, GlobalConfig.Playersfile, GlobalConfig.Prizesfile); int currentId = 1; if (tournaments.Count > 0) { currentId = tournaments.OrderByDescending(x => x.Id).First().Id + 1; } model.Id = currentId; model.SaveRoundsToFile(GlobalConfig.MatchupsFile, GlobalConfig.MatchupEntriesFile); tournaments.Add(model); tournaments.SavetoTournamentFile(GlobalConfig.Tournamentsfile); TTracker.TournamentLogic.UpdateTournamentResults(model); } public List<PersonModel> Get_PlayersAll() { return GlobalConfig.Playersfile.FullFilePath().LoadFile().ConverttoPlayerModel(); } public List<TeamModel> Get_TeamsAll() { return GlobalConfig.Teamsfile.FullFilePath().LoadFile().CoverttoTeamModel(GlobalConfig.Playersfile); } public List<TournamentModel> Get_TournamentsAll() { return GlobalConfig.Tournamentsfile.FullFilePath().LoadFile().ConvertToTournamentModel(GlobalConfig.Teamsfile, GlobalConfig.Playersfile, GlobalConfig.Prizesfile); } public void UpdateMatchup(MatchupModel m) { m.UpdateMatchuptoFile(); } } }
e2c8d96996b27ad73245342394ebc1cb4732edf4
{ "blob_id": "e2c8d96996b27ad73245342394ebc1cb4732edf4", "branch_name": "refs/heads/main", "committer_date": "2021-07-18T08:57:01", "content_id": "69e1bee8eea3283c6da860300dee55c650599788", "detected_licenses": [ "Apache-2.0" ], "directory_id": "957e36b84a58a21f6f7b9ee0d8dbfc0b7b254cfc", "extension": "cs", "filename": "TextConnector.cs", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 345182210, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3460, "license": "Apache-2.0", "license_type": "permissive", "path": "/TTracker/DataAccess/TextConnector.cs", "provenance": "stack-edu-0014.json.gz:519542", "repo_name": "omermehmeti/TournamentTracker", "revision_date": "2021-07-18T08:57:01", "revision_id": "4e16ebd13eb25a3d1460209ac68e58fd07ea9cc6", "snapshot_id": "bb0da6c4e06722b3d587dd26dbaabea5af243c94", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/omermehmeti/TournamentTracker/4e16ebd13eb25a3d1460209ac68e58fd07ea9cc6/TTracker/DataAccess/TextConnector.cs", "visit_date": "2023-06-22T13:02:49.828814", "added": "2024-11-18T23:36:23.716258+00:00", "created": "2021-07-18T08:57:01", "int_score": 2, "score": 2.40625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0032.json.gz" }
import numpy as np np.random.seed(123) from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten from keras.layers import Convolution2D, MaxPooling2D from keras.utils import np_utils from keras.datasets import mnist # globals: debugim=False # pre-shuffled data from the keras data loader... (X_train, y_train), (X_test, y_test) = mnist.load_data() print (X_train.shape) from matplotlib import pyplot as plt # show a first image in dataset if debugim: plt.imshow(X_train[0]) plt.show() a = X_test.shape[1] X_train = X_train.reshape(X_train.shape[0], a, a, 1) X_test = X_test.reshape(X_test.shape[0],a, a, 1) print(X_test.shape) # need brightness vales to be float32:s in [0,1] X_train = X_train.astype('float32') X_test = X_test.astype('float32') X_train /= 255 X_test /= 255 # print(y_train[:10]) # change number output to a bool-vector hit output (better?) y_train = np_utils.to_categorical(y_train, 10) y_test = np_utils.to_categorical(y_test, 10) ## --> [0, 0, 1, 0, 0, 0 ..., 0] == 2 model = Sequential() # note: step size == 1,1 can be changed using 'subsample' property model.add(Convolution2D(32, 3, 3, activation='relu', input_shape=(a, a, 1))) # DEBUG # print(model.output_shape) model.add(Convolution2D(32,3,3,activation='relu')) model.add(MaxPooling2D(pool_size=(2,2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(10, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(X_train, y_train, batch_size=32, epochs=10, verbose=1)
cd307bdc2a54983d93d4a35373a9ef39ed088e78
{ "blob_id": "cd307bdc2a54983d93d4a35373a9ef39ed088e78", "branch_name": "refs/heads/master", "committer_date": "2018-11-21T11:03:05", "content_id": "0272b15d55ac49933c46a65ad4c9952d14e94ecb", "detected_licenses": [ "MIT" ], "directory_id": "e7be47f632d30203c553572f25f3dd9fd82059ad", "extension": "py", "filename": "keras_tutorial_deeplearning.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 156521892, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1671, "license": "MIT", "license_type": "permissive", "path": "/keras0/keras_tutorial_deeplearning.py", "provenance": "stack-edu-0056.json.gz:406691", "repo_name": "jakobbohem/aiwords", "revision_date": "2018-11-21T11:03:05", "revision_id": "b9b92b19ce144f93dcf95d91cbe6673447e6b7f1", "snapshot_id": "a7596013c912c865308f0344e5f00547645fd737", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jakobbohem/aiwords/b9b92b19ce144f93dcf95d91cbe6673447e6b7f1/keras0/keras_tutorial_deeplearning.py", "visit_date": "2020-04-05T03:38:36.578858", "added": "2024-11-19T03:22:56.805143+00:00", "created": "2018-11-21T11:03:05", "int_score": 3, "score": 2.640625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0074.json.gz" }
package service; import android.Manifest; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.media.MediaRecorder; import android.os.IBinder; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.util.Log; import java.io.IOException; public class PhoneService extends Service { private MediaRecorder mRecorder; private String mFileName="/mnt/adcard/vero.3gp"; private TelephonyManager tm; private MyPhoneStateListener listener; public PhoneService() { } @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { Log.i("PhoneService","onCreate"); tm= (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); listener=new MyPhoneStateListener(); tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE); } private class MyPhoneStateListener extends PhoneStateListener{ @Override public void onCallStateChanged(int state, String incomingNumber) { super.onCallStateChanged(state, incomingNumber); //电话状态改变监听 switch (state){ case TelephonyManager.CALL_STATE_IDLE: //电话空闲:即正常待机 if (mRecorder!=null){ stopRecording(); } break; case TelephonyManager.CALL_STATE_OFFHOOK: //电话接通状态 startRecording(); break; case TelephonyManager.CALL_STATE_RINGING: //电话正在响 break; } } } @Override public void onDestroy() { super.onDestroy(); tm.listen(listener,PhoneStateListener.LISTEN_NONE); } private void startRecording(){ mRecorder=new MediaRecorder(); //指定一个源:MIC:来自手机麦克风,VOICE_CALL:录制讲话的所有声音(对方讲话和自己讲话,美国法律不支持,中国可以) mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); //输出数据的格式 mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); //保存的位置 mRecorder.setOutputFile(mFileName); //使用什么解码器 mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); try { mRecorder.prepare(); mRecorder.start(); Log.e("startRecording","prepare()----startingggggggggggggg"); } catch (IOException e) { e.printStackTrace(); Log.e("startRecording","prepare()----failed"); } } private void stopRecording(){ mRecorder.stop(); mRecorder.release(); mRecorder=null; } }
4ef4481c3e79c0056233f4ef2838a0281ba65f1e
{ "blob_id": "4ef4481c3e79c0056233f4ef2838a0281ba65f1e", "branch_name": "refs/heads/master", "committer_date": "2017-04-20T13:17:41", "content_id": "1fcc5a527140efe4cc0cd88dff129da25dd51292", "detected_licenses": [ "Apache-2.0" ], "directory_id": "de2203a2d1b37785d25a584a0ef78250bb039f2c", "extension": "java", "filename": "PhoneService.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 48735866, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3076, "license": "Apache-2.0", "license_type": "permissive", "path": "/C2_UI_2/c2_10_电话窃听/src/main/java/service/PhoneService.java", "provenance": "stack-edu-0022.json.gz:701371", "repo_name": "wapalxj/Android_C2_UI", "revision_date": "2017-04-20T13:17:41", "revision_id": "72771a4c52ffa7a41065016f706ddf8b5bf75c33", "snapshot_id": "c91c441e5ef68509a39bbaaed214192bfb3f3d58", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/wapalxj/Android_C2_UI/72771a4c52ffa7a41065016f706ddf8b5bf75c33/C2_UI_2/c2_10_电话窃听/src/main/java/service/PhoneService.java", "visit_date": "2020-05-21T13:44:08.023414", "added": "2024-11-18T21:48:52.714460+00:00", "created": "2017-04-20T13:17:41", "int_score": 2, "score": 2.34375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0040.json.gz" }
package com.wxm.bbsdemo.utility; import java.text.DateFormat; import java.text.FieldPosition; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Date; public class DateUtil { public static long ONE_SECOND=1000; public static long ONE_MIN=60*1000; public static long ONE_HOUR=60*60*1000; public static long ONE_DAY=12*60*60*1000; public static long ONE_WEEK=7*12*60*60*1000; public static final String DATE_TIME_FORMAT_YYYY_M_D_HH_MI_SS = "yyyy-M-d HH:mm:ss"; public static String dateReform(Date date){ Date now=new Date(); long diff=Math.abs(now.getTime()-date.getTime()); String suffix=diff>0?"前":"后"; if(now.getTime()-date.getTime()<ONE_MIN) { return diff/ONE_SECOND+" 秒"+suffix; }else if(now.getTime()-date.getTime()<ONE_HOUR){ return diff/ONE_MIN+" 分钟"+suffix; } else if(now.getTime()-date.getTime()<ONE_DAY){ return diff/ONE_HOUR+" 小时"+suffix; } else if(now.getTime()-date.getTime()<ONE_WEEK){ return diff/ONE_DAY+" 天"+suffix; }else { SimpleDateFormat simpleDateFormat=new SimpleDateFormat(DATE_TIME_FORMAT_YYYY_M_D_HH_MI_SS); return simpleDateFormat.format(date); } } }
003c5608ecf560ee9a837dc59b6bb2a317aede96
{ "blob_id": "003c5608ecf560ee9a837dc59b6bb2a317aede96", "branch_name": "refs/heads/master", "committer_date": "2022-06-23T08:11:02", "content_id": "6bc3d4a77455816c494c47b4c782c4419182996d", "detected_licenses": [ "MIT" ], "directory_id": "3283f3906e14cf003bfa0fce9321b88d8e36449a", "extension": "java", "filename": "DateUtil.java", "fork_events_count": 0, "gha_created_at": "2019-08-22T05:42:11", "gha_event_created_at": "2022-06-23T08:11:04", "gha_language": "Java", "gha_license_id": "MIT", "github_id": 203722135, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1321, "license": "MIT", "license_type": "permissive", "path": "/src/main/java/com/wxm/bbsdemo/utility/DateUtil.java", "provenance": "stack-edu-0026.json.gz:752170", "repo_name": "kiritoxkiriko/bbsdemo", "revision_date": "2022-06-23T08:11:02", "revision_id": "218315a536f19079d98bb0249c6ecc2a8936f3dd", "snapshot_id": "80b792841201c238eefb5000c9e2c152abbf4c7f", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/kiritoxkiriko/bbsdemo/218315a536f19079d98bb0249c6ecc2a8936f3dd/src/main/java/com/wxm/bbsdemo/utility/DateUtil.java", "visit_date": "2022-07-09T19:43:18.340565", "added": "2024-11-19T01:37:54.157488+00:00", "created": "2022-06-23T08:11:02", "int_score": 3, "score": 2.984375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0044.json.gz" }
from sensorhub.hub import SensorHub class PiSensor: def __init__(self): self.hub = SensorHub(None) def ext_temp(self): try: return self.safe_value(self.hub.get_off_board_temperature()) except IOError: return None def humidity(self): try: return self.safe_value(self.hub.get_humidity()) except IOError: return None def int_temp(self): try: return self.safe_value(self.hub.get_temperature()) except IOError: return None def motion(self): try: return self.safe_value(self.hub.is_motion_detected()) except IOError: return None def brightness(self): try: return self.safe_value(self.hub.get_brightness()) except IOError: return None def bar_temp(self): try: return self.safe_value(self.hub.get_barometer_temperature()) except IOError: return None def pressure(self): try: return self.safe_value(self.hub.get_barometer_pressure()) except IOError: return None def safe_value(self, x): if x == -1: return None else: return x
e096f95d6cbce818c18c4b1a9f20e8bf36ef69e2
{ "blob_id": "e096f95d6cbce818c18c4b1a9f20e8bf36ef69e2", "branch_name": "refs/heads/master", "committer_date": "2021-01-25T14:59:22", "content_id": "05c060e19ad23646d9fe213617db0075ea854997", "detected_licenses": [ "MIT" ], "directory_id": "eb86ce50630487d2c24147a611ca690a47706b1b", "extension": "py", "filename": "pi_sensor.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 324536841, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1290, "license": "MIT", "license_type": "permissive", "path": "/app/pi_sensor.py", "provenance": "stack-edu-0066.json.gz:88556", "repo_name": "pzac/pi-weather-station", "revision_date": "2021-01-25T14:59:01", "revision_id": "6a70b6ff413394ae0339daac27e94251902f059f", "snapshot_id": "8ae17749f00b085d17101901f9c89a1fcf50fdbc", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/pzac/pi-weather-station/6a70b6ff413394ae0339daac27e94251902f059f/app/pi_sensor.py", "visit_date": "2023-02-21T16:39:20.118825", "added": "2024-11-18T23:15:59.041392+00:00", "created": "2021-01-25T14:59:01", "int_score": 2, "score": 2.453125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0084.json.gz" }
/* * AdventOfCode2019 * Copyright (C) 2022 SizableShrimp * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package me.sizableshrimp.adventofcode.days; import me.sizableshrimp.adventofcode.templates.SeparatedDay; import java.util.Arrays; import java.util.Collections; import java.util.stream.Collectors; public class Day16 extends SeparatedDay { int[] baseInput = Arrays.stream(lines.get(0).split("")).mapToInt(Integer::parseInt).toArray(); int[] pattern = {0, 1, 0, -1}; @Override protected Object part1() { int[] signal = baseInput; for (int phase = 0; phase < 100; phase++) { int[] next = new int[signal.length]; for (int i = 0; i < next.length; i++) { int result = 0; for (int j = 0; j < signal.length; j++) { result += signal[j] * getPattern(j, i + 1); } next[i] = Math.abs(result % 10); } signal = next; } return section(signal, 8); } private int getPattern(int index, int size) { return pattern[((index + 1) / size) % 4]; } @Override protected Object part2() { int offset = Integer.parseInt(section(baseInput, 7)); if (offset < baseInput.length / 2) throw new IllegalArgumentException("Solution is invalid for input"); int[] input = Collections.nCopies(10_000, baseInput).stream() .flatMapToInt(Arrays::stream).skip(offset).toArray(); return section(run(input), 8); } int[] run(int[] input) { int[] prev = input; for (int phase = 0; phase < 100; phase++) { int[] signal = Arrays.copyOf(prev, prev.length); for (int i = signal.length - 2; i >= 0; i--) { signal[i] = (prev[i] + signal[i + 1]) % 10; } prev = signal; } return prev; } private String section(int[] output, int i) { return Arrays.stream(output).boxed().limit(i).map(Object::toString).collect(Collectors.joining()); } }
85f0d9f79c4d061748a64f2a3b718d2880a1e6cb
{ "blob_id": "85f0d9f79c4d061748a64f2a3b718d2880a1e6cb", "branch_name": "refs/heads/master", "committer_date": "2022-12-04T00:17:00", "content_id": "dbc692211f6c474380db66bf786996e9feec51f2", "detected_licenses": [ "MIT" ], "directory_id": "136e1efc68dd46af286026b1981e20de99e2822e", "extension": "java", "filename": "Day16.java", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 224100231, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3118, "license": "MIT", "license_type": "permissive", "path": "/src/main/java/me/sizableshrimp/adventofcode/days/Day16.java", "provenance": "stack-edu-0026.json.gz:53377", "repo_name": "SizableShrimp/AdventOfCode2019", "revision_date": "2022-12-04T00:17:00", "revision_id": "73bbca397830f6c553db028baf1fdc18f1be592b", "snapshot_id": "be3cc9e6f7f9c4aae563a0df2367e6f4531e8635", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/SizableShrimp/AdventOfCode2019/73bbca397830f6c553db028baf1fdc18f1be592b/src/main/java/me/sizableshrimp/adventofcode/days/Day16.java", "visit_date": "2022-12-06T02:24:34.129340", "added": "2024-11-19T00:41:18.110780+00:00", "created": "2022-12-04T00:17:00", "int_score": 3, "score": 2.6875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0044.json.gz" }
#pragma once #include <util/generic/yexception.h> class TIOStatus { public: inline TIOStatus(int status) noexcept : Status_(status) { } static inline TIOStatus Error(int status) noexcept { return TIOStatus(status); } static inline TIOStatus Error() noexcept { return TIOStatus(LastSystemError()); } static inline TIOStatus Success() noexcept { return TIOStatus(0); } inline void Check() const { if (Status_) { ythrow TSystemError(Status_) << "io error"; } } inline bool Failed() const noexcept { return (bool)Status_; } inline bool Succeed() const noexcept { return !Failed(); } inline int Status() const noexcept { return Status_; } private: int Status_; }; class TContIOStatus { public: inline TContIOStatus(size_t processed, TIOStatus status) noexcept : Processed_(processed) , Status_(status) { } static inline TContIOStatus Error(TIOStatus status) noexcept { return TContIOStatus(0, status); } static inline TContIOStatus Error() noexcept { return TContIOStatus(0, TIOStatus::Error()); } static inline TContIOStatus Success(size_t processed) noexcept { return TContIOStatus(processed, TIOStatus::Success()); } static inline TContIOStatus Eof() noexcept { return Success(0); } inline ~TContIOStatus() { } inline size_t Processed() const noexcept { return Processed_; } inline int Status() const noexcept { return Status_.Status(); } inline size_t Checked() const { Status_.Check(); return Processed_; } private: size_t Processed_; TIOStatus Status_; };
281ab0636b18ace54a541f0bb681b3bb1e72ad04
{ "blob_id": "281ab0636b18ace54a541f0bb681b3bb1e72ad04", "branch_name": "refs/heads/master", "committer_date": "2019-01-10T14:15:07", "content_id": "f7d93175fe988dbf5e5113e79d31d45d36cde391", "detected_licenses": [ "Apache-2.0" ], "directory_id": "9ea60e28aff016fc0a766163159ac051321904fb", "extension": "h", "filename": "iostatus.h", "fork_events_count": 1, "gha_created_at": "2019-01-11T03:22:29", "gha_event_created_at": "2022-11-03T02:07:17", "gha_language": "C++", "gha_license_id": "Apache-2.0", "github_id": 165172125, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1798, "license": "Apache-2.0", "license_type": "permissive", "path": "/library/coroutine/engine/iostatus.h", "provenance": "stack-edu-0004.json.gz:171177", "repo_name": "yumoh/catboost_iter", "revision_date": "2019-01-10T14:15:07", "revision_id": "85b943bc3c1f010d1ec7272c27a36f89f0173318", "snapshot_id": "853865c5487dcb3b0bf11dc52886f296eb00cfe1", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/yumoh/catboost_iter/85b943bc3c1f010d1ec7272c27a36f89f0173318/library/coroutine/engine/iostatus.h", "visit_date": "2022-11-17T17:58:46.718348", "added": "2024-11-18T22:56:59.062528+00:00", "created": "2019-01-10T14:15:07", "int_score": 3, "score": 2.625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0022.json.gz" }
package org.scitokens.tools; import edu.uiuc.ncsa.security.core.exceptions.GeneralException; import edu.uiuc.ncsa.security.core.exceptions.NFWException; import edu.uiuc.ncsa.security.core.util.*; import edu.uiuc.ncsa.security.util.cli.CLIDriver; import edu.uiuc.ncsa.security.util.cli.Commands; import edu.uiuc.ncsa.security.util.cli.ConfigurableCommandsImpl; import edu.uiuc.ncsa.security.util.cli.InputLine; import edu.uiuc.ncsa.security.util.functor.parser.event.ParserUtil; import org.apache.commons.lang.StringUtils; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.List; import java.util.Vector; import static edu.uiuc.ncsa.security.util.cli.CommonCommands.BATCH_MODE_FLAG; /** * This creates SciTokens at the command line from the utilities and can verify them as well. * It also will generate signing keys. * <p>Created by Jeff Gaynor<br> * on 9/5/17 at 3:31 PM */ public class SciTokensUtil extends ConfigurableCommandsImpl { public SciTokensUtil(MyLoggingFacade logger) { super(logger); } public void about() { int width = 60; String stars = StringUtils.rightPad("", width + 1, "*"); say(stars); say(padLineWithBlanks("* SciTokens CLI (Command Line Interpreter)", width) + "*"); say(padLineWithBlanks("* Version " + LoggingConfigLoader.VERSION_NUMBER, width) + "*"); say(padLineWithBlanks("* By Jeff Gaynor NCSA", width) + "*"); say(padLineWithBlanks("* (National Center for Supercomputing Applications)", width) + "*"); say(padLineWithBlanks("*", width) + "*"); say(padLineWithBlanks("* type 'help' for a list of commands", width) + "*"); say(padLineWithBlanks("* 'exit' or 'quit' to end this session.", width) + "*"); say(stars); } @Override public ConfigurationLoader<? extends AbstractEnvironment> getLoader() { return null; } @Override public String getPrompt() { return "sciTokens>"; } @Override public String getComponentName() { return null; } @Override public void useHelp() { say("You may use this in both interactive mode and as a command line utility."); say("To use in batch mode, supply the " + BATCH_MODE_FLAG + " flag."); say("This will suppress all output and will not prompt for missing arguments to functions."); say("If you omit this flag, then missing arguments will still cause you to be prompted."); say("Here is a list of commands:"); say("Key commands"); say("------------"); say("create_keys"); say("set_keys"); say("list_keys"); say("list_key_ids"); say("set_default_id"); say("print_default_id"); say("print_well_known"); say("Claim Commands"); say("--------------"); say("create_claims"); say("parse_claims"); say("Token Commands"); say("--------------"); say("create_token"); say("print_token"); say("validate_token"); say("To get a full explanation of the command and its syntax, type \"command --help \"."); say("Command line options"); say("--------------------"); say("These are flags and arguments to the command line processor."); say(SHORT_VERBOSE_FLAG + "," + LONG_VERBOSE_FLAG + "= turn verbose mode on. This allows you to see the internal workings of processing"); say(" You can set this in a batch file by invoking set_verbose true|false"); say(SHORT_NO_OUTPUT_FLAG + ", " +LONG_NO_OUTPUT_FLAG + " = turn off all output"); say(" You can set this in a batch file by invoking set_no_ouput true|false"); say(BATCH_MODE_FLAG + "= interpret everything else on the command line as a command, aside from flags. Note this means you can execute a single command."); say(SciTokensUtilCommands.BATCH_FILE_MODE_FLAG + "= this is the fully qualified path to a file of commands which will be interpreted one after the other."); } protected static String DUMMY_FUNCTION = "dummy0"; // used to create initial command line public static String SHORT_HELP_FLAG = "-help"; public static String LONG_HELP_FLAG = "--help"; public static String SHORT_VERBOSE_FLAG = "-v"; public static String LONG_VERBOSE_FLAG = "--verbose"; public static String SHORT_NO_OUTPUT_FLAG = "-noOuput"; public static String LONG_NO_OUTPUT_FLAG = "--noOuput"; public static void main(String[] args) { Vector<String> vector = new Vector<>(); vector.add(DUMMY_FUNCTION); // Dummay zero-th arg. for (String arg : args) { vector.add(arg); } InputLine argLine = new InputLine(vector); // now we have a bunch of utilities for this // In order of importance for command line flags. if (argLine.hasArg(SHORT_HELP_FLAG) || argLine.hasArg(LONG_HELP_FLAG)) { SciTokensUtil sciTokensCLI = new SciTokensUtil(null); // no logging, just grab the help and exit; sciTokensCLI.useHelp(); return; } boolean isVerbose = argLine.hasArg(SHORT_VERBOSE_FLAG) || argLine.hasArg(LONG_VERBOSE_FLAG); // again, a batch file means every line in the file is a separate comamand, aside from comments boolean hasBatchFile = argLine.hasArg(SciTokensUtilCommands.BATCH_FILE_MODE_FLAG); // Batch mode means that the command line is interpreted as a single command. This execeuts one command, batch mode does many. boolean isBatchMode = argLine.hasArg(SciTokensUtilCommands.BATCH_MODE_FLAG); boolean isNoOuput = (argLine.hasArg(SHORT_NO_OUTPUT_FLAG) || argLine.hasArg(LONG_NO_OUTPUT_FLAG)); MyLoggingFacade myLoggingFacade = null; if (argLine.hasArg("-log")) { String logFileName = argLine.getNextArgFor("-log"); LoggerProvider loggerProvider = new LoggerProvider(logFileName, "SciTokensUtil logger", 1, 1000000, false, isVerbose, false); myLoggingFacade = loggerProvider.get(); // if verbose } SciTokensUtil sciTokensCLI = new SciTokensUtil(myLoggingFacade); SciTokensUtilCommands sciTokensCommands = new SciTokensUtilCommands(myLoggingFacade); sciTokensCommands.setVerbose(isVerbose); sciTokensCommands.setPrintOuput(!isNoOuput); try { CLIDriver cli = new CLIDriver(sciTokensCommands); // Easy case -- no arguments, so just start. if (args == null || args.length == 0) { sciTokensCLI.about(); cli.start(); return; } sciTokensCommands.setBatchMode(false); if (argLine.hasArg(SciTokensUtilCommands.BATCH_FILE_MODE_FLAG)) { sciTokensCLI.processBatchFile(argLine.getNextArgFor(SciTokensUtilCommands.BATCH_FILE_MODE_FLAG), cli); return; } if (argLine.hasArg(BATCH_MODE_FLAG)) { sciTokensCLI.processBatchModeCommand(cli, args); return; //this should end once a single command is processed. } // alternately, parse the arguments String cmdLine = args[0]; for (int i = 1; i < args.length; i++) { if (args[i].equals(BATCH_MODE_FLAG)) { sciTokensCommands.setBatchMode(true); } else { // don't keep the batch flag in the final arguments. cmdLine = cmdLine + " " + args[i]; } } cli.execute(cmdLine); } catch (Throwable t) { if (sciTokensCommands.isBatchMode()) { System.exit(1); } t.printStackTrace(); } } protected SciTokensUtilCommands getSciTokensCommands(CLIDriver cli) { for (Commands c : cli.getCLICommands()) { if (c instanceof SciTokensUtilCommands) { return (SciTokensUtilCommands) c; } } return null; } protected void processBatchModeCommand(CLIDriver cli, String[] args) throws Exception { SciTokensUtilCommands sciTokensCommands = getSciTokensCommands(cli); if (sciTokensCommands == null) { throw new NFWException("Error: No SciTokensUtilCommands configured, hence no logging."); } sciTokensCommands.setBatchMode(true); // need to tease out the intended line to execute. The arg line looks like // sciTokens -batch A B C // so we need to drop the name of the function and the -batch flag. String cmdLine = ""; for (String arg : args) { if (!arg.equals(DUMMY_FUNCTION) && !arg.equals(SciTokensUtilCommands.BATCH_MODE_FLAG)) { cmdLine = cmdLine + " " + arg; } } cli.execute(cmdLine); } protected void processBatchFile(String fileName, CLIDriver cli) throws Throwable { if(fileName == null || fileName.isEmpty()){ throw new FileNotFoundException("Error: The file name is missing."); } File file = new File(fileName); if (!file.exists()) { throw new FileNotFoundException("Error: The file \"" + fileName + "\" does not exist"); } if (!file.isFile()) { throw new FileNotFoundException("Error: The object \"" + fileName + "\" is not a file."); } if (!file.canRead()) { throw new GeneralException("Error: Cannot read file \"" + fileName + "\". Please check your permissions."); } FileReader fis = new FileReader(file); List<String> commands = ParserUtil.processInput(fis); SciTokensUtilCommands sciTokensCommands = getSciTokensCommands(cli); if (sciTokensCommands == null) { throw new NFWException("Error: No SciTokensUtilCommands configured, hence no logging."); } sciTokensCommands.setBatchMode(true); for(String command : commands){ try { int rc = cli.execute(command); switch (rc) { // Hint: The colons in the messages line up (more or less) so that the log file is very easily readable at a glance. case CLIDriver.ABNORMAL_RC: sciTokensCommands.error("Error: \"" + command + "\""); break; case CLIDriver.HELP_RC: sciTokensCommands.info(" Help: invoked."); break; case CLIDriver.OK_RC: default: if(sciTokensCommands.isVerbose()){ sciTokensCommands.info(" ok: \"" + command+ "\""); } } } catch (Throwable t) { sciTokensCommands.error(t, "Error executing batch file command \"" + command + "\""); } } } protected void start(String[] args) throws Exception { about(); if (!getOptions(args)) { say("Warning: no configuration file specified. type in 'load --help' to see how to load one."); return; } } }
072a2b2f9c20a82d0dcd4836a0fe8b19bccee2ea
{ "blob_id": "072a2b2f9c20a82d0dcd4836a0fe8b19bccee2ea", "branch_name": "refs/heads/master", "committer_date": "2021-12-20T16:36:46", "content_id": "2a4f51841104cdf0af13a3c7eabe97ebcd230bcd", "detected_licenses": [ "Apache-2.0" ], "directory_id": "d42b7513eaa27e5f801be894846b7dd94449b313", "extension": "java", "filename": "SciTokensUtil.java", "fork_events_count": 2, "gha_created_at": "2017-07-24T13:20:23", "gha_event_created_at": "2021-12-18T18:39:06", "gha_language": "Java", "gha_license_id": "Apache-2.0", "github_id": 98192959, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 11487, "license": "Apache-2.0", "license_type": "permissive", "path": "/scitokens-cli/src/main/java/org/scitokens/tools/SciTokensUtil.java", "provenance": "stack-edu-0029.json.gz:89087", "repo_name": "scitokens/scitokens-java", "revision_date": "2021-12-20T16:36:46", "revision_id": "df61b42b0aacd7ff852863f9f8b367c5547323bd", "snapshot_id": "346858adf4c4f853c8e8bf5a124b8eb6da017d95", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/scitokens/scitokens-java/df61b42b0aacd7ff852863f9f8b367c5547323bd/scitokens-cli/src/main/java/org/scitokens/tools/SciTokensUtil.java", "visit_date": "2021-12-24T16:08:25.815917", "added": "2024-11-18T20:38:18.430727+00:00", "created": "2021-12-20T16:36:46", "int_score": 2, "score": 2.296875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0047.json.gz" }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package samusik.hideabletree; /** * * @author Kola */ // *** HideableMutableTreeNode *** import javax.swing.*; import javax.swing.tree.*; /** * <code>HideableMutableTreeNode</code> is a <code>DefaultMutableTreeNode</code> * implementation that works with <code>HideableTreeModel</code>. */ public class HideableMutableTreeNode<T extends Object> extends DefaultMutableTreeNode { /** * The node is visible flag. */ public boolean visible = true; /** * Creates a tree node that has no parent and no children, but which * allows children. */ public HideableMutableTreeNode() { super(); } /** * Creates a tree node with no parent, no children, but which allows * children, and initializes it with the specified user object. * * @param userObject - an Object provided by the user that * constitutes the node's data */ public HideableMutableTreeNode(T userObject) { super(userObject); } /** * Creates a tree node with no parent, no children, initialized with the * specified user object, and that allows children only if specified. * * @param userObject - an Object provided by the user that * constitutes the node's data * @param allowsChildren - if true, the node is allowed to have child * nodes -- otherwise, it is always a leaf node */ public HideableMutableTreeNode(T userObject, boolean allowsChildren) { super(userObject, allowsChildren); } @Override public void setUserObject(Object userObject) { super.setUserObject(userObject); } @Override public T getUserObject() { return (T)super.getUserObject(); } /** * Checks if the node is visible. * * @return true if the node is visible, else false */ public boolean isVisible() { return this.visible; } /** * Sets if the node is visible. * * @param v true if the node is visible, else false */ public void setVisible(boolean v) { this.visible = v; } }
ae04726e8f71b6019c05293a2d08541738fc0afd
{ "blob_id": "ae04726e8f71b6019c05293a2d08541738fc0afd", "branch_name": "refs/heads/master", "committer_date": "2021-05-13T05:57:36", "content_id": "269508ddeaa5b56c865483a0fb868246edd9aa4c", "detected_licenses": [ "MIT" ], "directory_id": "234ca9de0a0233ba686d27d78615eafe9aa16ea0", "extension": "java", "filename": "HideableMutableTreeNode.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 53159418, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2138, "license": "MIT", "license_type": "permissive", "path": "/src/main/java/samusik/hideabletree/HideableMutableTreeNode.java", "provenance": "stack-edu-0024.json.gz:729412", "repo_name": "nolanlab/sandbox", "revision_date": "2021-05-13T05:57:36", "revision_id": "b2e1a5d8579e752466d8e9df6b2e8e8052f720a3", "snapshot_id": "215e4a51ac0714e86c70bd098b9bd21140632462", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/nolanlab/sandbox/b2e1a5d8579e752466d8e9df6b2e8e8052f720a3/src/main/java/samusik/hideabletree/HideableMutableTreeNode.java", "visit_date": "2021-06-05T06:03:16.120828", "added": "2024-11-18T23:13:49.533075+00:00", "created": "2021-05-13T05:57:36", "int_score": 3, "score": 3.203125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0042.json.gz" }
#include<stdio.h> #include<string.h> #include<math.h> int main() { char binary[65]; int len, decimal, power, i; printf("Enter the binary number: "); scanf("%s", &binary); decimal = 0; len= strlen(binary); power = len-1; for(i=0; i<len; i++){ decimal += (binary[i]-48) * pow(2, power); power--; } printf("Decimal value is %d\n", decimal); return 0; }
f8343f4a503cf63a84fa876cc27c4f5e1e985cc0
{ "blob_id": "f8343f4a503cf63a84fa876cc27c4f5e1e985cc0", "branch_name": "refs/heads/main", "committer_date": "2021-09-23T08:06:45", "content_id": "d74e59dce2a7881fe23b1f2916d6f512611d1f85", "detected_licenses": [ "MIT" ], "directory_id": "dbea9250c626838247fc92e5ed2b9b723ddc4da3", "extension": "c", "filename": "12.1.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 338761499, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 413, "license": "MIT", "license_type": "permissive", "path": "/Subin C ( 1st )/12.1.c", "provenance": "stack-edu-0001.json.gz:115739", "repo_name": "ASM-ATIKUR/Competitive_Programming_Atikur_Rahman", "revision_date": "2021-09-23T08:06:45", "revision_id": "9552e4dca7daad5c07542514d4b8c8baabea1989", "snapshot_id": "8db639403ef89a6374b9bcc4c430e816664b47f2", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ASM-ATIKUR/Competitive_Programming_Atikur_Rahman/9552e4dca7daad5c07542514d4b8c8baabea1989/Subin C ( 1st )/12.1.c", "visit_date": "2023-08-25T11:59:49.593390", "added": "2024-11-18T23:41:05.932769+00:00", "created": "2021-09-23T08:06:45", "int_score": 3, "score": 3.09375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0019.json.gz" }
// // // Code for reading QTI sensors // // // RIGHT 52 // 53 // LEFT 47 const int N_PINS_QTI = 3; const int PINS_QTI[N_PINS_QTI] = { 47, 53, 52 }; #define WHITE_BLACK_CUTOFF 10 //static int WHITE_BLACK_CUTOFF = 0; // Set all QTI pins to input or output void qti_set_io(int io_state) { for (int pin_i = 0; pin_i < N_PINS_QTI; pin_i++) { pinMode(PINS_QTI[pin_i], io_state); } } // Set all QTI pins to a certain digital state void qti_set_state(int state) { for (int pin_i = 0; pin_i < N_PINS_QTI; pin_i++) { digitalWrite(PINS_QTI[pin_i], state); } } // Return analog values indicating how long each sensor needs to decay as // integers in an array void qti_read_analog(int * output) { for (int pin_i = 0; pin_i < N_PINS_QTI; pin_i++) { output[pin_i] = 0; } /* boolean any = 1; long start_time = micros(); while (any) { any = 0; for (int pin_i = 0; pin_i < N_PINS_QTI; pin_i++) { int res = digitalRead(PINS_QTI[pin_i]) ? 1 : 0; any |= res; if (!res && output[pin_i] == 0) { long end_time = micros(); output[pin_i] = end_time - start_time; } } } */ boolean any = 1; while (any) { any = 0; for (int pin_i = 0; pin_i < N_PINS_QTI; pin_i++) { int res = digitalRead(PINS_QTI[pin_i]) ? 1 : 0; output[pin_i] += res; any |= res; } } char buf[32]; sprintf(buf, "%d %d %d", output[0], output[1], output[2]); Serial.println(buf); } // Return an integer where each bit represents the state of the QTI sensor array // LSB corresponds to the QTI sensor with the lowest pin number void qti_read_digital(boolean * output) { static int data[N_PINS_QTI]; qti_read_analog(data); /* if (WHITE_BLACK_CUTOFF == 0) { WHITE_BLACK_CUTOFF = (data[0] + data[1] + data[2]) / 3; char buf[32]; sprintf(buf, "Cutoff = %d", WHITE_BLACK_CUTOFF); Serial.println(buf); } */ for (int pin_i = 0; pin_i < N_PINS_QTI; pin_i++) { output[pin_i] = data[pin_i] > WHITE_BLACK_CUTOFF; } } // Initialize QTI sensors void qti_init() { qti_set_io(INPUT); qti_set_state(LOW); } // Execute the entire process of charging, discharging, and measuring sensors void qti_read(boolean * output) { // Charge the QTI sensors qti_set_io(OUTPUT); qti_set_state(HIGH); delay(1); // Read the QTI sensors qti_set_io(INPUT); qti_set_state(LOW); qti_read_digital(output); }
b752e715344aae612eb0fbc7cc2291be110cd77a
{ "blob_id": "b752e715344aae612eb0fbc7cc2291be110cd77a", "branch_name": "refs/heads/master", "committer_date": "2019-04-19T03:32:58", "content_id": "587c6da69a5f8f72129ca656654045dc2ecbc177", "detected_licenses": [ "Apache-2.0" ], "directory_id": "5863625fba43538c22961cbaa45a51633ab4cf77", "extension": "ino", "filename": "qti.ino", "fork_events_count": 3, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 172605416, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2414, "license": "Apache-2.0", "license_type": "permissive", "path": "/line_following/qti.ino", "provenance": "stack-edu-0005.json.gz:587718", "repo_name": "dwinkelman0/ECE110LabSection15", "revision_date": "2019-04-19T03:32:58", "revision_id": "91e273c4d0cc94421cf31f62810d94104199bd10", "snapshot_id": "623e4b71048fc9e1ff2f24b718b0cde6d0112c5c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/dwinkelman0/ECE110LabSection15/91e273c4d0cc94421cf31f62810d94104199bd10/line_following/qti.ino", "visit_date": "2020-04-25T07:09:57.932692", "added": "2024-11-18T21:49:34.727904+00:00", "created": "2019-04-19T03:32:58", "int_score": 3, "score": 3.09375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0023.json.gz" }
# RakeGem [![Rubocop Status](https://github.com/jubishop/rakegem/workflows/Rubocop/badge.svg)](https://github.com/jubishop/rakegem/actions/workflows/rubocop.yml) Rakefile gem helpers. ## Installation ### Global installation ```zsh gem install rakegem --source https://www.jubigems.org/ ``` ### In a Gemfile ```ruby gem 'rakegem', source: 'https://www.jubigems.org/' ``` ## Usage ### Bump minor version ```sh rake bump ``` ### Bump major version number ```sh rake bump[major] ``` ### Build gem ```sh rake build ``` ### Install gem ```sh rake install ``` ### Push gem to jubigems.org ```sh rake push ``` ## License The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
3b59deccc7d3655b706f3739db98b3459f04b46c
{ "blob_id": "3b59deccc7d3655b706f3739db98b3459f04b46c", "branch_name": "refs/heads/master", "committer_date": "2021-03-28T20:44:05", "content_id": "66c0fa6e0532403a268242bf1e77d0b0790a65b6", "detected_licenses": [ "MIT" ], "directory_id": "edb33ee9d5375c97467377fb9861675240d2b1ed", "extension": "md", "filename": "README.md", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 348540760, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 744, "license": "MIT", "license_type": "permissive", "path": "/README.md", "provenance": "stack-edu-markdown-0010.json.gz:181775", "repo_name": "jubishop/rakegem", "revision_date": "2021-03-28T20:44:05", "revision_id": "854a8f4bf77293aac8abfe85d92ff5055c41c945", "snapshot_id": "351f1e4e1a5e58ad4cf84088190622f06a6526d4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jubishop/rakegem/854a8f4bf77293aac8abfe85d92ff5055c41c945/README.md", "visit_date": "2023-03-26T21:24:26.830415", "added": "2024-11-19T00:21:46.700250+00:00", "created": "2021-03-28T20:44:05", "int_score": 3, "score": 3.296875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0010.json.gz" }
(function(){ 'use strict'; angular.module('app.filters') .filter('wrapParagraph', wrapParagraph); // wraps words /* example : some text .... | wrapParagraph:start:limit some text .... | wrapParagraph:0:25 */ function wrapParagraph() { 'use strict'; return function(items, begin, end) { if (items != null) { if (items.length > 25) return items.slice(begin, end) + "..."; else return items; } else { return "N/A"; } }; } })();
27f34773f81f5713e14d6dc4b55416122d9ee273
{ "blob_id": "27f34773f81f5713e14d6dc4b55416122d9ee273", "branch_name": "refs/heads/master", "committer_date": "2016-08-05T10:26:49", "content_id": "cf1a387680e3bf7cd681dcad15763b44a3ab0ae0", "detected_licenses": [ "MIT" ], "directory_id": "3318431b77588f7f51aeae13e19c5162be276765", "extension": "js", "filename": "wrapParagraph.filter.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 49409291, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 598, "license": "MIT", "license_type": "permissive", "path": "/sandbox/app19/app/filters/wrapParagraph.filter.js", "provenance": "stack-edu-0032.json.gz:67793", "repo_name": "Himanshu-Mishr/angular-apps", "revision_date": "2016-08-05T10:26:49", "revision_id": "5ee3e791b09209b82d1e533386c9662785b533a8", "snapshot_id": "4c3cf61c9be8d134989ea511d92648ad4a228820", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Himanshu-Mishr/angular-apps/5ee3e791b09209b82d1e533386c9662785b533a8/sandbox/app19/app/filters/wrapParagraph.filter.js", "visit_date": "2021-01-17T14:13:53.668936", "added": "2024-11-19T02:04:45.630368+00:00", "created": "2016-08-05T10:26:49", "int_score": 3, "score": 2.703125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0050.json.gz" }
# -*- coding:utf-8 -*- import cv2 import os import argparse import sys def video2image(): cap = cv2.VideoCapture(args.videopath) i = 0 name = 0 while cap.isOpened(): ret, frame = cap.read() time = cap.get(cv2.CAP_PROP_POS_MSEC) index = cap.get(cv2.CAP_PROP_POS_FRAMES) print('frames: %d --- times: %f' % (index, time/1000)) if frame is None: break i += 1 if args.videofps <= 0: cv2.imwrite(os.path.join(args.imagepath, str(name)) + '.jpg', frame) name += 1 print('(height: %d, weight: %d, channel: %d)' % frame.shape) else: if i == args.videofps: # cv2.imshow('frame', frame) # k = cv2.waitKey(20) # k = cv2.waitKey(0) i = 0 cv2.imwrite(os.path.join(args.imagepath, str(name)) + '.jpg', frame) name += 1 print('(height: %d, weight: %d, channel: %d)' % frame.shape) cap.release() cv2.destroyAllWindows() def image2video(): video_writer = cv2.VideoWriter(filename=args.videopath, fourcc=cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), fps=args.videofps, frameSize=(videosize[0], videosize[1])) list = os.listdir(args.imagepath) list.sort() for jpg in list: video_writer.write(cv2.imread(os.path.join(args.imagepath, jpg))) video_writer.release() if __name__ == '__main__': parser = argparse.ArgumentParser(description='video args', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--videopath', type=str, default='/home/workspace/DATASET/labixiaoxin2.flv', help='path of video') parser.add_argument('--videosize', type=str, default='800, 600', help='frame size of generated video') parser.add_argument('--videofps', type=int, default=24, help='fps of generated video or rate image from video') parser.add_argument('--imagepath', type=str, default='image', help='path of image') parser.add_argument('--ope', type=str, default='2img', help='2img for video to image,2video for image to video') args = parser.parse_args() videosize = [int(l) for l in args.videosize.split(',')] if args.ope == '2img': if not os.path.exists(args.imagepath): os.mkdir(args.imagepath) video2image() elif args.ope == '2video': if not os.path.exists(args.videopath): os.mkdir(args.videopath) image2video()
414b4654df2700deba62fd4a30f3605416e492fc
{ "blob_id": "414b4654df2700deba62fd4a30f3605416e492fc", "branch_name": "refs/heads/master", "committer_date": "2017-09-26T22:31:55", "content_id": "68e0bd917f1913f6a4527ce1c19c384df5f3d52c", "detected_licenses": [ "Apache-2.0" ], "directory_id": "346a343964155627de3d87867cfc8843da300141", "extension": "py", "filename": "video_tool.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2706, "license": "Apache-2.0", "license_type": "permissive", "path": "/mxnet/cv_tools/video_tool.py", "provenance": "stack-edu-0064.json.gz:527016", "repo_name": "lrt05hust/mlAlgorithms", "revision_date": "2017-09-26T22:31:55", "revision_id": "9ef7f962bf7881d25da1e0dd7dd30df7f8c94da0", "snapshot_id": "fe7f92febace1aa8a62187fd449c29286992fb93", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/lrt05hust/mlAlgorithms/9ef7f962bf7881d25da1e0dd7dd30df7f8c94da0/mxnet/cv_tools/video_tool.py", "visit_date": "2020-03-11T08:48:35.356808", "added": "2024-11-18T18:46:58.065527+00:00", "created": "2017-09-26T22:31:55", "int_score": 2, "score": 2.390625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0082.json.gz" }
package net.sourceforge.cruisecontrol; import java.io.ByteArrayInputStream; import java.io.InputStream; import junit.framework.TestCase; import net.sourceforge.cruisecontrol.CruiseControlOptions; import net.sourceforge.cruisecontrol.config.FileResolver; import net.sourceforge.cruisecontrol.config.XmlResolver; import net.sourceforge.cruisecontrol.util.Util; import org.jdom2.Element; public class CruiseControlConfigIncludeTest extends TestCase implements ResolverHolder { private Element rootElement; private Element includeElement; private XmlResolver xmlResolver; private FileResolver fileResolver; @Override protected void setUp() throws Exception { CruiseControlOptions.getInstance(this); final StringBuilder configText = new StringBuilder(200); configText.append("<cruisecontrol>"); configText.append(" <plugin name='foo.project'"); configText.append(" classname='net.sourceforge.cruisecontrol.MockProjectInterface'/>"); configText.append(" <include.projects file='include.xml'/>"); configText.append(" <foo.project name='in.root'/>"); configText.append("</cruisecontrol>"); rootElement = elementFromString(configText.toString()); final StringBuilder includeText = new StringBuilder(200); includeText.append("<cruisecontrol>"); includeText.append(" <foo.project name='in.include'/>"); includeText.append("</cruisecontrol>"); includeElement = elementFromString(includeText.toString()); xmlResolver = new IncludeXmlResolver(includeElement); fileResolver = new EmptyFileResolver(); } @Override protected void tearDown() throws Exception { CruiseControlOptions.delInstance(this); rootElement = null; includeElement = null; xmlResolver = null; } public void testShouldLoadIncludedProjects() throws Exception { final CruiseControlConfig config = new CruiseControlConfig(rootElement, this, null); assertEquals(2, config.getProjectNames().size()); assertIsFooProject(config.getProject("in.root")); assertIsFooProject(config.getProject("in.include")); } public void testShouldLoadedNestedIncludes() throws Exception { final StringBuilder includeText = new StringBuilder(200); includeText.append("<cruisecontrol>"); includeText.append(" <include.projects file='include.xml'/>"); includeText.append(" <foo.project name='in.first.include'/>"); includeText.append("</cruisecontrol>"); final Element includeWithNestedInclude = elementFromString(includeText.toString()); final Element[] elements = new Element[2]; elements[0] = includeWithNestedInclude; elements[1] = includeElement; xmlResolver = new IncludeXmlResolver(elements); final CruiseControlConfig config = new CruiseControlConfig(rootElement, this, null); assertEquals(3, config.getProjectNames().size()); assertIsFooProject(config.getProject("in.root")); assertIsFooProject(config.getProject("in.first.include")); assertIsFooProject(config.getProject("in.include")); } public void testIncludesCanDefinePlugins() throws CruiseControlException { final String newProjectTag = "new.project.type"; final Element pluginElement = new Element("plugin"); pluginElement.setAttribute("name", newProjectTag); pluginElement.setAttribute("classname", MockProjectInterface.class.getName()); includeElement.addContent(pluginElement); final Element barElement = new Element(newProjectTag); barElement.setAttribute("name", "bar"); includeElement.addContent(barElement); final CruiseControlConfig config = new CruiseControlConfig(rootElement, this, null); assertEquals(3, config.getProjectNames().size()); assertIsFooProject(config.getProject("bar")); } public void testPropertiesShouldBeAvailableToIncludedProjects() throws CruiseControlException { final Element property = new Element("property"); property.setAttribute("name", "baz"); property.setAttribute("value", "goo"); rootElement.addContent(property); final Element project = new Element("foo.project"); project.setAttribute("name", "${baz}"); includeElement.addContent(project); final CruiseControlConfig config = new CruiseControlConfig(rootElement, this); assertEquals(3, config.getProjectNames().size()); assertIsFooProject(config.getProject("goo")); } public void testErrorsInIncludeShouldBeContained() throws CruiseControlException { final Element unknownPlugin = new Element("unknown.plugin.error"); includeElement.addContent(unknownPlugin); final CruiseControlConfig config = new CruiseControlConfig(rootElement, this); assertEquals(1, config.getProjectNames().size()); assertIsFooProject(config.getProject("in.root")); } public void testErrorsParsingIncludeShouldBeContained() throws CruiseControlException { xmlResolver = new XmlResolver() { public Element getElement(String path) throws CruiseControlException { throw new CruiseControlException("simulate parse error"); } }; final CruiseControlConfig config = new CruiseControlConfig(rootElement, this); assertEquals(1, config.getProjectNames().size()); assertIsFooProject(config.getProject("in.root")); } public void testIncludeFilenameContainsProperty() throws CruiseControlException { xmlResolver = new XmlResolver() { private final Element includePropertyElement; { final StringBuilder includeText = new StringBuilder(200); includeText.append("<cruisecontrol>"); includeText.append(" <foo.project name='in.include.withproperty'/>"); includeText.append("</cruisecontrol>"); includePropertyElement = elementFromString(includeText.toString()); } public Element getElement(String path) throws CruiseControlException { assertEquals("include_FOO_.xml", path); return includePropertyElement; } }; final Element propertyElement = new Element("property"); propertyElement.setAttribute("name", "filenameswitch"); propertyElement.setAttribute("value", "_FOO_"); rootElement.addContent(propertyElement); rootElement.removeChild("include.projects"); final Element includeTagElement = new Element("include.projects"); includeTagElement.setAttribute("file", "include${filenameswitch}.xml"); rootElement.addContent(includeTagElement); final CruiseControlConfig config = new CruiseControlConfig(rootElement, this); assertEquals(2, config.getProjectNames().size()); assertIsFooProject(config.getProject("in.root")); assertIsFooProject(config.getProject("in.include.withproperty")); } public void testIncludeFilenameContainsUnsetProperty() throws CruiseControlException { xmlResolver = new XmlResolver() { public Element getElement(String path) throws CruiseControlException { throw new CruiseControlException("failed to load file []"); } }; rootElement.removeChild("include.projects"); final Element includeTagElement = new Element("include.projects"); includeTagElement.setAttribute("file", "include${filenameswitch}.xml"); rootElement.addContent(includeTagElement); final CruiseControlConfig config = new CruiseControlConfig(rootElement, this); assertEquals(1, config.getProjectNames().size()); assertIsFooProject(config.getProject("in.root")); } public static Element elementFromString(final String text) throws CruiseControlException { final InputStream is = new ByteArrayInputStream(text.getBytes()); return Util.loadRootElement(is); } public FileResolver getFileResolver() { return fileResolver; } public XmlResolver getXmlResolver() { return xmlResolver; } private void assertIsFooProject(final ProjectInterface project) { assertNotNull(project); assertEquals(MockProjectInterface.class.getName(), project.getClass().getName()); } private class IncludeXmlResolver implements XmlResolver { private final Element[] includeElements; private int count = 0; IncludeXmlResolver(final Element element) { includeElements = new Element[] {element}; } IncludeXmlResolver(final Element[] elements) { includeElements = elements; } public Element getElement(final String path) throws CruiseControlException { assertEquals("include.xml", path); final Element element = includeElements[count]; count++; return element; } } private class EmptyFileResolver implements FileResolver { public InputStream getInputStream(final String path) throws CruiseControlException { // FIXME add correct implementation, if required! throw new CruiseControlException("Method not implemented yet! Fix it!"); } } }
d6568364b25dec4e4136c49ed217c6ef54639ab2
{ "blob_id": "d6568364b25dec4e4136c49ed217c6ef54639ab2", "branch_name": "refs/heads/master", "committer_date": "2019-01-14T07:05:22", "content_id": "49990d6a6b36b71268c1182dcfd957f31a3af551", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "3a386369c77240cd95d2fc3925d9ec972fee16df", "extension": "java", "filename": "CruiseControlConfigIncludeTest.java", "fork_events_count": 0, "gha_created_at": "2014-01-07T03:04:44", "gha_event_created_at": "2019-01-14T07:05:23", "gha_language": "Java", "gha_license_id": "NOASSERTION", "github_id": 15693674, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 9791, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/main/test/net/sourceforge/cruisecontrol/CruiseControlConfigIncludeTest.java", "provenance": "stack-edu-0022.json.gz:729584", "repo_name": "wuliupo/cruisecontrol", "revision_date": "2019-01-14T07:05:22", "revision_id": "4215b94d9e13305b58635fa9400087323fe4e204", "snapshot_id": "0e503fbe83d1598b7aa9c0836d768bd8700442bf", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/wuliupo/cruisecontrol/4215b94d9e13305b58635fa9400087323fe4e204/main/test/net/sourceforge/cruisecontrol/CruiseControlConfigIncludeTest.java", "visit_date": "2020-12-03T00:45:16.689493", "added": "2024-11-18T23:03:10.314356+00:00", "created": "2019-01-14T07:05:22", "int_score": 2, "score": 2.109375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0040.json.gz" }
<?php namespace App; use Illuminate\Database\Eloquent\Model; class MuaHang extends Model { protected $table="muahang"; }
abd82e770a627ff658cf4625ecaa0990c8fe63dc
{ "blob_id": "abd82e770a627ff658cf4625ecaa0990c8fe63dc", "branch_name": "refs/heads/master", "committer_date": "2021-05-11T08:01:57", "content_id": "c9bdbafc00ef3b92b3d4d6932135ced2d2bb5d25", "detected_licenses": [ "MIT" ], "directory_id": "46d3b5a4b1610081ae70da5b3816d2d2f9e9d0c5", "extension": "php", "filename": "MuaHang.php", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 348214269, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 130, "license": "MIT", "license_type": "permissive", "path": "/BanGiay/app/MuaHang.php", "provenance": "stack-edu-0052.json.gz:397415", "repo_name": "khuatduc/bai1", "revision_date": "2021-05-11T08:01:57", "revision_id": "85a306648c3097826b0652734f95263043d78580", "snapshot_id": "5775d12de77ea08efef63958261f224fe84e7b0f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/khuatduc/bai1/85a306648c3097826b0652734f95263043d78580/BanGiay/app/MuaHang.php", "visit_date": "2023-04-16T20:59:02.444002", "added": "2024-11-18T21:58:42.195945+00:00", "created": "2021-05-11T08:01:57", "int_score": 2, "score": 2.09375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0070.json.gz" }
# Copyright 2019 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ # python2 python3 """Interactive GUI for Spriteworld. Be aware that this UI overrides the action space and renderer for ease of playing, so those will be different from what are specified in the task config. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import logging as log import sys from absl import logging from matplotlib import gridspec import matplotlib.pylab as plt import numpy as np from spriteworld import action_spaces from spriteworld import environment from spriteworld import renderers class MatplotlibUI(object): """Class for visualising the environment based on Matplotlib.""" def __init__(self): self.rewards = 10 * [np.nan] self.rewards_bounds = [-10, 10] self.last_success = None plt.ion() self._fig = plt.figure( figsize=(9, 12), num='Spriteworld', facecolor='white') gs = gridspec.GridSpec(2, 1, height_ratios=[3, 1]) self._ax_image = plt.subplot(gs[0]) self._ax_image.axis('off') self._ax_scalar = plt.subplot(gs[1]) self._ax_scalar.spines['right'].set_visible(False) self._ax_scalar.spines['top'].set_visible(False) self._ax_scalar.xaxis.set_ticks_position('bottom') self._ax_scalar.yaxis.set_ticks_position('left') self._setup_callbacks() @property def ax_image(self): return self._ax_image def _setup_callbacks(self): """Default callbacks for the UI.""" # Pressing escape should stop the UI def _onkeypress(event): if event.key == 'escape': # Stop UI logging.info('Pressed escape, stopping UI.') plt.close(self._fig) sys.exit() self._fig.canvas.mpl_connect('key_release_event', _onkeypress) # Disable default keyboard shortcuts for key in ('keymap.fullscreen', 'keymap.home', 'keymap.back', 'keymap.forward', 'keymap.pan', 'keymap.zoom', 'keymap.save', 'keymap.quit', 'keymap.grid', 'keymap.yscale', 'keymap.xscale', 'keymap.all_axes'): plt.rcParams[key] = '' # Disable logging of some matplotlib events log.getLogger('matplotlib').setLevel('WARNING') def _draw_observation(self, image, action): """Draw the latest observation.""" self._ax_image.clear() self._ax_image.imshow(image, interpolation='none') self._ax_image.set_xticks([]) self._ax_image.set_yticks([]) if action is not None: self._ax_image.annotate( '', xycoords='axes fraction', xy=action[:2], # Start of arrow xytext=action[2:], # End of arrow arrowprops={ 'arrowstyle': '<|-', 'color': 'red', 'lw': 4, }) # Indicate success linewidth = 1 color = 'black' if np.isnan(self.rewards[-1]): linewidth = 8 color = 'green' if self.last_success else 'red' for sp in self._ax_image.spines.values(): sp.set_color(color) sp.set_linewidth(linewidth) def _draw_rewards(self): """Draw the past rewards plot.""" self._ax_scalar.clear() self._ax_scalar.set_ylabel('Rewards') self._ax_scalar.set_xlabel('Timestep') xs = np.arange(-len(self.rewards), 0) self._ax_scalar.set_xticks(xs) self._ax_scalar.axhline(y=0.0, color='lightgrey', linestyle='--') self._ax_scalar.stem(xs, self.rewards, basefmt=' ') self._ax_scalar.set_xlim((xs[0] - 1.0, xs[-1] + 1.0)) self._ax_scalar.set_ylim( (self.rewards_bounds[0] - 1.0, self.rewards_bounds[1] + 1.0)) def register_callback(self, event_name, callback): """Register a callback for the given event.""" self._fig.canvas.mpl_connect(event_name, callback) def update(self, timestep, action): """Update the visualisation with the latest timestep and action.""" reward = timestep.reward if reward is None: reward = np.nan self.rewards = self.rewards[1:] + [reward] self.rewards_bounds[0] = np.nanmin( [np.nanmin(self.rewards), self.rewards_bounds[0]]) self.rewards_bounds[1] = np.nanmax( [np.nanmax(self.rewards), self.rewards_bounds[1]]) self._draw_observation(timestep.observation['image'], action) self._draw_rewards() plt.show(block=False) self.last_success = timestep.observation['success'] class HumanDragAndDropAgent(object): """Demo agent for mouse-clicking interface with DragAndDrop action space.""" def __init__(self, action_space, timeout=600): self._action_space = action_space self._click = None self._timeout = timeout def help(self): logging.info('Click to select an object, then click again to select where ' 'to move it.') def register_callbacks(self, ui): """Register the matplotlib callbacks required by the agent.""" def _onclick(event): if event.inaxes and event.inaxes == ui.ax_image: # Map the click into axis-fraction positions (origin at bottom-left). self._click = event.inaxes.transAxes.inverted().transform( (event.x, event.y)) else: self._click = None return ui.register_callback('button_press_event', _onclick) def begin_episode(self): logging.info('Starting episode') def step(self, timestep): """Take a step.""" del timestep # Unused def _get_click(): """Get mouse click.""" click = None while click is None: x = plt.waitforbuttonpress(timeout=self._timeout) if x is None: logging.info('Timed out. You took longer than %d seconds to click.', self._timeout) elif x: logging.info('You pressed a key, but were supposed to click with the ' 'mouse.') self.help() else: click = self._click return click def _get_action(): """Get action from user.""" logging.info('Select sprite') click_from = _get_click() logging.info('Select target') click_to = _get_click() try: action = np.concatenate((click_from, click_to)).astype(np.float32) if any(np.isnan(action)): raise ValueError self._action_space.action_spec().validate(action) return action except (ValueError, TypeError): logging.info('Select a valid action') return _get_action() action = _get_action() return action class HumanEmbodiedAgent(object): """Demo agent for keyboard interface with Embodied action space.""" MOTION_KEY_TO_ACTION = { 'up': 0, 'left': 1, 'down': 2, 'right': 3, 'w': 0, 'a': 1, 's': 2, 'd': 3 } def __init__(self, action_space, timeout=600): self._action_space = action_space self._key_press = None self._carry = False self._movement = None self._timeout = timeout def help(self): logging.info('Use WASD/arrow keys to move, hold Space to carry.') def register_callbacks(self, ui): """Register the matplotlib callbacks required by the agent.""" def _onkeypress(event): if event.key in HumanEmbodiedAgent.MOTION_KEY_TO_ACTION: self._movement = HumanEmbodiedAgent.MOTION_KEY_TO_ACTION[event.key] elif event.key == ' ': self._carry = True else: self.help() ui.register_callback('key_press_event', _onkeypress) def _onkeyrelease(event): if event.key == ' ': self._carry = False elif event.key in HumanEmbodiedAgent.MOTION_KEY_TO_ACTION: self._movement = None ui.register_callback('key_release_event', _onkeyrelease) def begin_episode(self): logging.info('Starting episode') def step(self, timestep): """Take a step.""" del timestep # Unused def _wait_for_movement_key_press(): """Get key press.""" ready = False while not ready: x = plt.waitforbuttonpress(timeout=self._timeout) if x is None: logging.info('Timed out. You took longer than %d seconds to click.', self._timeout) elif not x: logging.info('You clicked, but you are supposed to use the Keyboard.') self.help() elif self._movement is not None: ready = True def _get_action(): """Get action from user.""" _wait_for_movement_key_press() action = (int(self._carry), self._movement) for spec, a in zip(self._action_space.action_spec(), action): spec.validate(a) return action return _get_action() def setup_run_ui(env_config, render_size, task_hsv_colors, anti_aliasing): """Start a Demo UI given an env_config.""" if isinstance(env_config['action_space'], action_spaces.SelectMove): # DragAndDrop is a bit easier to demo than the SelectMove action space #env_config['action_space'] = action_spaces.DragAndDrop(scale=0.5, noise_scale=np.array([0,0,0.025,0.025]), proportional_motion_noise=0.35) env_config['action_space'] = action_spaces.DragAndDrop(scale=0.5, noise_scale=0.02, proportional_motion_noise=0.35, filter_distribs=env_config['metadata']['filter_distribs']) agent = HumanDragAndDropAgent(env_config['action_space']) elif isinstance(env_config['action_space'], action_spaces.Embodied): agent = HumanEmbodiedAgent(env_config['action_space']) else: raise ValueError( 'Demo is not configured to run with action space {}.'.format( env_config['action_space'])) env_config['renderers'] = { 'image': renderers.PILRenderer( image_size=(render_size, render_size), color_to_rgb=renderers.color_maps.hsv_to_rgb if task_hsv_colors else None, anti_aliasing=anti_aliasing), 'success': renderers.Success() } env = environment.Environment(**env_config) ui = MatplotlibUI() agent.register_callbacks(ui) # Start RL loop timestep = env.reset() ui.update(timestep, action=None) while True: action = agent.step(timestep) timestep = env.step(action) if isinstance(env_config['action_space'], action_spaces.DragAndDrop): ui.update(timestep, action) else: ui.update(timestep, None)
c4193a5dab36bdb5cf2addb93aa6432035aa238c
{ "blob_id": "c4193a5dab36bdb5cf2addb93aa6432035aa238c", "branch_name": "refs/heads/master", "committer_date": "2020-02-19T18:24:24", "content_id": "44bcf2c6909dc83d78a46470499407b1f99438d5", "detected_licenses": [ "Apache-2.0" ], "directory_id": "6813d0bf9b3d5cbba44eb945aced556564aa9c3b", "extension": "py", "filename": "demo_ui.py", "fork_events_count": 0, "gha_created_at": "2020-01-03T19:45:55", "gha_event_created_at": "2020-01-03T19:45:56", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 231654200, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10856, "license": "Apache-2.0", "license_type": "permissive", "path": "/spriteworld/demo_ui.py", "provenance": "stack-edu-0062.json.gz:214450", "repo_name": "pemami4911/spriteworld", "revision_date": "2020-02-19T18:24:24", "revision_id": "1fecf884d1dffc7015445821234e2ae4ab7c039a", "snapshot_id": "83375a0b79b2bcf538169b64dca65cea2bbd0659", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/pemami4911/spriteworld/1fecf884d1dffc7015445821234e2ae4ab7c039a/spriteworld/demo_ui.py", "visit_date": "2020-12-04T06:23:48.045710", "added": "2024-11-19T00:40:18.803208+00:00", "created": "2020-02-19T18:24:24", "int_score": 2, "score": 2.4375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0080.json.gz" }
START TRANSACTION; DROP INDEX IF EXISTS identity__name__bearer__uniq; CREATE UNIQUE INDEX identity__account__provider__bearer__uniq ON identity ( account, provider DESC ) WHERE deleted_on IS NULL AND type = 'bearer'; COMMIT;
c582950b09cd4e714ce2f23f9042cf859ef3ff05
{ "blob_id": "c582950b09cd4e714ce2f23f9042cf859ef3ff05", "branch_name": "refs/heads/master", "committer_date": "2021-04-12T09:01:39", "content_id": "4878f43fdf52ec31307f134c525ba0140d9c71c5", "detected_licenses": [ "MIT" ], "directory_id": "a33736bbaac4b1beab077930388208b5b5aa08e1", "extension": "sql", "filename": "0046.alter-identity-index-constraint.sql", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 229, "license": "MIT", "license_type": "permissive", "path": "/server/lib/components/store/migrations/0046.alter-identity-index-constraint.sql", "provenance": "stack-edu-0070.json.gz:541310", "repo_name": "glasseyes42/kubernaut", "revision_date": "2021-04-12T09:01:39", "revision_id": "ad793068a0255cb431f3511990cd2d0c6a5966b0", "snapshot_id": "25c545fe1d1b305e50a45f20e3701d52b6d1e25e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/glasseyes42/kubernaut/ad793068a0255cb431f3511990cd2d0c6a5966b0/server/lib/components/store/migrations/0046.alter-identity-index-constraint.sql", "visit_date": "2023-03-16T17:34:10.296749", "added": "2024-11-19T01:36:57.166377+00:00", "created": "2021-04-12T09:01:39", "int_score": 3, "score": 3.21875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0088.json.gz" }
const path = require('path'); const fs = require('fs'); const webpack = require('webpack'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const jsDir = './src/js/'; const jsFiles = fs.readdirSync(jsDir) // get all files in directory .filter(v => /^[^_].*(?<!\.esm)\.[a-z]*$/.test(v)) // filter out modules (starting with _ or ending in .esm.js) and directories .reduce((a, v) => ({ ...a, [path.parse(v).name]: jsDir + v }), {}); // create object from filenames console.log(jsFiles); module.exports = (env, {mode}) => ({ mode: mode, entry: jsFiles, devtool: mode === 'development' ? 'source-map' : false, module: { rules: [ { test: /\.(eot|woff|woff2|ttf|svg|png|jpe?g|gif)$/i, type: 'asset/resource', generator: { filename: '[name][ext]' } }, { test: /\.js$/, exclude: /node_modules/, use: [ { loader: 'babel-loader', options: { presets: ['@babel/preset-env'], plugins: [ ["@babel/transform-runtime"] ] } } ] }, { test: /\.scss$/, use: [ MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader', 'sass-loader' ] } ] }, plugins: [ new MiniCssExtractPlugin({ filename: '[name].css', }) ], output: { path: path.resolve(__dirname, './assets'), filename: '[name].js', clean: true } });
38e10a56f8771857723dd2a608f7e55de3508a93
{ "blob_id": "38e10a56f8771857723dd2a608f7e55de3508a93", "branch_name": "refs/heads/main", "committer_date": "2021-09-27T18:32:20", "content_id": "5f5ebd30deb53017fb41b4724dede461e2e8083e", "detected_licenses": [ "MIT" ], "directory_id": "85dc6a2ec3f0628afe4561cbcb852d6c49e35398", "extension": "js", "filename": "webpack.config.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1379, "license": "MIT", "license_type": "permissive", "path": "/webpack.config.js", "provenance": "stack-edu-0036.json.gz:299594", "repo_name": "boxxroom/shopify2skeleton", "revision_date": "2021-09-27T18:32:20", "revision_id": "c6c96b1882f40bde6ad49eb9268704f50b3e5460", "snapshot_id": "3fb79f5fab00f45f89b058114dc74dafecb728e5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/boxxroom/shopify2skeleton/c6c96b1882f40bde6ad49eb9268704f50b3e5460/webpack.config.js", "visit_date": "2023-08-14T09:42:46.724728", "added": "2024-11-19T00:17:10.313264+00:00", "created": "2021-09-27T18:32:20", "int_score": 2, "score": 2.046875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0054.json.gz" }
package bot import ( "bytes" "context" "crypto/aes" "crypto/cipher" "crypto/ed25519" "crypto/md5" "crypto/rand" "encoding/base64" "encoding/binary" "encoding/json" "io" "strings" "golang.org/x/crypto/curve25519" ) type LiveMessagePayload struct { Width int `json:"width"` Height int `json:"height"` ThumbUrl string `json:"thumb_url"` Url string `json:"url"` } type ImageMessagePayload struct { AttachmentId string `json:"attachment_id"` Width int `json:"width"` Height int `json:"height"` MimeType string `json:"mime_type"` Thumbnail string `json:"thumbnail"` Size int64 `json:"size"` } type RecallMessagePayload struct { MessageId string `json:"message_id"` } type MessageRequest struct { ConversationId string `json:"conversation_id"` RecipientId string `json:"recipient_id"` MessageId string `json:"message_id"` Category string `json:"category"` Data string `json:"data"` RepresentativeId string `json:"representative_id"` QuoteMessageId string `json:"quote_message_id"` } type ReceiptAcknowledgementRequest struct { MessageId string `json:"message_id"` Status string `json:"status"` } func PostMessages(ctx context.Context, messages []*MessageRequest, clientId, sessionId, secret string) error { msg, err := json.Marshal(messages) if err != nil { return err } accessToken, err := SignAuthenticationToken(clientId, sessionId, secret, "POST", "/messages", string(msg)) if err != nil { return err } body, err := Request(ctx, "POST", "/messages", msg, accessToken) if err != nil { return err } var resp struct { Error Error `json:"error"` } err = json.Unmarshal(body, &resp) if err != nil { return err } if resp.Error.Code > 0 { return resp.Error } return nil } func PostMessage(ctx context.Context, conversationId, recipientId, messageId, category, data string, clientId, sessionId, secret string) error { request := MessageRequest{ ConversationId: conversationId, RecipientId: recipientId, MessageId: messageId, Category: category, Data: data, } return PostMessages(ctx, []*MessageRequest{&request}, clientId, sessionId, secret) } func PostAcknowledgements(ctx context.Context, requests []*ReceiptAcknowledgementRequest, clientId, sessionId, secret string) error { array, err := json.Marshal(requests) if err != nil { return err } path := "/acknowledgements" accessToken, err := SignAuthenticationToken(clientId, sessionId, secret, "POST", path, string(array)) if err != nil { return err } body, err := Request(ctx, "POST", path, array, accessToken) if err != nil { return err } var resp struct { Error Error `json:"error"` } err = json.Unmarshal(body, &resp) if err != nil { return err } if resp.Error.Code > 0 { return resp.Error } return nil } func UniqueConversationId(userId, recipientId string) string { minId, maxId := userId, recipientId if strings.Compare(userId, recipientId) > 0 { maxId, minId = userId, recipientId } h := md5.New() io.WriteString(h, minId) io.WriteString(h, maxId) sum := h.Sum(nil) sum[6] = (sum[6] & 0x0f) | 0x30 sum[8] = (sum[8] & 0x3f) | 0x80 id, _ := UuidFromBytes(sum) return id.String() } func Chunked(source []interface{}, size int) [][]interface{} { var result [][]interface{} index := 0 for index < len(source) { end := index + size if end >= len(source) { end = len(source) } result = append(result, source[index:end]) index += size } return result } func EncryptMessageData(data string, sessions []*Session, privateKey string) (string, error) { dataBytes, err := base64.RawURLEncoding.DecodeString(data) if err != nil { return "", err } key := make([]byte, 16) _, err = rand.Read(key) if err != nil { return "", err } nonce := make([]byte, 12) _, err = rand.Read(nonce) if err != nil { return "", err } block, err := aes.NewCipher(key) if err != nil { return "", err } aesgcm, err := cipher.NewGCM(block) if err != nil { return "", err } ciphertext := aesgcm.Seal(nil, nonce, dataBytes, nil) var sessionLen [2]byte binary.LittleEndian.PutUint16(sessionLen[:], uint16(len(sessions))) privateBytes, err := base64.RawURLEncoding.DecodeString(privateKey) if err != nil { return "", err } private := ed25519.PrivateKey(privateBytes) pub, _ := PublicKeyToCurve25519(ed25519.PublicKey(private[32:])) var sessionsBytes []byte for _, s := range sessions { clientPublic, err := base64.RawURLEncoding.DecodeString(s.PublicKey) if err != nil { return "", err } var priv [32]byte PrivateKeyToCurve25519(&priv, private) dst, err := curve25519.X25519(priv[:], clientPublic) if err != nil { return "", err } block, err := aes.NewCipher(dst) if err != nil { return "", err } padding := aes.BlockSize - len(key)%aes.BlockSize padtext := bytes.Repeat([]byte{byte(padding)}, padding) shared := make([]byte, len(key)) copy(shared[:], key[:]) shared = append(shared, padtext...) ciphertext := make([]byte, aes.BlockSize+len(shared)) iv := ciphertext[:aes.BlockSize] _, err = rand.Read(iv) if err != nil { return "", err } mode := cipher.NewCBCEncrypter(block, iv) mode.CryptBlocks(ciphertext[aes.BlockSize:], shared) id, err := UuidFromString(s.SessionID) if err != nil { return "", err } sessionsBytes = append(sessionsBytes, id.Bytes()...) sessionsBytes = append(sessionsBytes, ciphertext...) } result := []byte{1} result = append(result, sessionLen[:]...) result = append(result, pub[:]...) result = append(result, sessionsBytes...) result = append(result, nonce[:]...) result = append(result, ciphertext...) return base64.RawURLEncoding.EncodeToString(result), nil } func DecryptMessageData(data string, sessionId, private string) (string, error) { bytes, err := base64.RawURLEncoding.DecodeString(data) if err != nil { return "", err } size := 16 + 48 // session id bytes + encypted key bytes size total := len(bytes) if total < 1+2+32+size+12 { return "", nil } sessionLen := int(binary.LittleEndian.Uint16(bytes[1:3])) prefixSize := 35 + sessionLen*size var key []byte for i := 35; i < prefixSize; i += size { if uid, _ := UuidFromBytes(bytes[i : i+16]); uid.String() == sessionId { private, err := base64.RawURLEncoding.DecodeString(private) if err != nil { return "", err } var priv [32]byte var pub []byte copy(pub[:], bytes[3:35]) PrivateKeyToCurve25519(&priv, ed25519.PrivateKey(private)) dst, err := curve25519.X25519(priv[:], pub) if err != nil { return "", err } block, err := aes.NewCipher(dst[:]) if err != nil { return "", err } iv := bytes[i+16 : i+16+aes.BlockSize] key = bytes[i+16+aes.BlockSize : i+size] mode := cipher.NewCBCDecrypter(block, iv) mode.CryptBlocks(key, key) key = key[:16] break } } if len(key) != 16 { return "", nil } nonce := bytes[prefixSize : prefixSize+12] block, err := aes.NewCipher(key) if err != nil { return "", nil // TODO } aesgcm, err := cipher.NewGCM(block) if err != nil { return "", nil // TODO } plaintext, err := aesgcm.Open(nil, nonce, bytes[prefixSize+12:], nil) if err != nil { return "", nil // TODO } return base64.RawURLEncoding.EncodeToString(plaintext), nil }
0975e4906c0be5b7235f0bb1a926693f62ff79ad
{ "blob_id": "0975e4906c0be5b7235f0bb1a926693f62ff79ad", "branch_name": "refs/heads/master", "committer_date": "2023-08-30T07:56:34", "content_id": "0a1d9fd62217c025f10621a25d521f63d2ab699b", "detected_licenses": [ "Apache-2.0" ], "directory_id": "222e6b40bd6a9e62a0c586d2202356eef5268499", "extension": "go", "filename": "message.go", "fork_events_count": 21, "gha_created_at": "2018-04-27T07:08:39", "gha_event_created_at": "2023-09-06T04:59:00", "gha_language": "Go", "gha_license_id": "Apache-2.0", "github_id": 131259422, "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 7345, "license": "Apache-2.0", "license_type": "permissive", "path": "/message.go", "provenance": "stack-edu-0016.json.gz:595099", "repo_name": "MixinNetwork/bot-api-go-client", "revision_date": "2023-08-30T07:56:34", "revision_id": "41927f54213eb8b7cc6e78327cc02ce6af796bd0", "snapshot_id": "2cc4b894a590a343cc83129020342604371e4cac", "src_encoding": "UTF-8", "star_events_count": 29, "url": "https://raw.githubusercontent.com/MixinNetwork/bot-api-go-client/41927f54213eb8b7cc6e78327cc02ce6af796bd0/message.go", "visit_date": "2023-08-31T21:17:58.176568", "added": "2024-11-19T01:52:00.411124+00:00", "created": "2023-08-30T07:56:34", "int_score": 2, "score": 2.171875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0034.json.gz" }
from flask import Flask from flask_appconfig import HerokuConfig def create_sample_app(): app = Flask('testapp') HerokuConfig(app) return app def test_herokupostgres(monkeypatch): monkeypatch.setenv('HEROKU_POSTGRESQL_ORANGE_URL', 'heroku-db-uri') app = create_sample_app() assert app.config['SQLALCHEMY_DATABASE_URI'] == 'heroku-db-uri'
d0c3ec6999de6464502f6dbc225ebc27039ebc78
{ "blob_id": "d0c3ec6999de6464502f6dbc225ebc27039ebc78", "branch_name": "refs/heads/master", "committer_date": "2021-02-04T09:08:40", "content_id": "86ebfc32e5da592e6e4c3fa48a02c7a3cbe0a2ce", "detected_licenses": [ "MIT" ], "directory_id": "ebfcae1c5ba2997b2ac4471d5bedc3f5daffcb31", "extension": "py", "filename": "test_heroku.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 367, "license": "MIT", "license_type": "permissive", "path": "/flask-appconfig-master/tests/test_heroku.py", "provenance": "stack-edu-0064.json.gz:476805", "repo_name": "babiato/flaskapp1", "revision_date": "2021-02-04T09:08:40", "revision_id": "530beb9e3b8516e0e93960b99521c23a523ef546", "snapshot_id": "84de2d0b26a54f5820d3bbe97926782ad41e005c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/babiato/flaskapp1/530beb9e3b8516e0e93960b99521c23a523ef546/flask-appconfig-master/tests/test_heroku.py", "visit_date": "2023-02-26T16:36:49.760632", "added": "2024-11-18T20:29:55.754833+00:00", "created": "2021-02-04T09:08:40", "int_score": 2, "score": 2.0625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0082.json.gz" }
package mzb.teamcity.plugin.swagger.deployer.server; import jetbrains.buildServer.serverSide.PropertiesProcessor; import jetbrains.buildServer.serverSide.RunType; import jetbrains.buildServer.serverSide.RunTypeRegistry; import jetbrains.buildServer.web.openapi.PluginDescriptor; import mzb.teamcity.plugin.swagger.deployer.common.SwaggerDeployerRunnerConstants; import org.jetbrains.annotations.NotNull; import java.util.HashMap; import java.util.Map; public class SwaggerDeployerRunType extends RunType { private final PluginDescriptor myDescriptor; public SwaggerDeployerRunType(@NotNull final RunTypeRegistry registry, @NotNull final PluginDescriptor descriptor) { myDescriptor = descriptor; registry.registerRunType(this); } @NotNull @Override public String getType() { return SwaggerDeployerRunnerConstants.SWAGGER_RUN_TYPE; } @Override public String getDisplayName() { return "Swagger Upload"; } @Override public String getDescription() { return "Deploys swagger artifact to swagger hub"; } @Override public PropertiesProcessor getRunnerPropertiesProcessor() { return new SwaggerDeployerPropertiesProcessor(); } @Override public String getEditRunnerParamsJspFilePath() { return myDescriptor.getPluginResourcesPath() + "editSwaggerDeployerParams.jsp"; } @Override public String getViewRunnerParamsJspFilePath() { return myDescriptor.getPluginResourcesPath() + "viewSwaggerDeployerParams.jsp"; } @Override public Map<String, String> getDefaultRunnerProperties() { return new HashMap<String, String>(); } @NotNull @Override public String describeParameters(@NotNull Map<String, String> parameters) { StringBuilder sb = new StringBuilder(); //sb.append("SwaggerHub API token: ").append(parameters.get(SwaggerDeployerRunnerConstants.PARAM_API_KEY)); sb.append("User name: ").append(parameters.get(SwaggerDeployerRunnerConstants.PARAM_USER_NAME)).append("\n"); sb.append("API name: ").append(parameters.get(SwaggerDeployerRunnerConstants.PARAM_API_NAME)).append("\n"); sb.append("API version: ").append(parameters.get(SwaggerDeployerRunnerConstants.PARAM_API_VERSION)).append("\n"); sb.append("Private API: ").append(parameters.get(SwaggerDeployerRunnerConstants.PARAM_PRIVATE_FLAG)).append("\n"); sb.append("Force Overwrite: ").append(parameters.get(SwaggerDeployerRunnerConstants.PARAM_FORCE_FLAG)); return sb.toString(); } }
40c6e27502c80b9f938437bed028f57d2f3a65bf
{ "blob_id": "40c6e27502c80b9f938437bed028f57d2f3a65bf", "branch_name": "refs/heads/master", "committer_date": "2019-06-09T09:09:11", "content_id": "89516a8420f9ed538a40b9df0dd7c6641dfd95fd", "detected_licenses": [ "Apache-2.0" ], "directory_id": "21f16c86aeed0cdf104ea6b11792917bedc608d0", "extension": "java", "filename": "SwaggerDeployerRunType.java", "fork_events_count": 1, "gha_created_at": "2019-06-08T08:02:36", "gha_event_created_at": "2019-07-08T11:26:38", "gha_language": "Java", "gha_license_id": "Apache-2.0", "github_id": 190861732, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2628, "license": "Apache-2.0", "license_type": "permissive", "path": "/swagger-deploy-runner-server/src/main/java/mzb/teamcity/plugin/swagger/deployer/server/SwaggerDeployerRunType.java", "provenance": "stack-edu-0022.json.gz:440727", "repo_name": "mzb-spots/teamcity-swagger-deploy-plugin", "revision_date": "2019-06-08T08:02:37", "revision_id": "761239136b41c67d0a4ead136413f190f53afb8f", "snapshot_id": "d478c69a6f76644df365e836895851b2392d1b94", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/mzb-spots/teamcity-swagger-deploy-plugin/761239136b41c67d0a4ead136413f190f53afb8f/swagger-deploy-runner-server/src/main/java/mzb/teamcity/plugin/swagger/deployer/server/SwaggerDeployerRunType.java", "visit_date": "2020-06-01T17:13:40.187549", "added": "2024-11-18T21:50:03.747574+00:00", "created": "2019-06-08T08:02:37", "int_score": 2, "score": 2.078125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0040.json.gz" }
#include "pch.h" using namespace DirectX; namespace Library { const XMFLOAT4X4 MatrixHelper::Identity = XMFLOAT4X4(1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); const XMFLOAT4X4 MatrixHelper::Zero = XMFLOAT4X4(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f); void MatrixHelper::GetForward(CXMMATRIX matrix, XMFLOAT3 &vector) { XMFLOAT4 m3; XMStoreFloat4(&m3, matrix.r[2]); vector.x = -m3.x; vector.y = -m3.y; vector.z = -m3.z; } void MatrixHelper::GetUp(CXMMATRIX matrix, XMFLOAT3 &vector) { XMFLOAT4 m2; XMStoreFloat4(&m2, matrix.r[1]); vector.x = m2.x; vector.y = m2.y; vector.z = m2.z; } void MatrixHelper::GetRight(CXMMATRIX matrix, XMFLOAT3 &vector) { XMFLOAT4 m1; XMStoreFloat4(&m1, matrix.r[0]); vector.x = m1.x; vector.y = m1.y; vector.z = m1.z; } void MatrixHelper::GetTranslation(CXMMATRIX matrix, XMFLOAT3 &vector) { XMFLOAT4 m4; XMStoreFloat4(&m4, matrix.r[3]); vector.x = m4.x; vector.y = m4.y; vector.z = m4.z; } void MatrixHelper::SetForward(XMMATRIX& matrix, XMFLOAT3 &forward) { XMFLOAT4 m3; XMStoreFloat4(&m3, matrix.r[2]); m3.x = -forward.x; m3.y = -forward.y; m3.z = -forward.z; matrix.r[2] = XMLoadFloat4(&m3); } void MatrixHelper::SetUp(XMMATRIX& matrix, XMFLOAT3 &up) { XMFLOAT4 m2; XMStoreFloat4(&m2, matrix.r[1]); m2.x = up.x; m2.y = up.y; m2.z = up.z; matrix.r[1] = XMLoadFloat4(&m2); } void MatrixHelper::SetRight(XMMATRIX& matrix, XMFLOAT3 &right) { XMFLOAT4 m1; XMStoreFloat4(&m1, matrix.r[0]); m1.x = right.x; m1.y = right.y; m1.z = right.z; matrix.r[0] = XMLoadFloat4(&m1); } void MatrixHelper::SetTranslation(XMMATRIX& matrix, XMFLOAT3 &translation) { XMFLOAT4 m4; XMStoreFloat4(&m4, matrix.r[3]); m4.x = translation.x; m4.y = translation.y; m4.z = translation.z; matrix.r[3] = XMLoadFloat4(&m4); } }
9121ebd9cf188e8f6321728703c12156b3b978e9
{ "blob_id": "9121ebd9cf188e8f6321728703c12156b3b978e9", "branch_name": "refs/heads/master", "committer_date": "2017-06-18T18:13:56", "content_id": "17546a18369eeb4088a05ec890e0f76f8449bd4f", "detected_licenses": [ "MIT" ], "directory_id": "82dac3ee9a1bc656f3fc8b68620c3fd430af6bb5", "extension": "cpp", "filename": "MatrixHelper.cpp", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 94703938, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2164, "license": "MIT", "license_type": "permissive", "path": "/Assignment2/source/Library.Shared/MatrixHelper.cpp", "provenance": "stack-edu-0002.json.gz:520732", "repo_name": "Siddhant628/Solar-System", "revision_date": "2017-06-18T18:13:56", "revision_id": "9f34e9f3f169c518f1e503b1b3f470e6ba486297", "snapshot_id": "3465fc50b80f4024d51460adac49b6ba719fc99e", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/Siddhant628/Solar-System/9f34e9f3f169c518f1e503b1b3f470e6ba486297/Assignment2/source/Library.Shared/MatrixHelper.cpp", "visit_date": "2021-01-25T00:56:47.283331", "added": "2024-11-18T22:24:48.840478+00:00", "created": "2017-06-18T18:13:56", "int_score": 2, "score": 2.421875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0020.json.gz" }
<?php class IRM_IPRestrictionManager_sugar extends Basic { public $new_schema = true; public $module_dir = 'IRM_IPRestrictionManager'; public $object_name = 'IRM_IPRestrictionManager'; public $table_name = 'irm_iprestrictionmanager'; public $importable = true; public $assigned_user_id; public $assigned_user_name; public $assigned_user_link; public $id; public $name; public $date_entered; public $date_modified; public $modified_user_id; public $modified_by_name; public $created_by; public $created_by_name; public $doc_owner; public $user_favorites; public $description; public $deleted; public $created_by_link; public $modified_user_link; public $activities; public $following; public $following_link; public $my_favorite; public $favorite_link; public $ip_range; public $status; public $platforms; public $disable_row_level_security = true; public function __construct() { parent::__construct(); } public function bean_implements($interface) { switch ($interface) { case 'ACL': return true; } return false; } }
578626d427460ad347d2c446b7080bce9cd65db2
{ "blob_id": "578626d427460ad347d2c446b7080bce9cd65db2", "branch_name": "refs/heads/master", "committer_date": "2018-05-24T13:42:33", "content_id": "8ae3ccdeee601834e5575961b102b2368ea58d23", "detected_licenses": [ "Apache-2.0" ], "directory_id": "d12f74945908d8da63d3cd80016a92a16f32efc0", "extension": "php", "filename": "IRM_IPRestrictionManager_sugar.php", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 19858897, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1229, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/SugarModules/modules/IRM_IPRestrictionManager/IRM_IPRestrictionManager_sugar.php", "provenance": "stack-edu-0054.json.gz:246747", "repo_name": "geraldclark/IPRestrictionManager", "revision_date": "2018-05-24T13:42:33", "revision_id": "148dcb611c9daf7ff959b73a36c9d603dfd309d3", "snapshot_id": "83d2115dfc2ac692de46d2b3ec270be41fc91a67", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/geraldclark/IPRestrictionManager/148dcb611c9daf7ff959b73a36c9d603dfd309d3/src/SugarModules/modules/IRM_IPRestrictionManager/IRM_IPRestrictionManager_sugar.php", "visit_date": "2021-03-19T16:34:12.991204", "added": "2024-11-19T02:57:49.427024+00:00", "created": "2018-05-24T13:42:33", "int_score": 2, "score": 2.03125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0072.json.gz" }
import { UserCollectionProxy } from "./user-collection-proxy"; import { UserCollection } from "../model/user-collection"; import { IAdvanceUserModel, IBasicUserModel } from "../interfaces/i-user-detail"; export class UserCollectionProxyForAdmin extends UserCollectionProxy { protected fetUserList():Array<IBasicUserModel | IAdvanceUserModel> { let userColl:UserCollection = new UserCollection(); return userColl.getUserList(); } }
d1df91ec4cadbb1c448a884d79ee908cf84970f2
{ "blob_id": "d1df91ec4cadbb1c448a884d79ee908cf84970f2", "branch_name": "refs/heads/master", "committer_date": "2018-10-20T06:43:25", "content_id": "159e952353a62c350a177fac9a17640b81bba9da", "detected_licenses": [ "MIT" ], "directory_id": "79210b81e7f2aab1771ea3c37588b3b0673c8866", "extension": "ts", "filename": "user-collection-proxy-admin.ts", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 153113472, "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 466, "license": "MIT", "license_type": "permissive", "path": "/src/proxies/user-collection-proxy-admin.ts", "provenance": "stack-edu-0074.json.gz:684505", "repo_name": "pervezalam777/DesignPattern-Proxy", "revision_date": "2018-10-20T06:43:25", "revision_id": "d5371b6f0e74d339287f564d35aa916fac9be226", "snapshot_id": "0d5158cb2b7e438e9dcc22a45ca93d7546570040", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/pervezalam777/DesignPattern-Proxy/d5371b6f0e74d339287f564d35aa916fac9be226/src/proxies/user-collection-proxy-admin.ts", "visit_date": "2020-04-01T10:20:33.205975", "added": "2024-11-19T00:04:16.778208+00:00", "created": "2018-10-20T06:43:25", "int_score": 2, "score": 2.109375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0092.json.gz" }
/* Checks if web push permission has been granted, and updates on changes to this permission Possible states: unsupported ( this browser does not support push notifications ) default ( awaiting response to prompt) granted ( all good, notifications are enabled ) denied ( user had selected block, notifications are not enabled ) */ import { useEffect, useState, useRef } from "react"; import getNotificationPreference from "../Utility/GetNotificationPreference"; import useStores from "../Basics/UseStores"; export default function usePushEnabled() { const [permissionState, setPermissionState] = useState("default"); const { patientStore } = useStores(); const prevPref = useRef(); const mounted = useRef(false); const checkAndSetState = () => { if (mounted.current) { //Ensure component is currently rendered to prevent memory leak error setPermissionState(getNotificationPreference()); } }; const listenForPermissionsChange = () => { if ("permissions" in navigator) { navigator.permissions .query({ name: "notifications" }) .then((notificationPerm) => { notificationPerm.onchange = checkAndSetState; }); } }; useEffect(() => { if (prevPref.current === "denied" && permissionState === "granted") { //If newly opted in, ensure that credentials are up to date patientStore.subscribeToNotifications(); } else if (permissionState === "denied") { //Log change on server if newly denied, opt patientStore.logPushPermissionStatus(); } prevPref.current = permissionState; }, [permissionState]); useEffect(() => { mounted.current = true; listenForPermissionsChange(); checkAndSetState(); return function cleanup() { //Mark unmount to prevent updating state on unmounted component - for help https://stackoverflow.com/questions/57624060 mounted.current = false; }; }, []); return permissionState; }
56e167c1c97336be66ce1b3f7b0f67d646cbf6d1
{ "blob_id": "56e167c1c97336be66ce1b3f7b0f67d646cbf6d1", "branch_name": "refs/heads/develop", "committer_date": "2023-03-15T18:35:46", "content_id": "5320481679c9f13711ed7f4732f99dac139fa182", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "7cbf35d2c918edcfc0eb9e46f5d5cb31f6b27ffe", "extension": "js", "filename": "PushEnabled.js", "fork_events_count": 4, "gha_created_at": "2018-02-21T22:57:20", "gha_event_created_at": "2023-03-30T17:43:46", "gha_language": "JavaScript", "gha_license_id": "BSD-3-Clause", "github_id": 122404441, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1994, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/Hooks/PushEnabled.js", "provenance": "stack-edu-0044.json.gz:54588", "repo_name": "uwcirg/tb-mobile-app", "revision_date": "2023-03-15T18:35:46", "revision_id": "dfd51912a8fcc1a9871a62ba371e47d0720f0ce3", "snapshot_id": "e3cc0ae2fd2d95fe554dda527968211eac78cd9c", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/uwcirg/tb-mobile-app/dfd51912a8fcc1a9871a62ba371e47d0720f0ce3/src/Hooks/PushEnabled.js", "visit_date": "2023-04-08T04:23:59.335708", "added": "2024-11-19T01:29:26.495982+00:00", "created": "2023-03-15T18:35:46", "int_score": 3, "score": 2.859375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0062.json.gz" }
package gocbcore import ( "sync" "time" "github.com/couchbase/gocbcore/v10/memd" ) type statsComponent struct { kvMux *kvMux tracer *tracerComponent defaultRetryStrategy RetryStrategy } func newStatsComponent(kvMux *kvMux, defaultRetry RetryStrategy, tracer *tracerComponent) *statsComponent { return &statsComponent{ kvMux: kvMux, tracer: tracer, defaultRetryStrategy: defaultRetry, } } func (sc *statsComponent) Stats(opts StatsOptions, cb StatsCallback) (PendingOp, error) { tracer := sc.tracer.StartTelemeteryHandler(metricValueServiceKeyValue, "Stats", opts.TraceContext) iter, err := sc.kvMux.PipelineSnapshot() if err != nil { tracer.Finish() return nil, err } stats := make(map[string]SingleServerStats) var statsLock sync.Mutex op := new(multiPendingOp) op.isIdempotent = true var expected uint32 pipelines := make([]*memdPipeline, 0) switch target := opts.Target.(type) { case nil: iter.Iterate(0, func(pipeline *memdPipeline) bool { pipelines = append(pipelines, pipeline) expected++ return false }) case VBucketIDStatsTarget: expected = 1 srvIdx, err := iter.NodeByVbucket(target.VbID, 0) if err != nil { return nil, err } pipelines = append(pipelines, iter.PipelineAt(srvIdx)) default: return nil, errInvalidArgument } opHandledLocked := func() { completed := op.IncrementCompletedOps() if expected-completed == 0 { tracer.Finish() cb(&StatsResult{ Servers: stats, }, nil) } } var userFrame *memd.UserImpersonationFrame if len(opts.User) > 0 { userFrame = &memd.UserImpersonationFrame{ User: []byte(opts.User), } } if opts.RetryStrategy == nil { opts.RetryStrategy = sc.defaultRetryStrategy } for _, pipeline := range pipelines { serverAddress := pipeline.Address() handler := func(resp *memdQResponse, req *memdQRequest, err error) { statsLock.Lock() defer statsLock.Unlock() // Fetch the specific stats key for this server. Creating a new entry // for the server if we did not previously have one. curStats, ok := stats[serverAddress] if !ok { stats[serverAddress] = SingleServerStats{ Stats: make(map[string]string), } curStats = stats[serverAddress] } if err != nil { // Store the first (and hopefully only) error into the Error field of this // server's stats entry. if curStats.Error == nil { curStats.Error = err } else { logDebugf("Got additional error for stats: %s: %v", serverAddress, err) } opHandledLocked() return } // Check if the key and value length is zero. This indicates that we have reached // the ending of the stats listing by this server. if len(resp.Key) == 0 && len(resp.Value) == 0 { // As this is a persistent request, we must manually cancel it to remove // it from the pending ops list. To ensure we do not race multiple cancels, // we only handle it as completed the one time cancellation succeeds. if req.internalCancel(err) { opHandledLocked() } return } curStats.StatsKeys = append(curStats.StatsKeys, resp.Key) curStats.StatsChunks = append(curStats.StatsChunks, resp.Value) if len(resp.Key) == 0 { // We do this for the sake of consistency. curStats.Stats[""] += string(resp.Value) } else { // Add the stat for this server to the list of stats. curStats.Stats[string(resp.Key)] += string(resp.Value) } // If we don't reassign this then we lose any values added to StatsKeys and StatsChunks. stats[serverAddress] = curStats } req := &memdQRequest{ Packet: memd.Packet{ Magic: memd.CmdMagicReq, Command: memd.CmdStat, Datatype: 0, Cas: 0, Key: []byte(opts.Key), Value: nil, UserImpersonationFrame: userFrame, }, Persistent: true, Callback: handler, RootTraceContext: tracer.RootContext(), RetryStrategy: opts.RetryStrategy, } curOp, err := sc.kvMux.DispatchDirectToAddress(req, pipeline) if err != nil { statsLock.Lock() stats[serverAddress] = SingleServerStats{ Error: err, } opHandledLocked() statsLock.Unlock() continue } if !opts.Deadline.IsZero() { start := time.Now() req.SetTimer(time.AfterFunc(opts.Deadline.Sub(start), func() { connInfo := req.ConnectionInfo() count, reasons := req.Retries() req.cancelWithCallbackAndFinishTracer(&TimeoutError{ InnerError: errAmbiguousTimeout, OperationID: "Unlock", Opaque: req.Identifier(), TimeObserved: time.Since(start), RetryReasons: reasons, RetryAttempts: count, LastDispatchedTo: connInfo.lastDispatchedTo, LastDispatchedFrom: connInfo.lastDispatchedFrom, LastConnectionID: connInfo.lastConnectionID, }, tracer) })) } op.ops = append(op.ops, curOp) } return op, nil } // SingleServerStats represents the stats returned from a single server. type SingleServerStats struct { Stats map[string]string // StatsKeys and StatsChunks provide access to the raw keys and values returned on a per packet basis. // This is useful for stats keys such as connections which, unlike most stats keys, return us a complex object // per packet. Keys and chunks maintain the same ordering for indexes. StatsKeys [][]byte StatsChunks [][]byte Error error } // StatsTarget is used for providing a specific target to the Stats operation. type StatsTarget interface { } // VBucketIDStatsTarget indicates that a specific vbucket should be targeted by the Stats operation. type VBucketIDStatsTarget struct { VbID uint16 } // StatsOptions encapsulates the parameters for a Stats operation. type StatsOptions struct { Key string // Target indicates that something specific should be targeted by the operation. If left nil // then the stats command will be sent to all servers. Target StatsTarget RetryStrategy RetryStrategy Deadline time.Time // Internal: This should never be used and is not supported. User string TraceContext RequestSpanContext } // StatsResult encapsulates the result of a Stats operation. type StatsResult struct { Servers map[string]SingleServerStats }
c96b6bd42eaf1d7f56094338da89c9e335a37313
{ "blob_id": "c96b6bd42eaf1d7f56094338da89c9e335a37313", "branch_name": "refs/heads/master", "committer_date": "2023-08-31T07:00:05", "content_id": "17ff78c93b09540960c9d2bd81eaf1f996db61f5", "detected_licenses": [ "Apache-2.0" ], "directory_id": "2d079c185ef45d44723309530b3bffd7acbb0a54", "extension": "go", "filename": "statscomponent.go", "fork_events_count": 14, "gha_created_at": "2015-01-15T20:04:28", "gha_event_created_at": "2023-08-22T17:31:33", "gha_language": "Go", "gha_license_id": "Apache-2.0", "github_id": 29315695, "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 6369, "license": "Apache-2.0", "license_type": "permissive", "path": "/statscomponent.go", "provenance": "stack-edu-0015.json.gz:618078", "repo_name": "couchbase/gocbcore", "revision_date": "2023-08-30T11:16:14", "revision_id": "7e04f6776f94a45dbb6bc9d8eab60f77744fe3a1", "snapshot_id": "833625e3a61b4e1a2a70bd42f0df70f0ed7ef34d", "src_encoding": "UTF-8", "star_events_count": 21, "url": "https://raw.githubusercontent.com/couchbase/gocbcore/7e04f6776f94a45dbb6bc9d8eab60f77744fe3a1/statscomponent.go", "visit_date": "2023-08-31T13:13:31.742545", "added": "2024-11-18T19:37:44.522654+00:00", "created": "2023-08-30T11:16:14", "int_score": 2, "score": 2.375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0033.json.gz" }
<?php namespace Consolidation\Config\Inject; use Consolidation\Config\Util\ConfigMerge; /** * Given an object that contains configuration methods, inject any * configuration found in the configuration file. * * The proper use for this method is to call setter methods of the * provided object. Using configuration to call methods that do work * is an abuse of this mechanism. */ class ConfigForSetters { protected $config; public function __construct($config, $group, $prefix = '', $postfix = '') { if (!empty($group) && empty($postfix)) { $postfix = '.'; } $this->config = new ConfigMerge($config, $group, $prefix, $postfix); } public function apply($object, $configurationKey) { $settings = $this->config->get($configurationKey); foreach ($settings as $setterMethod => $args) { $fn = [$object, $setterMethod]; if (is_callable($fn)) { $result = call_user_func_array($fn, (array)$args); // We require that $fn must only be used with setter methods. // Setter methods are required to always return $this so that // they may be chained. We will therefore throw an exception // for any setter that returns something else. if ($result != $object) { $methodDescription = get_class($object) . "::$setterMethod"; $propertyDescription = $this->config->describe($configurationKey); throw new \Exception("$methodDescription did not return '\$this' when processing $propertyDescription."); } } } } }
6d424e115e2ff9a487ad04120c2f82a8477085b9
{ "blob_id": "6d424e115e2ff9a487ad04120c2f82a8477085b9", "branch_name": "refs/heads/master", "committer_date": "2021-10-08T08:15:21", "content_id": "5ec87042919feea7f8be47de0bbd1a874509f1c4", "detected_licenses": [ "MIT" ], "directory_id": "f10fa1011205d6b7dbc9effb3e6a96b99107fce9", "extension": "php", "filename": "ConfigForSetters.php", "fork_events_count": 0, "gha_created_at": "2019-11-08T19:18:02", "gha_event_created_at": "2022-12-10T08:18:27", "gha_language": "PHP", "gha_license_id": "MIT", "github_id": 220532859, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1698, "license": "MIT", "license_type": "permissive", "path": "/vendor/consolidation/config/src/Inject/ConfigForSetters.php", "provenance": "stack-edu-0053.json.gz:790634", "repo_name": "stratus-meridian/apigee-kickstart-drupal8-drops", "revision_date": "2021-10-08T08:15:21", "revision_id": "36f092728bda115f169146b36d1a2dd9aaf2d16c", "snapshot_id": "25a9442a4dcc37cc34b3bb1147769d21ceaf4d71", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/stratus-meridian/apigee-kickstart-drupal8-drops/36f092728bda115f169146b36d1a2dd9aaf2d16c/vendor/consolidation/config/src/Inject/ConfigForSetters.php", "visit_date": "2022-12-24T12:16:33.011763", "added": "2024-11-18T22:33:50.198160+00:00", "created": "2021-10-08T08:15:21", "int_score": 3, "score": 2.8125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0071.json.gz" }
from uuid import uuid4 import arrow import pytest from databases import Database from httpx import AsyncClient from sqlalchemy import func, select from starlette import status from cyberbox import orm @pytest.fixture() async def create_data_for_test(db: Database, logged_user): username, access_token, headers = logged_user async def create(count: int): values = [ dict( uid=uuid4(), owner=username, filename=f"f{i}", content_type="", created=arrow.utcnow().datetime, ) for i in range(count) ] await db.execute_many(orm.File.insert(), values) return create @pytest.mark.asyncio @pytest.mark.parametrize( "count, page, limit, items_len, expected_items, total, pages, has_next, has_previous, " "next_page_number, previous_page_number", [ [12, None, None, 12, [f"f{i}" for i in range(12)], 12, 1, False, False, None, None], [12, 1, 5, 5, [f"f{i}" for i in range(5)], 12, 3, True, False, 2, None], [12, 2, 5, 5, [f"f{i}" for i in range(5, 10)], 12, 3, True, True, 3, 1], [12, 3, 5, 2, [f"f{i}" for i in range(10, 12)], 12, 3, False, True, None, 2], [12, 4, 5, 0, [], 12, 3, False, True, None, 3], [12, 5, 5, 0, [], 12, 3, False, True, None, 4], [10, 2, 5, 5, [f"f{i}" for i in range(5, 10)], 10, 2, False, True, None, 1], ], ) async def test_file_pagination( create_data_for_test, db: Database, client: AsyncClient, logged_user, count, page, limit, items_len, expected_items, total, pages, has_next, has_previous, next_page_number, previous_page_number, ): username, access_token, headers = logged_user await create_data_for_test(count) assert await db.execute(select([func.count()]).select_from(orm.File)) == count response = await client.get("/file", headers=headers, params=dict(_page=page, _limit=limit)) assert response.status_code == status.HTTP_200_OK json = response.json() assert len(json["items"]) == items_len assert [i["filename"] for i in json["items"]] == expected_items assert json["total"] == total assert json["pages"] == pages assert json["has_next"] == has_next assert json["has_previous"] == has_previous assert json["next_page_number"] == next_page_number assert json["previous_page_number"] == previous_page_number
c8f30a2ded2cae8e42d56d8fce6eb1a36e549f64
{ "blob_id": "c8f30a2ded2cae8e42d56d8fce6eb1a36e549f64", "branch_name": "refs/heads/master", "committer_date": "2020-10-24T13:06:08", "content_id": "d26ddde4d920b2207a64c7beb18f9bdd51e3a995", "detected_licenses": [ "MIT" ], "directory_id": "9b97f5dbaddeaa849c45c69a267c2dd9fd353a2c", "extension": "py", "filename": "test_file_pagination.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 257007618, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2483, "license": "MIT", "license_type": "permissive", "path": "/tests/test_file_pagination.py", "provenance": "stack-edu-0057.json.gz:512084", "repo_name": "artslob/cyberbox", "revision_date": "2020-10-24T13:06:08", "revision_id": "edb58851cefc7bcadbabd1f599fc06c0a0a3bd3b", "snapshot_id": "c425e976e638fca526e65f3b0411df7b4dd449e2", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/artslob/cyberbox/edb58851cefc7bcadbabd1f599fc06c0a0a3bd3b/tests/test_file_pagination.py", "visit_date": "2023-01-02T23:42:48.733498", "added": "2024-11-19T02:59:21.050568+00:00", "created": "2020-10-24T13:06:08", "int_score": 2, "score": 2.3125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0075.json.gz" }
import React, { useMemo, useEffect } from 'react'; import PropTypes from 'prop-types'; import { ReactReduxContext } from './Context'; import Subscription from '../utils/Subscription'; function Provider(_ref) { var store = _ref.store, context = _ref.context, children = _ref.children; // 从contetx中获取管理的值 当store改变的时候 contextValue 也就改变 var contextValue = useMemo(function () { // 实例化 subscription 其中模拟的就是redux的状态管理方式 var subscription = new Subscription(store); // subscription.onStateChange = notify() {} subscription.onStateChange = subscription.notifyNestedSubs; return { store: store, subscription: subscription }; }, [store]); // 返回上一次的状态 var previousState = useMemo(function () { return store.getState(); }, [store]); // 管理两个状态  当上一个的状态 previousState 发生了改变 或者 contextValue 在 store 改变的前提下进行改变 // 一般情况下store注册后 引用地址不会改变了 // 当上一个状态发生改变 执行 useEffect(function () { var subscription = contextValue.subscription; // 执行两个方法, subscription.onStateChange // 执行一个callback subscription.trySubscribe(); if (previousState !== store.getState()) { // notify(){} 其中没执行任何代码 // 上面执行了 trySubscribe() 更新了原来的 listeners 数组,用循坏将 losteners数组进行更新其中的状态 subscription.notifyNestedSubs(); } // 置为初始值 return function () { subscription.tryUnsubscribe(); subscription.onStateChange = null; }; }, [contextValue, previousState]); // 没传 context 的话基本就是react的context // React.createContext(null) { Provider , Consumer } var Context = context || ReactReduxContext; return React.createElement(Context.Provider, { value: contextValue }, children); } Provider.propTypes = { store: PropTypes.shape({ subscribe: PropTypes.func.isRequired, dispatch: PropTypes.func.isRequired, getState: PropTypes.func.isRequired }), context: PropTypes.object, children: PropTypes.any }; export default Provider;
d3694193287d21f74cb3963b4c90c4a049d723c7
{ "blob_id": "d3694193287d21f74cb3963b4c90c4a049d723c7", "branch_name": "refs/heads/master", "committer_date": "2020-09-23T02:56:53", "content_id": "e813997169123aa2459d3e0478073a0a7480a0fd", "detected_licenses": [ "MIT" ], "directory_id": "e84e865aef4f83a6b4db9c9a95d0fa3377af5daa", "extension": "js", "filename": "Provider.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 279008668, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2267, "license": "MIT", "license_type": "permissive", "path": "/前端/主流框架/Redux/react redux/es/components/Provider.js", "provenance": "stack-edu-0035.json.gz:400060", "repo_name": "BillJC-Liu/learning-road", "revision_date": "2020-09-23T02:56:53", "revision_id": "54add55365f8ea8933c7bb60929f36301efce786", "snapshot_id": "1d69255b6b952538ccd78382664ab370a02ccbaa", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/BillJC-Liu/learning-road/54add55365f8ea8933c7bb60929f36301efce786/前端/主流框架/Redux/react redux/es/components/Provider.js", "visit_date": "2022-12-26T07:38:55.910864", "added": "2024-11-19T01:48:29.623038+00:00", "created": "2020-09-23T02:56:53", "int_score": 3, "score": 2.671875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0053.json.gz" }
package exqueue import ( "context" "github.com/lichao-mobanche/go-extractor-server/server/global" "sync" "github.com/spf13/viper" ) type exRequest interface { Url() string Executor(req interface{}) } type ExQueue struct { Threads int *exList wake chan struct{} mut sync.Mutex // guards wake exitc chan struct{} } type exList struct { MaxSize int lock *sync.RWMutex size int first *exItem last *exItem } type exItem struct { Request exRequest Next *exItem } // New creates a new queue func New(conf *viper.Viper) (*ExQueue, error) { var workerNumber, maxQueueNum int if conf.IsSet("worker.number") { workerNumber = conf.GetInt("worker.number") } if conf.IsSet("queue.number") { maxQueueNum = conf.GetInt("queue.number") } return &ExQueue{ workerNumber, &exList{lock: &sync.RWMutex{}, MaxSize: maxQueueNum}, nil, sync.Mutex{}, make(chan struct{}), }, nil } // AddRequest adds a new Request to the queue func (q *ExQueue) AddRequest(r exRequest) error { q.mut.Lock() waken := q.wake != nil q.mut.Unlock() if !waken { return global.QueueUnavailableError(r.Url()) } err := q.Add(r) if err != nil { return err } q.wake <- struct{}{} return nil } func (q *ExQueue) run() error { q.mut.Lock() if q.wake != nil { q.mut.Unlock() panic("cannot call duplicate ExQueue.Run") } q.wake = make(chan struct{}) q.mut.Unlock() requestc := make(chan exRequest) complete, errc := make(chan struct{}), make(chan error, 1) for i := 0; i < q.Threads; i++ { go independentRunner(requestc, complete) } go q.loop(requestc, complete, errc) defer close(requestc) return <-errc } func (q *ExQueue) loop(requestc chan<- exRequest, complete <-chan struct{}, errc chan<- error) { var active int for { sent := requestc req := q.Get() if req == nil { sent = nil } Sent: for { select { case sent <- req: active++ break Sent case <-q.wake: if sent == nil { break Sent } case <-complete: active-- if sent == nil && active == 0 { break Sent } case <-q.exitc: if active <= 0 { goto End } q.exitc <- struct{}{} } } } End: errc <- nil } // OnStart TODO func (q *ExQueue) OnStart(ctx context.Context) (err error) { go q.run() return } // OnStop TODO func (q *ExQueue) OnStop(ctx context.Context) (err error) { q.exitc <- struct{}{} return } func independentRunner(requestc <-chan exRequest, complete chan<- struct{}) { for req := range requestc { req.Executor(req) complete <- struct{}{} } } // Add add request to exList func (l *exList) Add(r exRequest) error { l.lock.Lock() defer l.lock.Unlock() // Discard URLs if size limit exceeded if l.MaxSize > 0 && l.size >= l.MaxSize { return global.QueueFullError(r.Url()) } i := &exItem{Request: r} if l.first == nil { l.first = i } else { l.last.Next = i } l.last = i l.size++ return nil } // Get get request from exList func (l *exList) Get() exRequest { l.lock.Lock() defer l.lock.Unlock() if l.size == 0 { return nil } r := l.first.Request l.first = l.first.Next l.size-- return r } // Size get the size of exList func (l *exList) Size() (int, error) { l.lock.Lock() defer l.lock.Unlock() return l.size, nil }
0363312ec5c1ac7046ca500efb7de700444c2030
{ "blob_id": "0363312ec5c1ac7046ca500efb7de700444c2030", "branch_name": "refs/heads/master", "committer_date": "2021-07-29T06:20:47", "content_id": "f88ed61a3f0544334bd9f220ec26f193e37318ab", "detected_licenses": [ "MIT" ], "directory_id": "343f004e939cae2b4ce1ffb21d01cbe9ddc6425c", "extension": "go", "filename": "exqueue.go", "fork_events_count": 2, "gha_created_at": "2020-09-22T08:25:03", "gha_event_created_at": "2020-11-13T03:00:39", "gha_language": "Go", "gha_license_id": "MIT", "github_id": 297583780, "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 3257, "license": "MIT", "license_type": "permissive", "path": "/server/exqueue/exqueue.go", "provenance": "stack-edu-0018.json.gz:633651", "repo_name": "lichao-mobanche/go-extractor-server", "revision_date": "2021-07-29T06:20:47", "revision_id": "54ac56b905897f6a415458d2c9eccaff41a243a0", "snapshot_id": "852af41fb83837e62ced1f09d7ce6a5b35d14acb", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/lichao-mobanche/go-extractor-server/54ac56b905897f6a415458d2c9eccaff41a243a0/server/exqueue/exqueue.go", "visit_date": "2023-07-01T08:23:22.673560", "added": "2024-11-19T00:54:09.376657+00:00", "created": "2021-07-29T06:20:47", "int_score": 3, "score": 2.984375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0036.json.gz" }
package com.puresoltechnologies.javafx.perspectives; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.UUID; import java.util.function.Predicate; import com.puresoltechnologies.javafx.perspectives.parts.Part; import javafx.scene.Node; import javafx.scene.layout.BorderPane; public abstract class AbstractPerspective implements Perspective { private PerspectiveElement element = null; private final BorderPane borderPane = new BorderPane(); private final UUID id = UUID.randomUUID(); private final PerspectiveHandler perspectiveHandler; private final String name; public AbstractPerspective(String name) { super(); this.perspectiveHandler = new PerspectiveHandler(this); this.name = name; createNewContent(); } private void createNewContent() { element = createContent(); setContext(element); borderPane.setCenter(element.getContent()); ((AbstractPerspectiveElement) element).setPerspectiveHandler(perspectiveHandler); } protected void setContext(PerspectiveElement element) { if (element instanceof PartSplit) { ((PartSplit) element).setParent(this); ((PartSplit) element).setPerspectiveHandler(perspectiveHandler); } else if (element instanceof PartStack) { ((PartStack) element).setParent(this); ((PartStack) element).setPerspectiveHandler(perspectiveHandler); } else { throw new IllegalStateException("Element of type '" + element.getClass().getName() + "' is not supported."); } } protected abstract PerspectiveElement createContent(); @Override public final UUID getId() { return id; } @Override public final String getName() { return name; } @Override public final void reset() { createNewContent(); } @Override public final PerspectiveElement getRootElement() { return element; } @Override public final Node getContent() { return borderPane; } @Override public final PerspectiveElement getParent() { // There is no parent for a perspective. return null; } @Override public final List<PerspectiveElement> getElements() { return Arrays.asList(element); } @Override public final void addElement(PerspectiveElement e) { if (element != null) { throw new IllegalStateException("Root element was already set."); } element = e; setContext(element); borderPane.setCenter(element.getContent()); } @Override public final void addElement(int index, PerspectiveElement e) { addElement(e); } @Override public final void removeElement(UUID id) { if (id.equals(element.getId())) { element = null; borderPane.setCenter(null); } } @Override public final void removeElement(PerspectiveElement element) { removeElement(element.getId()); } @Override public final void openPart(Part part) { openPart(element, part); } private final void openPart(PerspectiveElement element, Part part) { if (element instanceof PartSplit) { openPart(element.getElements().get(0), part); } else if (element instanceof PartStack) { ((PartStack) element).openPart(part); } } @Override public Set<Part> findPart(Predicate<Part> filter) { Set<Part> parts = new HashSet<>(); findPart(element, filter, parts); return parts; } private void findPart(PerspectiveElement parent, Predicate<Part> filter, Set<Part> parts) { for (PerspectiveElement element : parent.getElements()) { if (PartStack.class.isAssignableFrom(element.getClass())) { PartStack partStack = (PartStack) element; partStack.getParts().stream().filter(filter).forEach(part -> parts.add(part)); } else { findPart(element, filter, parts); } } } }
8e8c054a9f625cb99471b371d41bcbe9365ed95a
{ "blob_id": "8e8c054a9f625cb99471b371d41bcbe9365ed95a", "branch_name": "refs/heads/master", "committer_date": "2020-11-02T21:05:43", "content_id": "cb6618865755dc6537a59fcd26bd89ba3ecca063", "detected_licenses": [ "Apache-2.0" ], "directory_id": "4f36092747079bf75e706ab1d63a5f8f54e93863", "extension": "java", "filename": "AbstractPerspective.java", "fork_events_count": 1, "gha_created_at": "2018-02-27T21:32:06", "gha_event_created_at": "2019-08-27T20:56:19", "gha_language": "Java", "gha_license_id": "Apache-2.0", "github_id": 123191219, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3787, "license": "Apache-2.0", "license_type": "permissive", "path": "/perspectives/src/main/java/com/puresoltechnologies/javafx/perspectives/AbstractPerspective.java", "provenance": "stack-edu-0022.json.gz:827076", "repo_name": "PureSolTechnologies/javafx", "revision_date": "2020-11-02T21:05:43", "revision_id": "6c7622b1383683b2a3d0c2f5adbded7bbf15949f", "snapshot_id": "d692c4e1009a56ae1244d845e042ae0d030ef2fe", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/PureSolTechnologies/javafx/6c7622b1383683b2a3d0c2f5adbded7bbf15949f/perspectives/src/main/java/com/puresoltechnologies/javafx/perspectives/AbstractPerspective.java", "visit_date": "2021-01-24T16:27:09.708691", "added": "2024-11-18T23:57:10.532905+00:00", "created": "2020-11-02T21:05:43", "int_score": 3, "score": 2.671875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0040.json.gz" }
/** * @author Mugen87 / https://github.com/Mugen87 */ import { EventDispatcher, Vector3, Logger } from '../../../../build/yuka.module.js'; import world from './World.js'; const PI05 = Math.PI / 2; const direction = new Vector3(); const velocity = new Vector3(); let currentSign = 1; let elapsedTime = 0; class FirstPersonControls extends EventDispatcher { constructor( owner = null ) { super(); this.owner = owner; this.movementX = 0; // mouse left/right this.movementY = 0; // mouse up/down this.acceleration = 80; this.brakingPower = 10; this.lookingSpeed = 1; this.headMovement = 0.8; this.input = { forward: false, backward: false, right: false, left: false }; this._mouseDownHandler = onMouseDown.bind( this ); this._mouseMoveHandler = onMouseMove.bind( this ); this._pointerlockChangeHandler = onPointerlockChange.bind( this ); this._pointerlockErrorHandler = onPointerlockError.bind( this ); this._keyDownHandler = onKeyDown.bind( this ); this._keyUpHandler = onKeyUp.bind( this ); } connect() { document.addEventListener( 'mousedown', this._mouseDownHandler, false ); document.addEventListener( 'mousemove', this._mouseMoveHandler, false ); document.addEventListener( 'pointerlockchange', this._pointerlockChangeHandler, false ); document.addEventListener( 'pointerlockerror', this._pointerlockErrorHandler, false ); document.addEventListener( 'keydown', this._keyDownHandler, false ); document.addEventListener( 'keyup', this._keyUpHandler, false ); document.body.requestPointerLock(); } disconnect() { document.removeEventListener( 'mousedown', this._mouseDownHandler, false ); document.removeEventListener( 'mousemove', this._mouseMoveHandler, false ); document.removeEventListener( 'pointerlockchange', this._pointerlockChangeHandler, false ); document.removeEventListener( 'pointerlockerror', this._pointerlockErrorHandler, false ); document.removeEventListener( 'keydown', this._keyDownHandler, false ); document.removeEventListener( 'keyup', this._keyUpHandler, false ); } exit() { document.exitPointerLock(); this.input.forward = false; this.input.backward = false; this.input.right = false; this.input.left = false; this.owner.velocity.set( 0, 0, 0 ); } update( delta ) { const input = this.input; const owner = this.owner; velocity.x -= velocity.x * this.brakingPower * delta; velocity.z -= velocity.z * this.brakingPower * delta; direction.z = Number( input.forward ) - Number( input.backward ); direction.x = Number( input.left ) - Number( input.right ); direction.normalize(); if ( input.forward || input.backward ) velocity.z -= direction.z * this.acceleration * delta; if ( input.left || input.right ) velocity.x -= direction.x * this.acceleration * delta; owner.velocity.copy( velocity ).applyRotation( owner.rotation ); // const speed = owner.getSpeed(); elapsedTime += delta * speed; // scale delta with movement speed const motion = Math.sin( elapsedTime * this.headMovement ); this._updateHead( motion ); this._updateWeapon( motion ); } setRotation( yaw, pitch ) { this.movementX = yaw; this.movementY = pitch; this.owner.rotation.fromEuler( 0, this.movementX, 0 ); this.owner.head.rotation.fromEuler( this.movementY, 0, 0 ); } _updateHead( motion ) { const owner = this.owner; const headContainer = owner.headContainer; // some simple head bobbing headContainer.position.x = motion * 0.14; headContainer.position.y = Math.abs( motion ) * 0.12; // const sign = Math.sign( Math.cos( elapsedTime * this.headMovement ) ); if ( sign < currentSign ) { currentSign = sign; const audio = world.audios.get( 'step1' ); if ( audio.isPlaying === true ) audio.stop(); audio.play(); } if ( sign > currentSign ) { currentSign = sign; const audio = world.audios.get( 'step2' ); if ( audio.isPlaying === true ) audio.stop(); audio.play(); } } _updateWeapon( motion ) { const owner = this.owner; const weaponContainer = owner.weaponContainer; weaponContainer.position.x = motion * 0.005; weaponContainer.position.y = Math.abs( motion ) * 0.002; } } // handler function onMouseDown( event ) { if ( event.which === 1 ) { this.owner.weapon.shoot(); } } function onMouseMove( event ) { this.movementX -= event.movementX * 0.001 * this.lookingSpeed; this.movementY -= event.movementY * 0.001 * this.lookingSpeed; this.movementY = Math.max( - PI05, Math.min( PI05, this.movementY ) ); this.owner.rotation.fromEuler( 0, this.movementX, 0 ); // yaw this.owner.head.rotation.fromEuler( this.movementY, 0, 0 ); // pitch } function onPointerlockChange() { if ( document.pointerLockElement === document.body ) { this.dispatchEvent( { type: 'lock' } ); } else { this.disconnect(); this.dispatchEvent( { type: 'unlock' } ); } } function onPointerlockError() { Logger.warn( 'YUKA.Player: Unable to use Pointer Lock API.' ); } function onKeyDown( event ) { switch ( event.keyCode ) { case 38: // up case 87: // w this.input.forward = true; break; case 37: // left case 65: // a this.input.left = true; break; case 40: // down case 83: // s this.input.backward = true; break; case 39: // right case 68: // d this.input.right = true; break; case 82: // r this.owner.weapon.reload(); break; } } function onKeyUp( event ) { switch ( event.keyCode ) { case 38: // up case 87: // w this.input.forward = false; break; case 37: // left case 65: // a this.input.left = false; break; case 40: // down case 83: // s this.input.backward = false; break; case 39: // right case 68: // d this.input.right = false; break; } } export { FirstPersonControls };
335b37e5ee9309a0db0823bc6e952e94be57daab
{ "blob_id": "335b37e5ee9309a0db0823bc6e952e94be57daab", "branch_name": "refs/heads/master", "committer_date": "2023-01-16T10:09:21", "content_id": "f2547c798bf908de56758f1ba3def7bc94069e8a", "detected_licenses": [ "MIT" ], "directory_id": "eca5edb1c13125061fa52caa9011aa390e20bc19", "extension": "js", "filename": "FirstPersonControls.js", "fork_events_count": 90, "gha_created_at": "2017-07-07T21:19:47", "gha_event_created_at": "2023-07-19T07:55:53", "gha_language": "JavaScript", "gha_license_id": "MIT", "github_id": 96577416, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 5841, "license": "MIT", "license_type": "permissive", "path": "/examples/playground/hideAndSeek/src/FirstPersonControls.js", "provenance": "stack-edu-0032.json.gz:272359", "repo_name": "Mugen87/yuka", "revision_date": "2023-01-16T10:09:21", "revision_id": "10591304811222d6856020d5de129b39ef43b58d", "snapshot_id": "c5a589a8c244f7e40294b3f557ace65938686d22", "src_encoding": "UTF-8", "star_events_count": 928, "url": "https://raw.githubusercontent.com/Mugen87/yuka/10591304811222d6856020d5de129b39ef43b58d/examples/playground/hideAndSeek/src/FirstPersonControls.js", "visit_date": "2023-07-26T07:29:56.478719", "added": "2024-11-18T21:35:04.430041+00:00", "created": "2023-01-16T10:09:21", "int_score": 3, "score": 2.6875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0050.json.gz" }
<?php namespace wxsdk\core\model; use function rapidPHP\B; class WXUserInfoModel { /** * @var string|null */ public $openId; /** * @var string|null */ public $unionId; /** * @var string|null */ public $nickname; /** * @var string|null */ public $header; /** * @var int|string|null */ public $gender; /** * @var string|null */ public $language; /** * @var string|null */ public $country; /** * @var string|null */ public $province; /** * @var string|null */ public $city; /** * 是否关注 * @var bool|null */ public $is_subscribe; /** * 关注时间戳 * @var int|null */ public $subscribe_time; /** * 备注 * @var string|null */ public $remark; /** * groupid * @var int|null */ public $groupId; /** * tagId_list * @var array|null */ public $tagIdList = []; /** * 关注场景 * @var string|null */ public $subscribeScene; /** * 扫码场景 * @var string|null */ public $qrScene; /** * 扫码参数 * @var string|null */ public $qrSceneStr; /** * @return string|null */ public function getOpenId(): ?string { return $this->openId; } /** * @param string|null $openId */ public function setOpenId(?string $openId): void { $this->openId = $openId; } /** * @return string|null */ public function getUnionId(): ?string { return $this->unionId; } /** * @param string|null $unionId */ public function setUnionId(?string $unionId): void { $this->unionId = $unionId; } /** * @return string|null */ public function getNickname(): ?string { return $this->nickname; } /** * @param string|null $nickname */ public function setNickname(?string $nickname): void { $this->nickname = $nickname; } /** * @return string|null */ public function getHeader(): ?string { return $this->header; } /** * @param string|null $header */ public function setHeader(?string $header): void { $this->header = $header; } /** * @return int|null */ public function getGender(): ?int { return $this->gender; } /** * @param int|string|null $gender */ public function setGender($gender): void { if (!is_numeric($gender)) $gender = B()->getData(['男' => 1, '女' => 2], (string)$gender); $this->gender = $gender; } /** * @return string|null */ public function getLanguage(): ?string { return $this->language; } /** * @param string|null $language */ public function setLanguage(?string $language = 'zh_CN'): void { $this->language = $language; } /** * @return string|null */ public function getCountry(): ?string { return $this->country; } /** * @param string|null $country */ public function setCountry(?string $country = '中国'): void { $this->country = $country; } /** * @return string|null */ public function getProvince(): ?string { return $this->province; } /** * @param string|null $province */ public function setProvince(?string $province): void { $this->province = $province; } /** * @return string|null */ public function getCity(): ?string { return $this->city; } /** * @param string|null $city */ public function setCity(?string $city): void { $this->city = $city; } /** * @return bool|null */ public function getIsSubscribe(): ?bool { return $this->is_subscribe; } /** * @param bool|null $is_subscribe */ public function setIsSubscribe(?bool $is_subscribe = false): void { $this->is_subscribe = $is_subscribe; } /** * @return int|null */ public function getSubscribeTime(): ?int { return $this->subscribe_time; } /** * @param int|null $subscribe_time */ public function setSubscribeTime(?int $subscribe_time): void { $this->subscribe_time = $subscribe_time; } /** * @return string|null */ public function getRemark(): ?string { return $this->remark; } /** * @param string|null $remark */ public function setRemark(?string $remark): void { $this->remark = $remark; } /** * @return int|null */ public function getGroupId(): ?int { return $this->groupId; } /** * @param int|null $groupId */ public function setGroupId(?int $groupId): void { $this->groupId = $groupId; } /** * @return array|null */ public function getTagIdList(): ?array { return $this->tagIdList; } /** * @param array|null $tagIdList */ public function setTagIdList(?array $tagIdList): void { $this->tagIdList = $tagIdList; } /** * @return string|null */ public function getSubscribeScene(): ?string { return $this->subscribeScene; } /** * @param string|null $subscribeScene */ public function setSubscribeScene(?string $subscribeScene): void { $this->subscribeScene = $subscribeScene; } /** * @return string|null */ public function getQrScene(): ?string { return $this->qrScene; } /** * @param string|null $qrScene */ public function setQrScene(?string $qrScene): void { $this->qrScene = $qrScene; } /** * @return string|null */ public function getQrSceneStr(): ?string { return $this->qrSceneStr; } /** * @param string|null $qrSceneStr */ public function setQrSceneStr(?string $qrSceneStr): void { $this->qrSceneStr = $qrSceneStr; } }
64abbacf6b4147a155b73bb8a5f7c4a33408fec9
{ "blob_id": "64abbacf6b4147a155b73bb8a5f7c4a33408fec9", "branch_name": "refs/heads/master", "committer_date": "2023-03-23T03:53:34", "content_id": "7e91e5d392d557c27b27e1813e4d3323d1584841", "detected_licenses": [ "MIT" ], "directory_id": "c299ff72b98bfcb285c629b5992b77d5861b618a", "extension": "php", "filename": "WXUserInfoModel.php", "fork_events_count": 19, "gha_created_at": "2020-03-22T10:01:29", "gha_event_created_at": "2023-04-19T21:05:59", "gha_language": "PHP", "gha_license_id": "MIT", "github_id": 249155684, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 6345, "license": "MIT", "license_type": "permissive", "path": "/apps/wxsdk/core/model/WXUserInfoModel.php", "provenance": "stack-edu-0047.json.gz:517206", "repo_name": "wgx954418992/rapid-php", "revision_date": "2023-03-23T03:53:34", "revision_id": "f57b2ea96b1ed229ffe2c73a8fff058288eb22ce", "snapshot_id": "f591e2f986379b9e3af8050b2f7db7e4fd01216b", "src_encoding": "UTF-8", "star_events_count": 94, "url": "https://raw.githubusercontent.com/wgx954418992/rapid-php/f57b2ea96b1ed229ffe2c73a8fff058288eb22ce/apps/wxsdk/core/model/WXUserInfoModel.php", "visit_date": "2023-05-01T02:54:45.308737", "added": "2024-11-18T22:13:05.696483+00:00", "created": "2023-03-23T03:53:34", "int_score": 3, "score": 2.75, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0065.json.gz" }
using ERHMS.Desktop.Infrastructure; using ERHMS.EpiInfo; using System.Diagnostics; using System.IO; using System.Reflection; using System.Windows.Input; using Module = ERHMS.EpiInfo.Module; namespace ERHMS.Desktop.ViewModels { public class MainViewModel : ViewModel { private static MainViewModel current; public static MainViewModel Current { get { if (current == null) { current = new MainViewModel(); } return current; } } private ViewModel content; public ViewModel Content { get { return content; } set { Log.Default.Debug($"Displaying: {value}"); SetProperty(ref content, value); } } public ICommand GoHomeCommand { get; } public ICommand OpenEpiInfoCommand { get; } public ICommand OpenFileExplorerCommand { get; } private MainViewModel() { GoHomeCommand = new SimpleCommand(GoHome); OpenEpiInfoCommand = new SimpleCommand(OpenEpiInfo); OpenFileExplorerCommand = new SimpleCommand(OpenFileExplorer); } private void GoHome() { Content = new HomeViewModel(); } private void OpenEpiInfo() { Module.Menu.Start(); } private void OpenFileExplorer() { string entryDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); Process.Start(entryDirectory); } } }
61328c67394d82676fc0d8cbc5316bb4550337c3
{ "blob_id": "61328c67394d82676fc0d8cbc5316bb4550337c3", "branch_name": "refs/heads/master", "committer_date": "2020-07-17T21:30:14", "content_id": "55b465bbcb35e72fe4ff578b35f07ebf0d2c4fd8", "detected_licenses": [ "Apache-2.0" ], "directory_id": "e7a6d0a0ae003228d696242af3076a2c05d8628e", "extension": "cs", "filename": "MainViewModel.cs", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1771, "license": "Apache-2.0", "license_type": "permissive", "path": "/ERHMS.Desktop/ViewModels/MainViewModel.cs", "provenance": "stack-edu-0011.json.gz:466606", "repo_name": "Tubbz-alt/erhms-info-manager", "revision_date": "2020-07-17T21:30:14", "revision_id": "7a112158bac18ff30972d302ee10b90c16551a7f", "snapshot_id": "c51299f62f9bddd0b4fa7b00734c2b7eb423f864", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Tubbz-alt/erhms-info-manager/7a112158bac18ff30972d302ee10b90c16551a7f/ERHMS.Desktop/ViewModels/MainViewModel.cs", "visit_date": "2022-11-20T03:04:28.845182", "added": "2024-11-18T22:47:06.971832+00:00", "created": "2020-07-17T21:30:14", "int_score": 2, "score": 2.296875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0029.json.gz" }
/* Motor <[email protected]> see LICENSE for detail */ #include <stdafx.h> #include <motor/meta/classinfo.meta.hh> #include <motor/plugin/plugin.hh> namespace Motor { namespace Debug { minitl::assertion_result assertionCallback(const char* file, int line, const char* expr, const char* message); class AssertSetup : public minitl::refcountable { private: minitl::assertion_callback_t m_previousAssertionCallback; public: AssertSetup(const AssertSetup& other) = delete; AssertSetup& operator=(const AssertSetup& other) = delete; explicit AssertSetup(const Motor::Plugin::Context& /*context*/) : m_previousAssertionCallback(minitl::set_assertion_callback(&assertionCallback)) { motor_debug(Log::system(), "installed assert callback"); } ~AssertSetup() override { minitl::set_assertion_callback(m_previousAssertionCallback); } }; }} // namespace Motor::Debug MOTOR_PLUGIN_REGISTER(Motor::Debug::AssertSetup)
5f4461b194f76df662bf1eb1f18f2649f0423192
{ "blob_id": "5f4461b194f76df662bf1eb1f18f2649f0423192", "branch_name": "refs/heads/master", "committer_date": "2023-07-07T14:01:20", "content_id": "b7ebc64b0ad3bcdf0d4826d11f91e838df765855", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "68e2df11645278a9997eeae804a9a075585b59f2", "extension": "cc", "filename": "plugin.cc", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 398261504, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1034, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/plugin/debug/assert/src/plugin.cc", "provenance": "stack-edu-0002.json.gz:348160", "repo_name": "motor-dev/Motor", "revision_date": "2023-07-07T14:01:20", "revision_id": "edd724bba99af63d938a0db165dec07403a40fb6", "snapshot_id": "df673aafcd4040a7ce7e6ef9301c38270982d544", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/motor-dev/Motor/edd724bba99af63d938a0db165dec07403a40fb6/src/plugin/debug/assert/src/plugin.cc", "visit_date": "2023-07-22T10:19:26.028314", "added": "2024-11-18T21:50:58.460883+00:00", "created": "2023-07-07T14:01:20", "int_score": 2, "score": 2.078125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0020.json.gz" }
/* * Copyright 2009 Joubin Houshyar * * 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, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jredis.connector; import java.util.concurrent.Future; import org.jredis.ClientRuntimeException; import org.jredis.NotSupportedException; import org.jredis.ProviderException; import org.jredis.RedisException; import org.jredis.protocol.Command; import org.jredis.protocol.Response; /** * {@link FaultedConnection} is a support class for implementors of JRedis API. * * @optional * @author Joubin Houshyar ([email protected]) * @version alpha.0, Apr 11, 2009 * @since alpha.0 * */ public class FaultedConnection implements Connection { /** */ final private String errorMsg; /** */ final private ConnectionSpec connSpec; /** * instantiates a faulted connection for the given {@link ConnectionSpec} * @param connSpec * @param errMsg */ public FaultedConnection (ConnectionSpec connSpec, String errMsg) { this.errorMsg = errMsg; this.connSpec = connSpec; } /* (non-Javadoc) @see org.jredis.connector.Connection#getSpec() */ @Override public ConnectionSpec getSpec() { return connSpec; } /* (non-Javadoc) @see org.jredis.connector.Connection#serviceRequest(org.jredis.protocol.Command, byte[][]) */ @Override public Response serviceRequest(Command cmd, byte[]... args) throws RedisException, ClientRuntimeException, ProviderException { throw new ClientRuntimeException (errorMsg); } /* (non-Javadoc) @see org.jredis.connector.Connection#queueRequest(org.jredis.protocol.Command, byte[][]) */ @Override public Future<Response> queueRequest(Command cmd, byte[]... args) throws ClientRuntimeException, ProviderException { throw new ClientRuntimeException (errorMsg); } /* (non-Javadoc) @see org.jredis.connector.Connection#addListener(org.jredis.connector.Connection.Listener) */ @Override final public boolean addListener (Listener connListener) { throw new NotSupportedException("Events not supported"); } /* (non-Javadoc) @see org.jredis.connector.Connection#removeListener(org.jredis.connector.Connection.Listener) */ @Override final public boolean removeListener (Listener connListener) { throw new NotSupportedException("Events not supported"); } }
fa09677af48c3ed61e6535e24cf76aa7cb68e364
{ "blob_id": "fa09677af48c3ed61e6535e24cf76aa7cb68e364", "branch_name": "refs/heads/master", "committer_date": "2023-08-18T23:47:16", "content_id": "cfe009015a57eeb8156118fdf990ebf3c2a50383", "detected_licenses": [ "Apache-2.0" ], "directory_id": "d76382a7503623d88ac7ea8794977dfc59ecd623", "extension": "java", "filename": "FaultedConnection.java", "fork_events_count": 114, "gha_created_at": "2009-03-27T18:58:45", "gha_event_created_at": "2023-08-18T23:47:17", "gha_language": "Java", "gha_license_id": "Apache-2.0", "github_id": 161180, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2797, "license": "Apache-2.0", "license_type": "permissive", "path": "/core/api/src/main/java/org/jredis/connector/FaultedConnection.java", "provenance": "stack-edu-0030.json.gz:160398", "repo_name": "alphazero/jredis", "revision_date": "2023-08-18T23:47:16", "revision_id": "98b4c73701b8583529ca98911a6428a76b020c2d", "snapshot_id": "1aef31f3085f94a47f59a3bc90e83e853f0c62ed", "src_encoding": "UTF-8", "star_events_count": 220, "url": "https://raw.githubusercontent.com/alphazero/jredis/98b4c73701b8583529ca98911a6428a76b020c2d/core/api/src/main/java/org/jredis/connector/FaultedConnection.java", "visit_date": "2023-09-03T04:27:47.136455", "added": "2024-11-19T00:30:53.949343+00:00", "created": "2023-08-18T23:47:16", "int_score": 2, "score": 2.1875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0048.json.gz" }
/* PHASE 0 INITIALISATION DES GLOBALES VARIABLES */ var Data_Europa = [] var map = ""; var Zoom = []; var legend = ""; var valeurStyle = "" var table = {} var data = {} var chart = {} var filtre = false var Choix = ""; var Annee = ""; var Indic = ""; var Choix2 = ""; var PopulationChoix = ""; var PIBChoix = ""; var Choix3 = "reset" var str = { selection: "" } var CPays = ""; var T = 0 // Lancement du script à l'execution de la page traitementDonnee() /* ------------------------------------------------------------------------------------------------------------------------------*/ /* PHASE 1 TRAITEMENT DES DONNEES */ function traitementDonnee() { // Fonction de lancement CreateDataEuropa() setTimeout(function() { traitementPIB('data/pib.tsv'); traitementPopulation('data/population.tsv'); traitementDechet('data/dechet.tsv'); traitementElectricite('data/electricite.tsv'); AffectationGroupe(Data_Europa); TraitementEurope("Population_An2013"); }, 500) }; // Traitement du fichier sur le PIB function traitementPIB(fichier1) { d3.tsv(fichier1, function(data) { var Pib = []; var Pib_Data = []; Pib = data; Pib.forEach(function(c) { var pib_Objet = {}; if (c[Object.getOwnPropertyNames(c)[0]].length <= 21) { pib_Objet['Code_Pays'] = c[Object.getOwnPropertyNames(c)[0]].slice(19, 21).trim(); pib_Objet['An2011'] = +c[Object.getOwnPropertyNames(c)[17]].slice(0, 5).trim(); pib_Objet['An2012'] = +c[Object.getOwnPropertyNames(c)[18]].slice(0, 5).trim(); pib_Objet['An2013'] = +c[Object.getOwnPropertyNames(c)[19]].slice(0, 5).trim(); Pib_Data.push(pib_Objet); } }); Data_Europa.forEach(function(Data_Europa) { var result = Pib_Data.filter(function(Pib_Data) { return Pib_Data.Code_Pays === Data_Europa.Code_Pays; }); Data_Europa.Pib_An2011 = (result[0] !== undefined) ? result[0].An2011 : null; Data_Europa.Pib_An2012 = (result[0] !== undefined) ? result[0].An2012 : null; Data_Europa.Pib_An2013 = (result[0] !== undefined) ? result[0].An2013 : null; }) }); } // Traitement du fichier sur la population function traitementPopulation(fichier2) { d3.tsv(fichier2, function(data) { var Pop = []; var Pop_Data = []; Pop = data; Pop.forEach(function(c) { var pop_Objet = {} if (c[Object.getOwnPropertyNames(c)[0]].length <= 21) { pop_Objet['Code_Pays'] = c[Object.getOwnPropertyNames(c)[0]].slice(4, 6).trim(); pop_Objet['An2011_p'] = +c[Object.getOwnPropertyNames(c)[9]].trim().slice(0, 8); pop_Objet['An2012_p'] = +c[Object.getOwnPropertyNames(c)[10]].trim().slice(0, 8); pop_Objet['An2013_p'] = +c[Object.getOwnPropertyNames(c)[11]].trim().slice(0, 8); Pop_Data.push(pop_Objet); } }) Data_Europa.forEach(function(Data_Europa) { var result = Pop_Data.filter(function(Pop_Data) { return Pop_Data.Code_Pays === Data_Europa.Code_Pays; }); Data_Europa.Population_An2011 = (result[0] !== undefined) ? result[0].An2011_p : null; Data_Europa.Population_An2012 = (result[0] !== undefined) ? result[0].An2012_p : null; Data_Europa.Population_An2013 = (result[0] !== undefined) ? result[0].An2013_p : null; }) }) } // Traitement du fichier sur les déchets function traitementDechet(fichier3) { d3.tsv(fichier3, function(data) { var Dechet = []; var Dechet_Data = []; Dechet = data; Dechet.forEach(function(c) { var dechet_Objet = {} if (c[Object.getOwnPropertyNames(c)[0]].length <= 21) { dechet_Objet['Code_Pays'] = c[Object.getOwnPropertyNames(c)[0]].slice(10, 12).trim(); dechet_Objet['An2011_d'] = +c[Object.getOwnPropertyNames(c)[17]].trim().slice(0, 4); dechet_Objet['An2012_d'] = +c[Object.getOwnPropertyNames(c)[18]].trim().slice(0, 4); dechet_Objet['An2013_d'] = +c[Object.getOwnPropertyNames(c)[19]].trim().slice(0, 4); Dechet_Data.push(dechet_Objet); } }) Data_Europa.forEach(function(Data_Europa) { var result = Dechet_Data.filter(function(Dechet_Data) { return Dechet_Data.Code_Pays === Data_Europa.Code_Pays; }); Data_Europa.Dechet_An2011 = (result[0] !== undefined) ? result[0].An2011_d : null; Data_Europa.Dechet_An2012 = (result[0] !== undefined) ? result[0].An2012_d : null; Data_Europa.Dechet_An2013 = (result[0] !== undefined) ? result[0].An2013_d : null; }) }) } // Traitement du fichier sur l'eletricité function traitementElectricite(fichier4) { d3.tsv(fichier4, function(data) { var Electricity = []; var Electricity_Data = []; Electricity = data; Electricity.forEach(function(c) { var electricity_Objet = {} if (c[Object.getOwnPropertyNames(c)[0]].length <= 21) { electricity_Objet['Code_Pays'] = c[Object.getOwnPropertyNames(c)[0]].slice(10, 12).trim(); electricity_Objet['An2011_e'] = +c[Object.getOwnPropertyNames(c)[9]].trim(); electricity_Objet['An2012_e'] = +c[Object.getOwnPropertyNames(c)[10]].trim(); electricity_Objet['An2013_e'] = +c[Object.getOwnPropertyNames(c)[11]].trim(); Electricity_Data.push(electricity_Objet); } }) Data_Europa.forEach(function(Data_Europa) { var result = Electricity_Data.filter(function(Electricity_Data) { return Electricity_Data.Code_Pays === Data_Europa.Code_Pays; }); Data_Europa.ElectricitePropre_An2011 = (result[0] !== undefined) ? result[0].An2011_e : null; Data_Europa.ElectricitePropre_An2012 = (result[0] !== undefined) ? result[0].An2012_e : null; Data_Europa.ElectricitePropre_An2013 = (result[0] !== undefined) ? result[0].An2013_e : null; }) }) } // Affectation d'un groupe européen selon le pays function AffectationGroupe(array1) { array1.forEach(function(d) { if ($.inArray(d.Code_Pays, UeGrp6) > -1) { d.GroupeEurope = "GRP6"; } else if ($.inArray(d.Code_Pays, UeGrp15) > -1) { d.GroupeEurope = "GRP15"; } else { d.GroupeEurope = "GRP28" } }) } // Création de la variable Data_Europa + importation du premier fichier sur les taxes function CreateDataEuropa() { d3.tsv("data/taxe.tsv", function(data) { Taxe = data; string_a = "ENV,MIO_EUR,"; UeGrp6 = ["DE", "FR", "BE", "IT", "LU", "NL"]; UeGrp15 = ["AT", "DK", "EL", "ES", "FI", "IE", "PT", "SE", "UK"]; NotUE = ["ENV,MIO_EUR,CH", "ENV,MIO_EUR,EA19", "ENV,MIO_EUR,EU28", "ENV,MIO_EUR,LI", "ENV,MIO_EUR,NO", "ENV,MIO_EUR,RS", "ENV,MIO_EUR,TR"]; Taxe.forEach(function(c) { var Data_Europa_Objet = {} string_t = c[Object.getOwnPropertyNames(c)[0]].trim() if (string_t.indexOf(string_a) > -1) { if ($.inArray(string_t, NotUE) > -1) {} else { Data_Europa_Objet['Code_Pays'] = string_t.slice(12, 14); Data_Europa_Objet['Taxe_An2011'] = +c[Object.getOwnPropertyNames(c)[3]].slice(0, 5).trim(); Data_Europa_Objet['Taxe_An2012'] = +c[Object.getOwnPropertyNames(c)[2]].slice(0, 5).trim(); Data_Europa_Objet['Taxe_An2013'] = +c[Object.getOwnPropertyNames(c)[1]].slice(0, 5).trim(); Data_Europa.push(Data_Europa_Objet); } } else {} }); }) } /* ------------------------------------------------------------------------------------------------------------------------------*/ /* PHASE 2 CREATION ET GESTION DE LA CARTOGRAPHIE */ function TraitementEurope(k) { // Création de la carte map = L.map('map').setView([48.06217, 6.95827], 3); map.dragging.disable(); map.doubleClickZoom.disable(); map.scrollWheelZoom.disable(); L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoiYmtyc2giLCJhIjoiY2lsdzduaTU2MDA5ZXZtbTV4YmV4ZnhtYSJ9.TJWAdBBuNcbdMO_9Hf-2vQ', { attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' + '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' + 'Imagery © <a href="http://mapbox.com">Mapbox</a>', id: 'mapbox.light' }).addTo(map); // Importation des données géographiques $.getJSON("data/countries.geojson", function(data) { dataToDisplay = {} dataToDisplay.type = "FeatureCollection" dataToDisplay.features = [] data.features.forEach(function(d) { for (i = 0; i < Data_Europa.length; i++) { if (d.properties.iso_a2 === Data_Europa[i].Code_Pays || d.properties.iso_a2 === "GR" && Data_Europa[i].Code_Pays == "EL" || d.properties.iso_a2 === "GB" && Data_Europa[i].Code_Pays === "UK") { Data_Europa[i].Nom_Pays = d.properties.name; dataToDisplay.features[i] = d; d.properties = {}; d.properties.Code_Pays = Data_Europa[i].Code_Pays; d.properties.Nom_Pays = Data_Europa[i].Nom_Pays; d.properties.Taxe_An2011 = Data_Europa[i].Taxe_An2011; d.properties.Taxe_An2012 = Data_Europa[i].Taxe_An2012; d.properties.Taxe_An2013 = Data_Europa[i].Taxe_An2013; d.properties.Pib_An2011 = Data_Europa[i].Pib_An2011; d.properties.Pib_An2012 = Data_Europa[i].Pib_An2012; d.properties.Pib_An2013 = Data_Europa[i].Pib_An2013; d.properties.Population_An2011 = Data_Europa[i].Population_An2011; d.properties.Population_An2012 = Data_Europa[i].Population_An2012; d.properties.Population_An2013 = Data_Europa[i].Population_An2013; d.properties.Dechet_An2011 = Data_Europa[i].Dechet_An2011; d.properties.Dechet_An2012 = Data_Europa[i].Dechet_An2012; d.properties.Dechet_An2013 = Data_Europa[i].Dechet_An2013; d.properties.ElectricitePropre_An2011 = Data_Europa[i].ElectricitePropre_An2011; d.properties.ElectricitePropre_An2012 = Data_Europa[i].ElectricitePropre_An2012; d.properties.ElectricitePropre_An2013 = Data_Europa[i].ElectricitePropre_An2013; } else { delete(d) } } }) // Création de la borne de valeur en fonction du choix valeurStyle = MinMax(k) function onEachFeature(feature, layer) { var int = {}; int.cp = feature.properties.Code_Pays; int.coord = layer.getBounds(); Zoom.push(int) layer.on({ mouseover: Viewinfo, mouseout: function(e) { geojson.setStyle({ fillOpacity: 0.6, weight: 1 }); } }); } geojson = L.geoJson(dataToDisplay, { style: style, onEachFeature: onEachFeature }).addTo(map); }) setTimeout(function() { CreateLegend() }, 500); } // Fonction pour avoir un tableau de valeurs (max, min , valeur intermédiaire) pour la gestion des couleurs et de la légende function MinMax(str) { Val = []; Val[0] = Data_Europa.reduce(function(o, n) { if (n[str] < o[str]) return n; return o; })[str]; Val[1] = Data_Europa.reduce(function(o, n) { if (n[str] > o[str]) return n; return o; })[str]; Val[2] = str; Ecart = Val[1] - Val[0]; EchelleV = Math.trunc(((Ecart % 6) + Ecart) / 6); for (i = 1; i < 7; i++) { Val[i + 2] = EchelleV * i } return Val } // Fonction de style initial function style(feature) { return { fillColor: "#003399", fillOpacity: 0.9, weight: 1, color: "#FFCA00", opacity: 1, }; } // Mise à jour du style function UpdateStyle(Indicator) { valeurStyle = MinMax(Indicator); geojson.setStyle(function(feature) { return { fillColor: getColor(feature.properties[valeurStyle[2]]), fillOpacity: 0.6, weight: 1, color: "#000", opacity: 1, } }) UpdateLegend(); } function InterGoogleLeaflet(coord) { map.fitBounds(coord); } // Fonction apppelée lorsque l'utilisateur passe sur la carte avec sa souris function Viewinfo(e) { var layer = e.target; layer.setStyle({ fillOpacity: 0.8, weight: 2 }); var prop = e.target.feature.properties; var flag = ""; Test = Choix; Choix2011 = Choix.slice(0, Choix.length - 4) + "2011"; Choix2012 = Choix.slice(0, Choix.length - 4) + "2012"; Choix2013 = Choix.slice(0, Choix.length - 4) + "2013"; if (Choix.slice(0, 1) === 'E') { strchoix = "Energie propre"; unite = "%" } else if (Choix.slice(0, 1) === 'D') { strchoix = Choix.slice(0, Choix.length - 7); unite = "%" } else { strchoix = Choix.slice(0, Choix.length - 7); unite = "millions d'euros" } map.setView([48.06217, 11.95827], 4); if (Test === "") {} else { $('#help').css('display', 'none'); $('#infobox').css({ 'display': 'block' }) $('#listepays').css({ 'margin-top': 5, 'display': 'block' }) if (prop.Code_Pays === "UK") { flag = "GB" } else if (prop.Code_Pays === "EL") { flag = "GR" } else { flag = prop.Code_Pays } document.getElementById("NOM").innerHTML = prop.Nom_Pays; document.getElementById("CODE").innerHTML = prop.Code_Pays; CPays = prop.Code_Pays; document.getElementById("flagg").innerHTML = "<img id='flag' src='http://www.geognos.com/api/en/countries/flag/" + flag + ".png'/>" document.getElementById("C2011").innerHTML = strchoix + " 2011: " + prop[Choix2011] + " " + unite document.getElementById("C2012").innerHTML = strchoix + " 2012: " + prop[Choix2012] + " " + unite document.getElementById("C2013").innerHTML = strchoix + " 2013: " + prop[Choix2013] + " " + unite str.selection = prop.Code_Pays drawTable(2); drawTable(3); } } // Gestion des couleurs function getColor(d) { Test = Choix switch (Test.slice(0, 1)) { case "D": return d > valeurStyle[8] ? '#800026' : d > valeurStyle[7] ? '#BD0026' : d > valeurStyle[6] ? '#FC4E2A' : d > valeurStyle[5] ? '#FD8D3C' : d > valeurStyle[4] ? '#FEB24C' : d > valeurStyle[3] ? '#FED976' : '#FFEDA0'; break; case "E": return d > valeurStyle[8] ? '#005a32' : d > valeurStyle[7] ? '#238443' : d > valeurStyle[6] ? '#41ab5d' : d > valeurStyle[5] ? '#78c679' : d > valeurStyle[4] ? '#addd8e' : d > valeurStyle[3] ? '#d9f0a3' : '#ffffcc'; break; case "T": return d > valeurStyle[8] ? '#0c2c84' : d > valeurStyle[7] ? '#225ea8' : d > valeurStyle[6] ? '#1d91c0' : d > valeurStyle[5] ? '#41b6c4' : d > valeurStyle[4] ? '#7fcdbb' : d > valeurStyle[3] ? '#c7e9b4' : '#ffffcc'; break; } } // MIse à jour de la légende function UpdateLegend() { legend.removeFrom(map) legend = L.control({ position: 'bottomright' }); legend.onAdd = function(map) { var div = L.DomUtil.create('div', 'info legend'), grades = [valeurStyle[8], valeurStyle[7], valeurStyle[6], valeurStyle[5], valeurStyle[4], valeurStyle[3]], labels = ["<i>Légende</i>", LegendTitle()], from, to; for (var i = 0; i < grades.length; i++) { from = grades[i]; to = grades[i + 1]; labels.push( '<i style="background:' + getColor(from + 1) + '"></i> ' + from + (to ? '&ndash;' + to : '-')); } div.innerHTML = labels.join('<br>'); return div; }; legend.addTo(map); } // Création de la légende function CreateLegend() { legend = L.control({ position: 'bottomright' }); legend.onAdd = function(map) { var div = L.DomUtil.create('div', 'info legend'), grades = [valeurStyle[8], valeurStyle[7], valeurStyle[6], valeurStyle[5], valeurStyle[4], valeurStyle[3]], labels = ["<i>Légende</i>"], from, to; labels.push( '<i style="background:#003399"></i> Pays U.E'); div.innerHTML = labels.join('<br>'); return div; }; legend.addTo(map); } // Titre de la légende function LegendTitle() { Test = valeurStyle[2] titleL = "" switch (Test.slice(0, 1)) { case "D": return titleL = "Dechet " + Annee.replace("An", "") break; case "E": return titleL = "Energie propre" + Annee.replace("An", " ") break; case "T": return titleL = "Taxe" + Annee.replace("An", " ") break; } } /* ------------------------------------------------------------------------------------------------------------------------------*/ /* PHASE 3 CREATION ET GESTION DU TABLEAU DE BORD */ setTimeout(function() { google.charts.load('current', { 'packages': ['table', 'corechart'] }); google.charts.setOnLoadCallback(drawTable); }, 500) function drawTable(a) { var cssClassNames = { headerRow: 'headerRow', tableRow: 'tableRow', oddTableRow: 'oddTableRow', selectedTableRow: 'selectedTableRow', hoverTableRow: 'hoverTableRow', headerCell: 'headerCell', tableCell: 'tableCell', rowNumberCell: 'rowNumberCell' } setTimeout(function() { data = createData(Data_Europa, false, 17) }, 500) switch (a) { // GRAPHIQUE EVOLUTION DE LA POPULATION case 2: chart = new google.visualization.ColumnChart(document.getElementById('EvolutionPopulation')); chart.draw(createView("B1", data, 17), { title: "Evolution de la population de 2011 à 2013", fontSize: 12, colors: ['#a4ffd3', '#64d6ab', '#389874'], vAxis: { title: 'Population' }, bar: { groupWidth: "100%" }, chartArea: { width: '50%', height: '80%' }, legend: { textStyle: { fontSize: 12 } } }); // GRAPHIQUE EVOLUTION DU PIB case 3: chart = new google.visualization.ColumnChart(document.getElementById('EvolutionPIB')); chart.draw(createView("B2", data, 17), { title: "Evolution du PIB par habitant de 2011 à 2013", fontSize: 12, colors: ['#4e00ff', '#3c00c6', '#25007b'], vAxis: { title: 'PIB(Produit Intérieur Brut) par habitant' }, bar: { groupWidth: "100%" }, chartArea: { width: '50%', height: '80%' }, legend: { textStyle: { fontSize: 12 } } }); break; // DASHBOARD START case 4: // CREATION DU BAR CHART BarChart = new google.visualization.BarChart(document.getElementById('BarChart')); optionBarChart = { title: ChartText(2), colors: ['#b0120a'], hAxis: { title: ChartText(4), }, titlePosition: 'out', vAxis: { title: 'Pays' }, size: 40, width: 600, height: 500, chartArea: { width: '45%', height: '85%', top: 40 }, legend: { position: 'none' }, colors: [ChartColor(1, false, true), ChartColor(2, false, true), ChartColor(3, false, true)] } BarData = createView("B", data, 17, data.getColumnIndex(Choix2)) BarChart.draw(BarData, optionBarChart); // CREATION DU BUUBLE CHART var BubbleChart = new google.visualization.BubbleChart(document.getElementById('BubbleChart')); var optionBubbleChart = { title: ChartText(3), hAxis: { title: 'Population', viewWindow: { min: 0 } }, vAxis: { title: 'PIB(Produit intérieur brut par habitant (euro))', }, sizeAxis: { minSize: 10, maxSize: 30 }, bubble: { textStyle: { fontSize: 11, auraColor: 'none', }, sortBubblesBySize: true, }, width: 1400, height: 400, chartArea: { width: '80%', height: '75%', top: 50, }, colors: [ChartColor(1, true, false), ChartColor(2, true, false), ChartColor(3, true, false)] } BubbleData = createView("BU", data, data.getColumnIndex("Code Pays"), data.getColumnIndex(PopulationChoix), data.getColumnIndex(PIBChoix), data.getColumnIndex("GroupeEurope"), data.getColumnIndex(Choix2)) BubbleChart.draw(BubbleData, optionBubbleChart); // CREATION DU PIE CHART grouped_data = google.visualization.data.group(createView("P", data, 4, data.getColumnIndex(Choix2)), [0], [{ 'column': 1, 'aggregation': google.visualization.data.avg, 'type': 'number' }]); var optionsPiechart = { legend: 'none', pieSliceText: 'label', title: ChartText(1), width: 500, height: 500, pieHole: 0.4, chartArea: { width: '90%', height: '70%', backgroundColor: { stroke: '#fff', strokeWidth: 1, } }, colors: [ChartColorPie(2, false, false), ChartColorPie(3, false, false), ChartColorPie(1), false, false] }; var PieChart = new google.visualization.PieChart(document.getElementById('PieChart')); PieChart.draw(grouped_data, optionsPiechart); break; case 5: table = new google.visualization.Table(document.getElementById('tableChart')); table.draw(createView("T1", data, 17), { width: '100%', height: '100px', sortAscending: true, allowHtml: true, cssClassNames: cssClassNames }); google.visualization.events.addListener(table, 'select', selectHandler); break; } } // Création de la datatable googlechart function createData(array1, sort, col) { namecol = Object.keys(array1[0]); data = []; data = new google.visualization.DataTable(); numbercol = 0 for (i = 0; i < namecol.length; i++) { res = namecol[i].replace("_An", " ") res = res.replace("_", " ") data.addColumn(typeof(array1[0][namecol[i]]), res); } array1.forEach(function(d) { data.addRows([ [d[namecol[0]], { v: d[namecol[1]], f: d[namecol[1]] + " millions euros" }, { v: d[namecol[2]], f: d[namecol[2]] + " millions euros" }, { v: d[namecol[3]], f: d[namecol[3]] + " millions euros" }, { v: d[namecol[4]], f: d[namecol[4]].replace("GRP", "Groupe ") }, { v: d[namecol[5]], f: d[namecol[5]] + " euros/hab" }, { v: d[namecol[6]], f: d[namecol[6]] + " euros/hab" }, { v: d[namecol[7]], f: d[namecol[7]] + " euros/hab" }, { v: d[namecol[8]], f: d[namecol[8]] + " habitants" }, { v: d[namecol[9]], f: d[namecol[9]] + " habitants" }, { v: d[namecol[10]], f: d[namecol[10]] + " habitants" }, { v: d[namecol[11]], f: d[namecol[11]] + " %" }, { v: d[namecol[12]], f: d[namecol[12]] + " %" }, { v: d[namecol[13]], f: d[namecol[13]] + " %" }, { v: d[namecol[14]], f: d[namecol[14]] + " %" }, { v: d[namecol[15]], f: d[namecol[15]] + " %" }, { v: d[namecol[16]], f: d[namecol[16]] + " %" }, d[namecol[17]], ] ]); }); data.sort([{ column: col, desc: sort }]); return data; } // Création des vues utilisées pour les graphiques function createView(type, d, i, i2, i3, i4, i5) { var view = new google.visualization.DataView(d); switch (type) { case "T1": view.setColumns([i]); data.sort([{ column: i, desc: false, }]) return view; break; case "B2": //GRAPHIQUE POPULATION view.setColumns([i, 5, 6, 7]); view.setRows(data.getFilteredRows([{ column: 0, value: str.selection }])) return view; break; case "B1": view.setColumns([i, 8, 9, 10]); view.setRows(data.getFilteredRows([{ column: 0, value: str.selection }])) return view; break; case "B": view.setColumns([i, i2]); data.sort([{ column: i2, desc: true }]); if (Choix3 === "reset") {} else { view.setRows(data.getFilteredRows([{ column: 4, value: Choix3 }])) } return view; break; case "P": view.setColumns([i, i2]); return view; break; case "BU": view.setColumns([i, i2, i3, i4, i5]); if (Choix3 === "reset") {} else { view.setRows(data.getFilteredRows([{ column: 4, value: Choix3 }])) } return view; break; } } // Fonction pour la gestion de l'intéractivité entre la carte et les graphiques de l'onglet cartographie function selectHandler() { var selection = table.getSelection(); for (var i = 0; i < selection.length; i++) { var item = selection[i]; if (item.row != null) { var tr = data.getFormattedValue(item.row, 0); } } tmp1 = Indic.slice(0, -1) + " 2011"; tmp2 = Indic.slice(0, -1) + " 2012"; tmp3 = Indic.slice(0, -1) + " 2013"; Zoom.forEach(function(d) { if (tr === d.cp) { InterGoogleLeaflet(d.coord) str.selection = tr if (Test === "") {} else { $('#help').css('display', 'none') $('#infobox').css({ 'display': 'block' }) $('#tableChart').css({ 'margin-top': 1 }) $('#listepays').css({ 'margin-top': 5, 'display': 'block' }) } drawTable(2); drawTable(3); document.getElementById("NOM").innerHTML = data.getFormattedValue(item.row, 17); document.getElementById("CODE").innerHTML = data.getFormattedValue(item.row, 0); CPays = data.getFormattedValue(item.row, 0); label = "" if (Choix.slice(0, 1) === 'E') { label = "Energie propre" } else { label = Choix.slice(0, -7) } document.getElementById("C2011").innerHTML = label + " 2011: " + data.getFormattedValue(item.row, data.getColumnIndex(tmp1)); document.getElementById("C2012").innerHTML = label + " 2012: " + data.getFormattedValue(item.row, data.getColumnIndex(tmp2)); document.getElementById("C2013").innerHTML = label + " 2013: " + data.getFormattedValue(item.row, data.getColumnIndex(tmp3)); if (data.getFormattedValue(item.row, 0) === "UK") { flag = "GB" } else if (data.getFormattedValue(item.row, 0) === "EL") { flag = "GR" } else { flag = data.getFormattedValue(item.row, 0) } document.getElementById("flagg").innerHTML = "<img id='flag' src='http://www.geognos.com/api/en/countries/flag/" + flag + ".png'/>" } }) } // Fonction pour la création de titre ou légende dynamique pour les graphiques function ChartText(Nb) { Test = Choix Text = "" switch (Test.slice(0, 1)) { case "D": //DECHET if (Nb === 1) { return Text = "Part des déchets ménagers recyclés en moyenne par groupe européen" } else if (Nb === 2) { return Text = "Part des déchets ménagers recyclés par pays" } else if (Nb === 3) { return Text = "Taux des déchets ménagers recyclés en fonction du PIB et de la population par pays" } else { return Text = "Part des déchets ménagers recyclés(%)" } break; case "E": //ENERGIE PROPRE if (Nb === 1) { return Text = "Part de la production moyenne d'énergie propre par groupe européen" } else if (Nb === 2) { return Text = "Part des énergies propres produites par pays" } else if (Nb === 3) { return Text = "Taux des énergies propres produites en fonction du PIB et de la population par pays" } else { return Text = "Part des énergies propres(%)" } break; case "T": // TAXE if (Nb === 1) { return Text = "Montant des taxes liées à l'environnement en moyenne par groupe européen" } else if (Nb === 2) { return Text = "Montant des taxes liées à l'environnement perçues par pays" } else if (Nb === 3) { return Text = "Montant des taxes liées à l'environnement en fonction du PIB et de la population par pays" } else { return Text = "Revenus perçus (en millions d'euros)" } break; } } // Fonction pour la gestion des couleurs des graphiques function ChartColor(Nb, t, g) { Test = Choix Color = "" switch (Choix3) { case 'reset': switch (Test.slice(0, 1)) { case "D": if (Nb === 1) { if (g == false) { return Color = '#800026' } else { return Color = '#808080' } } else if (Nb === 2) { return Color = '#FD8D3C' } else { return Color = '#FED976' } break; case "E": if (t === true) { if (Nb === 1) { return Color = "#78c679" } else if (Nb === 2) { return Color = "#d9f0a3" } else { return Color = "#005a32" } } else { if (Nb === 1) { if (g == false) { return Color = '#005a32' } else { return Color = '#808080' } } else if (Nb === 2) { return Color = "#78c679" } else { return Color = "#d9f0a3" } } break; case "T": if (Nb === 1) { if (g == false) { return Color = '#0c2c84' } else { return Color = '#808080' } } else if (Nb === 2) { return Color = "#41b6c4" } else { return Color = "#c7e9b4" } break; } break; case 'GRP6': switch (Test.slice(0, 1)) { case "D": return Color = '#800026'; break; case "E": return Color = "#005a32"; break; case "T": return Color = "#0c2c84"; break; } break; case 'GRP15': switch (Test.slice(0, 1)) { case "D": return Color = '#FD8D3C'; break; case "E": return Color = "#78c679"; break; case "T": return Color = "41b6c4"; break } break; case 'GRP28': switch (Test.slice(0, 1)) { case "D": return Color = '#FED976'; break; case "E": return Color = "#d9f0a3"; break; case "T": return Color = "c7e9b4"; break } break; } } // Fonction pour la gestion des couleurs du PieChart function ChartColorPie(Nb) { Test = Choix Color = "" switch (Test.slice(0, 1)) { case "D": if (Nb === 1) { return Color = '#800026' } else if (Nb === 2) { return Color = '#FD8D3C' } else { return Color = '#FED976' } break; case "E": if (Nb === 1) { return Color = "#005a32" } else if (Nb === 2) { return Color = "#78c679" } else { return Color = "#d9f0a3" } break; case "T": if (Nb === 1) { return Color = "#0c2c84" } else if (Nb === 2) { return Color = "#41b6c4" } else { return Color = "#c7e9b4" } break; } } /* ------------------------------------------------------------------------------------------------------------------------------*/ /* PHASE 4 INTERACTIVITE GLOBALE DE L'APPLICATION */ // Gestion des boutons indicateur function SelectionIndic(a) { $('#help').css('display', 'none') Choix = "" Indic = a Choix = Indic + Annee Choix2 = Indic + Annee Choix2 = Choix2.replace("_An", " ") var Test = Indic.slice(0, 1) switch (Test) { case 'D': $("#D").addClass("selectedIndic"); $("#E").removeClass("selectedIndic"); $("#T").removeClass("selectedIndic"); break; case 'E': $("#E").addClass("selectedIndic"); $("#D").removeClass("selectedIndic"); $("#T").removeClass("selectedIndic"); break; case 'T': $("#T").addClass("selectedIndic"); $("#D").removeClass("selectedIndic"); $("#E").removeClass("selectedIndic"); break; } if (Annee === "") { alert("Veuillez choisir une année") } else { PopulationChoix = "Population " + Annee.replace("An", "") PIBChoix = "Pib " + Annee.replace("An", "") UpdateStyle(Choix) drawTable(4, Choix3); drawTable(5); $('#listepays').css({ 'display': 'block' }) } if ($('#infobox').css('display') == 'block') { function trouvePays(pays) { return pays.Code_Pays === CPays; } Choix2011 = Choix.slice(0, Choix.length - 4) + "2011"; Choix2012 = Choix.slice(0, Choix.length - 4) + "2012"; Choix2013 = Choix.slice(0, Choix.length - 4) + "2013"; label = "" if (Choix.slice(0, 1) === 'E') { label = "Energie propre" } else { label = Choix.slice(0, -7) } if (Choix.slice(0, 1) === 'T') { unite = "millions d'euros" } else { unite = "%" } document.getElementById("C2011").innerHTML = label + " 2011: " + Data_Europa.find(trouvePays)[Choix2011] + " " + unite document.getElementById("C2012").innerHTML = label + " 2012: " + Data_Europa.find(trouvePays)[Choix2012] + " " + unite document.getElementById("C2013").innerHTML = label + " 2013: " + Data_Europa.find(trouvePays)[Choix2013] + " " + unite } } // Gestion des boutons année function SelectionAnnee(b) { $('#help').css('display', 'none') Choix = ""; Annee = b Choix = Indic + Annee Choix2 = Indic + Annee Choix2 = Choix2.replace("_An", " ") var Test = Annee.slice(2, 6) switch (Test) { case '2011': $("#2011").addClass("selectedIndic"); $("#2012").removeClass("selectedIndic"); $("#2013").removeClass("selectedIndic"); break; case '2012': $("#2012").addClass("selectedIndic"); $("#2011").removeClass("selectedIndic"); $("#2013").removeClass("selectedIndic"); break; case '2013': $("#2013").addClass("selectedIndic"); $("#2011").removeClass("selectedIndic"); $("#2012").removeClass("selectedIndic"); break; } if (Indic === "") { alert("Veuillez choisir un indicateur") } else { PopulationChoix = "Population " + Annee.replace("An", "") PIBChoix = "Pib " + Annee.replace("An", "") UpdateStyle(Choix) drawTable(4, Choix3); drawTable(5) $('#listepays').css({ 'display': 'block' }) } }; // Gestion des boutons groupe dans l'onglet tableau de bord function FiltrerGroupe(c) { Choix3 = c switch (Choix3) { case 'reset': $("#reset").addClass("selectedGrp"); $("#GRP6").removeClass("selectedGrp"); $("#GRP15").removeClass("selectedGrp"); $("#GRP28").removeClass("selectedGrp"); break; case 'GRP6': $("#GRP6").addClass("selectedGrp"); $("#reset").removeClass("selectedGrp"); $("#GRP15").removeClass("selectedGrp"); $("#GRP28").removeClass("selectedGrp"); break; case 'GRP15': $("#GRP15").addClass("selectedGrp"); $("#reset").removeClass("selectedGrp"); $("#GRP6").removeClass("selectedGrp"); $("#GRP28").removeClass("selectedGrp"); break; case 'GRP28': $("#GRP28").addClass("selectedGrp"); $("#reset").removeClass("selectedGrp"); $("#GRP6").removeClass("selectedGrp"); $("#GRP15").removeClass("selectedGrp"); break; } drawTable(4, Choix3) }; // Gestion des onglets function Hide(c, d) { $('#help').css('display', 'none') if (c === "#container1") { $('.Grp').css("display", "block") if (T == 0){ $("#reset").addClass("selectedGrp"); $("#GRP6").removeClass("selectedGrp"); $("#GRP15").removeClass("selectedGrp"); $("#GRP28").removeClass("selectedGrp");} $("#TDB").addClass("selectedMenu"); $("#CARTO").removeClass("selectedMenu") T = 1 } else { $('.Grp').css("display", "none") $("#CARTO").addClass("selectedMenu"); $("#TDB").removeClass("selectedMenu") } $(c).fadeOut(500, function() {}) $(d).fadeIn(500, function() {}) } function Help() { $('#infobox').fadeOut(0, function() {}) $('#help').fadeIn(0, function() {}) $('#listepays').css({ 'margin-top': 5, 'display': 'block' }) } /* -----------------------------------------------------FIN------------------------------------------------------------------------*/
da6a20fce74ef416d33af3b8927d9ed23ccae4c8
{ "blob_id": "da6a20fce74ef416d33af3b8927d9ed23ccae4c8", "branch_name": "refs/heads/master", "committer_date": "2016-04-04T11:49:58", "content_id": "eb62d81632fdfc225e987106dc7fc7688f90ddaf", "detected_licenses": [ "MIT" ], "directory_id": "e2f2cd07000df1439ef251a68ce44a8f7398f40e", "extension": "js", "filename": "script.js", "fork_events_count": 0, "gha_created_at": "2016-02-24T19:33:24", "gha_event_created_at": "2016-03-29T15:15:20", "gha_language": null, "gha_license_id": null, "github_id": 52468915, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 42984, "license": "MIT", "license_type": "permissive", "path": "/lib/script.js", "provenance": "stack-edu-0040.json.gz:110246", "repo_name": "BKRSH/bkrsh.github.io", "revision_date": "2016-04-04T11:49:58", "revision_id": "9d9b2a6a9a8e15a8759b2e7087546b292b809f65", "snapshot_id": "392d7278460d61509566e4915d59ba476ba545d0", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/BKRSH/bkrsh.github.io/9d9b2a6a9a8e15a8759b2e7087546b292b809f65/lib/script.js", "visit_date": "2021-01-13T00:56:34.727819", "added": "2024-11-19T00:06:53.826878+00:00", "created": "2016-04-04T11:49:58", "int_score": 2, "score": 2.390625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0058.json.gz" }