text
stringlengths
20
812k
id
stringlengths
40
40
metadata
dict
# Change log This document represents a high-level overview of changes made to this project. It will not list every miniscule change, but will allow you to view - at a glance - what to expact from upgrading to a new version. ## [unpublished] ### Added ### Changed ### Fixed ### Security ### Deprecated ### Removed ## [0.1.3] - 2018-06-30 ### Fixed - Prevent `timespan_in_words`, when limited to one output unit, from returning sub-unit timespans as '0'. This fixes eg `timespan_in_words(30, unit: :minutes)` from returning '0m' instead of '0.5 min'. ## [0.1.2] - 2017-01-06 ### Fixed - Removes seconds part of output of `timespan_in_words` in single-unit mode due to floating point inaccuracies. ## [0.1.1] - 2017-01-03 ### Fixed - Missing rounding within `::timespan_in_words.` ## [0.1.0] - 2017-01-03 ### Added - Function to convert timespan in seconds to human-readable words. - Function to convert integer to string with thousands-separator - Function to convert fraction to rounded percentage
e7a9a979b9ae7ae26b8b6efdaccaddc42cbbe5c7
{ "blob_id": "e7a9a979b9ae7ae26b8b6efdaccaddc42cbbe5c7", "branch_name": "refs/heads/master", "committer_date": "2018-06-30T20:48:06", "content_id": "f40143567272ee45a7e35126dcfd609afda91f99", "detected_licenses": [ "Apache-2.0" ], "directory_id": "d49324af037ad6a72b09b76159a9d8bda24b6bc6", "extension": "md", "filename": "CHANGELOG.md", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 108839641, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1028, "license": "Apache-2.0", "license_type": "permissive", "path": "/CHANGELOG.md", "provenance": "stack-edu-markdown-0008.json.gz:258550", "repo_name": "Dragaera/silverball", "revision_date": "2018-06-30T20:48:06", "revision_id": "fdfa418ecff918b896fbaaf8973d5fa886671805", "snapshot_id": "be1a3a18996a46ea92d920af70914d4d6bee736b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Dragaera/silverball/fdfa418ecff918b896fbaaf8973d5fa886671805/CHANGELOG.md", "visit_date": "2021-09-17T10:49:29.152557", "added": "2024-11-18T21:40:34.060784+00:00", "created": "2018-06-30T20:48:06", "int_score": 3, "score": 3.015625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0008.json.gz" }
/* * Write a program to check a C program for rudimentary syntax errors like * unbalanced parentheses, brackets, and braces. Don't forget about * quotes, both single and double, escape sequences, and comments. (This * program is hard if you do it in full generality.) */ #include <stdio.h> int rcomment(int c); void incomment(int c, int d); void inquotes(int c); void parsing_error(char *msg); main() { int c, parenthesis, brackets, braces; parenthesis = brackets = braces = 0; while ((c = getchar()) != EOF) { c = rcomment(c); if ('(' == c) { parenthesis++; } else if (')' == c) { parenthesis--; } else if ('[' == c) { brackets++; } else if (']' == c) { brackets--; } else if ('{' == c) { braces++; } else if ('}' == c) { braces--; } } if (parenthesis) { printf("Syntax error: unbalanced parenthesis (%d)\n", parenthesis); } if (brackets) { printf("Syntax error: unbalanced brackets (%d)\n", brackets); } if (braces) { printf("Syntax error: unbalanced braces (%d)\n", braces); } return 0; } int rcomment(int c) { int d; if ('/' == c) { d = getchar(); if ('*' == d) { incomment(c, d); } else { return rcomment(d); } } else if ('\'' == c || '"' == c) { inquotes(c); } return c; } void incomment(int c, int d) { int search; search = 1; while (search) { if ('*' == c && '/' == d) { search = 0; } else { c = d; d = getchar(); if (EOF == d) { parsing_error("end of file with unclosed comment"); search = 0; } else if ('/' == c && '*' == d) { parsing_error("nested comments"); search = 0; } } } } void inquotes(int c) { int d, search; search = 1; while (search) { if ((d = getchar()) == EOF) { parsing_error("end of file whith unclosed quote"); search = 0; } else if (d == c) { search = 0; } else if ('\\' == d) { d = getchar(); } } } void parsing_error(char *msg) { printf("\nParsing error: %s\n", msg); }
d22c0fda708b597321415f08336a67ceda581cc5
{ "blob_id": "d22c0fda708b597321415f08336a67ceda581cc5", "branch_name": "refs/heads/master", "committer_date": "2019-05-18T13:46:54", "content_id": "0b8f009cd3659a3f176d973585dc58f46216faca", "detected_licenses": [ "Apache-2.0" ], "directory_id": "d17a6d263cb0739f40e524d9005958501b7d6014", "extension": "c", "filename": "exercise_01-24.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 169207776, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1964, "license": "Apache-2.0", "license_type": "permissive", "path": "/ch_01/exercise_01-24.c", "provenance": "stack-edu-0000.json.gz:136388", "repo_name": "daltonvlm/the-c-programming-language-solutions", "revision_date": "2019-05-18T13:46:54", "revision_id": "523e637665175e7c49294f028ba11e905991c2e0", "snapshot_id": "587171d264803df65210419cfc7238fd17577cc5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/daltonvlm/the-c-programming-language-solutions/523e637665175e7c49294f028ba11e905991c2e0/ch_01/exercise_01-24.c", "visit_date": "2020-04-21T00:50:55.428757", "added": "2024-11-18T22:07:58.276611+00:00", "created": "2019-05-18T13:46:54", "int_score": 4, "score": 3.65625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0018.json.gz" }
from multiprocessing import Process, Manager, Pool, cpu_count import sys import os import re import subprocess import time import random import numpy as np def battle(pt1, opponents): wincnt = 0 for pt2 in opponents: if pt1.split('|')[1] == pt2.split('|')[1] and pt1.split('|')[1] == 'ditto': if pt1.split('|')[6].split(',')[0] > pt2.split('|')[6].split(',')[0]: wincnt += 1 proc = subprocess.run(['node', './bot/.sim-dist/examples/battle-stream-example',pt1, pt2], stdout=subprocess.PIPE, text=True) battleData = proc.stdout.split('\n') try: result = str([i for i in battleData if re.match('\|win\|Bot \d',i)][0]) except: print(battleData) if result == '|win|Bot 1': wincnt += 1 return wincnt def wrapper(args): return battle(*args) if __name__ == '__main__': path = './train_data03/' opponent = open(path + 'extract.txt').read().split('\n') speciesCnt = 80 prop = [opponent[i*5] for i in range(speciesCnt)] battleData = list() #battle count = 80 * 80 * 5 => 32000 (about 12800s, 3.5h) s = time.time() for i in prop: print('\r%d' % (time.time()-s), end='') tmp = list() que = [[i,opponent[j*5:j*5+5]] for j in range(speciesCnt)] core = cpu_count() p = Pool(core) tmp = p.map(wrapper, que) poke = [i.split('|')[1]] poke.extend(tmp) poke = [str(j) for j in poke] battleData.append(poke) # for test pokemons = [i.split('|')[1] for i in prop] pokemons = ['FtF'] + pokemons with open(path + 'FtFvalue.txt', 'w') as f: f.write(','.join(pokemons)) f.write('\n') for i in battleData: f.write(','.join(i)) f.write('\n')
89af20ea213622a0c02f9bfbfe4a0d7a0e9fbba7
{ "blob_id": "89af20ea213622a0c02f9bfbfe4a0d7a0e9fbba7", "branch_name": "refs/heads/main", "committer_date": "2021-07-07T14:39:33", "content_id": "06259edf5e7731e8c51e334fce05e363a36a7574", "detected_licenses": [ "MIT" ], "directory_id": "572a30163ead366f3bc67157238b60809a5ebba7", "extension": "py", "filename": "FtFeval.py", "fork_events_count": 1, "gha_created_at": "2020-12-02T08:07:51", "gha_event_created_at": "2021-07-07T14:39:34", "gha_language": "TypeScript", "gha_license_id": "MIT", "github_id": 317792016, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1898, "license": "MIT", "license_type": "permissive", "path": "/FtFeval.py", "provenance": "stack-edu-0064.json.gz:503415", "repo_name": "ogadra/party-make", "revision_date": "2021-07-07T14:39:33", "revision_id": "9606d360b524a8b1affc0ccfe1263adb568bc04e", "snapshot_id": "de8c014d598adaf07082b81678e42d9bca0b767b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ogadra/party-make/9606d360b524a8b1affc0ccfe1263adb568bc04e/FtFeval.py", "visit_date": "2023-06-11T17:32:19.859402", "added": "2024-11-19T01:02:16.063818+00:00", "created": "2021-07-07T14:39:33", "int_score": 3, "score": 2.5625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0082.json.gz" }
#include "regex_yaml.h" #include "stream.h" #include "gtest/gtest.h" using YAML::RegEx; using YAML::Stream; namespace { const auto MIN_CHAR = Stream::eof() + 1; TEST(RegExTest, Empty ) { RegEx empty; EXPECT_TRUE(empty . Matches (std::string()) ); EXPECT_EQ(0, empty. Match (std::string()) ); for ( int i = MIN_CHAR; i < 128; ++i) { auto str = std::string(1, char(i)); EXPECT_FALSE(empty . Matches(str) ); EXPECT_EQ(-1, empty. Match(str) ); } } TEST(RegExTest, Range ) { for ( int i = MIN_CHAR; i < 128; ++i) { for ( int j = MIN_CHAR; j < 128; ++j) { RegEx ex((char) i, (char) j); for ( int k = MIN_CHAR; k < 128; ++k) { auto str = std::string(1, char(k)); if (i <= k&& k <= j) { EXPECT_TRUE(ex . Matches(str) ); EXPECT_EQ(1, ex. Match(str) ); } else { EXPECT_FALSE(ex . Matches(str) ); EXPECT_EQ(-1, ex. Match(str) ); } } } } } TEST(RegExTest, EmptyString ) { RegEx ex = RegEx(std::string()); EXPECT_TRUE(ex . Matches (std::string()) ); EXPECT_EQ(0, ex. Match (std::string()) ); // Matches anything, unlike RegEx()! EXPECT_TRUE(ex . Matches(std::string("hello") )); EXPECT_EQ(0, ex. Match(std::string("hello") )); } TEST(RegExTest, SingleCharacterString ) { for ( int i = MIN_CHAR; i < 128; ++i) { RegEx ex(std::string(1, (char) i)); for ( int j = MIN_CHAR; j < 128; ++j) { auto str = std::string(1, char(j)); if (j == i) { EXPECT_TRUE(ex . Matches(str) ); EXPECT_EQ(1, ex. Match(str) ); // Match at start of string only! std::string prefixed = std::string(1, i + 1) + std::string("prefix: ") + str; EXPECT_FALSE(ex . Matches(prefixed) ); EXPECT_EQ(-1, ex. Match(prefixed) ); } else { EXPECT_FALSE(ex . Matches(str) ); EXPECT_EQ(-1, ex. Match(str) ); } } } } TEST(RegExTest, MultiCharacterString ) { RegEx ex(std::string("ab")); EXPECT_FALSE(ex . Matches(std::string("a") )); EXPECT_EQ(-1, ex. Match(std::string("a") )); EXPECT_TRUE(ex . Matches(std::string("ab") )); EXPECT_EQ(2, ex. Match(std::string("ab") )); EXPECT_TRUE(ex . Matches(std::string("abba") )); EXPECT_EQ(2, ex. Match(std::string("abba") )); // match at start of string only! EXPECT_FALSE(ex . Matches(std::string("baab") )); EXPECT_EQ(-1, ex. Match(std::string("baab") )); } TEST(RegExTest, OperatorNot ) { RegEx ex = !RegEx(std::string("ab")); EXPECT_TRUE(ex . Matches(std::string("a") )); EXPECT_EQ(1, ex. Match(std::string("a") )); EXPECT_FALSE(ex . Matches(std::string("ab") )); EXPECT_EQ(-1, ex. Match(std::string("ab") )); EXPECT_FALSE(ex . Matches(std::string("abba") )); EXPECT_EQ(-1, ex. Match(std::string("abba") )); // match at start of string only! EXPECT_TRUE(ex . Matches(std::string("baab") )); // Operator not causes only one character to be matched. EXPECT_EQ(1, ex. Match(std::string("baab") )); } TEST(RegExTest, OperatorOr ) { for ( int i = MIN_CHAR; i < 127; ++i) { for ( int j = i + 1; j < 128; ++j) { auto iStr = std::string(1, char(i)); auto jStr = std::string(1, char(j)); RegEx ex1 = RegEx(iStr) | RegEx(jStr); RegEx ex2 = RegEx(jStr) | RegEx(iStr); for ( int k = MIN_CHAR; k < 128; ++k) { auto str = std::string(1, char(k)); if (i == k || j == k) { EXPECT_TRUE(ex1 . Matches(str) ); EXPECT_TRUE(ex2 . Matches(str) ); EXPECT_EQ(1, ex1. Match(str) ); EXPECT_EQ(1, ex2. Match(str) ); } else { EXPECT_FALSE(ex1 . Matches(str) ); EXPECT_FALSE(ex2 . Matches(str) ); EXPECT_EQ(-1, ex1. Match(str) ); EXPECT_EQ(-1, ex2. Match(str) ); } } } } } TEST(RegExTest, OperatorOrShortCircuits ) { RegEx ex1 = RegEx(std::string("aaaa")) | RegEx(std::string("aa")); RegEx ex2 = RegEx(std::string("aa")) | RegEx(std::string("aaaa")); EXPECT_TRUE(ex1 . Matches(std::string("aaaaa") )); EXPECT_EQ(4, ex1. Match(std::string("aaaaa") )); EXPECT_TRUE(ex2 . Matches(std::string("aaaaa") )); EXPECT_EQ(2, ex2. Match(std::string("aaaaa") )); } TEST(RegExTest, OperatorAnd ) { RegEx emptySet = RegEx('a') & RegEx(); EXPECT_FALSE(emptySet . Matches(std::string("a") )); } TEST(RegExTest, OperatorAndShortCircuits ) { RegEx ex1 = RegEx(std::string("aaaa")) & RegEx(std::string("aa")); RegEx ex2 = RegEx(std::string("aa")) & RegEx(std::string("aaaa")); EXPECT_TRUE(ex1 . Matches(std::string("aaaaa") )); EXPECT_EQ(4, ex1. Match(std::string("aaaaa") )); EXPECT_TRUE(ex2 . Matches(std::string("aaaaa") )); EXPECT_EQ(2, ex2. Match(std::string("aaaaa") )); } TEST(RegExTest, OperatorPlus ) { RegEx ex = RegEx(std::string("hello ")) + RegEx(std::string("there")); EXPECT_TRUE(ex . Matches(std::string("hello there") )); EXPECT_FALSE(ex . Matches(std::string("hello ") )); EXPECT_FALSE(ex . Matches(std::string("there") )); EXPECT_EQ(11, ex. Match(std::string("hello there") )); } TEST(RegExTest, StringOr ) { std::string str = "abcde"; RegEx ex = RegEx(str, YAML::REGEX_OR); for ( size_t i = 0; i<str. size(); ++i) { EXPECT_TRUE(ex . Matches(str . substr(i, 1))); EXPECT_EQ(1, ex. Match(str . substr(i, 1))); } EXPECT_EQ(1, ex. Match(str) ); } } // namespace
e245caae3f36745603b7df007b5d30bdc48aacf8
{ "blob_id": "e245caae3f36745603b7df007b5d30bdc48aacf8", "branch_name": "refs/heads/main", "committer_date": "2021-03-02T02:06:42", "content_id": "8a2f3bdd5216f9d965b1e2e793be92bba868ff44", "detected_licenses": [ "MIT" ], "directory_id": "7b036019d714dc0b7b330cd3645d668b4d6eb797", "extension": "cpp", "filename": "regex_test.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": 4851, "license": "MIT", "license_type": "permissive", "path": "/include/common/yaml-cpp/test/regex_test.cpp", "provenance": "stack-edu-0007.json.gz:96428", "repo_name": "andres-fernandez-fuks/taller_wolfenstein3D", "revision_date": "2021-03-02T02:06:42", "revision_id": "0c970f5f24345ca2179be246bff93b7c2b78fb5a", "snapshot_id": "e06278c0953ab9cfa24d2aceeac6ddcabb4d42e4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/andres-fernandez-fuks/taller_wolfenstein3D/0c970f5f24345ca2179be246bff93b7c2b78fb5a/include/common/yaml-cpp/test/regex_test.cpp", "visit_date": "2023-03-17T02:01:26.386039", "added": "2024-11-18T22:01:43.722228+00:00", "created": "2021-03-02T02:06:42", "int_score": 3, "score": 2.859375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0025.json.gz" }
import React from 'react'; import { shallow } from 'enzyme'; import CreateUserForm from '../CreateUserForm'; jest.mock('utils/createUser'); import createUser from '../../../utils/createUser'; describe('CreateUserForm', () => { it('renders', () => { const wrapper = shallow(<CreateUserForm />); expect(wrapper).toBeTruthy(); }); it('should have three inputs: first name, last name, and email', () => { const wrapper = shallow(<CreateUserForm />); const inputs = wrapper.find('InputField'); expect(inputs.length).toEqual(3); }); it('should have a submit button', () => { const wrapper = shallow(<CreateUserForm />); const submitButton = wrapper.find('button'); expect(submitButton.exists()).toBeTruthy(); expect(submitButton.text()).toBeTruthy(); expect(submitButton.prop('type')).toEqual('submit'); }); it('should preventDefault and call the createUser function onSubmit with the correct values', () => { const preventDefaultSpy = jest.fn(); const wrapper = shallow(<CreateUserForm />); const form = wrapper.find('form').first(); form.simulate('submit', { preventDefault: preventDefaultSpy, // this shouldn't matter, read from state target: [], }); expect(preventDefaultSpy).toHaveBeenCalled(); expect(createUser).toHaveBeenCalled(); }); });
a095508a2facd5960f729286a7f0e4040cdf5c36
{ "blob_id": "a095508a2facd5960f729286a7f0e4040cdf5c36", "branch_name": "refs/heads/master", "committer_date": "2019-10-08T16:43:11", "content_id": "59d7d5b8ab4c5fb9abb14da4a3a54c1457d28db2", "detected_licenses": [ "MIT" ], "directory_id": "32a2d9c98656cfdf55882761115bab83773db6cf", "extension": "js", "filename": "index.test.js", "fork_events_count": 0, "gha_created_at": "2019-10-07T16:02:37", "gha_event_created_at": "2022-12-11T08:32:37", "gha_language": "JavaScript", "gha_license_id": "MIT", "github_id": 213427311, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1358, "license": "MIT", "license_type": "permissive", "path": "/app/components/CreateUserForm/tests/index.test.js", "provenance": "stack-edu-0036.json.gz:357326", "repo_name": "mrterry06/react-workshop", "revision_date": "2019-10-08T16:43:11", "revision_id": "c8333b8258ef8343d53295e9bed90ed3c0de27fd", "snapshot_id": "e01e97a4ed9c5747031f691a8386690f7cc526d8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mrterry06/react-workshop/c8333b8258ef8343d53295e9bed90ed3c0de27fd/app/components/CreateUserForm/tests/index.test.js", "visit_date": "2023-01-09T16:32:38.559271", "added": "2024-11-18T21:13:38.782779+00:00", "created": "2019-10-08T16:43:11", "int_score": 2, "score": 2.3125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0054.json.gz" }
#include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <netinet/in.h> #include <netinet/ip_icmp.h> #include <stdio.h> #include <string.h> #include <ifaddrs.h> #include "icmp_utils.h" void handle_socket_creating_error(); void handle_socket_bind_error(); void handle_socket_nonbloc_mode_error(); uint16_t get_process_id(); uint32_t get_current_host_address(); uint16_t calculate_checksum(void *data, int length); static uint16_t sequence_number = 1; int create_raw_icmp_socket() { int socket_descriptor = 0; if ((socket_descriptor = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) == -1) { handle_socket_creating_error(); return -1; } return socket_descriptor; } int bind_socket_to_all_interfaces(int socket_descriptor) { struct sockaddr_in socket_address; socket_address.sin_addr.s_addr = htonl(INADDR_ANY); socket_address.sin_family = AF_INET; socket_address.sin_port = htons(0); if (bind(socket_descriptor, (const struct sockaddr*)&socket_address, sizeof(socket_address)) == -1) { handle_socket_bind_error(); return -1; } return 0; } int set_socket_ttl_option(int socket_descriptor, int ttl) { if (setsockopt(socket_descriptor, SOL_IP, IP_TTL, &ttl, sizeof(ttl)) == -1) { perror("set socket option failed: ttl\n"); return -1; } return 0; } int set_socket_nonblock_mode(int socket_descriptor) { int socket_flags = 0; socket_flags = fcntl(socket_descriptor, F_GETFL); socket_flags |= O_NONBLOCK; if (fcntl(socket_descriptor, F_SETFL, socket_flags) == -1) { handle_socket_nonbloc_mode_error(); return -1; } return 0; } void close_socket(int socket_descriptor) { if (close(socket_descriptor) == -1) { perror("socket closing error.\n"); } } void initialize_echo_request(uint32_t src, uint32_t dst, uint32_t ttl, struct ECHO_REQUEST* request) { int index = 0; memset(request, 0, sizeof(struct ECHO_REQUEST)); request -> icmp_header.type = ICMP_ECHO; request -> icmp_header.code = 0; request -> icmp_header.id = get_process_id(); request -> icmp_header.sequence_number = sequence_number++; request -> ip_header.version = 4; request -> ip_header.header_length = IP_HEADER_LENGTH; request -> ip_header.type_of_service = 0; request -> ip_header.total_length = htons(sizeof(struct ECHO_REQUEST)); request -> ip_header.flag_off = 0; request -> ip_header.ttl = (uint8_t)ttl; request -> ip_header.protocol = IPPROTO_ICMP; request -> ip_header.src_address = src ? src : get_current_host_address(); request -> ip_header.dst_address = dst; request -> ip_header.checksum = calculate_checksum(&(request -> ip_header), sizeof(struct IP_HEADER)); for (index = 0; index < FILL_DATASIZE; index ++) { request -> data[index] = '0' + index; } request -> data[index] = '\0'; request -> icmp_header.checksum = calculate_checksum( &(request -> icmp_header), sizeof(struct ICMP_HEADER) + FILL_DATASIZE ); } int send_echo_request(int socket_descriptor, struct ECHO_REQUEST request) { return 0; } int wait_echo_reply(int socket_descriptor, struct ECHO_REPLY* reply) { return 0; } void print_echo_reply(struct ECHO_REPLY reply) { } uint16_t get_process_id() { return (uint16_t)getpid(); } uint32_t get_current_host_address() { struct ifaddrs *addresses, *temp; struct sockaddr_in *p_address, *current_address; getifaddrs(&addresses); temp = addresses; while (temp) { if (temp -> ifa_addr && temp -> ifa_addr -> sa_family == AF_INET) { p_address = (struct sockaddr_in *) temp -> ifa_addr; } temp = temp -> ifa_next; } memcpy(current_address, p_address, sizeof(struct sockaddr_in)); freeifaddrs(addresses); return current_address -> sin_addr.s_addr; } uint16_t calculate_checksum(void *data, int length) { uint16_t *buffer = data; uint32_t checksum = 0; uint16_t result; for (checksum = 0; length > 1; length -= 2 ) { checksum += *buffer++; } if (length == 1) { checksum += *(unsigned char*)buffer; } checksum = (checksum >> 16) + (checksum & 0xFFFF); checksum += (checksum >> 16); result = (uint16_t) ~checksum; return result; } void handle_socket_creating_error() { int error_number = errno; perror("socket creating failed:\n"); switch(error_number) { case EACCES: perror("Permission to create a socket of the specified type and/or protocol is denied.\n"); break; case EAFNOSUPPORT: perror("The implementation does not support the specified address family.\n"); break; case EPROTONOSUPPORT: perror("The protocol type or the specified protocol is not supported within this domain.\n"); break; default: perror("Uncknown error.\n"); break; } } void handle_socket_bind_error() { int error_number = errno; perror("socket binding failed:\n"); switch(error_number) { case EACCES: perror("The address is protected, and the user is not the superuser.\n"); break; case EADDRINUSE: perror("The given address is already in use.\n"); break; default: perror("Unknown error.\n"); break; } } void handle_socket_nonbloc_mode_error() { int error_number = errno; perror("set socket nonblock mode failed:\n"); switch(error_number) { case EACCES: perror("Operation is prohibited by locks held by other processes.\n"); break; default: perror("Unknown error.\n"); break; } }
86c217255eba7066051e4fd6b0a6e890bdb34266
{ "blob_id": "86c217255eba7066051e4fd6b0a6e890bdb34266", "branch_name": "refs/heads/master", "committer_date": "2017-03-15T09:16:21", "content_id": "1cb3f5fae3d370d1d1e022185044b7a47583fe7d", "detected_licenses": [ "MIT" ], "directory_id": "1a07656487789bfe4b3998762e6c0ab098672cc9", "extension": "c", "filename": "icmp_utils.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 81859027, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5919, "license": "MIT", "license_type": "permissive", "path": "/ICMP/Ping_v1/icmp_utils.c", "provenance": "stack-edu-0000.json.gz:363014", "repo_name": "AntonPashkowskiy/Networks", "revision_date": "2017-03-15T09:16:21", "revision_id": "1e5850774fda76cb4f1a3210a7e609560ca5e40c", "snapshot_id": "3755352c9dc765b1eb7318c56ce41b06049066be", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/AntonPashkowskiy/Networks/1e5850774fda76cb4f1a3210a7e609560ca5e40c/ICMP/Ping_v1/icmp_utils.c", "visit_date": "2021-01-22T07:52:11.314481", "added": "2024-11-18T22:40:00.313307+00:00", "created": "2017-03-15T09:16:21", "int_score": 3, "score": 2.515625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0018.json.gz" }
import { FabrixApp } from '@fabrix/fabrix' import { FabrixGeneric } from '@fabrix/fabrix/dist/common' import { Broadcast } from './Broadcast' import { isArray } from 'lodash' import { regexdot } from '@fabrix/regexdot' import { BroadcastEvent } from './api/models' import { __await } from 'tslib' import { BroadcastEntity } from './BroadcastEntity' export interface BroadcastSubscriberParams { app: FabrixApp channel: BroadcastChannel event: BroadcastEvent options: {[key: string]: any} broker: {[key: string]: any}, broadcaster?: Broadcast } export class BroadcastSubscriber { public channel: BroadcastChannel public event: BroadcastEvent public options: {[key: string]: any} public broker: {[key: string]: any} public broadcaster: Broadcast public isAcknowledged: boolean constructor( public app: FabrixApp, { channel, event, options, broker, broadcaster }: { channel: BroadcastChannel, event: BroadcastEvent, options: {[key: string]: any}, broker: {[key: string]: any}, broadcaster?: Broadcast } ) { this.app = app this.channel = channel this.event = event this.options = options this.broker = broker this.broadcaster = broadcaster this.isAcknowledged = false } get name() { return this.constructor.name } async run (): Promise<BroadcastSubscriber> { return Promise.resolve(this) } /** * Publishes Event to eligible "rooms" */ async publish (): Promise<BroadcastSubscriber> { const json = this.event.toJSON() const rooms = this.channel.patterns(this.broker.pattern_raw, this.event) rooms.forEach(v => { // Bad because this may be or may not be async this.app.sockets.room(v).clients((ids = []) => { this.app.log.debug(`Publishing ${v} to ${(ids || []).length} subscribers`) }) // Send the JSON to the room this.app.sockets.room(v).write(json) }) return Promise.resolve(this) } // /** // * Acknowledge the event // */ // async ack(): Promise<any> { // if (!this.isAcknowledged) { // this.isAcknowledged = true // return Promise.resolve([this.event, this.options]) // } // else { // this.app.log.warn(`${this.name} attempting to ack a message that already responded`) // return Promise.resolve([this.event, this.options]) // } // } // // /** // * Don't Acknowledge the event // */ // async nack(): Promise<any> { // if (!this.isAcknowledged) { // this.isAcknowledged = true // return Promise.reject([this.event, this.options]) // } // else { // this.app.log.warn(`${this.name} attempting to nack a message that already responded`) // return Promise.reject([this.event, this.options]) // } // } // // /** // * Reject the event // */ // async reject(): Promise<any> { // if (!this.isAcknowledged) { // this.isAcknowledged = true // return Promise.reject([this.event, this.options]) // } // else { // this.app.log.warn(`${this.name} attempting to reject a message that already responded`) // return Promise.reject([this.event, this.options]) // } // } } export class BroadcastChannel extends BroadcastEntity { private _channel private _subscribers: Map<string, string> = new Map() public permissions: Map<string, any> = new Map() constructor(app: FabrixApp) { super(app, 'channels') } /** * Returns the socket channel */ get channel() { return this._channel } /** * Returns the BroadcastSubscribers */ get subscribers() { return this._subscribers } hasSubscriber(name) { return this._subscribers.has(name) } // Initial Function to run when a Socket connects this BroadcastChannel initialize() { } /** * Returns the possible patterns for an event O(n) * @param pattern * @param event */ patterns(pattern, event) { // Add the raw to the query const queryOr = new Set([`${pattern}`]) let built = pattern // Grab the keys to build the OR query const { keys } = regexdot(pattern) // If the keys are viable if ( keys !== false && typeof keys !== 'boolean' && isArray(keys) ) { // If normal object, use it, if an array, grab the first as the basis const compare = !isArray(event.data) ? event.data : event.data[0] keys.forEach(k => { if (k && compare && compare[k]) { built = built.replace(`:${k}`, `${compare[k]}`) // Add a fully built version queryOr.add(built) // Add a just replace single param version const singleParam = (`${pattern}`).replace(`:${k}`, `${compare[k]}`) queryOr.add(singleParam) } }) } return Array.from(queryOr).map(k => { return `${this.name}.${k}` }) } /** * Called when a spark first joins a room * @param spark * @param room */ subscribed(spark, room) { return } /** * Called when a spark first leaves a room * @param spark * @param room */ unsubscribed(spark, room) { return } disconnect(spark, data) { return } /** * Destroys the Channel and all connections to it */ destroy() { // this.channel.destroy() } }
00ea358cea94d0e97f870956112ed2998b28565e
{ "blob_id": "00ea358cea94d0e97f870956112ed2998b28565e", "branch_name": "refs/heads/master", "committer_date": "2020-07-20T18:51:43", "content_id": "b8e3bd04ff78f13487e7a7d8db9bfff3ceff7a0f", "detected_licenses": [ "MIT" ], "directory_id": "e5daa87abf8b211abc2984f9df6df6efe91f8efd", "extension": "ts", "filename": "BroadcastChannel.ts", "fork_events_count": 0, "gha_created_at": "2019-09-16T16:09:54", "gha_event_created_at": "2022-12-30T18:41:06", "gha_language": "TypeScript", "gha_license_id": "MIT", "github_id": 208843232, "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5348, "license": "MIT", "license_type": "permissive", "path": "/lib/BroadcastChannel.ts", "provenance": "stack-edu-0072.json.gz:856648", "repo_name": "fabrix-app/spool-broadcast", "revision_date": "2020-07-20T18:51:43", "revision_id": "ce1c01f582d77074e0c8b7304c8e0db86e57528f", "snapshot_id": "3446d3f833d11054db0c0c8a52af25b4c62f52fc", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/fabrix-app/spool-broadcast/ce1c01f582d77074e0c8b7304c8e0db86e57528f/lib/BroadcastChannel.ts", "visit_date": "2023-01-12T02:08:33.326390", "added": "2024-11-18T21:36:12.544116+00:00", "created": "2020-07-20T18:51:43", "int_score": 2, "score": 2.265625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0090.json.gz" }
<?php // If it's going to need the database, then it's // probably smart to require it before we start. require_once(LIB_PATH.DS.'database.php'); class Libraries extends DatabaseObject { protected static $table_name="library_code"; protected static $db_fields = array('id', 'library_code', 'library'); public $id; public $library_code; public $library; public function code_name() { if(isset($this->library_code) && isset($this->library)) { return $this->library_code . " " . $this->library; } else { return ""; } } public static function lib_sql_where($keycode, $keyname){ $sql = ""; if($keycode !="") {$sql .=" AND library_code= '{$keycode}' "; } if($keyname !="") {$sql .=" AND LOCATE('{$keyname}',library) ";} return $sql; } public static function is_keyword($key) { global $database; $sql = "SELECT COUNT(*) FROM keywords WHERE keyword_code = '{$key}'"; $result_set = $database->query($sql); $row = $database->fetch_array($result_set); echo $key." ".array_shift($row); return array_shift($row); } public static function authenticate($library_code="") { global $database; $library_code = $database->escape_value($library_code); $sql = "SELECT * FROM library_code "; $sql .= "WHERE library_code = '{$library_code}' "; $sql .= "LIMIT 1"; $result_array = self::find_by_sql($sql); return !empty($result_array) ? array_shift($result_array) : false; } public static function library_err(){ global $database; $select_sql = "SELECT COUNT(*) FROM library_code WHERE library_code = '' OR library ='' "; $result_set = $database->query($select_sql); $rows = array_shift($database->fetch_array($result_set)); if(!empty($rows)) { return $rows; } else return '0'; } } ?>
60e2e9b85fa63737ed604b7cda3c0617bbac0b26
{ "blob_id": "60e2e9b85fa63737ed604b7cda3c0617bbac0b26", "branch_name": "refs/heads/master", "committer_date": "2018-06-17T07:09:19", "content_id": "add727224eb09ac7ebf6603900e17811fdaf3429", "detected_licenses": [ "MIT" ], "directory_id": "b69633ce1c6408b62cb7df419041f0b0ca70db1c", "extension": "php", "filename": "libraries.php", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 128732485, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1770, "license": "MIT", "license_type": "permissive", "path": "/includes/libraries.php", "provenance": "stack-edu-0047.json.gz:468839", "repo_name": "houjie1979/kamila", "revision_date": "2018-06-17T07:09:19", "revision_id": "df2321875b90d39431947301dd46873862f1847c", "snapshot_id": "b9c2fabc5b7f86b19f70a21f9463d2a8cbc8d718", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/houjie1979/kamila/df2321875b90d39431947301dd46873862f1847c/includes/libraries.php", "visit_date": "2020-03-09T10:26:26.086894", "added": "2024-11-18T23:36:52.288939+00:00", "created": "2018-06-17T07:09:19", "int_score": 3, "score": 2.671875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0065.json.gz" }
import jsdom from 'mocha-jsdom'; import React from 'react'; import chai from 'chai'; import { shallow } from 'enzyme'; import chaiEnzyme from 'chai-enzyme'; import { describe, it } from 'mocha'; import Login from './../../src/components/Login.jsx'; chai.use(chaiEnzyme()); const expect = chai.expect; describe('Login ', () => { jsdom(); it('should have 1 span tag', () => { const wrapper = shallow(<Login />); expect(wrapper.find('span')).to.have.length(1); }); it('should be a span item', () => { const wrapper = shallow(<Login />); expect(wrapper.type()).to.eql('span'); }); it('should have 1 div tag', () => { const wrapper = shallow(<Login />); expect(wrapper.find('span')).to.have.length(1); }); it('should have props for checkLogin and onSignIn', () => { const wrapper = shallow(<Login />); expect(wrapper.props().checkLogin).to.be.defined; expect(wrapper.props().onSignIn).to.be.defined; expect(wrapper.props().renderGoogleLoginButton).to.be.defined; }); it('should have 2 div tag', () => { const wrapper = shallow(<Login />); expect(wrapper).to.have.id('my-signin2'); }); it('Should have a component did mount function', () => { const wrapper = shallow(<Login />); wrapper.instance().componentDidMount(); }); it('Should have a onSignIn function', () => { const wrapper = shallow(<Login />); wrapper.instance().onSignIn(); }); });
c202ca4d375e3209fcc4c92b3b5140fd6636c207
{ "blob_id": "c202ca4d375e3209fcc4c92b3b5140fd6636c207", "branch_name": "refs/heads/master", "committer_date": "2017-05-30T14:11:29", "content_id": "281da6217f673fc281c1e25af4de3147524b6a61", "detected_licenses": [ "MIT" ], "directory_id": "016c26408c25e47a5698f43a8a7591c9cf59f458", "extension": "js", "filename": "Login.spec.js", "fork_events_count": 0, "gha_created_at": "2017-04-30T21:38:58", "gha_event_created_at": "2017-05-30T14:11:30", "gha_language": "JavaScript", "gha_license_id": null, "github_id": 89878851, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1440, "license": "MIT", "license_type": "permissive", "path": "/test/components/Login.spec.js", "provenance": "stack-edu-0045.json.gz:780634", "repo_name": "atomicman57/News-Feed-App", "revision_date": "2017-05-30T14:11:29", "revision_id": "cbd93895c20cfb088a821b217a7134777acf7416", "snapshot_id": "1ae706fa9eea177393acc22808de0772dd35ad63", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/atomicman57/News-Feed-App/cbd93895c20cfb088a821b217a7134777acf7416/test/components/Login.spec.js", "visit_date": "2021-01-20T06:27:42.187201", "added": "2024-11-19T02:42:16.722491+00:00", "created": "2017-05-30T14:11:29", "int_score": 2, "score": 2.09375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0063.json.gz" }
# Misq Misq is an official .NET Misskey library. ## Install available on nuget ## Usage ``` Csharp // Create your app instance var app = new Misq.App("https://misskey.io", "your app's secret key here"); // Authorize user var user = await app.Authorize(); // Let's post a message to Misskey user.Request("notes/create", new Dictionary<string, object> { { "text", "yee haw!" } }); ```
59a93543c11f2167d0355fb3fb7cf860a35d7e56
{ "blob_id": "59a93543c11f2167d0355fb3fb7cf860a35d7e56", "branch_name": "refs/heads/master", "committer_date": "2019-09-10T10:02:15", "content_id": "ea795d555bde0c1d5f2e0686676cd36f6ebd0f34", "detected_licenses": [ "MIT" ], "directory_id": "7039188c23a84ab63d24a7d1d9be1246a0d66cf6", "extension": "md", "filename": "README.md", "fork_events_count": 0, "gha_created_at": "2023-08-24T21:03:12", "gha_event_created_at": "2023-08-24T21:03:18", "gha_language": null, "gha_license_id": "MIT", "github_id": 682749924, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 390, "license": "MIT", "license_type": "permissive", "path": "/README.md", "provenance": "stack-edu-markdown-0006.json.gz:297632", "repo_name": "kap256/Misq", "revision_date": "2019-09-10T10:02:15", "revision_id": "9ee9d919eeed76d857f7efd2170a49d16d74c583", "snapshot_id": "7be54403b5ad394ca615602d62a2bed74820a976", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/kap256/Misq/9ee9d919eeed76d857f7efd2170a49d16d74c583/README.md", "visit_date": "2023-08-26T19:34:05.990982", "added": "2024-11-18T18:20:15.512060+00:00", "created": "2019-09-10T10:02:15", "int_score": 2, "score": 2.46875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0006.json.gz" }
#!/bin/bash for test in `find invalid_verif/ -type f` do python -c 'print("="*55)' echo -e "File : $test" ./source/krpsim_verif.py resources/simple $test if [ "$?" -eq 0 ] ; then echo -e "\e[32m Valid" else echo -e "\e[31m Invalid" fi echo -e "\e[0m" done
7ba2a0831a171221ad0c4cfccae27c408bced63e
{ "blob_id": "7ba2a0831a171221ad0c4cfccae27c408bced63e", "branch_name": "refs/heads/master", "committer_date": "2020-06-18T20:27:15", "content_id": "956435dd6fb803922fe7be899370f0fd9de2b3a1", "detected_licenses": [ "MIT" ], "directory_id": "21bb0cf526a6a7768212c0adcb42ad56887b8ddb", "extension": "", "filename": "all_wrong_verif_test", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 257394830, "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 268, "license": "MIT", "license_type": "permissive", "path": "/all_wrong_verif_test", "provenance": "stack-edu-0069.json.gz:648919", "repo_name": "ygarrot/KrpSim", "revision_date": "2020-06-18T20:27:15", "revision_id": "bb961a3719d1f2afbee993344b53ea417e8dd6c4", "snapshot_id": "7f55d4bbcf97f85de1e2ee8f39ff5c04a7eb235f", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/ygarrot/KrpSim/bb961a3719d1f2afbee993344b53ea417e8dd6c4/all_wrong_verif_test", "visit_date": "2022-11-18T09:10:46.351425", "added": "2024-11-19T01:15:35.534994+00:00", "created": "2020-06-18T20:27:15", "int_score": 3, "score": 3.0625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0087.json.gz" }
# comonadic-life Implementation of Conway's Game of Life using a comonad transformer. A simple port of https://github.com/gelisam/conway/blob/master/src/Conway.hs ## Installation ```sh git clone git://github.com/corajr/comonadic-life cd example npm install npm start ``` Visit `http://localhost:3000` in your browser and click Step to evolve. ## Available scripts ### watch `npm start` or `npm run watch` will start a development server, which hot-reloads your application when sources changes. ### serve `npm run serve` serves your application without watching for changes or hot-reloading. ### build `npm run build` bundles and minifies your application to run in production mode.
7d247618820f18b1098cf13b28ff3188dde6a7dd
{ "blob_id": "7d247618820f18b1098cf13b28ff3188dde6a7dd", "branch_name": "refs/heads/master", "committer_date": "2016-12-02T23:27:08", "content_id": "0c7804a2994e5580fcaee3db1094b974bffa89f7", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "70d5e414248f3f0e146afe6e0a28cce4c7e8319c", "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": 75132397, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 695, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/README.md", "provenance": "stack-edu-markdown-0013.json.gz:269799", "repo_name": "corajr/comonadic-life", "revision_date": "2016-12-02T23:27:08", "revision_id": "1970e3a32dca7a5e565e94466871d6db3e4ccf87", "snapshot_id": "04c0ac8014a7fe0eea98fa6df8f1d5c7a2699406", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/corajr/comonadic-life/1970e3a32dca7a5e565e94466871d6db3e4ccf87/README.md", "visit_date": "2020-06-18T13:49:10.829453", "added": "2024-11-18T22:43:10.480738+00:00", "created": "2016-12-02T23:27:08", "int_score": 3, "score": 2.859375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0013.json.gz" }
# Flubber Hi, I am Flubber. Your friendly time management utility and a companion for wonderful TailorDev/Watson time tracker. My purpose is not to replace Watson, but to bring those features you need most often to nice Gtk+ GUI and leave the power of Watson still available to you via its command line. ## Installation To install me properly you need also a branched version of Watson as its still lacking a feature from upstream which has not been merged yet. So to install that first: ``` $ pip uninstall td-watson $ git clone https://github.com/braincow/Watson.git $ cd Watson $ python setup.py install ``` After (uninstalling and) installing branched version of Watson you are ready to install Flubber: ``` $ git clone https://github.com/braincow/flubber.git $ cd flubber $ python setup.py install ``` ## Usage If installed system wide my .desktop file is also installed into /usr/share/applications and you can start me with your desktop environments application list. If I am not there however you can always execute me via "flubber" command from where setup.py installed my wrapper script (system wide default /usr/bin/) ## Support Please open an issue to receive support and to suggest improvements. ## Contributing Fork the project, create a new branch, make your changes, and submit a pull request.
77cf9e142272cee4990fa7760e5f045530c56eef
{ "blob_id": "77cf9e142272cee4990fa7760e5f045530c56eef", "branch_name": "refs/heads/master", "committer_date": "2018-04-10T08:08:25", "content_id": "c6b16f58305e2d7f0b15f6b9641f247b8f8c011e", "detected_licenses": [ "MIT" ], "directory_id": "e9a93b32c6f53a6b0de40c839841be8d9b81e384", "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": 127463989, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1322, "license": "MIT", "license_type": "permissive", "path": "/README.md", "provenance": "stack-edu-markdown-0006.json.gz:168837", "repo_name": "braincow/flubber", "revision_date": "2018-04-10T08:08:25", "revision_id": "691f1fd441d03fc9e093d9dabc7fd8940d1bef27", "snapshot_id": "efb240506477495e1e29fbdd2ea553abfb4e5c17", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/braincow/flubber/691f1fd441d03fc9e093d9dabc7fd8940d1bef27/README.md", "visit_date": "2020-03-07T11:47:56.033668", "added": "2024-11-18T22:29:55.371759+00:00", "created": "2018-04-10T08:08:25", "int_score": 3, "score": 2.8125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0006.json.gz" }
import urllib import urllib2 import json import argparse import sys from collections import Counter reload(sys) sys.setdefaultencoding('UTF8') parser = argparse.ArgumentParser(description='Send reminder emails to all invited (but not joined) members.') args = parser.parse_args() dfbToken = raw_input('Enter your Dropbox Business API App token (Team Member Management permission): ') # Get all DfB members, paging through member list if necessary def getDfbMembers(cursor): data = {"limit":100} if cursor is not None: data["cursor"] = cursor request = urllib2.Request('https://api.dropboxapi.com/2/team/members/list', json.dumps(data)) request.add_header("Authorization", "Bearer "+dfbToken) request.add_header("Content-type", 'application/json') try: response = json.loads(urllib2.urlopen(request).read()) members = response["members"] if response["has_more"]: members = members + getDfbMembers(cursor=response["cursor"]) return members # Exit on error here. Probably bad OAuth token. Show DfB response. except urllib2.HTTPError, error: parser.error(error.read()) # Sends a reminder def remind(memberId): params = {'.tag':'team_member_id','team_member_id':memberId} request = urllib2.Request('https://api.dropboxapi.com/2/team/members/send_welcome_email', data=json.dumps(params)) request.add_header("Authorization", "Bearer "+dfbToken) request.add_header("Content-type", 'application/json') try: urllib2.urlopen(request).read() except urllib2.HTTPError, error: parser.error(error.read()) members = getDfbMembers(None) print "Reminding invited members.." for member in members: if member["profile"]["status"][".tag"] == "invited": print " reminding "+member["profile"]["email"] remind(member["profile"]["team_member_id"]) print "Done"
972742c8e2f65ecdd23abf621f32032e2f7e6348
{ "blob_id": "972742c8e2f65ecdd23abf621f32032e2f7e6348", "branch_name": "refs/heads/master", "committer_date": "2021-07-09T14:45:15", "content_id": "4a06df79a6acb87bef0dffe0ac8eb8ae06eb888b", "detected_licenses": [ "Apache-2.0" ], "directory_id": "850e1bcdd5347393b51807d0c65d3f758b024b19", "extension": "py", "filename": "RemindPendingMembers.py", "fork_events_count": 25, "gha_created_at": "2015-11-06T21:43:31", "gha_event_created_at": "2020-10-02T07:45:38", "gha_language": "Python", "gha_license_id": "Apache-2.0", "github_id": 45709450, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1930, "license": "Apache-2.0", "license_type": "permissive", "path": "/Users/RemindPendingMembers.py", "provenance": "stack-edu-0064.json.gz:559858", "repo_name": "dropbox/DropboxBusinessScripts", "revision_date": "2021-07-09T14:45:15", "revision_id": "4f4c32ddd488b29e7fd16a40966761e70a758239", "snapshot_id": "12c12205f6fbc8dc90310e033ace8317969c745c", "src_encoding": "UTF-8", "star_events_count": 48, "url": "https://raw.githubusercontent.com/dropbox/DropboxBusinessScripts/4f4c32ddd488b29e7fd16a40966761e70a758239/Users/RemindPendingMembers.py", "visit_date": "2023-08-18T19:18:19.082896", "added": "2024-11-19T01:11:13.918824+00:00", "created": "2021-07-09T14:45:15", "int_score": 3, "score": 2.75, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0082.json.gz" }
package com.globant.bootcamp.LoginServiceRoot.data; import com.globant.bootcamp.LoginServiceRoot.domain.Account; import java.util.HashMap; public class LoginServiceMultipleDAO { private String message; private String lastResult; private HashMap<String, Account> accountsList; public LoginServiceMultipleDAO(){ } public LoginServiceMultipleDAO(String message, String result, HashMap accountsList) { super(); this.message = (message == null) ? "No Message" : message; this.lastResult = (result == null) ? "No Result " : result; this.accountsList = (accountsList == null) ? null : accountsList; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getLastResult() { return lastResult; } public void setLastResult(String lastResult) { this.lastResult = lastResult; } public HashMap getUserAccount() { return accountsList; } public void setUserAccount(HashMap<String, Account> accountsList) { this.accountsList = accountsList; } }
fbeca8a01e1b020af1a564c2183f5f8988ff03f9
{ "blob_id": "fbeca8a01e1b020af1a564c2183f5f8988ff03f9", "branch_name": "refs/heads/master", "committer_date": "2019-07-27T18:37:01", "content_id": "1a54166e6956bd13687959803477792744cda047", "detected_licenses": [ "Apache-2.0" ], "directory_id": "bc40d322188c8dd8e3e21954500d071d95409fbb", "extension": "java", "filename": "LoginServiceMultipleDAO.java", "fork_events_count": 0, "gha_created_at": "2019-07-05T14:08:22", "gha_event_created_at": "2019-07-27T18:37:02", "gha_language": "HTML", "gha_license_id": "Apache-2.0", "github_id": 195420006, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1168, "license": "Apache-2.0", "license_type": "permissive", "path": "/Week4/VictorMartinez/salesService/TestSaleService/src/main/java/com/globant/bootcamp/LoginServiceRoot/data/LoginServiceMultipleDAO.java", "provenance": "stack-edu-0027.json.gz:334311", "repo_name": "vmartinezsolarte/Final-Project-_-Bootcamp-2019-Globant", "revision_date": "2019-07-27T18:37:01", "revision_id": "447e60e292a920efb3af9aeddd970e2e6b84bd88", "snapshot_id": "a4cdbb078847effbdd3c3017b3769c50835c9f88", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/vmartinezsolarte/Final-Project-_-Bootcamp-2019-Globant/447e60e292a920efb3af9aeddd970e2e6b84bd88/Week4/VictorMartinez/salesService/TestSaleService/src/main/java/com/globant/bootcamp/LoginServiceRoot/data/LoginServiceMultipleDAO.java", "visit_date": "2020-06-15T23:25:09.928979", "added": "2024-11-19T00:31:04.387148+00:00", "created": "2019-07-27T18:37:01", "int_score": 2, "score": 2.40625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0045.json.gz" }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using AutoMapper; using CSharpFunctionalExtensions; using LiveClinic.Pharmacy.Core.Application.Inventory.Dtos; using LiveClinic.Pharmacy.Core.Domain.Inventory; using MediatR; using Serilog; namespace LiveClinic.Pharmacy.Core.Application.Inventory.Queries { public class GetInventory : IRequest<Result<List<InventoryDto>>> { public Guid? DrugId { get; } public GetInventory(Guid? drugId = null) { DrugId = drugId; } } public class GetInventoryHandler : IRequestHandler<GetInventory,Result<List<InventoryDto>>> { private readonly IMapper _mapper; private readonly IDrugRepository _drugRepository; public GetInventoryHandler( IMapper mapper,IDrugRepository drugRepository) { _mapper = mapper; _drugRepository = drugRepository; } public Task<Result<List<InventoryDto>>> Handle(GetInventory request, CancellationToken cancellationToken) { try { var drugs=new List<Drug>(); if(request.DrugId.HasValue) drugs = _drugRepository.LoadAll(x=>x.Id==request.DrugId.Value).ToList(); else drugs = _drugRepository.LoadAll().ToList(); var inventoryDtos = _mapper.Map<List<InventoryDto>>(drugs); return Task.FromResult(Result.Success(inventoryDtos)); } catch (Exception e) { var msg = $"Error {request.GetType().Name}"; Log.Error(e, msg); return Task.FromResult(Result.Failure<List<InventoryDto>>(msg)); } } } }
9259a5ca28aa1567a8a4968b0d79be8200ae1378
{ "blob_id": "9259a5ca28aa1567a8a4968b0d79be8200ae1378", "branch_name": "refs/heads/main", "committer_date": "2021-08-17T06:41:35", "content_id": "c9f76ec5edb9e330d3aec20f00a2201028f4a7b7", "detected_licenses": [ "MIT" ], "directory_id": "b4908c25910d718259b9197fc5e7eac19bbd7634", "extension": "cs", "filename": "GetInventroy.cs", "fork_events_count": 1, "gha_created_at": "2021-07-16T22:24:16", "gha_event_created_at": "2021-08-10T14:58:28", "gha_language": "C#", "gha_license_id": "MIT", "github_id": 386778274, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1822, "license": "MIT", "license_type": "permissive", "path": "/src/LiveClinic.Pharmacy.Core/Application/Inventory/Queries/GetInventroy.cs", "provenance": "stack-edu-0014.json.gz:360247", "repo_name": "koskedk/live-clinic", "revision_date": "2021-08-17T06:41:35", "revision_id": "4c114c20781dc1960692b078a8cd0630926feea0", "snapshot_id": "4c8e328c9b59142cf6f146060a46374dfb78df49", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/koskedk/live-clinic/4c114c20781dc1960692b078a8cd0630926feea0/src/LiveClinic.Pharmacy.Core/Application/Inventory/Queries/GetInventroy.cs", "visit_date": "2023-07-03T11:42:42.745920", "added": "2024-11-18T19:46:16.122197+00:00", "created": "2021-08-17T06:41:35", "int_score": 3, "score": 2.671875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0032.json.gz" }
(function(){ var ModalDialogService = function() { this._controller = null; }; ModalDialogService.prototype.setWidget = function(controller){ if (this._controller !== null) { throw new Error("Controller has already been set"); } if (!controller) { throw new Error("Controller must be provided"); } this._controller = controller; }; ModalDialogService.prototype.showDialog = function(title, newDirective, props) { if (this._controller === null) { throw new Error("ModalDialogWidgetController has not registered, is there a modaldialogwidget on the page?"); } this._controller.show(title, newDirective, props); }; ModalDialogService.prototype.closeDialog = function () { this._controller.hide(); }; module.exports = { ModalDialogService: ModalDialogService }; }())
7407b48b3870ee0d27514ac474afafe0cfd80070
{ "blob_id": "7407b48b3870ee0d27514ac474afafe0cfd80070", "branch_name": "refs/heads/master", "committer_date": "2019-04-14T11:15:48", "content_id": "96252d17662935d7bfe33b5dcff566530482ef32", "detected_licenses": [ "MIT" ], "directory_id": "f2745dc0a58c53ab77d0bb50b82975405636f915", "extension": "js", "filename": "modal-dialog.service.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 100458455, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 933, "license": "MIT", "license_type": "permissive", "path": "/app/widgets/modal-dialog-widget/modal-dialog.service.js", "provenance": "stack-edu-0035.json.gz:215354", "repo_name": "flakey-bit/ape-e-eye", "revision_date": "2019-04-14T07:53:18", "revision_id": "36441d295d3c7ed286e271c1cfcb45ded1732d5c", "snapshot_id": "6000b5a69db387c77e4748425c453b8c55237d30", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/flakey-bit/ape-e-eye/36441d295d3c7ed286e271c1cfcb45ded1732d5c/app/widgets/modal-dialog-widget/modal-dialog.service.js", "visit_date": "2021-10-27T05:33:10.600620", "added": "2024-11-19T01:27:43.198759+00:00", "created": "2019-04-14T07:53:18", "int_score": 2, "score": 2.296875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0053.json.gz" }
using UnityEngine; using System.Collections; [RequireComponent(typeof(Projector))] public class AoEMouseTarget : MonoBehaviour { public Camera Camera; public float YOffset = 10; public string ButtonName = "Fire1"; void Update() { if (Camera == null) { Camera = Camera.main; if (Camera == null) { Debug.LogError("AoETarget: Camera is null"); return; } } Ray ray = Camera.ScreenPointToRay(Input.mousePosition); RaycastHit hit = default(RaycastHit); if (Physics.Raycast(ray, out hit, float.MaxValue, ~GetComponent<Projector>().ignoreLayers)) { transform.position = new Vector3(hit.point.x, hit.point.y + YOffset, hit.point.z); if (Input.GetButtonUp(ButtonName)) { gameObject.SendMessage("CastSpell", hit.point); } } } }
befe64b8762a951b00aca0ca22d8b31600b19529
{ "blob_id": "befe64b8762a951b00aca0ca22d8b31600b19529", "branch_name": "refs/heads/master", "committer_date": "2015-04-12T07:13:00", "content_id": "9a3ee3091edbe5ead6aa783770234cf19a09620b", "detected_licenses": [ "MIT" ], "directory_id": "08346b889d2e9f582f5991e9590b42e7a549e47a", "extension": "cs", "filename": "AoEMouseTarget.cs", "fork_events_count": 0, "gha_created_at": "2015-03-18T06:47:52", "gha_event_created_at": "2015-03-18T06:47:52", "gha_language": null, "gha_license_id": null, "github_id": 32442625, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 954, "license": "MIT", "license_type": "permissive", "path": "/AoETargetingCircles/Assets/AoETarget/Scripts/AoEMouseTarget.cs", "provenance": "stack-edu-0012.json.gz:547570", "repo_name": "erebuswolf/unityassets", "revision_date": "2015-04-12T07:13:00", "revision_id": "dd7ab056bf423076459ec2ddbb729d26c34b7568", "snapshot_id": "dcdff797ad12938e3cf2396e00e89004e1713deb", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/erebuswolf/unityassets/dd7ab056bf423076459ec2ddbb729d26c34b7568/AoETargetingCircles/Assets/AoETarget/Scripts/AoEMouseTarget.cs", "visit_date": "2020-12-24T18:33:02.931136", "added": "2024-11-18T23:20:28.932257+00:00", "created": "2015-04-12T07:13:00", "int_score": 2, "score": 2.140625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0030.json.gz" }
using System.Collections.Generic; using System.Linq; using BenchmarkDotNet.Attributes; namespace StructLinq.Benchmark { [MemoryDiagnoser] public class SumOnList { private readonly List<int> list; public SumOnList() { list = Enumerable.Range(-1, 10000).ToList(); } [Benchmark(Baseline = true)] public int Linq() { return list.Sum(); } [Benchmark] public int StructLinq() { return list.ToStructEnumerable().Sum(x => x); } } }
754257ffb3176f1265831d04261984c0d70971e5
{ "blob_id": "754257ffb3176f1265831d04261984c0d70971e5", "branch_name": "refs/heads/master", "committer_date": "2021-07-12T09:40:25", "content_id": "0ea93eb91361088f29e75932f8b0e32439024308", "detected_licenses": [ "MIT" ], "directory_id": "1b0308bf92c51e8d18341d4b620317b45cd6db02", "extension": "cs", "filename": "SumOnList.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": 578, "license": "MIT", "license_type": "permissive", "path": "/src/StructLinq.Benchmark/SumOnList.cs", "provenance": "stack-edu-0009.json.gz:587694", "repo_name": "bubdm/StructLinq", "revision_date": "2021-07-12T09:40:25", "revision_id": "9f4d1f34bc4a5442e74141e2320d48d09042de94", "snapshot_id": "c47d776bcc60247495a328a6b447f6ee44a9136b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/bubdm/StructLinq/9f4d1f34bc4a5442e74141e2320d48d09042de94/src/StructLinq.Benchmark/SumOnList.cs", "visit_date": "2023-06-27T18:08:42.552525", "added": "2024-11-18T22:33:15.350768+00:00", "created": "2021-07-12T09:40:25", "int_score": 3, "score": 2.953125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0027.json.gz" }
// @flow import { openDirectDebitPopUp, closeDirectDebitPopUp, openDirectDebitGuarantee, closeDirectDebitGuarantee, updateSortCode, updateSortCodeString, updateAccountHolderName, updateAccountNumber, updateAccountHolderConfirmation, setDirectDebitFormError, resetDirectDebitFormError, } from '../directDebitActions'; describe('actions', () => { it('should create an action to open the direct debit pop up', () => { const expectedAction = { type: 'DIRECT_DEBIT_POP_UP_OPEN', }; expect(openDirectDebitPopUp()).toEqual(expectedAction); }); it('should create an action to close the direct debit pop up', () => { const expectedAction = { type: 'DIRECT_DEBIT_POP_UP_CLOSE', }; expect(closeDirectDebitPopUp()).toEqual(expectedAction); }); it('should create an action to open the direct debit guarantee section', () => { const expectedAction = { type: 'DIRECT_DEBIT_GUARANTEE_OPEN', }; expect(openDirectDebitGuarantee()).toEqual(expectedAction); }); it('should create an action to close the direct debit guarantee section', () => { const expectedAction = { type: 'DIRECT_DEBIT_GUARANTEE_CLOSE', }; expect(closeDirectDebitGuarantee()).toEqual(expectedAction); }); it('should create an action to update the sort code', () => { const partialSortCode: string = '12'; const expectedAction = { type: 'DIRECT_DEBIT_UPDATE_SORT_CODE', index: 0, partialSortCode, }; expect(updateSortCode(0, partialSortCode)).toEqual(expectedAction); }); it('should create an action to update the sort code string', () => { const sortCodeString: string = '121212'; const expectedAction = { type: 'DIRECT_DEBIT_UPDATE_SORT_CODE_STRING', sortCodeString, }; expect(updateSortCodeString(sortCodeString)).toEqual(expectedAction); }); it('should create an action to update the account number', () => { const accountNumber: string = '123456789'; const expectedAction = { type: 'DIRECT_DEBIT_UPDATE_ACCOUNT_NUMBER', accountNumber, }; expect(updateAccountNumber(accountNumber)).toEqual(expectedAction); }); it('should create an action to update the account holder name', () => { const accountHolderName: string = 'John Doe'; const expectedAction = { type: 'DIRECT_DEBIT_UPDATE_ACCOUNT_HOLDER_NAME', accountHolderName, }; expect(updateAccountHolderName(accountHolderName)).toEqual(expectedAction); }); it('should create an action to update the account holder confirmation', () => { const accountHolderConfirmation: boolean = true; const expectedAction = { type: 'DIRECT_DEBIT_UPDATE_ACCOUNT_HOLDER_CONFIRMATION', accountHolderConfirmation, }; expect(updateAccountHolderConfirmation(accountHolderConfirmation)).toEqual(expectedAction); }); it('should create an action to set the error message in the direct debit form', () => { const message: string = 'this is an error'; const expectedAction = { type: 'DIRECT_DEBIT_SET_FORM_ERROR', message, }; expect(setDirectDebitFormError(message)).toEqual(expectedAction); }); it('should create an action to reset the error message in the direct debit form', () => { const expectedAction = { type: 'DIRECT_DEBIT_RESET_FORM_ERROR', }; expect(resetDirectDebitFormError()).toEqual(expectedAction); }); });
c1e4d03ef4e57d0aeb7d9df65b33b131cb7f51e8
{ "blob_id": "c1e4d03ef4e57d0aeb7d9df65b33b131cb7f51e8", "branch_name": "refs/heads/master", "committer_date": "2020-04-30T15:34:26", "content_id": "fe654c7c611fe3b8880e88677ac6b102eb6667fa", "detected_licenses": [ "Apache-2.0" ], "directory_id": "6c2a24599d855837b4042eaef734182fd64fb3ae", "extension": "js", "filename": "directDebitActionsTest.js", "fork_events_count": 0, "gha_created_at": "2020-05-01T10:38:13", "gha_event_created_at": "2020-05-01T10:38:14", "gha_language": null, "gha_license_id": "NOASSERTION", "github_id": 260434535, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3441, "license": "Apache-2.0", "license_type": "permissive", "path": "/support-frontend/assets/components/directDebit/__tests__/directDebitActionsTest.js", "provenance": "stack-edu-0037.json.gz:312738", "repo_name": "mattoh1/support-frontend", "revision_date": "2020-04-30T15:34:26", "revision_id": "a92bf76fb5323a71bdd93540f9c6d7489d55af9a", "snapshot_id": "e464a2da02cb3e7fb9c4eae05d6041727872bd66", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mattoh1/support-frontend/a92bf76fb5323a71bdd93540f9c6d7489d55af9a/support-frontend/assets/components/directDebit/__tests__/directDebitActionsTest.js", "visit_date": "2022-05-26T08:03:49.509836", "added": "2024-11-19T01:48:51.277084+00:00", "created": "2020-04-30T15:34:26", "int_score": 2, "score": 2.125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0055.json.gz" }
[![Version](https://img.shields.io/cocoapods/v/EasyAlert.svg?style=flat)](http://cocoapods.org/pods/EasyAlert) [![License](https://img.shields.io/cocoapods/l/EasyAlert.svg?style=flat)](http://cocoapods.org/pods/EasyAlert) [![Platform](https://img.shields.io/cocoapods/p/EasyAlert.svg?style=flat)](http://cocoapods.org/pods/EasyAlert) EasyAlert is a bundle of convenient methods that wrap UIALertController to reduce the amount of boiler plate code needed. ##Installation via [Cocoapods](https://cocoapods.org/) To integrate EasyAlert into your Xcode project using CocoaPods, specify it in your `Podfile`: ```ruby source 'https://github.com/CocoaPods/Specs.git' platform :ios, '8.0' pod 'EasyAlert' ``` Then, run the following command: ```bash $ pod install ``` > CocoaPods 0.39.0+ is required to build EasyAlert. ##Usage EasyAlert is built on top of UIAlertController. It is composed of an alert view (pop up message) and an Action Sheet (bottom up menu). #### AlertController ####Creation ```objc #import <LEAAlertController.h> .... LEAAlertController *alert = [LEAAlertController dismissibleAlertViewWithTitle:@"Info" message:@"This is an Easy Alert example" cancelButtonTitle:@"Got it!"]; ``` #### Presentation ```objc [alert showInViewController:self]; ``` #### AlertController ####Creation ```objc #import <LEAActionSheet.h> .... LEAActionSheet *actionSheet = [LEAActionSheet actionSheetWithTitle:@"Select an option:"]; [actionSheet addButtonWithTitle:@"Regular option" andBlock:^(LEAActionSheet *actionSheet) { [self showDismissableAlert1:nil]; }]; ``` #### Presentation ```objc [actionSheet showInViewController:self]; ``` EasyAlert comes with an [example project](https://github.com/lagubull/EasyAlert/tree/master/Example/EasyAlertExample) to provide more details than listed above. ##Found an issue? Please open a [new Issue here](https://github.com/lagubull/EasyAlert/issues/new) if you run into a problem specific to EasyAlert, have a feature request, or want to share a comment. Pull requests are encouraged and greatly appreciated! Please try to maintain consistency with the existing. If you're considering taking on significant changes or additions to the project, please communicate in advance by opening a new Issue. This allows everyone to get onboard with upcoming changes, ensures that changes align with the project's design philosophy, and avoids duplicated work. Thank you!
ada5a4f7bfb8bff72319424bfd48062c9cc35f0d
{ "blob_id": "ada5a4f7bfb8bff72319424bfd48062c9cc35f0d", "branch_name": "refs/heads/master", "committer_date": "2016-01-29T10:14:42", "content_id": "ef1bfb04916a4d77b334ad7bda9616ca9a7f386b", "detected_licenses": [ "MIT" ], "directory_id": "edd838e5097fc424754861c2212d3a0530a40e54", "extension": "md", "filename": "README.md", "fork_events_count": 1, "gha_created_at": "2016-01-21T15:52:57", "gha_event_created_at": "2016-02-11T22:44:17", "gha_language": "Objective-C", "gha_license_id": null, "github_id": 50118099, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2683, "license": "MIT", "license_type": "permissive", "path": "/README.md", "provenance": "stack-edu-markdown-0005.json.gz:128922", "repo_name": "lagubull/EasyAlert", "revision_date": "2016-01-29T10:14:42", "revision_id": "5f46481f830e3ee9b57c2d19e16d61d7f41641d5", "snapshot_id": "d434e139474ac98a3baf00a1c9844e5fc07d294c", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/lagubull/EasyAlert/5f46481f830e3ee9b57c2d19e16d61d7f41641d5/README.md", "visit_date": "2021-01-10T08:03:30.132732", "added": "2024-11-19T01:02:30.822088+00:00", "created": "2016-01-29T10:14:42", "int_score": 4, "score": 3.625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0005.json.gz" }
dart_library.library('language/issue10581_test', null, /* Imports */[ 'dart_sdk', 'expect' ], function load__issue10581_test(exports, dart_sdk, expect) { 'use strict'; const core = dart_sdk.core; const dart = dart_sdk.dart; const dartx = dart_sdk.dartx; const expect$ = expect.expect; const issue10581_test = Object.create(null); let VoidTodynamic = () => (VoidTodynamic = dart.constFn(dart.definiteFunctionType(dart.dynamic, [])))(); issue10581_test.AxesObject = class AxesObject extends core.Object {}; issue10581_test.result = ''; issue10581_test.Point2DObject = class Point2DObject extends issue10581_test.AxesObject { Update() { issue10581_test.result = dart.notNull(issue10581_test.result) + 'P'; } }; dart.setSignature(issue10581_test.Point2DObject, { methods: () => ({Update: dart.definiteFunctionType(dart.dynamic, [])}) }); issue10581_test.BestFitObject = class BestFitObject extends issue10581_test.AxesObject { Update() { issue10581_test.result = dart.notNull(issue10581_test.result) + 'B'; } }; dart.setSignature(issue10581_test.BestFitObject, { methods: () => ({Update: dart.definiteFunctionType(dart.dynamic, [])}) }); issue10581_test.Foo = class Foo extends core.Object { AddAxesObject(type) { let a = null; switch (type) { case 100: { a = new issue10581_test.Point2DObject(); break; } case 200: { a = new issue10581_test.BestFitObject(); break; } } if (a != null) { a.Update(); } } AddAxesObject2(type) { let a = null; if (dart.equals(type, 100)) { a = new issue10581_test.Point2DObject(); } else if (dart.equals(type, 200)) { a = new issue10581_test.BestFitObject(); } if (a != null) { a.Update(); } } }; dart.setSignature(issue10581_test.Foo, { methods: () => ({ AddAxesObject: dart.definiteFunctionType(dart.dynamic, [dart.dynamic]), AddAxesObject2: dart.definiteFunctionType(dart.dynamic, [dart.dynamic]) }) }); issue10581_test.main = function() { let f = new issue10581_test.Foo(); f.AddAxesObject(100); f.AddAxesObject(200); f.AddAxesObject2(100); f.AddAxesObject2(200); expect$.Expect.equals('PBPB', issue10581_test.result); }; dart.fn(issue10581_test.main, VoidTodynamic()); // Exports: exports.issue10581_test = issue10581_test; });
7695671917963aafe75c38070673d431238e2ca8
{ "blob_id": "7695671917963aafe75c38070673d431238e2ca8", "branch_name": "refs/heads/master", "committer_date": "2016-08-03T00:16:07", "content_id": "40696b614090b9e2d2273cbbef1c2637e3bec5fd", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "f24a235a3caccc1d312bc9786188538f28f1b161", "extension": "js", "filename": "issue10581_test.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": 2497, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/test/codegen_expected/language/issue10581_test.js", "provenance": "stack-edu-0043.json.gz:425813", "repo_name": "dam0vm3nt/dev_compiler", "revision_date": "2016-08-03T00:16:07", "revision_id": "5fc554825310aecff61898172e2451e8cec26f77", "snapshot_id": "33226dee77b3836b8ea31a937ef1591613ddef35", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/dam0vm3nt/dev_compiler/5fc554825310aecff61898172e2451e8cec26f77/test/codegen_expected/language/issue10581_test.js", "visit_date": "2021-01-21T18:49:57.704441", "added": "2024-11-19T02:44:14.673920+00:00", "created": "2016-08-03T00:16:07", "int_score": 2, "score": 2.046875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0061.json.gz" }
import os usage = "usage : program LearningMethod Feature PositivePath NegativPath SavePath" base_learner_path = "../build-Learner-Desktop_Qt_5_5_0_MSVC2013_64bit-Release/release/Learner.exe" #base_learner_path = "\""+base_learner_path+"\"" learning_method = str(1) learning_feature = str(0) positive_data_path = "../../BinPicking Images/positive/set3" positive_data_path = "\""+positive_data_path+"\"" negative_data_path = "../../BinPicking Images/negative/all" negative_data_path = "\""+negative_data_path+"\"" save_path = "./MLP.txt" save_path = "\""+save_path+"\"" learn_cmd = base_learner_path + " " \ + str(learning_method) + " " \ + str(learning_feature) + " " \ + positive_data_path + " " \ + negative_data_path + " " \ + save_path print(learn_cmd) print(os.execl(base_learner_path, learning_method, learning_feature, positive_data_path, negative_data_path, save_path))
20e73ac85a8090341e1910077222f755632eeb8b
{ "blob_id": "20e73ac85a8090341e1910077222f755632eeb8b", "branch_name": "refs/heads/master", "committer_date": "2016-02-14T18:08:53", "content_id": "8b542e67cd05bfd23893f1191e2b232a95411286", "detected_licenses": [ "MIT" ], "directory_id": "e2b80d6bc00f7662c6f34ae81f3d27c44b7b28ed", "extension": "py", "filename": "Learning.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 40607753, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 954, "license": "MIT", "license_type": "permissive", "path": "/Learner/LearningTool/Learning.py", "provenance": "stack-edu-0055.json.gz:469158", "repo_name": "goddoe/Learner", "revision_date": "2016-02-14T18:08:53", "revision_id": "c499adda2f341003c6a3ec35bf41f2ca05c98833", "snapshot_id": "815afddec484342d989c4fedaf4c4790b61250fb", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/goddoe/Learner/c499adda2f341003c6a3ec35bf41f2ca05c98833/Learner/LearningTool/Learning.py", "visit_date": "2016-09-06T17:47:00.459770", "added": "2024-11-18T19:38:19.730793+00:00", "created": "2016-02-14T18:08:53", "int_score": 2, "score": 2.171875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0073.json.gz" }
import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class QuestionService { private questionSub = new BehaviorSubject<any>(null); private questionSearch = new BehaviorSubject<any>(null); QuestionsList = this.questionSub.asObservable(); SearchList = this.questionSearch.asObservable(); constructor() { } question; setQuestions(questions) { this.questionSub.next(questions) } setSearchQuestions(questions) { this.questionSearch.next(questions) } addQuestion(result,user,title,body,tags){ this.question={ "id": result.data.question.id, "title":title, "body":body, "user":{id:user.id,name:user.name,avatar:user.avatar}, "comments":[], "tags":this.addTags(tags), "created_at": "", "created_at_human": "now" } this.questionSub.value.unshift( this.question); } addTags(tags) { let tagsArray: Array<any> =[]; tags.forEach((tag) => { tagsArray.push(tag); }); return tagsArray; } // ======================================================================== addQuestionComment(question,comment,commentBody,user) { question.comments.push({ id:comment.data.comment.id, body:commentBody, user:user, created_at_human: "now", rated: 0, rates: 0 }) } deleteQuestionComment(question,comment) { let removeIndex; removeIndex=question.comments.indexOf(comment) question.comments.splice(removeIndex, 1); } }
d373c4e35d6ff8721fa56fd0a32471c522d6a372
{ "blob_id": "d373c4e35d6ff8721fa56fd0a32471c522d6a372", "branch_name": "refs/heads/master", "committer_date": "2020-06-16T09:10:40", "content_id": "a80989b988919f2996491d9518afeb892a85b5dc", "detected_licenses": [ "MIT" ], "directory_id": "91ea98e9042451935fbc3a55e78a69e7705a01b7", "extension": "ts", "filename": "question.service.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": 1607, "license": "MIT", "license_type": "permissive", "path": "/src/app/questions-section/question.service.ts", "provenance": "stack-edu-0075.json.gz:49176", "repo_name": "Sarah-Ibraheem/students-final-front-end", "revision_date": "2020-06-16T09:10:40", "revision_id": "fd440774adf33f55583b7ef83882724fd69fec05", "snapshot_id": "6312644f7594e09aa20df3bbe3edef2e3bff91c2", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Sarah-Ibraheem/students-final-front-end/fd440774adf33f55583b7ef83882724fd69fec05/src/app/questions-section/question.service.ts", "visit_date": "2022-11-16T17:45:04.828232", "added": "2024-11-18T21:59:16.812439+00:00", "created": "2020-06-16T09:10:40", "int_score": 2, "score": 2.390625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0093.json.gz" }
const { Message, Client } = require('discord.js') module.exports= { aliases: ['Unmute'], description: 'Unmutes Users', /** * @param {Message} message */ run : async(client, message) => { let args = message.content.split(" "); let reason = args.slice(2).join(" "); const Member = message.mentions.members.first() || message.guild.members.cache.get(args[0]) if(!Member) return message.channel.send('Member not found') const role = message.guild.roles.cache.find(r => r.name.toLowerCase() === 'muted'); if(reason.length<1) { return message.channel.send('There is no reason provided.'); } else { message.channel.send(`@${Member.displayName} has been unmuted for ${reason}.`); Member.roles.remove(role); } } }
cf1f1888422d4ba5c0c250d01dcb042c9259966d
{ "blob_id": "cf1f1888422d4ba5c0c250d01dcb042c9259966d", "branch_name": "refs/heads/main", "committer_date": "2021-02-02T06:01:21", "content_id": "35f394152a2cc837901cc9e7ccaec797a6634147", "detected_licenses": [ "Apache-2.0" ], "directory_id": "c0925b977619704236b9b90d0ec8aa02ed378fb0", "extension": "js", "filename": "unmute.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 331745301, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 840, "license": "Apache-2.0", "license_type": "permissive", "path": "/commands/mod/unmute.js", "provenance": "stack-edu-0044.json.gz:203200", "repo_name": "mrGriizz/SimpleBot", "revision_date": "2021-02-02T06:01:21", "revision_id": "7e47c37510c665410bc0a14c6e4e852848e0ef1c", "snapshot_id": "24f47ec07ef22e38479078d5f2ce370364d89e7e", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/mrGriizz/SimpleBot/7e47c37510c665410bc0a14c6e4e852848e0ef1c/commands/mod/unmute.js", "visit_date": "2023-02-27T08:06:52.087353", "added": "2024-11-18T23:58:50.804757+00:00", "created": "2021-02-02T06:01:21", "int_score": 3, "score": 2.625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0062.json.gz" }
// Copyright 2019 Google Inc. All Rights Reserved. // This file is available under the Apache license. package mtail_test import ( "fmt" "path" "sync" "testing" "github.com/google/mtail/internal/mtail" "github.com/google/mtail/internal/testutil" ) func TestBasicTail(t *testing.T) { if testing.Short() { t.Skip("skipping test in short mode") } if testing.Verbose() { defer testutil.TestSetFlag(t, "vmodule", "tail=2,log_watcher=2")() } for _, test := range mtail.LogWatcherTestTable { t.Run(fmt.Sprintf("%s %v", test.PollInterval, test.EnableFsNotify), func(t *testing.T) { logDir, rmLogDir := testutil.TestTempDir(t) defer rmLogDir() m, stopM := mtail.TestStartServer(t, test.PollInterval, test.EnableFsNotify, mtail.LogPathPatterns(logDir+"/*"), mtail.ProgramPath("../../examples/linecount.mtail")) defer stopM() lineCountCheck := m.ExpectMetricDeltaWithDeadline("lines_total", 3) logCountCheck := m.ExpectMetricDeltaWithDeadline("log_count", 1) logFile := path.Join(logDir, "log") f := testutil.TestOpenFile(t, logFile) for i := 1; i <= 3; i++ { testutil.WriteString(t, f, fmt.Sprintf("%d\n", i)) } var wg sync.WaitGroup wg.Add(2) go func() { defer wg.Done() lineCountCheck() }() go func() { defer wg.Done() logCountCheck() }() wg.Wait() }) } }
f591c76d6a36687e3c73ad038abfb8392a8d1ddc
{ "blob_id": "f591c76d6a36687e3c73ad038abfb8392a8d1ddc", "branch_name": "refs/heads/master", "committer_date": "2020-11-09T06:28:53", "content_id": "70e34899e7923eea652c1d54b0d478208acc2e98", "detected_licenses": [ "Apache-2.0" ], "directory_id": "e7b3660ec970f0cbde69b9b04b3f29b07ff839a9", "extension": "go", "filename": "basic_tail_integration_test.go", "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": "Go", "length_bytes": 1349, "license": "Apache-2.0", "license_type": "permissive", "path": "/internal/mtail/basic_tail_integration_test.go", "provenance": "stack-edu-0016.json.gz:572261", "repo_name": "zeta1999/mtail", "revision_date": "2020-11-09T06:28:53", "revision_id": "4d737b37691d884c68de3fedf00884b68d4aa793", "snapshot_id": "cca5ef90a9defb1457021e9d868f274d65df790f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/zeta1999/mtail/4d737b37691d884c68de3fedf00884b68d4aa793/internal/mtail/basic_tail_integration_test.go", "visit_date": "2023-01-24T01:17:51.759840", "added": "2024-11-19T01:48:04.719034+00:00", "created": "2020-11-09T06:28:53", "int_score": 2, "score": 2.28125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0034.json.gz" }
#include <stdio.h> #include <unistd.h> #include <inttypes.h> #include <stdbool.h> #include <tarantool/module.h> #include <msgpuck.h> #include "memcached.h" #include "memcached_layer.h" #include "error.h" #include "utils.h" int memcached_expire_process(struct memcached_service *p, box_iterator_t **iterp) { box_iterator_t *iter = *iterp; box_tuple_t *tpl = NULL; box_txn_begin(); int i = 0; for (i = 0; i < p->expire_count; ++i) { if (box_iterator_next(iter, &tpl) == -1) { box_txn_rollback(); return -1; } else if (tpl == NULL) { box_iterator_free(iter); if (box_txn_commit() == -1) { return -1; } *iterp = NULL; return 0; } else if (is_expired_tuple(p, tpl)) { uint32_t klen = 0; const char *kpos = box_tuple_field(tpl, 0); kpos = mp_decode_str(&kpos, &klen); size_t sz = mp_sizeof_array(1) + mp_sizeof_str(klen); char *begin = (char *)box_txn_alloc(sz); if (begin == NULL) { box_txn_rollback(); memcached_error_ENOMEM(sz, "key"); return -1; } char *end = mp_encode_array(begin, 1); end = mp_encode_str(end, kpos, klen); if (box_delete(p->space_id, 0, begin, end, NULL)) { box_txn_rollback(); return -1; } p->stat.evictions++; } } if (box_txn_commit() == -1) { return -1; } return 0; } int memcached_expire_loop(va_list ap) { static int box_ro; struct memcached_service *p = va_arg(ap, struct memcached_service *); char key[2], *key_end = mp_encode_array(key, 0); box_iterator_t *iter = NULL; int rv = 0; say_info("Memcached expire fiber started"); restart: ; int old_state = box_ro; if (memcached_box_is_ro(&box_ro) != true) { say_error("Cannot get box.info.ro value"); goto finish; } if (box_ro) { if (old_state != box_ro) { say_info("Expire: the instance has been moved to a read-only mode"); } goto delay; } if (rv == -1 || iter == NULL) { iter = box_index_iterator(p->space_id, 0, ITER_ALL, key, key_end); } if (iter == NULL) { const box_error_t *err = box_error_last(); say_error("Unexpected error %u: %s", box_error_code(err), box_error_message(err)); goto finish; } rv = memcached_expire_process(p, &iter); if (rv == -1) { const box_error_t *err = box_error_last(); say_error("Unexpected error %u: %s", box_error_code(err), box_error_message(err)); goto finish; } delay: ; /* This part is where we rest after all deletes */ double delay = ((double )p->expire_count * p->expire_time) / (box_index_len(p->space_id, 0) + 1); if (delay > 1) delay = 1; fiber_set_cancellable(true); fiber_sleep(delay); if (fiber_is_cancelled()) goto finish; fiber_set_cancellable(false); goto restart; finish: if (iter) box_iterator_free(iter); return 0; } int memcached_expire_start(struct memcached_service *p) { if (p->expire_fiber != NULL) return -1; struct fiber *expire_fiber = NULL; char name[128]; snprintf(name, 128, "__mc_%s_expire", p->name); box_error_clear(); expire_fiber = fiber_new(name, memcached_expire_loop); const box_error_t *err = box_error_last(); if (err) { say_error("Can't start the expire fiber"); say_error("%s", box_error_message(err)); return -1; } p->expire_fiber = expire_fiber; fiber_set_joinable(expire_fiber, true); fiber_start(expire_fiber, p); return 0; } void memcached_expire_stop(struct memcached_service *p) { if (p->expire_fiber == NULL) return; fiber_cancel(p->expire_fiber); fiber_join(p->expire_fiber); p->expire_fiber = NULL; }
4a61090b0b7cd4d7c658d2db06181735bf889467
{ "blob_id": "4a61090b0b7cd4d7c658d2db06181735bf889467", "branch_name": "refs/heads/master", "committer_date": "2023-07-03T13:55:18", "content_id": "f189ddf3e55c8093ab659995fbeabe5b69493193", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "bbe9714204043d77bf874a84b530a23f814edca4", "extension": "c", "filename": "expiration.c", "fork_events_count": 13, "gha_created_at": "2015-09-25T11:24:08", "gha_event_created_at": "2023-07-03T13:55:19", "gha_language": "C", "gha_license_id": "BSD-2-Clause", "github_id": 43135716, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3497, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/memcached/internal/expiration.c", "provenance": "stack-edu-0001.json.gz:5177", "repo_name": "tarantool/memcached", "revision_date": "2023-06-27T09:37:07", "revision_id": "8dcf6569482ec1e6fc540263054d15a233db347b", "snapshot_id": "939489207c605e2b42a95abfa83c8cbe428eb0fe", "src_encoding": "UTF-8", "star_events_count": 34, "url": "https://raw.githubusercontent.com/tarantool/memcached/8dcf6569482ec1e6fc540263054d15a233db347b/memcached/internal/expiration.c", "visit_date": "2023-07-09T02:19:07.145408", "added": "2024-11-18T22:28:34.375508+00:00", "created": "2023-06-27T09:37:07", "int_score": 2, "score": 2.21875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0019.json.gz" }
import React from 'react'; import { HTMLElementProps } from '@leafygreen-ui/lib'; export const DeprecatedSize = { /** @deprecated */ Small: 'small', } as const; export type DeprecatedSize = (typeof DeprecatedSize)[keyof typeof DeprecatedSize]; export const Size = { XSmall: 'xsmall', Default: 'default', Large: 'large', } as const; export type Size = (typeof Size)[keyof typeof Size]; export interface SegmentedControlProps extends Omit<HTMLElementProps<'div'>, 'onChange'> { /** * Options provided in the segmented control * * @type `<SegmentedControlOption />` */ children: React.ReactNode; /** * Defines the size of the segmented control. Can be either `xsmall`, `default`, or `large` */ size?: Size | DeprecatedSize; /** * Toggles dark mode */ darkMode?: boolean; /** * Defines the default, or initial value of the component. Ignored if `value` is also provided. */ defaultValue?: string; /** * Controls the value of the component. * If provided, you must update the value in the `onChange` method, * or other user actions (such as routing) */ value?: string; /** * A text label to the left of the segmented control. Sets the `name` prop if none is provided. */ label?: React.ReactNode; /** * Identifies the segmented control group to screen readers. Auto-generated if no `name` or `label` is provided. * * It's recommended for accessability to set this to a meaningful value. */ name?: string; /** * Defines whether the selection should automatically follow focus. * If set to true, the arrow keys can be used to switch selection, * otherwise a keyboard user will need to press enter to make a selection. * * Default: `true` */ followFocus?: boolean; /** * Identifies the element(s) whose contents/presence is controlled by the segmented control. * * Required as a prop on the control, or on each individual option. */ 'aria-controls'?: string; /** * Callback that gets called when a user makes a new selection. */ onChange?: (value: string) => void; }
a108e73335039203b818fac5587f1a7bec63a008
{ "blob_id": "a108e73335039203b818fac5587f1a7bec63a008", "branch_name": "refs/heads/main", "committer_date": "2023-08-31T14:41:33", "content_id": "913309794a40be9e3840b24dd9d8629e8e5fbafb", "detected_licenses": [ "Apache-2.0" ], "directory_id": "ea37c69d783fe1ff56afbb6ef5b67e3ee5cd0a71", "extension": "ts", "filename": "SegmentedControl.types.ts", "fork_events_count": 76, "gha_created_at": "2018-11-08T01:14:44", "gha_event_created_at": "2023-09-14T20:25:47", "gha_language": "TypeScript", "gha_license_id": "Apache-2.0", "github_id": 156630873, "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2123, "license": "Apache-2.0", "license_type": "permissive", "path": "/packages/segmented-control/src/SegmentedControl/SegmentedControl.types.ts", "provenance": "stack-edu-0072.json.gz:485435", "repo_name": "mongodb/leafygreen-ui", "revision_date": "2023-08-31T14:41:33", "revision_id": "45f3c9636f99adb4864e2f81f8da92f762699317", "snapshot_id": "b77856910e771bcd3444af76c4b5e2d31cca6d36", "src_encoding": "UTF-8", "star_events_count": 176, "url": "https://raw.githubusercontent.com/mongodb/leafygreen-ui/45f3c9636f99adb4864e2f81f8da92f762699317/packages/segmented-control/src/SegmentedControl/SegmentedControl.types.ts", "visit_date": "2023-09-02T06:33:29.259074", "added": "2024-11-18T21:38:05.536616+00:00", "created": "2023-08-31T14:41:33", "int_score": 3, "score": 3, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0090.json.gz" }
import { DBSchema, IDBPDatabase, openDB } from 'idb' import { LifecycleAware } from '../domain/lifecycle' import { NodeMetadata, Replica } from '../moveoperation/moveoperation-types' import { JoinProtocol } from '../replicaset/join-protocol' import { assert } from '../utils/util' /** * A representation of all the log moves that we need to persist to allow for * processing new incoming events. This table will be garbage collected once we * can identify at what clock we are causally stable. */ export interface LogMoveRecord { clock: number replicaId: string oldParentId: string oldPayload: NodeMetadata newParentId: string newPayload: NodeMetadata childId: string /** * We need to store all lovemoverecords regardless of whether we applied them * or not. We may decline to apply an event if perhaps its parent is not yet * known at this time because the parent creation event has not arrived yet. * When we undo the logmoverecords we need to be able to determine whether or * not this event was applied. */ applied: boolean } interface LogMoveSchema extends DBSchema { logmoveops: { key: [number, string] value: LogMoveRecord indexes: { 'ops-for-replica': [string, number] } } } export interface EventStorageListener { eventStored(event: LogMoveRecord): void eventDeleted(event: LogMoveRecord): void } export class IdbLogMoveStorage implements LifecycleAware { #db: IDBPDatabase<LogMoveSchema> #listeners: EventStorageListener[] = [] #clock = -1 #knownReplicaSet: { [key: string]: number } = {} constructor(readonly dbName: string, readonly joinProtocol: JoinProtocol) {} async init(): Promise<void> { this.#db = await openDB<LogMoveSchema>(this.dbName, 1, { upgrade(db) { const logmoveStore = db.createObjectStore('logmoveops', { keyPath: ['clock', 'replicaId'], autoIncrement: false, // we generate our own keys, this is required since compound indexes with an auto-incremented key do not work everywhere (yet) }) logmoveStore.createIndex('ops-for-replica', ['replicaId', 'clock']) }, }) console.log(`clock is '${this.#clock}' at startup`) await this.checkReplicaSetJoined() if (!this.joinProtocol.hasJoinedReplicaSet()) { this.joinProtocol.JoinEvent.on(async () => await this.checkReplicaSetJoined()) } } private async checkReplicaSetJoined() { if (this.joinProtocol.hasJoinedReplicaSet()) { const maxClock = await this.getMaxClock() const serverKnownClock = this.joinProtocol.getServerKnownClock() const newClock = Math.max(0, Math.max(maxClock, serverKnownClock)) + 1 // TODO: fix bug because we have: Setting new clock to 'NaN' because maxClock = -1 and serverKnownClock = undefined console.log( `Setting new clock to '${newClock}' because maxClock = ${maxClock} and serverKnownClock = ${serverKnownClock}` ) this.#clock = newClock } } private ensureClockIsInitialized() { assert( this.#clock > -1, `Our local clock is not initialized: '${ this.#clock }', we probably have not joined the replicaset yet` ) } async deinit(): Promise<void> { if (this.#db) { this.#db.close() this.#db = null } } getAndIncrementClock(): number { this.ensureClockIsInitialized() const clock = this.#clock this.#clock++ return clock } updateWithExternalClock(externalClock: number): void { this.ensureClockIsInitialized() if (externalClock > this.#clock) { this.#clock = externalClock + 1 } } addListener(listener: EventStorageListener): void { this.#listeners.push(listener) } removeListener(listener: EventStorageListener): void { const index = this.#listeners.indexOf(listener) if (index > -1) { this.#listeners.splice(index, 1) } } private notifyListeners(callback: (EventStorageListener) => void) { for (const listener of this.#listeners) { callback(listener) } } async storeEvent(logMoveRecord: LogMoveRecord): Promise<void> { if (this.#knownReplicaSet) { // if we already have a replicaset cache, make sure to update it const existingKnownClock = this.#knownReplicaSet[logMoveRecord.replicaId] if (!existingKnownClock || existingKnownClock < logMoveRecord.clock) { this.#knownReplicaSet[logMoveRecord.replicaId] = logMoveRecord.clock } } this.ensureClockIsInitialized() const tx = this.#db.transaction('logmoveops', 'readwrite') try { // we only need to wait for onsuccess if we are interested in generated keys, and we are not since they are pregenerated await tx.store.add(logMoveRecord) await tx.done // TODO: this needs to be move to an async op at this point the events are not stored yet this.notifyListeners((listener: EventStorageListener) => listener.eventStored(logMoveRecord)) } catch (error) { console.error( `store error for logMoveRecords ${JSON.stringify(logMoveRecord)}: `, JSON.stringify(error), error ) throw error } } async updateEvent(logMoveRecord: LogMoveRecord): Promise<void> { this.ensureClockIsInitialized() await this.#db.put('logmoveops', logMoveRecord) } async undoAllNewerLogmoveRecordsInReverse( clock: number, replicaId: string ): Promise<LogMoveRecord[]> { this.ensureClockIsInitialized() const deletedLogMoveRecords = [] const tx = this.#db.transaction('logmoveops', 'readwrite') // iterate over the logmoverecords in reverse, newest logmoveop first let cursor = await tx.store.openCursor(null, 'prev') while (cursor) { const currentRecord = cursor.value // This is our total ordering operator on logmoverecords if ( currentRecord.clock > clock || (currentRecord.clock == clock && currentRecord.replicaId > replicaId) ) { await cursor.delete() cursor = await cursor.continue() deletedLogMoveRecords.push(currentRecord) } else { break } } await tx.done return Promise.resolve(deletedLogMoveRecords) } private async getMaxClock(): Promise<number> { const cursor = await this.#db .transaction('logmoveops', 'readonly') .store.openCursor(null, 'prev') if (cursor) { return cursor.value.clock } else { return -1 } } async getEventsForReplicaSince( replicaId: string, clock: number, batchSize: number ): Promise<LogMoveRecord[]> { const range = IDBKeyRange.bound([replicaId, clock], [replicaId, Number.MAX_VALUE], true, true) // do not include lower bound return await this.#db.getAllFromIndex('logmoveops', 'ops-for-replica', range, batchSize) } async getKnownReplicaSet(): Promise<Replica[]> { if (!this.#knownReplicaSet) { // we don't yet have a cached replicaset, so build it lazily const knownReplicaSet: { [key: string]: number } = {} let cursor = await this.#db.transaction('logmoveops', 'readonly').store.openCursor() while (cursor) { const logmoveRecord = cursor.value const existingReplicaClock = knownReplicaSet[logmoveRecord.replicaId] if (!existingReplicaClock || existingReplicaClock < logmoveRecord.clock) { knownReplicaSet[logmoveRecord.replicaId] = logmoveRecord.clock } cursor = await cursor.continue() } this.#knownReplicaSet = knownReplicaSet } return Object.keys(this.#knownReplicaSet).map((key) => { return { replicaId: key, clock: this.#knownReplicaSet[key] } }) } }
ba9c44e09cfccd3256d84a42df5fd55db2046ac3
{ "blob_id": "ba9c44e09cfccd3256d84a42df5fd55db2046ac3", "branch_name": "refs/heads/master", "committer_date": "2022-09-21T08:03:38", "content_id": "f997bf1f12034e75c7c635160842c30fb0f50785", "detected_licenses": [ "Apache-2.0" ], "directory_id": "83576089a85c30470e2992b3fa9735e0bb24872a", "extension": "ts", "filename": "idb-logmovestorage.ts", "fork_events_count": 1, "gha_created_at": "2017-10-25T07:37:53", "gha_event_created_at": "2023-03-04T02:49:41", "gha_language": "TypeScript", "gha_license_id": "Apache-2.0", "github_id": 108236258, "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 7682, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/ts/storage/idb-logmovestorage.ts", "provenance": "stack-edu-0074.json.gz:710011", "repo_name": "aggregat4/dendriform", "revision_date": "2022-09-21T08:03:38", "revision_id": "bb79babace8694316342a37c66d573fd3c471ace", "snapshot_id": "87fa640a004cd8aba764918cf49bedc76b59d90c", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/aggregat4/dendriform/bb79babace8694316342a37c66d573fd3c471ace/src/ts/storage/idb-logmovestorage.ts", "visit_date": "2023-03-15T14:46:18.361803", "added": "2024-11-18T21:49:54.402946+00:00", "created": "2022-09-21T08:03:38", "int_score": 3, "score": 2.703125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0092.json.gz" }
package com.cafeform.iumfs.twitterfs; /** * Standalone progrem to setup Twitter account * which is called from setup shell script. */ public class Setup { public static void main(String args[]) { if (1 == args.length) { String username = args[0]; TwitterFactoryAdapter.getAccessToken(username); if (Prefs.get(username + "/accessToken").isEmpty()) { System.out.println("Failed to setup Twitter access token"); } else { System.out.println("Twitter access token setup sucessfully"); } } else { System.out.println("Usage: iumfs.twitterfs.Setup <username>"); } } }
5456e4777795c77cb58ce9bdb585039f6bb985ae
{ "blob_id": "5456e4777795c77cb58ce9bdb585039f6bb985ae", "branch_name": "refs/heads/master", "committer_date": "2014-01-19T06:38:23", "content_id": "bfe8e55c43e16244fbb285b7f91ddf371ba823f4", "detected_licenses": [ "Apache-2.0" ], "directory_id": "d6b894587e5e8e3e38f144239b0ee964d542d44f", "extension": "java", "filename": "Setup.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 1966340, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 779, "license": "Apache-2.0", "license_type": "permissive", "path": "/cmd/src/com/cafeform/iumfs/twitterfs/Setup.java", "provenance": "stack-edu-0022.json.gz:568404", "repo_name": "kaizawa/iumfs-twitterfs", "revision_date": "2014-01-19T06:38:23", "revision_id": "5abf7e188bcb525ce8577024cd17225a359c5d3f", "snapshot_id": "ca1c857b396aa085d8b17431cb3b5d57cbca06d9", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/kaizawa/iumfs-twitterfs/5abf7e188bcb525ce8577024cd17225a359c5d3f/cmd/src/com/cafeform/iumfs/twitterfs/Setup.java", "visit_date": "2021-01-01T06:33:35.499502", "added": "2024-11-18T23:03:46.115529+00:00", "created": "2014-01-19T06:38:23", "int_score": 3, "score": 2.796875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0040.json.gz" }
import urllib, urllib2, json from settings import * from Movie import Movie from Person import Person from Review import Review class Allocine(object): class SearchResults(object): def __init__(self, d): self.movies = [Movie(**i) for i in d.get("movie",[])] self.persons = [Person(**i) for i in d.get("person",[])] def __init__(self): pass def search(self, qry, count = 10): url = "http://api.allocine.fr/rest/v3/search?partner=%s&format=json&q=%s&count=%s" % (PARTNER_CODE, urllib.quote_plus(qry), count) d = json.loads(urllib2.urlopen(url).read()) return self.SearchResults(d["feed"]) def getMovie(self, code, profile = DEFAULT_PROFILE): retval = Movie(code = code) retval.getInfo(profile) return retval def getPerson(self, code, profile = DEFAULT_PROFILE): retval = Person(code = code) retval.getInfo(profile) return retval def reviewList(self, movie_code): d = json.loads(urllib.urlopen("http://api.allocine.fr/rest/v3/reviewlist?partner=%s&format=json&code=%s" % (PARTNER_CODE, movie_code)).read()) return [Review(**i) for i in d["feed"]["review"]] if __name__ == "__main__": p = Allocine().search("robert de niro").persons[0] p.getFilmography() for m in p.filmography: print("%s played in %s" % (p, m.movie)) m = Movie(code= 32070) m.getInfo(profile = "large") print("searching 'le parrain'") results = Allocine().search("the godfather") movie = results.movies[0] print("first result is %s" % movie) movie.getInfo() print("synopsis of %s : %s" % (movie, movie.synopsisShort))
3453c6925f154b4347d32fac77c91085328071db
{ "blob_id": "3453c6925f154b4347d32fac77c91085328071db", "branch_name": "refs/heads/master", "committer_date": "2012-10-23T22:02:07", "content_id": "d19dc96e3a528cf01e29e43db0d76428b948e162", "detected_licenses": [ "MIT" ], "directory_id": "47d6888bd90673810f6c4538f2e37d6a7866d6b7", "extension": "py", "filename": "Allocine.py", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 6342255, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1593, "license": "MIT", "license_type": "permissive", "path": "/allocine/Allocine.py", "provenance": "stack-edu-0059.json.gz:594028", "repo_name": "gtnx/python-allocine", "revision_date": "2012-10-23T22:02:07", "revision_id": "2a11e2b3a67c45f1aad205f51c005e2e4180f5ea", "snapshot_id": "f65f7806fc31fe47052c1b2564ed692d24c48983", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/gtnx/python-allocine/2a11e2b3a67c45f1aad205f51c005e2e4180f5ea/allocine/Allocine.py", "visit_date": "2020-05-19T11:57:17.666787", "added": "2024-11-18T20:29:48.788199+00:00", "created": "2012-10-23T22:02:07", "int_score": 3, "score": 2.8125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0077.json.gz" }
# -*- coding:utf-8 -*- # class TreeLinkNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # self.next = None class Solution: def GetNext(self, pNode): if not pNode: return None if pNode.right: # 如果有右子树,下一个节点就是右子树最左边的点 pNode = pNode.right while pNode.left: pNode = pNode.left return pNode else: # 如果没有右子树 while pNode.next: # 回到上一个父节点 proot = pNode.next # 如果父节点的左子节点是就自己,说明自己在左子树 if proot.left == pNode: # 下一个节点就是父节点 return proot # 如果自己在右子树,说明自己所在的子树已经遍历完了 # 回到父节点去 pNode = pNode.next
20b5c10dc7bc9e06adbe85616bd20763ced3d4bf
{ "blob_id": "20b5c10dc7bc9e06adbe85616bd20763ced3d4bf", "branch_name": "refs/heads/master", "committer_date": "2023-06-05T05:51:41", "content_id": "2527506bc13762e788997ac2afa41290a10ab56b", "detected_licenses": [ "MIT" ], "directory_id": "ec45bee420713f64d2d00a5d1c15a9a5f66a940b", "extension": "py", "filename": "二叉树的下一个节点.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 253447370, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1034, "license": "MIT", "license_type": "permissive", "path": "/ProgrammingQuestions/牛客/二叉树的下一个节点.py", "provenance": "stack-edu-0059.json.gz:51259", "repo_name": "strawsyz/straw", "revision_date": "2023-06-05T05:51:41", "revision_id": "cdf785856941f7ea546aee56ebcda8801cbb04de", "snapshot_id": "a7dc5afef9525eeb3b1a471b5a90d869a3ba5084", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/strawsyz/straw/cdf785856941f7ea546aee56ebcda8801cbb04de/ProgrammingQuestions/牛客/二叉树的下一个节点.py", "visit_date": "2023-06-08T17:18:53.073514", "added": "2024-11-19T01:55:25.484761+00:00", "created": "2023-06-05T05:51:41", "int_score": 3, "score": 3.359375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0077.json.gz" }
#include <assert.h> #include <printf.h> #include "hardware.h" void PollSensors(Move* arr, int size) { printf("Polling the sensors\n"); // TODO(matt): Actually do what we should do and not jsut return true for everything. for (int i = 0; i < size; i++) { arr[i].dir_ = NORTH; arr[i].is_valid_ = true; } } void HardwareMove(direction_t direction) { switch (direction) { case NORTH: printf("Moving north\n"); // TODO(matt): Implement break; case SOUTH: printf("Moving south\n"); // TODO(matt): Implement break; case EAST: printf("Moving east\n"); // TODO(matt): Implement break; case WEST: printf("Moving west\n"); // TODO(matt): Implement break; default: printf("Unknown move"); break; } }
d1839255f64ec54aa7109fe0af8520b4e77de9c0
{ "blob_id": "d1839255f64ec54aa7109fe0af8520b4e77de9c0", "branch_name": "refs/heads/master", "committer_date": "2017-04-08T05:59:43", "content_id": "d5a97572785eaac71083e68e9605b22be8bac380", "detected_licenses": [ "MIT" ], "directory_id": "29dcab3418174662df93d566cf9f4fb1a21684c8", "extension": "c", "filename": "hardware.c", "fork_events_count": 1, "gha_created_at": "2016-09-24T21:00:17", "gha_event_created_at": "2017-04-08T05:59:43", "gha_language": "C++", "gha_license_id": null, "github_id": 69127459, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 812, "license": "MIT", "license_type": "permissive", "path": "/src/main/c/com/micromouse/hardware/hardware.c", "provenance": "stack-edu-0000.json.gz:15001", "repo_name": "Northeastern-Micromouse/MicroMouse2017", "revision_date": "2017-04-08T05:59:43", "revision_id": "162d6153665da0cf58a572fc138abcd92579710d", "snapshot_id": "1cff3620c2d16646df1f134378b860493648923d", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/Northeastern-Micromouse/MicroMouse2017/162d6153665da0cf58a572fc138abcd92579710d/src/main/c/com/micromouse/hardware/hardware.c", "visit_date": "2021-01-12T13:47:02.121347", "added": "2024-11-18T22:59:50.471088+00:00", "created": "2017-04-08T05:59:43", "int_score": 3, "score": 2.75, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0018.json.gz" }
package tech.tobot.morevillagers.mixin; import net.minecraft.entity.passive.VillagerEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.ActionResult; import net.minecraft.util.Hand; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import tech.tobot.morevillagers.item.CouponItem; @Mixin(value = VillagerEntity.class) public class VillagerEntityInteractionMixin { @Inject(method = "interactMob", at = @At(value = "HEAD"), cancellable = true) private void onUseCoupon(PlayerEntity player, Hand hand, CallbackInfoReturnable<ActionResult> info) { if(player.getStackInHand(hand).getItem() instanceof CouponItem) { info.setReturnValue(player.getStackInHand(hand).useOnEntity(player, (VillagerEntity) (Object) this, hand)); } } }
7131da201f88f0c6a3da3a686d761f85980cb26c
{ "blob_id": "7131da201f88f0c6a3da3a686d761f85980cb26c", "branch_name": "refs/heads/main", "committer_date": "2021-06-21T13:43:04", "content_id": "3dce8ab32ddacaf4cbef55c9b4d3a1c2be003160", "detected_licenses": [ "CC0-1.0", "MIT" ], "directory_id": "d6bb430cee185b9ad67bfe0136febee2f53d89c3", "extension": "java", "filename": "VillagerEntityInteractionMixin.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 341915039, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 949, "license": "CC0-1.0,MIT", "license_type": "permissive", "path": "/src/main/java/tech/tobot/morevillagers/mixin/VillagerEntityInteractionMixin.java", "provenance": "stack-edu-0028.json.gz:559939", "repo_name": "Toby222/MoreVillagerTypes", "revision_date": "2021-06-21T13:43:04", "revision_id": "ab49bd7a9f85520c856cf7e1ed7979ff5e3d4942", "snapshot_id": "45ba46fa48620c31d2efb67466c7cbcdf26ce95f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Toby222/MoreVillagerTypes/ab49bd7a9f85520c856cf7e1ed7979ff5e3d4942/src/main/java/tech/tobot/morevillagers/mixin/VillagerEntityInteractionMixin.java", "visit_date": "2023-06-02T20:48:37.330494", "added": "2024-11-18T22:52:40.697423+00:00", "created": "2021-06-21T13:43:04", "int_score": 2, "score": 2.0625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0046.json.gz" }
<?php namespace App\Policies; use App\Models\User; use App\Models\Venue; use Illuminate\Auth\Access\HandlesAuthorization; class VenuePolicy { use HandlesAuthorization, CheckRoles; public function viewAny(User $user): bool { // No-one but Site Administrator can create a new season return false; } public function create(User $user): bool { // No-one but Site Administrator can create a new season return false; } public function update(User $user, Venue $venue): bool { // No-one but Site Administrator can create a new season return false; } public function delete(User $user, Venue $venue): bool { // No-one but Site Administrator can create a new season return false; } }
696e786a1d7040af02a7185d1dfcd1d45653bd63
{ "blob_id": "696e786a1d7040af02a7185d1dfcd1d45653bd63", "branch_name": "refs/heads/main", "committer_date": "2021-07-13T19:00:40", "content_id": "182e364d34c2bc85addd5592582b7ecbe0cfec16", "detected_licenses": [ "MIT" ], "directory_id": "9edeffa5697d1729de4237608d8f5f9837c545d6", "extension": "php", "filename": "VenuePolicy.php", "fork_events_count": 0, "gha_created_at": "2016-02-02T18:23:32", "gha_event_created_at": "2023-06-23T17:31:47", "gha_language": "PHP", "gha_license_id": "MIT", "github_id": 50941713, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 798, "license": "MIT", "license_type": "permissive", "path": "/app/Policies/VenuePolicy.php", "provenance": "stack-edu-0047.json.gz:510337", "repo_name": "troccoli/lva", "revision_date": "2021-07-13T19:00:40", "revision_id": "dfbf868628a612518b9da837678f7eb77b52795a", "snapshot_id": "7505702df648f8186343b2186857684e0d5a15b6", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/troccoli/lva/dfbf868628a612518b9da837678f7eb77b52795a/app/Policies/VenuePolicy.php", "visit_date": "2023-07-14T12:00:29.957585", "added": "2024-11-18T21:01:09.613027+00:00", "created": "2021-07-13T19:00:40", "int_score": 2, "score": 2.421875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0065.json.gz" }
module ComposeEverything # Module that when included will add many functional methods to the class # if it implements #[] module FunctionalGoodies require 'composeeverything/refinements' def compose(with) ->(x) { with[self[x]] } end def f_map(func) compose(func) end def f_flat_map(func) ComposeEverything::Refinements.make ->(this, x) { this[x].f_map(func) }, self end def f_filter(func) ComposeEverything::Refinements.make ->(this) { this.filter_indexed ->(_idx, x) { func[x] } }, self end def filter_indexed(func) lambda do |x| a = self[x] func[x, a] ? a : nil end end def f_add(idx, output) ComposeEverything::Refinements.make ->(this) { this.union ->(x) { output if x == idx } }, self end def intersect(with) ComposeEverything::Refinements.make ->(this) { this.filter_indexed ->(idx, x) { x == with[idx] } }, self end def union(with) ComposeEverything::Refinements.make ->(this, x) { a = this.f_get x a.nil? ? with[x] : a }, self end def f_delete(a) ComposeEverything::Refinements.make ->(this) { this.remove ->(_x) { a } }, self end def remove(removed) ComposeEverything::Refinements.make ->(this) { this.filter_indexed ->(idx, x) { removed[idx] != x } }, self end def f_get(x) self[x] rescue StandardError nil end end end
fc8549f166153437fd257f01a8abe803773493c6
{ "blob_id": "fc8549f166153437fd257f01a8abe803773493c6", "branch_name": "refs/heads/master", "committer_date": "2015-10-17T20:09:49", "content_id": "fe7a8e2db39cba15f4f560faa62353f3b53fb6cc", "detected_licenses": [ "MIT" ], "directory_id": "04a58b0cde5e2dd1e23aeb8e47fb9b235f009c76", "extension": "rb", "filename": "functionalgoodies.rb", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 43613781, "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1530, "license": "MIT", "license_type": "permissive", "path": "/lib/composeeverything/functionalgoodies.rb", "provenance": "stack-edu-0067.json.gz:114768", "repo_name": "trajing/compose-everything", "revision_date": "2015-10-17T20:09:49", "revision_id": "7ef1b8c2cedd12fa2b262b23f4a5ce8c3a92bc38", "snapshot_id": "e48ff120637c18902a2767bb0fed1e92428100cd", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/trajing/compose-everything/7ef1b8c2cedd12fa2b262b23f4a5ce8c3a92bc38/lib/composeeverything/functionalgoodies.rb", "visit_date": "2021-01-10T01:56:23.442674", "added": "2024-11-18T20:44:39.707633+00:00", "created": "2015-10-17T20:09:49", "int_score": 3, "score": 2.6875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0085.json.gz" }
<?php namespace App\Http\Controllers\Shop; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Response; use App\Models\Product; class ShopController extends Controller { public function index(){ $products = Product::get(); return view('shop.index',[ 'products' =>$products ]); } public function subgroup(Request $request){ if($request->type == 'all'){ $products = Product::where('body',$request->body)->get(); }else{ $products = Product::where('type',$request->type)->where('body',$request->body)->get(); } return view('shop.index',[ 'products' =>$products ]); } public function type(Request $request){ $products = Product::where('type',$request->type)->get(); return view('shop.index',[ 'products' =>$products ]); } }
27c39fb77e0f53b36154f33021f9433ea16fde70
{ "blob_id": "27c39fb77e0f53b36154f33021f9433ea16fde70", "branch_name": "refs/heads/master", "committer_date": "2021-07-05T03:42:51", "content_id": "0d212aa0d66d7e94e5a88cf5bfbdf35521dd8011", "detected_licenses": [ "MIT" ], "directory_id": "04298ef8ee0378886c1755181b4949f0af7ba41a", "extension": "php", "filename": "ShopController.php", "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": "PHP", "length_bytes": 959, "license": "MIT", "license_type": "permissive", "path": "/app/Http/Controllers/Shop/ShopController.php", "provenance": "stack-edu-0050.json.gz:311326", "repo_name": "At0kSharma/ecommerce-laravel", "revision_date": "2021-07-05T03:42:51", "revision_id": "f033d49f35c459e3fa6aae9837ca419986d2007c", "snapshot_id": "13f8ce8edf6ec146b40dbcc1d06c1baa5b294f9a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/At0kSharma/ecommerce-laravel/f033d49f35c459e3fa6aae9837ca419986d2007c/app/Http/Controllers/Shop/ShopController.php", "visit_date": "2023-08-17T02:25:17.544441", "added": "2024-11-19T03:09:51.158227+00:00", "created": "2021-07-05T03:42:51", "int_score": 2, "score": 2.1875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0068.json.gz" }
import numpy as np from transformation import Transformation class Data(object): def __init__(self): self.vicon_lists = [] self.vicon_ts = [] self.vicon_x = [] self.vicon_y = [] self.vicon_z = [] self.vicon_qw = [] self.vicon_qx = [] self.vicon_qy = [] self.vicon_qz = [] self.opti_lists = [] self.opti_ts = [] self.opti_x = [] self.opti_y = [] self.opti_z = [] self.opti_qw = [] self.opti_qx = [] self.opti_qy = [] self.opti_qz = [] self.opti_orig_lists = [] # Original (i.e., opti to wand) before transformation self.opti_orig_ts = [] self.opti_orig_x = [] self.opti_orig_y = [] self.opti_orig_z = [] self.opti_orig_qw = [] self.opti_orig_qx = [] self.opti_orig_qy = [] self.opti_orig_qz = [] self.T_ts = [] self.T_x = [] self.T_y = [] self.T_z = [] self.T_qw = [] self.T_qx = [] self.T_qy = [] self.T_qz = [] self.T_vicon_to_opti_positions = [] self.T_vicon_to_opti_quats = [] self.T_obj = Transformation() def add_vicon_data(self, data): self.vicon_lists.append(data) def add_opti_data(self, data): self.opti_lists.append(data) def add_opti_orig_data(self, data): self.opti_orig_lists.append(data) def set_vicon(self): self.vicon_ts = np.asarray([data[0] for data in self.vicon_lists]) self.vicon_x = np.asarray([data[1] for data in self.vicon_lists]) self.vicon_y = np.asarray([data[2] for data in self.vicon_lists]) self.vicon_z = np.asarray([data[3] for data in self.vicon_lists]) self.vicon_qw = np.asarray([data[4] for data in self.vicon_lists]) self.vicon_qx = np.asarray([data[5] for data in self.vicon_lists]) self.vicon_qy = np.asarray([data[6] for data in self.vicon_lists]) self.vicon_qz = np.asarray([data[7] for data in self.vicon_lists]) def set_opti(self): self.opti_ts = np.asarray([data[0] for data in self.opti_lists]) self.opti_x = np.asarray([data[1] for data in self.opti_lists]) self.opti_y = np.asarray([data[2] for data in self.opti_lists]) self.opti_z = np.asarray([data[3] for data in self.opti_lists]) self.opti_qw = np.asarray([data[4] for data in self.opti_lists]) self.opti_qx = np.asarray([data[5] for data in self.opti_lists]) self.opti_qy = np.asarray([data[6] for data in self.opti_lists]) self.opti_qz = np.asarray([data[7] for data in self.opti_lists]) def set_opti_orig(self): self.opti_orig_ts = np.asarray([data[0] for data in self.opti_orig_lists]) self.opti_orig_x = np.asarray([data[1] for data in self.opti_orig_lists]) self.opti_orig_y = np.asarray([data[2] for data in self.opti_orig_lists]) self.opti_orig_z = np.asarray([data[3] for data in self.opti_orig_lists]) self.opti_orig_qw = np.asarray([data[4] for data in self.opti_orig_lists]) self.opti_orig_qx = np.asarray([data[5] for data in self.opti_orig_lists]) self.opti_orig_qy = np.asarray([data[6] for data in self.opti_orig_lists]) self.opti_orig_qz = np.asarray([data[7] for data in self.opti_orig_lists]) def find_nearest_idx(self, array, value): idx = (np.abs(array-value)).argmin() return idx def diff(self, value_1, value_2): return np.absolute(value_1 - value_2) def optimize_T(self): for vicon_idx in range(len(self.vicon_ts)): opti_idx = self.find_nearest_idx(self.opti_ts, self.vicon_ts[vicon_idx]) x_diff = self.diff(self.vicon_x[vicon_idx], self.opti_x[opti_idx]) y_diff = self.diff(self.vicon_y[vicon_idx], self.opti_y[opti_idx]) z_diff = self.diff(self.vicon_z[vicon_idx], self.opti_z[opti_idx]) qw_diff = self.diff(np.absolute(self.vicon_qw[vicon_idx]), np.absolute(self.opti_qw[opti_idx])) qx_diff = self.diff(np.absolute(self.vicon_qx[vicon_idx]), np.absolute(self.opti_qx[opti_idx])) qy_diff = self.diff(np.absolute(self.vicon_qy[vicon_idx]), np.absolute(self.opti_qy[opti_idx])) qz_diff = self.diff(np.absolute(self.vicon_qz[vicon_idx]), np.absolute(self.opti_qz[opti_idx])) if x_diff <= 0.03 and y_diff <= 0.03 and z_diff <= 0.03 and \ qw_diff <= 0.03 and qx_diff <= 0.03 and qy_diff <= 0.03 and qz_diff <= 0.03: # T_vicon_to_wand T_vicon_to_wand = self.T_obj.convert_to_T_matrix( position=np.array([self.vicon_x[vicon_idx], self.vicon_y[vicon_idx], self.vicon_z[vicon_idx]]), quat=np.array([self.vicon_qw[vicon_idx], self.vicon_qx[vicon_idx], self.vicon_qy[vicon_idx], self.vicon_qz[vicon_idx]])) # T_opti_to_wand T_opti_to_wand = self.T_obj.convert_to_T_matrix( position=np.array([self.opti_orig_x[opti_idx], self.opti_orig_y[opti_idx], self.opti_orig_z[opti_idx]]), quat=np.array([self.opti_orig_qw[opti_idx], self.opti_orig_qx[opti_idx], self.opti_orig_qy[opti_idx], self.opti_orig_qz[opti_idx]])) # T_wand_to_opti T_wand_to_opti = self.T_obj.inverse_matrix(T_opti_to_wand) # T_vicon_to_opti T_vicon_to_opti = np.dot(T_vicon_to_wand, T_wand_to_opti) T_vicon_to_opti_position, T_vicon_to_opti_quat = \ self.T_obj.convert_T_matrix_to_position_and_quat(T_vicon_to_opti) print 'T_vicon_to_opti: \nPos (x y z): {}\nQuat (w x y z): {}'.format( T_vicon_to_opti_position, T_vicon_to_opti_quat) # Save result self.T_vicon_to_opti_positions.append(T_vicon_to_opti_position) self.T_vicon_to_opti_quats.append(T_vicon_to_opti_quat) # Add data for visualization self.T_ts.append(self.opti_ts[opti_idx]) self.T_x.append(self.opti_x[opti_idx]) self.T_y.append(self.opti_y[opti_idx]) self.T_z.append(self.opti_z[opti_idx]) self.T_qw.append(self.opti_qw[opti_idx]) self.T_qx.append(self.opti_qx[opti_idx]) self.T_qy.append(self.opti_qy[opti_idx]) self.T_qz.append(self.opti_qz[opti_idx]) print len(self.T_vicon_to_opti_positions) print np.mean(self.T_vicon_to_opti_positions, axis=0) print np.mean(self.T_vicon_to_opti_quats, axis=0) def error(self): x_err = [] y_err = [] z_err = [] qx_err = [] qy_err = [] qz_err = [] qw_err = [] self.vicon_ts = self.vicon_ts[::5] self.vicon_x = self.vicon_x[::5] self.vicon_y = self.vicon_y[::5] self.vicon_z = self.vicon_z[::5] self.vicon_qw = self.vicon_qw[::5] self.vicon_qx = self.vicon_qx[::5] self.vicon_qy = self.vicon_qy[::5] self.vicon_qz = self.vicon_qz[::5] self.opti_ts = self.opti_ts[::5] self.opti_x = self.opti_x[::5] self.opti_y = self.opti_y[::5] self.opti_z = self.opti_z[::5] self.opti_qw = self.opti_qw[::5] self.opti_qx = self.opti_qx[::5] self.opti_qy = self.opti_qy[::5] self.opti_qz = self.opti_qz[::5] for vicon_idx in range(len(self.vicon_ts)): print vicon_idx, '/', len(self.vicon_ts) opti_idx = self.find_nearest_idx(self.opti_ts, self.vicon_ts[vicon_idx]) if self.diff(self.vicon_ts[vicon_idx], self.opti_ts[opti_idx]) < 0.1: x_err.append(self.diff(self.vicon_x[vicon_idx], self.opti_x[opti_idx])) y_err.append(self.diff(self.vicon_y[vicon_idx], self.opti_y[opti_idx])) z_err.append(self.diff(self.vicon_z[vicon_idx], self.opti_z[opti_idx])) qw_err.append(self.diff(self.vicon_qw[vicon_idx], -self.opti_qw[opti_idx])) qx_err.append(self.diff(self.vicon_qx[vicon_idx], -self.opti_qx[opti_idx])) qy_err.append(self.diff(self.vicon_qy[vicon_idx], -self.opti_qy[opti_idx])) qz_err.append(self.diff(self.vicon_qz[vicon_idx], -self.opti_qz[opti_idx])) print np.mean(x_err) print np.mean(y_err) print np.mean(z_err) print np.mean(qw_err) print np.mean(qx_err) print np.mean(qy_err) print np.mean(qz_err)
2ed6dd95f7eacb88a1adb807c06728e007881fba
{ "blob_id": "2ed6dd95f7eacb88a1adb807c06728e007881fba", "branch_name": "refs/heads/master", "committer_date": "2018-03-01T00:11:54", "content_id": "ed52243131d6f7b02eaccb971539c1d44fa24c3e", "detected_licenses": [ "MIT" ], "directory_id": "cfaf18ccb70ac8ae272ed6670a8a15fb151171a6", "extension": "py", "filename": "data.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 121994320, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9130, "license": "MIT", "license_type": "permissive", "path": "/src/trajectory/data.py", "provenance": "stack-edu-0059.json.gz:508174", "repo_name": "dkkim93/vicon_optitrack_merge", "revision_date": "2018-03-01T00:11:54", "revision_id": "b0e03d2cb404115dd36ac91fc58e46a29bd6003c", "snapshot_id": "f564b1afcc9b71026e58795f7c52080cac330609", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/dkkim93/vicon_optitrack_merge/b0e03d2cb404115dd36ac91fc58e46a29bd6003c/src/trajectory/data.py", "visit_date": "2021-04-28T15:40:21.292338", "added": "2024-11-19T01:43:44.916497+00:00", "created": "2018-03-01T00:11:54", "int_score": 2, "score": 2.265625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0077.json.gz" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace DarkStyle { /// <summary> /// InputDialog.xaml 的交互逻辑 /// </summary> public partial class InputDialog : Window { public static string ShowInputDialog(string title, string desc, string def = null, bool eng = false) { InputDialog input = new InputDialog(); input.TBTitle.Text = title; input.TBDesc.Text = desc; input.InputValue = def; input.TBContent.Text = input.InputValue; input.TBContent.Focus(); input.TBContent.SelectAll(); if(eng) { input.BtnOK.Content = "Ok"; input.BtnCancel.Content = "Cancel"; } if (input.ShowDialog() == true) return input.InputValue; else return def; } private InputDialog() { InitializeComponent(); } private string InputValue { get; set; } private void BtnOK_Click(object sender, RoutedEventArgs e) { InputValue = TBContent.Text; DialogResult = true; Close(); } private void BtnCancel_Click(object sender, RoutedEventArgs e) { DialogResult = false; Close(); } private void Window_MouseDown(object sender, MouseButtonEventArgs e) { if (e.LeftButton == MouseButtonState.Pressed) DragMove(); } private void TBContent_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { BtnOK_Click(null, null); } } } }
ca6cbc29ff5954a349244faf24d7b1e4a73a2130
{ "blob_id": "ca6cbc29ff5954a349244faf24d7b1e4a73a2130", "branch_name": "refs/heads/main", "committer_date": "2022-05-15T11:31:44", "content_id": "bfd0106fe6b63a4cd03d7dcfee02dfd1e95f3b40", "detected_licenses": [ "MIT" ], "directory_id": "3e011ca4922f5e131808c989972d8ccc83b68031", "extension": "cs", "filename": "InputDialog.xaml.cs", "fork_events_count": 11, "gha_created_at": "2020-01-19T21:14:49", "gha_event_created_at": "2021-02-11T16:55:44", "gha_language": "Visual Basic .NET", "gha_license_id": "MIT", "github_id": 234969107, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2058, "license": "MIT", "license_type": "permissive", "path": "/DarkStyle/InputDialog.xaml.cs", "provenance": "stack-edu-0009.json.gz:287325", "repo_name": "Lazuplis-Mei/SuperPVZTrainner", "revision_date": "2022-05-15T11:31:44", "revision_id": "f6eb4cd704caf30342609b7bd78a5c2821e2c197", "snapshot_id": "a2574b8a257176bb92e60f0fd2309cde71d10aa3", "src_encoding": "UTF-8", "star_events_count": 32, "url": "https://raw.githubusercontent.com/Lazuplis-Mei/SuperPVZTrainner/f6eb4cd704caf30342609b7bd78a5c2821e2c197/DarkStyle/InputDialog.xaml.cs", "visit_date": "2022-05-25T13:09:59.364744", "added": "2024-11-18T23:05:07.688055+00:00", "created": "2022-05-15T11:31:44", "int_score": 2, "score": 2.5, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0027.json.gz" }
#include <stdio.h> #include <unistd.h> #include "p/rpc/async_worker.h" #include "p/rpc/acceptor.h" #include "stream_crypt.h" #include <assert.h> #include <endian.h> // The following address types are defined: // 0x01: host is a 4-byte IPv4 address. // 0x03: host is a variable length string, starting with a 1-byte length, followed by up to 255-byte domain name. // 0x04: host is a 16-byte IPv6 address. constexpr int kAddressTypeIpv4 = 0x01; constexpr int kAddressTypeString = 0x03; constexpr int kAddressTypeIpv6= 0x04; constexpr int kMaxHeaderLen = 256 + 64; const char* g_passwd = "3.e4e5926w"; void dec_func(char * buf, int len, void* arg) { p::rpc::ss::StreamDecrypt* dec = (p::rpc::ss::StreamDecrypt*)arg; dec->decrypt(buf, len); } void enc_func(char * buf, int len, void* arg) { p::rpc::ss::StreamEncrypt* enc = (p::rpc::ss::StreamEncrypt*)arg; enc->encrypt(buf, len); } class ShadowSocket; class RemoteSocket : public p::rpc::Socket { public: RemoteSocket(ShadowSocket* s) : ss_(s) { LOG_DEBUG << this << " RemoteSocket New"; } ~RemoteSocket() override { LOG_DEBUG << this << " RemoteSocket Free"; } void on_msg_read(p::base::ZBuffer* zbuf) override; void on_connected() override; void on_msg_sended(int err, void* arg) override { LOG_DEBUG << this << " RemoteSocket on on_msg_sended err=" << err; } void on_failed() override ; int eof_; ShadowSocket* ss_; }; class ShadowSocket : public p::rpc::Socket { public: ShadowSocket() { LOG_DEBUG << this << " ShadowSocket New, rmt=" << remote_side() << ",lcs=" << local_side(); } ~ShadowSocket() { LOG_DEBUG << this << " ShadowSocket Free"; } int try_to_decrypt() { std::unique_ptr<p::rpc::ss::StreamDecrypt> ptr; for (int i = 0; ; ++i) { char buf[kMaxHeaderLen]; int len = buf_.copy_front(buf, kMaxHeaderLen); ptr.reset(p::rpc::ss::StreamDecrypt::get_one(i)); if (!ptr) { // all method failed return -1; } ptr->init_key(g_passwd); int used = ptr->init_iv(buf, len); if (used <= 0) { continue; } LOG_DEBUG << this << " ShadowSocket buf=" << buf_.size() << ",used=" << used; char* p = &buf[used]; char* end = &buf[len]; if (end <= p) { continue; } ptr->decrypt(p, end - p); char addr_type = p[0]; ++p; if (kAddressTypeIpv6 == addr_type) { continue; } if (kAddressTypeIpv4 == addr_type) { ; } else if (kAddressTypeString == addr_type) { int16_t host_len = p[0]; ++p; if (host_len <= 0 || host_len > 253 || p + host_len + 2 > end) { continue; } } else { continue; } LOG_DEBUG << this << " ShadowSocket found decrypt, i=" << i; dec_.reset(ptr->NewStreamDecrypt()); dec_->init_key(g_passwd); used = dec_->init_iv(buf, len); buf_.popn(buf, used); buf_.map(dec_func, dec_.get()); return 0; } return 0; } int connect_remote() { char ip_type; buf_.popn(&ip_type, 1); char buf[255]; p::base::EndPoint addr; if (ip_type == 0x01) { in_addr_t ip; buf_.popn((char*)&ip, sizeof(in_addr_t)); addr = p::base::EndPoint(ip, 0); buf[0] = 0; } else { char host_len; buf_.popn(&host_len, 1); buf_.popn(buf, host_len); buf[(int)host_len] = 0; addr = p::base::EndPoint(buf, 0); } uint16_t port; buf_.popn((char*)&port, 2); addr.set_port(be16toh(port)); remote_ = new RemoteSocket(this); LOG_DEBUG << this << " ShadowSocket get address:" << buf << ",port=" << port << ",ep=" << addr << "remote=" << remote_ << ",rmt=" << remote_side() << ",lcs=" << local_side(); int ret = remote_->try_connect(addr); if (ret < 0) { delete remote_; remote_ = nullptr; LOG_WARN << this << "connect failed"; return -1; } if (ret > 0) { delete remote_; remote_ = nullptr; LOG_WARN << this << "connect retry later "; return -2; } LOG_DEBUG << this << "ShadowSocket RemoteSocket=" << remote_ << " doing connecting"; return 0; } virtual void on_msg_read(p::base::ZBuffer* zbuf) { if (zbuf == nullptr) { eof_ = true; set_failed(3456); return ; } if (xxx_) { xxx_ = false; LOG_DEBUG << this << " ShadowSocket New, rmt=" << remote_side() << ",lcs=" << local_side(); } LOG_DEBUG << this << " ShadowSocket on read len=" << zbuf->size(); if (!dec_) { buf_.append(std::move(*zbuf)); if (try_to_decrypt() == 0) { if (connect_remote()) { set_failed(46585); } } return ; } if (!remote_->connected()) { zbuf->map(dec_func, dec_.get()); buf_.append(std::move(*zbuf)); return ; } zbuf->map(dec_func, dec_.get()); remote_->send_msg(std::move(*zbuf), (void*)1234); } virtual void on_msg_sended(int err, void* arg) { LOG_DEBUG << this << " ShadowSocket on writed " << " : " << arg << ",err=" << err; if (arg == nullptr) { assert(0); } if (err) { on_failed(); return ; } if (remote_ && remote_->connected()) { LOG_DEBUG << this << " ShadowSocket start read RemoteSocket"; remote_->try_read(); } } virtual void on_failed() { LOG_DEBUG << this << " on failed"; if (remote_) { remote_->set_failed(error()); remote_ = nullptr; } } void on_remote_connected() { remote_->send_msg(std::move(buf_), this); enc_.reset(dec_->NewStreamEncrypt()); p::base::ZBuffer iv; iv.append(enc_->get_ivbuf(), enc_->get_ivlen()); // TODO send_msg(std::move(iv), this); if (eof_) { //remote_->close(); } } void send_reply(p::base::ZBuffer* buf) { buf->map(enc_func, enc_.get()); LOG_DEBUG << this << " ShadowSocket send len=" << buf->size(); send_msg(std::move(*buf), this); } private: p::base::ZBuffer buf_; std::unique_ptr<p::rpc::ss::StreamEncrypt> enc_; std::unique_ptr<p::rpc::ss::StreamDecrypt> dec_; Socket* remote_ = nullptr; bool eof_ = false; bool xxx_ = true; }; void RemoteSocket::on_connected() { LOG_DEBUG << this << " RemoteSocket on on_connected" << ",rms=" << remote_side() << ",lcs" << local_side(); ss_->on_remote_connected(); } void RemoteSocket::on_msg_read(p::base::ZBuffer* zbuf) { if (zbuf == nullptr) { LOG_DEBUG << this << " RemoteSocket on on_msg_readn EOF"; set_failed(8888); return ; } LOG_DEBUG << this << " RemoteSocket on on_msg_read len=" << zbuf->size(); LOG_DEBUG << this << " RemoteSocket stop read"; stop_read(); ss_->send_reply(zbuf); } void RemoteSocket::on_failed() { LOG_DEBUG << this << " RemoteSocket on failed"; //ss_->set_failed(error()); ss_->set_failed(9999); }
298c5c113a90f7151957d032139d1fbc980f0098
{ "blob_id": "298c5c113a90f7151957d032139d1fbc980f0098", "branch_name": "refs/heads/master", "committer_date": "2018-11-15T10:52:52", "content_id": "418757d7f78a28aca22cc4938f56a738e289e5ff", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "43f6088442c1323749bd0f70af27143045713d76", "extension": "h", "filename": "shadowsocket.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": 7875, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/example/ss/include/shadowsocket.h", "provenance": "stack-edu-0007.json.gz:623558", "repo_name": "3172564983/p-rpc", "revision_date": "2018-11-15T10:52:52", "revision_id": "7d5c00b90d8abeaaecb14a919623ea5c1cb54dcc", "snapshot_id": "f5811a9c4238c7a18ff6f78ee5aa3992c1f4b140", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/3172564983/p-rpc/7d5c00b90d8abeaaecb14a919623ea5c1cb54dcc/example/ss/include/shadowsocket.h", "visit_date": "2020-06-23T11:53:07.311368", "added": "2024-11-18T22:01:31.109403+00:00", "created": "2018-11-15T10:52:52", "int_score": 2, "score": 2.34375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0025.json.gz" }
using ExpressionTreeTestObjects; using System; using System.Collections.Generic; using System.Globalization; using System.Linq.Dynamic.Core; using System.Linq.Dynamic.Core.Parser; using System.Linq.Expressions; using static System.Linq.Expressions.Expression; using static System.Linq.Dynamic.Core.DynamicExpressionParser; using System.Linq; using static ZSpitz.Util.Functions; using static ExpressionTreeTestObjects.Categories; namespace ExpressionTreeToString.Tests { [ObjectContainer] public static partial class DynamicLinqTestObjects { internal static Expression Expr<T>(Expression<Func<Person, T>> expr) => expr; internal static Expression Expr(Expression<Action<Person>> expr) => expr; internal static Expression Expr(string selector, params object[] constants) => new ExpressionParser( new[] { Parameter(typeof(Person)) }, selector, constants, ParsingConfig.Default ).Parse(null); internal static LambdaExpression Lambda(string selector, params object[] constants) => ParseLambda(new[] { Parameter(typeof(Person)) }, null, selector, constants); [TestObject("Dynamic LINQ")] internal static readonly Expression Parameter = Expr(p => p); [TestObject("Dynamic LINQ")] internal static readonly Expression In = Expr(p => p.LastName == "A" || p.LastName == "B"); [TestObject("Dynamic LINQ")] internal static readonly Expression MultipleFieldsIn = Expr(p => p.LastName == "A" || p.LastName == "B" || p.FirstName == "C" || p.FirstName == "D"); // tests for multiple fields, some of which have a single value, and some of which have multiple vales [TestObject("Dynamic LINQ")] internal static readonly Expression MultipleFieldSingleValueIn = Expr(p => p.LastName == "A" || p.LastName == "B" || p.DOB == DateTime.MinValue || p.FirstName == "C" || p.FirstName == "D"); // pending https://github.com/zzzprojects/System.Linq.Dynamic.Core/issues/441 //[TestObject("Invocation")] //internal static readonly Expression Invocation = Expr(p => ((Func<string>)(() => p.LastName + p.FirstName))()); // pending https://github.com/zzzprojects/System.Linq.Dynamic.Core/issues/441 //[TestObject("Invocation")] //internal static readonly Expression InvocationArguments = Expr(p => ((Func<Person, string>)(p1 => p1.LastName + p1.FirstName))(p)); [TestObject("Dynamic LINQ")] internal static readonly Expression ParameterTypeAs = Expr(p => p as object); [TestObject("Dynamic LINQ")] internal static readonly Expression ParameterTypeIs = Expr(p => p is object); [TestObject("Dynamic LINQ")] internal static readonly Expression StringEscaping = Expr("\"\\\"\""); [TestObject("Dynamic LINQ")] internal static readonly Expression CharEscaping = Expr("'\"'"); [TestObject("Dynamic LINQ")] internal static readonly Expression StringEscapingLambda = Expr(p => "\""); [TestObject("Dynamic LINQ")] internal static readonly Expression CharEscapingLambda = Expr(p => '"'); [TestObject("Dynamic LINQ")] internal static readonly Expression QueryableWhere = Enumerable.Empty<Person>() .AsQueryable() .Where(x => x.Age <= 20) .Expression; [TestObject("Dynamic LINQ")] internal static readonly Expression QueryableMultiple = Enumerable.Empty<Person>() .AsQueryable() .Where(x => x.Age <= 20) .OrderBy(x => x != null && x.LastName != null ? x.LastName[0] : ' ') .ThenBy(x => x != null && x.FirstName != null ? x.FirstName[0] : ' ') .Expression; [TestObject("Dynamic LINQ")] internal static readonly Expression QueryableTake = Enumerable.Empty<Person>().AsQueryable().Take(5).Expression; [TestObject(TypeChecks)] internal static readonly Expression PropertyTypeIsDerived = Expr(p => p.Property is string); [TestObject(TypeChecks)] internal static readonly Expression PropertyTypeIsBase = Expr(p => p.LastName is object); public static readonly Dictionary<string, object[]> Parameters = new() { { nameof(Random), new[] { new Random() } }, { nameof(NpChainWithMethodsParameters), new[] { CultureInfo.GetCultureInfo("en-US") }}, { nameof(NpChainWithMethodsParameters1), new[] { CultureInfo.GetCultureInfo("en-US"), CultureInfo.GetCultureInfo("he-IL") }}, { nameof(Contains1), new object[] { EmptyArray<string>() } }, { nameof(ClosureValue), new object [] {5}}, { nameof(LambdaRandom), new[] {new Random()}} }; } }
741feb57c5cf8399729a0c465cf3283d8b641459
{ "blob_id": "741feb57c5cf8399729a0c465cf3283d8b641459", "branch_name": "refs/heads/master", "committer_date": "2022-02-25T07:03:25", "content_id": "9d6fa4170a42bc2b0e3d90ebdd8511c654535ba5", "detected_licenses": [ "MIT" ], "directory_id": "29e6eff7b1b3a37abcf8f9e4a55108653410e1fd", "extension": "cs", "filename": "DynamicLinqTestObjects.cs", "fork_events_count": 11, "gha_created_at": "2019-12-14T23:42:33", "gha_event_created_at": "2023-06-27T23:13:20", "gha_language": "C#", "gha_license_id": "MIT", "github_id": 228104502, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4962, "license": "MIT", "license_type": "permissive", "path": "/Tests/dynamicLinqTestObjects/DynamicLinqTestObjects.cs", "provenance": "stack-edu-0009.json.gz:45268", "repo_name": "zspitz/ExpressionTreeToString", "revision_date": "2022-02-25T07:03:25", "revision_id": "ca6e099c1f92a1dbe152d95484da75f6eafd157b", "snapshot_id": "2ad888316fe946161ff81c630a8a4e5dfa60ad34", "src_encoding": "UTF-8", "star_events_count": 142, "url": "https://raw.githubusercontent.com/zspitz/ExpressionTreeToString/ca6e099c1f92a1dbe152d95484da75f6eafd157b/Tests/dynamicLinqTestObjects/DynamicLinqTestObjects.cs", "visit_date": "2023-07-17T13:43:14.110008", "added": "2024-11-18T21:51:53.827726+00:00", "created": "2022-02-25T07:03:25", "int_score": 2, "score": 2.390625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0027.json.gz" }
package be.unamur.info.b314.compiler.exception; /** * * @author James Ortiz - james.ortizvega@unamur.be */ public class SymbolNotFoundException extends Exception{ public SymbolNotFoundException(String message) { super(message); } public SymbolNotFoundException(String message, Exception cause) { super(message, cause); } }
d15948e218429a2eac7108f0d3dc7e238876ff8d
{ "blob_id": "d15948e218429a2eac7108f0d3dc7e238876ff8d", "branch_name": "refs/heads/master", "committer_date": "2021-02-14T15:02:35", "content_id": "b4839c79b0a084d8501e79f030e5cd038665331b", "detected_licenses": [ "MIT" ], "directory_id": "9411883e89cda1644251f78e5efa8473d1d57ee3", "extension": "java", "filename": "SymbolNotFoundException.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 268292237, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 369, "license": "MIT", "license_type": "permissive", "path": "/src/main/java/be/unamur/info/b314/compiler/exception/SymbolNotFoundException.java", "provenance": "stack-edu-0027.json.gz:590117", "repo_name": "fredunam/compilateur", "revision_date": "2021-02-14T15:02:35", "revision_id": "2909ba37b7dac63d2a1c29e698f280e6dcf380b7", "snapshot_id": "7becb2c14e2b1ce0d70d28cc6fba6c2bb23bfb6d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/fredunam/compilateur/2909ba37b7dac63d2a1c29e698f280e6dcf380b7/src/main/java/be/unamur/info/b314/compiler/exception/SymbolNotFoundException.java", "visit_date": "2023-03-10T06:41:15.170966", "added": "2024-11-19T01:04:46.515303+00:00", "created": "2021-02-14T15:02:35", "int_score": 2, "score": 2.015625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0045.json.gz" }
# Meta-Learning Adversarial Domain Adaptation Network for Few-Shot Text Classification ### Data We ran experiments on a total of 4 datasets. You may unzip our processed data file `data.zip` and put the data files under `data/` folder. | Dataset | Notes | |---|---| | 20 Newsgroups ([link](http://qwone.com/~jason/20Newsgroups/ "20 Newsgroups")) | Processed data available. We used the `20news-18828` version, available at the link provided. | Reuters-21578 ([link](https://kdd.ics.uci.edu/databases/reuters21578/reuters21578.html "Reuters")) | Processed data available. | | Amazon reviews ([link](http://jmcauley.ucsd.edu/data/amazon/ "Amazon")) | We used a subset of the product review data. Processed data available. | | HuffPost&nbsp;headlines&nbsp;([link](https://www.kaggle.com/rmisra/news-category-dataset "HuffPost")) | Processed data available. | Please download pretrain word vector file `wiki.en.vec` from [here](https://dl.fbaipublicfiles.com/fasttext/vectors-wiki/wiki.en.vec) and put it under `pretrain_wordvec/` folder. ### Quickstart After you have finished configuring the `data/` folder and the `pretrain_wordvec/` folder, you can run our model with the following commands. ``` cd bin sh mlada.sh ``` You can also adjust the model by modifying the parameters in the `malada.sh` file. ### Dependencies - Python 3.7 - PyTorch 1.6.0 - numpy 1.18.5 - torchtext 0.7.0 - termcolor 1.1.0 - tqdm 4.46.0 - CUDA 10.2
a9d831738589f5064f8a3221285cb184562ccc87
{ "blob_id": "a9d831738589f5064f8a3221285cb184562ccc87", "branch_name": "refs/heads/master", "committer_date": "2021-02-01T14:25:18", "content_id": "fe702ab8984fd0862bd753703387c87d6cc0eae7", "detected_licenses": [ "MIT" ], "directory_id": "60fa8ae2b85002d2f62b3ef41387570aa2733362", "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": 316219689, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1462, "license": "MIT", "license_type": "permissive", "path": "/README.md", "provenance": "stack-edu-markdown-0015.json.gz:275248", "repo_name": "zeqiufan/Distributional-Signatures", "revision_date": "2021-02-01T14:25:18", "revision_id": "fcda2739af36fc99341794a37ab89667fbe2b719", "snapshot_id": "17268c37595fd72ef085be2b40263066d406d888", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/zeqiufan/Distributional-Signatures/fcda2739af36fc99341794a37ab89667fbe2b719/README.md", "visit_date": "2023-03-01T21:41:42.950929", "added": "2024-11-19T00:56:18.659298+00:00", "created": "2021-02-01T14:25:18", "int_score": 3, "score": 3.296875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0015.json.gz" }
package com.isaev.ee.lazyload.application; import com.isaev.ee.lazyload.database.exception.DataMapperException; import com.isaev.ee.lazyload.database.utils.QueryExecutor; import com.isaev.ee.lazyload.people.PersonMapper; import org.apache.log4j.Logger; import java.util.stream.IntStream; public class Application { private static final Logger logger = Logger.getLogger(Application.class); private static final PersonMapper personMapper = new PersonMapper(); private static final int NUMBER_OF_PEOPLE_TO_CREATE = 100; private static final String MESSAGE_TEMPLATE_CANNOT_FIND_PERSON = "Cannot find person by ID: %s"; public static void main(String[] args) { initiateDatabase(); generateData(); runApplication(); } private static void runApplication() { IntStream.range(0, NUMBER_OF_PEOPLE_TO_CREATE).forEach(id -> { try { System.out.println(personMapper.findById(id).orElseThrow()); } catch (DataMapperException e) { var message = String.format(MESSAGE_TEMPLATE_CANNOT_FIND_PERSON, id); logger.error(message, e); } }); } protected static void initiateDatabase() { QueryExecutor.createUser(); QueryExecutor.createDatabase(); QueryExecutor.createTables(); } private static void deleteDatabase() { QueryExecutor.deleteDatabase(); } protected static void generateData() { DataGenerator dataGenerator = new DataGenerator(); dataGenerator.generatePeople(NUMBER_OF_PEOPLE_TO_CREATE); } }
b69bcbb582c6a6fc3081e73286442e284c666b41
{ "blob_id": "b69bcbb582c6a6fc3081e73286442e284c666b41", "branch_name": "refs/heads/master", "committer_date": "2022-09-06T15:29:48", "content_id": "2d0a23a390192cb2b6804d817c51a2944461b968", "detected_licenses": [ "MIT" ], "directory_id": "01a7b7b67536286650f900e3d763f10c4f52f519", "extension": "java", "filename": "Application.java", "fork_events_count": 0, "gha_created_at": "2020-04-08T14:28:23", "gha_event_created_at": "2022-11-23T22:25:30", "gha_language": "Java", "gha_license_id": "MIT", "github_id": 254111101, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1618, "license": "MIT", "license_type": "permissive", "path": "/lazy-load/src/main/java/com/isaev/ee/lazyload/application/Application.java", "provenance": "stack-edu-0031.json.gz:406881", "repo_name": "Georgich88/enterprise-patterns", "revision_date": "2022-09-06T15:29:48", "revision_id": "6cc21b3ab85773e24af791a12704664b32c7e93b", "snapshot_id": "9ef10a48df09df2d59ab9f0bd2524c8957da63cb", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Georgich88/enterprise-patterns/6cc21b3ab85773e24af791a12704664b32c7e93b/lazy-load/src/main/java/com/isaev/ee/lazyload/application/Application.java", "visit_date": "2022-11-29T08:53:20.782453", "added": "2024-11-19T00:13:15.561439+00:00", "created": "2022-09-06T15:29:48", "int_score": 3, "score": 2.703125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0049.json.gz" }
import unittest import json import jc.parsers.timestamp class MyTests(unittest.TestCase): def test_timestamp_nodata(self): """ Test 'timestamp' with no data """ self.assertEqual(jc.parsers.timestamp.parse('', quiet=True), {}) def test_10_digit_timestamp(self): """ Test 10 digit timestamp string """ data = r'1658599410' expected = json.loads(r"""{"naive":{"year":2022,"month":"Jul","month_num":7,"day":23,"weekday":"Sat","weekday_num":6,"hour":11,"hour_24":11,"minute":3,"second":30,"period":"AM","day_of_year":204,"week_of_year":29,"iso":"2022-07-23T11:03:30"},"utc":{"year":2022,"month":"Jul","month_num":7,"day":23,"weekday":"Sat","weekday_num":6,"hour":6,"hour_24":18,"minute":3,"second":30,"period":"PM","utc_offset":"+0000","day_of_year":204,"week_of_year":29,"iso":"2022-07-23T18:03:30+00:00"}}""") self.assertEqual(jc.parsers.timestamp.parse(data, quiet=True), expected) def test_13_digit_timestamp(self): """ Test 13 digit timestamp string (with milliseconds) """ data = r'1658604427154' expected = json.loads(r"""{"naive":{"year":2022,"month":"Jul","month_num":7,"day":23,"weekday":"Sat","weekday_num":6,"hour":12,"hour_24":12,"minute":27,"second":7,"period":"PM","day_of_year":204,"week_of_year":29,"iso":"2022-07-23T12:27:07"},"utc":{"year":2022,"month":"Jul","month_num":7,"day":23,"weekday":"Sat","weekday_num":6,"hour":7,"hour_24":19,"minute":27,"second":7,"period":"PM","utc_offset":"+0000","day_of_year":204,"week_of_year":29,"iso":"2022-07-23T19:27:07+00:00"}}""") self.assertEqual(jc.parsers.timestamp.parse(data, quiet=True), expected) if __name__ == '__main__': unittest.main()
e7e1875aff7e90c91fc0f40c59309a1a8fb8ba3b
{ "blob_id": "e7e1875aff7e90c91fc0f40c59309a1a8fb8ba3b", "branch_name": "refs/heads/master", "committer_date": "2023-07-30T17:08:39", "content_id": "3a63b3fe571b12f5102d2df9294a65b4390bb39d", "detected_licenses": [ "MIT" ], "directory_id": "c19bcbc98555ef06276f9f0dcffc9ac35942a7c4", "extension": "py", "filename": "test_timestamp.py", "fork_events_count": 185, "gha_created_at": "2019-10-15T22:04:52", "gha_event_created_at": "2023-09-08T14:52:22", "gha_language": "Python", "gha_license_id": "MIT", "github_id": 215404927, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1751, "license": "MIT", "license_type": "permissive", "path": "/tests/test_timestamp.py", "provenance": "stack-edu-0058.json.gz:297184", "repo_name": "kellyjonbrazil/jc", "revision_date": "2023-07-30T17:08:39", "revision_id": "4cd721be8595db52b620cc26cd455d95bf56b85b", "snapshot_id": "4e81a5421cd20be5965baf375f4a5671c2ef0410", "src_encoding": "UTF-8", "star_events_count": 6278, "url": "https://raw.githubusercontent.com/kellyjonbrazil/jc/4cd721be8595db52b620cc26cd455d95bf56b85b/tests/test_timestamp.py", "visit_date": "2023-08-30T09:53:18.284296", "added": "2024-11-18T19:27:50.609653+00:00", "created": "2023-07-30T17:08:39", "int_score": 3, "score": 2.78125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0076.json.gz" }
html5-image-upload-gui ====================== This is a simple and effective GUI for a generic batch image uploader using HTML5 & Javascript with Twitter Bootstrap. ## Demo [http://demo.smrtr.co.uk/html5-image-upload-gui/](http://demo.smrtr.co.uk/html5-image-upload-gui/) ## Credits - Twitter for [Twitter Bootstrap](https://github.com/twitter/bootstrap). - August Lilleaas for the js-unzip and js-inflate libraries. https://github.com/augustl/js-unzip and https://github.com/augustl/js-inflate. - Niklas von Hertzen for the [Base64 to ArrayBuffer converter](https://github.com/niklasvh/base64-arraybuffer). - Kyle Fox for the [jquery modal plugin](https://github.com/kylefox/jquery-modal).
270240f9a239122672d8293d0e6b45eac29764d9
{ "blob_id": "270240f9a239122672d8293d0e6b45eac29764d9", "branch_name": "refs/heads/master", "committer_date": "2013-07-20T20:49:02", "content_id": "d129ea654c41fb34fc0fb29ffc818989c446f72e", "detected_licenses": [ "MIT" ], "directory_id": "68923550a304c5942ffc6264ccf66e3583746727", "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": 699, "license": "MIT", "license_type": "permissive", "path": "/README.md", "provenance": "stack-edu-markdown-0006.json.gz:169500", "repo_name": "joegreen88/html5-image-upload-gui", "revision_date": "2013-07-20T20:49:02", "revision_id": "aa0d3c5bf65c47eaac8e50230df789f6c8ad3d07", "snapshot_id": "ab57f6674fad5b753ecd015936f9e4347e624b3d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/joegreen88/html5-image-upload-gui/aa0d3c5bf65c47eaac8e50230df789f6c8ad3d07/README.md", "visit_date": "2020-05-31T02:36:06.770664", "added": "2024-11-18T22:54:39.210783+00:00", "created": "2013-07-20T20:49:02", "int_score": 2, "score": 2.484375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0006.json.gz" }
package io.ballerina.openapi.generators.common; /** * Constants for openapi code generator unit test cases. */ public class TestConstants { private static String clientConfigRecordDoc = "" + "# Provides a set of configurations for controlling the behaviours when communicating with a remote " + "HTTP endpoint."; private static String commonClientConfigurationFields = "# The HTTP version understood by the client\n" + " string httpVersion = \"1.1\";\n" + " # Configurations related to HTTP/1.x protocol\n" + " http:ClientHttp1Settings http1Settings = {};\n" + " # Configurations related to HTTP/2 protocol\n" + " http:ClientHttp2Settings http2Settings = {};\n" + " # The maximum time to wait (in seconds) for a response before closing the connection\n" + " decimal timeout = 60;\n" + " # The choice of setting `forwarded`/`x-forwarded` header\n" + " string forwarded = \"disable\";\n" + " # Configurations associated with Redirection\n" + " http:FollowRedirects? followRedirects = ();\n" + " # Configurations associated with request pooling\n" + " http:PoolConfiguration? poolConfig = ();\n" + " # HTTP caching related configurations\n" + " http:CacheConfig cache = {};\n" + " # Specifies the way of handling compression (`accept-encoding`) header\n" + " http:Compression compression = http:COMPRESSION_AUTO;\n" + " # Configurations associated with the behaviour of the Circuit Breaker\n" + " http:CircuitBreakerConfig? circuitBreaker = ();\n" + " # Configurations associated with retrying\n" + " http:RetryConfig? retryConfig = ();\n" + " # Configurations associated with cookies\n" + " http:CookieConfig? cookieConfig = ();\n" + " # Configurations associated with inbound response size limits\n" + " http:ResponseLimitConfigs responseLimits = {};\n" + " # SSL/TLS-related options\n" + " http:ClientSecureSocket? secureSocket = ();\n" + "|};"; public static final String HTTP_BASIC_AUTH_CONFIG_REC = "" + clientConfigRecordDoc + "public type ClientConfig record {|\n" + " # Configurations related to client authentication\n" + " http:CredentialsConfig auth;\n" + commonClientConfigurationFields; public static final String HTTP_BEARER_AUTH_CONFIG_REC = "" + clientConfigRecordDoc + "public type ClientConfig record {|\n" + " # Configurations related to client authentication\n" + " http:BearerTokenConfig auth;\n" + commonClientConfigurationFields; public static final String HTTP_MULTI_AUTH_CONFIG_REC = "" + clientConfigRecordDoc + "public type ClientConfig record {|\n" + " # Configurations related to client authentication\n" + " http:BearerTokenConfig|http:CredentialsConfig auth;\n" + commonClientConfigurationFields; public static final String HTTP_CLIENT_CONFIG_PARAM = "ClientConfig clientConfig, string serviceUrl = \"https:localhost/8080\""; public static final String HTTP_CLIENT_CONFIG_PARAM_NO_URL = "ClientConfig clientConfig, string serviceUrl"; public static final String HTTP_CLIENT_DECLARATION = "" + "http:Client httpEp = check new (serviceUrl, clientConfig);"; public static final String OAUTH2_AUTHORIZATION_CODE_CONFIG_REC = "" + clientConfigRecordDoc + "public type ClientConfig record {|\n" + " # Configurations related to client authentication\n" + " http:BearerTokenConfig|http:OAuth2RefreshTokenGrantConfig auth;\n" + commonClientConfigurationFields; public static final String OAUTH2_IMPLICIT_CONFIG_REC = "" + clientConfigRecordDoc + "public type ClientConfig record {|\n" + " # Configurations related to client authentication\n" + " http:BearerTokenConfig auth;\n" + commonClientConfigurationFields; public static final String OAUTH2_PASSWORD_CONFIG_REC = "" + clientConfigRecordDoc + "public type ClientConfig record {|\n" + " # Configurations related to client authentication\n" + " http:OAuth2PasswordGrantConfig auth;\n" + commonClientConfigurationFields; public static final String OAUTH2_CLIENT_CRED_CONFIG_REC = "" + clientConfigRecordDoc + "public type ClientConfig record {|\n" + " # Configurations related to client authentication\n" + " http:OAuth2ClientCredentialsGrantConfig auth;\n" + commonClientConfigurationFields; public static final String OAUTH2_MULTI_FLOWS_CONFIG_REC = "" + clientConfigRecordDoc + "public type ClientConfig record {|\n" + " # Configurations related to client authentication\n" + " http:OAuth2PasswordGrantConfig|http:BearerTokenConfig|http:OAuth2RefreshTokenGrantConfig auth;\n" + commonClientConfigurationFields; public static final String API_KEY_CONFIG_VAR = "final readonly & ApiKeysConfig apiKeyConfig;"; public static final String API_KEY_CONFIG_PARAM = "" + "ApiKeysConfig apiKeyConfig, http:ClientConfiguration clientConfig = {}, " + "string serviceUrl = \"https:localhost/8080\""; public static final String API_KEY_CONFIG_PARAM_NO_URL = "" + "ApiKeysConfig apiKeyConfig, string serviceUrl, http:ClientConfiguration clientConfig = {}"; public static final String API_KEYS_CONFIG_RECORD = "# Provides API key configurations needed when communicating " + "with a remote HTTP endpoint.\n" + "public type ApiKeysConfig record {|\n" + " # API key to authorize requests.\n" + " string appid;\n" + " # API key to authorize requests.\n" + " string apiXKey;\n" + "|};"; public static final String API_KEY_ASSIGNMENT = "self.apiKeyConfig = apiKeyConfig.cloneReadOnly();"; public static final String DEFAULT_API_KEY_DOC_COMMENT = "API key configuration details"; public static final String MULTIPLE_API_KEY_RECORD = "# Provides API key configurations needed when " + "communicating with a remote HTTP endpoint.\n" + "public type ApiKeysConfig record {|\n" + " # API key to authorize GET requests.\n" + " string appid;\n" + " # API key to authorize POST requests.\n" + " string xApiKey;\n" + "|};"; }
8617b74275388b224f363e3ae971ac52d8fe8a7c
{ "blob_id": "8617b74275388b224f363e3ae971ac52d8fe8a7c", "branch_name": "refs/heads/master", "committer_date": "2021-09-25T15:24:34", "content_id": "ba537e0a019e350383091ae3b035019af778a8c4", "detected_licenses": [ "Apache-2.0" ], "directory_id": "0b2bf53aa85d76290730948c0891d43d215753e7", "extension": "java", "filename": "TestConstants.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": 6894, "license": "Apache-2.0", "license_type": "permissive", "path": "/openapi-cli/src/test/java/io/ballerina/openapi/generators/common/TestConstants.java", "provenance": "stack-edu-0027.json.gz:304139", "repo_name": "LahiruRajapaksha/ballerina-openapi", "revision_date": "2021-09-25T15:24:34", "revision_id": "95ca5064eea6b59da4077bac491f9ad9c30e5010", "snapshot_id": "d69c9981c37ae9a7980bb9ebbf4863923f30cdff", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/LahiruRajapaksha/ballerina-openapi/95ca5064eea6b59da4077bac491f9ad9c30e5010/openapi-cli/src/test/java/io/ballerina/openapi/generators/common/TestConstants.java", "visit_date": "2023-08-16T20:23:45.145523", "added": "2024-11-18T23:06:34.564471+00:00", "created": "2021-09-25T15:24:34", "int_score": 2, "score": 2.09375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0045.json.gz" }
"""Tests written to ensure the MiceImputer in the imputations package works. Note that this also tests the MultipleImputer, which really just passes to the SingleImputer. SingleImputer has tests, some of which are the same as here. Tests use the pytest library. The tests in this module ensure the following: - `test_stochastic_predictive_imputer` test stochastic strategy. - `test_bayesian_reg_imputer` test bayesian regression strategy. - `test_bayesian_logistic_imputer` test bayesian logistic strategy. - `test_pmm_lrd_imputer` test pmm and lrd strategy. - `test_normal_unit_variance_imputer` test unit variance imputer """ import pytest from autoimpute.imputations import MiceImputer from autoimpute.utils import dataframes dfs = dataframes # pylint:disable=len-as-condition # pylint:disable=pointless-string-statement def test_stochastic_predictive_imputer(): """Test stochastic works for numerical columns of PredictiveImputer.""" # generate linear, then stochastic imp_p = MiceImputer(strategy={"A":"least squares"}) imp_s = MiceImputer(strategy={"A":"stochastic"}) # make sure both work _ = imp_p.fit_transform(dfs.df_num) _ = imp_s.fit_transform(dfs.df_num) assert imp_p.imputed_["A"] == imp_s.imputed_["A"] def test_bayesian_reg_imputer(): """Test bayesian works for numerical column of PredictiveImputer.""" # test designed first - test kwargs and params imp_b = MiceImputer(strategy={"y":"bayesian least squares"}, imp_kwgs={"y":{"fill_value": "random", "am": 11, "cores": 2}}) imp_b.fit_transform(dfs.df_bayes_reg) # test on numerical in general imp_n = MiceImputer(strategy="bayesian least squares") imp_n.fit_transform(dfs.df_num) def test_bayesian_logistic_imputer(): """Test bayesian works for binary column of PredictiveImputer.""" imp_b = MiceImputer(strategy={"y":"bayesian binary logistic"}, imp_kwgs={"y":{"fill_value": "random"}}) imp_b.fit_transform(dfs.df_bayes_log) def test_pmm_lrd_imputer(): """Test pmm and lrd work for numerical column of PredictiveImputer.""" # test pmm first - test kwargs and params imp_pmm = MiceImputer(strategy={"y":"pmm"}, imp_kwgs={"y": {"fill_value": "random", "copy_x": False}}) imp_pmm.fit_transform(dfs.df_bayes_reg) # test lrd second - test kwargs and params imp_lrd = MiceImputer(strategy={"y":"lrd"}, imp_kwgs={"y": {"fill_value": "random", "copy_x": False}}) imp_lrd.fit_transform(dfs.df_bayes_reg) def test_normal_unit_variance_imputer(): """Test normal unit variance imputer for numerical column""" imp_pmm = MiceImputer(strategy={"y":"normal unit variance"},) imp_pmm.fit_transform(dfs.df_bayes_reg) def test_partial_dependence_imputer(): """Test to ensure that edge case for partial dependence whandled""" imp = MiceImputer(strategy='stochastic') imp.fit_transform(dfs.df_partial_dependence)
aa573a91ed86ce153f4c5d2c84e8ccc85c8fd554
{ "blob_id": "aa573a91ed86ce153f4c5d2c84e8ccc85c8fd554", "branch_name": "refs/heads/master", "committer_date": "2023-05-24T04:43:28", "content_id": "4a0fab0db78df078b4210f40f8dcf34818b0aa1c", "detected_licenses": [ "MIT" ], "directory_id": "45d01a6c5fbf766ad4d996c044412dc2b268ef07", "extension": "py", "filename": "test_mice_imputer.py", "fork_events_count": 27, "gha_created_at": "2019-01-30T23:09:47", "gha_event_created_at": "2022-09-10T22:36:57", "gha_language": "Python", "gha_license_id": "MIT", "github_id": 168429609, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3118, "license": "MIT", "license_type": "permissive", "path": "/tests/test_imputations/test_mice_imputer.py", "provenance": "stack-edu-0064.json.gz:315002", "repo_name": "kearnz/autoimpute", "revision_date": "2023-05-24T04:43:28", "revision_id": "6ef82663464aad187fd341fcace8e97bd0222aaf", "snapshot_id": "2cf88d8cf4a1ab6b8b6579c8dca2ecd38eb1aaf9", "src_encoding": "UTF-8", "star_events_count": 245, "url": "https://raw.githubusercontent.com/kearnz/autoimpute/6ef82663464aad187fd341fcace8e97bd0222aaf/tests/test_imputations/test_mice_imputer.py", "visit_date": "2023-06-07T21:08:23.584459", "added": "2024-11-18T22:00:44.147639+00:00", "created": "2023-05-24T04:43:28", "int_score": 3, "score": 2.953125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0082.json.gz" }
package com.hys.exam.dao.local.jdbc; import com.hys.exam.dao.BaseDao; import com.hys.exam.dao.local.GroupClassInfoDAO; import com.hys.exam.model.CVT; import com.hys.exam.model.GroupClassInfo; import com.hys.exam.utils.StringUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Attributes; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper; import java.util.ArrayList; import java.util.List; public class GroupClassInfoJDBCDAO extends BaseDao implements GroupClassInfoDAO { private static final String QUERY_CLASS_SQL = "select * from group_class_info where class_id= ? "; //private static final String QUERY_TREE_SQL = " select c.id,0 as pId,c.name from cv c where c.id = ? " + " union all " + " select u.id,1 as pId,u.name from cv_ref_unit r left join cv_unit u on r.unit_id = u.id where r.cv_id = ?" ; private static final String QUERY_TREE_SQL = " select c.id,0 as pId,c.name,0 as sequenceNum,0 AS type from cv c where c.id = ? " + " union all " + " select u.id,1 as pId,u.name,u.sequenceNum, u.TYPE from cv_ref_unit r left join cv_unit u on r.unit_id = u.id where r.cv_id = ? order by sequenceNum asc " ; //YHQ,2017-05-26,按照单元顺序排序 private static final String QUERY_SQL = " select * from group_class_info info where 1 = 1 order by info.state desc "; @Override public boolean addGroupClassInfo(GroupClassInfo group) { //YHQ,2017-05-17 String classContentHtml = group.getClassContent() ; String mediaType = null , mediaId = null ; if (classContentHtml != null) { Document htmlDoc = Jsoup.parse(classContentHtml) ; if (htmlDoc != null) { Elements htmlAllImg = htmlDoc.getElementsByTag("img") ; for (Element imgElt : htmlAllImg) { Attributes allProp = imgElt.attributes() ; String altAttr = allProp.get("alt") ; String urlAttr = allProp.get("_url") ; String onclickAttr = allProp.get("onclick") ; //play(this); if (!StringUtils.checkNull(urlAttr)) { if (!StringUtils.checkNull(altAttr)) { if (altAttr.equals("paper")) {//试卷 mediaType = "paper" ; mediaId = urlAttr ; break ; } if (altAttr.equals("bingli")) {//病例 mediaType = "bingli" ; mediaId = urlAttr ; break ; } if (altAttr.equals("talk")) {//讨论 mediaType = "talk" ; mediaId = urlAttr ; break ; } } if (!StringUtils.checkNull(onclickAttr) && onclickAttr.equals("play(this);")) { mediaType = "video" ; mediaId = urlAttr ; break ; } } } } } String sql = " insert into group_class_info(class_id,class_name,class_parent_id,class_parent_name,class_content,template_type,create_date) " + " values (" + group.getClassId() + ",'" + group.getClassName() + "'," + group.getClassParentId() + ",'" + group.getClassParentName() +"','" + classContentHtml + "','" + group.getTemplateType() + "',sysdate())"; if (mediaType != null && mediaId != null) { sql = " insert into group_class_info(class_id,class_name,class_parent_id,class_parent_name,class_content,template_type,create_date,media_type,media_id) " + " values (" + group.getClassId() + ",'" + group.getClassName() + "'," + group.getClassParentId() + ",'" + group.getClassParentName() +"','" + classContentHtml + "','" + group.getTemplateType() + "',sysdate(),'" + mediaType + "','" + mediaId + "')"; } int result = getSimpleJdbcTemplate().update(sql); if(result>0){ return true; }else{ return false; } } @Override public List<GroupClassInfo> queryGroupClassContent(int classId){ List <GroupClassInfo> list = new ArrayList<GroupClassInfo>(); list = getJdbcTemplate().query(QUERY_CLASS_SQL, ParameterizedBeanPropertyRowMapper.newInstance(GroupClassInfo.class), classId); return list; } @Override public void updateGroupClassInfo(GroupClassInfo group) throws Exception { //YHQ,2017-05-17 String classContentHtml = group.getClassContent() ; String mediaType = null , mediaId = null ; if (classContentHtml != null) { Document htmlDoc = Jsoup.parse(classContentHtml) ; if (htmlDoc != null) { Elements htmlAllImg = htmlDoc.getElementsByTag("img") ; for (Element imgElt : htmlAllImg) { Attributes allProp = imgElt.attributes() ; String altAttr = allProp.get("alt") ; String urlAttr = allProp.get("_url") ; String onclickAttr = allProp.get("onclick") ; //play(this); if (!StringUtils.checkNull(urlAttr)) { if (!StringUtils.checkNull(altAttr)) { if (altAttr.equals("paper")) {//试卷 mediaType = "paper" ; mediaId = urlAttr ; break ; } if (altAttr.equals("bingli")) {//病例 mediaType = "bingli" ; mediaId = urlAttr ; break ; } if (altAttr.equals("talk")) {//讨论 mediaType = "talk" ; mediaId = urlAttr ; break ; } } if (!StringUtils.checkNull(onclickAttr) && onclickAttr.equals("play(this);")) { mediaType = "video" ; mediaId = urlAttr ; break ; } } } } } String sql = "update group_class_info set class_content = ? , template_type = ? where class_id = ?"; if (mediaType != null && mediaId != null) { sql = "update group_class_info set class_content = ? , template_type = ? , media_type = ? , media_id = ? where class_id = ?"; getJdbcTemplate().update(sql,classContentHtml,group.getTemplateType(),mediaType,mediaId,group.getClassId()); } else { getJdbcTemplate().update(sql,classContentHtml,group.getTemplateType(),group.getClassId()); } } @Override public List<CVT> queryCVTList(int classId) throws Exception { List <CVT> list = new ArrayList<CVT>(); list = getJdbcTemplate().query(QUERY_TREE_SQL, ParameterizedBeanPropertyRowMapper.newInstance(CVT.class), classId,classId); return list; } @Override public List<GroupClassInfo> queryList() throws Exception { List <GroupClassInfo> list = new ArrayList<GroupClassInfo>(); list = getJdbcTemplate().query(QUERY_SQL, ParameterizedBeanPropertyRowMapper.newInstance(GroupClassInfo.class)); return list; } //YHQ 2017-03-04,更新课程单元的评分 @Override public boolean updateUnitQuota(Long unitId, Double unitQuota) throws Exception { if (unitId != null && unitQuota != null) { String sql = "update cv_unit set quota=" + unitQuota + " where id=" + unitId ; int updateNum = getJdbcTemplate().update(sql) ; if (updateNum > 0) return true ; } return false ; } }
098eb1e97131e1aa0ef5f018ecd8878400c84cf5
{ "blob_id": "098eb1e97131e1aa0ef5f018ecd8878400c84cf5", "branch_name": "refs/heads/master", "committer_date": "2018-01-15T01:54:21", "content_id": "7328f4ac7f95d57e37cbb66a6df0555e2cfa5b6b", "detected_licenses": [ "Apache-2.0" ], "directory_id": "dc0e271669780a11284b9626919846a51b00d54c", "extension": "java", "filename": "GroupClassInfoJDBCDAO.java", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 117482274, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 6962, "license": "Apache-2.0", "license_type": "permissive", "path": "/model/com/hys/exam/dao/local/jdbc/GroupClassInfoJDBCDAO.java", "provenance": "stack-edu-0031.json.gz:5413", "repo_name": "1224500506/NCME-Admin", "revision_date": "2018-01-15T01:54:21", "revision_id": "e4f0969938ed6d9c076a9d647681dd56a1bf2679", "snapshot_id": "4a4b8e62f85b352dee0a96f096748b04fbf1b67e", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/1224500506/NCME-Admin/e4f0969938ed6d9c076a9d647681dd56a1bf2679/model/com/hys/exam/dao/local/jdbc/GroupClassInfoJDBCDAO.java", "visit_date": "2021-04-24T19:28:33.899711", "added": "2024-11-18T21:49:58.058443+00:00", "created": "2018-01-15T01:54:21", "int_score": 2, "score": 2.125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0049.json.gz" }
<?php namespace SchemaOrg\Enum; use MyCLabs\Enum\Enum; /** * A business entity type is a conceptual entity representing the legal form, the size, the main line of business, the position in the value chain, or any combination thereof, of an organization or business person. * * Commonly used values: * * http://purl.org/goodrelations/v1#Business * http://purl.org/goodrelations/v1#Enduser * http://purl.org/goodrelations/v1#PublicInstitution * http://purl.org/goodrelations/v1#Reseller * * * * @see http://schema.org/BusinessEntityType Documentation on Schema.org * * @ORM\MappedSuperclass */ class BusinessEntityType extends Enum { }
197e881b77e1988a25f1417fe88c6aae37b74422
{ "blob_id": "197e881b77e1988a25f1417fe88c6aae37b74422", "branch_name": "refs/heads/master", "committer_date": "2014-08-27T22:43:33", "content_id": "82273933a7de76379d2311905f385a37021fee8f", "detected_licenses": [ "MIT" ], "directory_id": "31c6943b90472ff4e6ee73f998e4e2072513305c", "extension": "php", "filename": "BusinessEntityType.php", "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": "PHP", "length_bytes": 685, "license": "MIT", "license_type": "permissive", "path": "/examples/full/SchemaOrg/Enum/BusinessEntityType.php", "provenance": "stack-edu-0052.json.gz:406398", "repo_name": "jaymecd/php-schema.org-model", "revision_date": "2014-08-27T22:43:33", "revision_id": "b76aba729d06815a8d9bac2dbe5358f7cbb18b5a", "snapshot_id": "71c306c848b543fe35c2c858bbc531a432bdd504", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jaymecd/php-schema.org-model/b76aba729d06815a8d9bac2dbe5358f7cbb18b5a/examples/full/SchemaOrg/Enum/BusinessEntityType.php", "visit_date": "2020-07-14T17:59:40.040463", "added": "2024-11-18T21:54:16.331934+00:00", "created": "2014-08-27T22:43:33", "int_score": 2, "score": 2.40625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0070.json.gz" }
// Copyright 2017 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. #include "components/wallpaper/wallpaper_color_calculator.h" #include <string> #include <utility> #include "base/bind.h" #include "base/metrics/histogram_macros.h" #include "base/task_runner.h" #include "base/task_runner_util.h" namespace wallpaper { WallpaperColorCalculator::WallpaperColorCalculator( const gfx::ImageSkia& image, color_utils::LumaRange luma, color_utils::SaturationRange saturation, scoped_refptr<base::TaskRunner> task_runner) : image_(image), luma_(luma), saturation_(saturation), task_runner_(std::move(task_runner)), weak_ptr_factory_(this) {} WallpaperColorCalculator::~WallpaperColorCalculator() {} void WallpaperColorCalculator::AddObserver( WallpaperColorCalculatorObserver* observer) { observers_.AddObserver(observer); } void WallpaperColorCalculator::RemoveObserver( WallpaperColorCalculatorObserver* observer) { observers_.RemoveObserver(observer); } bool WallpaperColorCalculator::StartCalculation() { start_calculation_time_ = base::Time::Now(); image_.MakeThreadSafe(); if (base::PostTaskAndReplyWithResult( task_runner_.get(), FROM_HERE, base::Bind(&color_utils::CalculateProminentColorOfBitmap, *image_.bitmap(), luma_, saturation_), base::Bind(&WallpaperColorCalculator::NotifyCalculationComplete, weak_ptr_factory_.GetWeakPtr()))) { return true; } LOG(WARNING) << "PostSequencedWorkerTask failed. " << "Wallpaper promiment color may not be calculated."; prominent_color_ = SK_ColorTRANSPARENT; return false; } void WallpaperColorCalculator::SetTaskRunnerForTest( scoped_refptr<base::TaskRunner> task_runner) { task_runner_ = task_runner; } void WallpaperColorCalculator::NotifyCalculationComplete( SkColor prominent_color) { UMA_HISTOGRAM_MEDIUM_TIMES("Ash.Wallpaper.TimeSpentExtractingColors", base::Time::Now() - start_calculation_time_); prominent_color_ = prominent_color; for (auto& observer : observers_) observer.OnColorCalculationComplete(); // This could be deleted! } } // namespace wallpaper
59bdfeb6ed17988d9191798c75078a7a6f6b0c49
{ "blob_id": "59bdfeb6ed17988d9191798c75078a7a6f6b0c49", "branch_name": "refs/heads/master", "committer_date": "2017-04-08T12:28:57", "content_id": "0096d5d19161120856ab32d3931036ce9db9d7ad", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "8567438779e6af0754620a25d379c348e4cd5a5d", "extension": "cc", "filename": "wallpaper_color_calculator.cc", "fork_events_count": 1, "gha_created_at": "2017-03-06T13:04:15", "gha_event_created_at": "2022-10-25T19:47:15", "gha_language": null, "gha_license_id": "BSD-3-Clause", "github_id": 84073924, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2336, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/components/wallpaper/wallpaper_color_calculator.cc", "provenance": "stack-edu-0004.json.gz:228142", "repo_name": "thngkaiyuan/chromium", "revision_date": "2017-04-08T12:28:57", "revision_id": "dab56a4a71f87f64ecc0044e97b4a8f247787a68", "snapshot_id": "c389ac4b50ccba28ee077cbf6115c41b547955ae", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/thngkaiyuan/chromium/dab56a4a71f87f64ecc0044e97b4a8f247787a68/components/wallpaper/wallpaper_color_calculator.cc", "visit_date": "2022-11-10T02:50:29.326119", "added": "2024-11-18T22:27:21.780572+00:00", "created": "2017-04-08T12:28:57", "int_score": 2, "score": 2.203125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0022.json.gz" }
/* Searches and sorts can be tricky to visualize and understand. If you need to, go through the video a few more times until it really sinks in. Here is a supplementary visualization that might help as well! Swift arrays have a method called index(of:), which just does a search and returns the first index with an instance of that value. Next, you'll write a function that has the same result, but searches faster, using binary search. Keep in mind the constraint for this exercise—for binary search to work, the elements must be in increasing order. Binary Search Practice You're going to write a binary search method using loops. Your function should take two inputs: an array to search through, and the value you're searching for. Assume the array only has distinct elements, meaning there are no repeated values, and that elements are in a strictly increasing order. Return the index where value exists in the array, or nil if the value is not present. */ // Return the index in the array, of the desired value // If the value can't be found, return nil func binarySearch(_ array: [Int], value: Int) -> Int? { // Your code goes here guard !array.isEmpty else { return nil } var lowEnd = 0 var highEnd = array.count - 1 var index = (lowEnd + highEnd) / 2 var x: Int! while true { x = array[index] if x == value { return index } else if x < value { lowEnd = index + 1 } else if x > value { highEnd = index - 1 } index = (lowEnd + highEnd) / 2 if index == lowEnd { return nil } } } // Test cases let testArray = [1, 3, 9, 11, 15, 19, 29] let testVal1 = 25 let testVal2 = 15 print(binarySearch(testArray, value: testVal1)) // Should be nil print(binarySearch(testArray, value: testVal2)!) // Should be 4 /* nil 4 */
76a6516b40eec11c2c510d87351811f00b92f98b
{ "blob_id": "76a6516b40eec11c2c510d87351811f00b92f98b", "branch_name": "refs/heads/main", "committer_date": "2021-11-18T22:27:50", "content_id": "59ffcc982f3778fb0c4bd7135ad75c2358573b7f", "detected_licenses": [ "MIT" ], "directory_id": "39313c725e8d2da3aecde39879179ccfa9ce4f82", "extension": "swift", "filename": "binary-search.swift", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 163247093, "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 1881, "license": "MIT", "license_type": "permissive", "path": "/Archived on Wednesday, 1 September 2021/binary-search.swift", "provenance": "stack-edu-0072.json.gz:2376", "repo_name": "NicholasTD07/swift-data-structure-and-algorithms", "revision_date": "2021-11-18T22:27:50", "revision_id": "75f9a9b33a534cbcd96e65024b211d20b148c476", "snapshot_id": "c7c1f75eda8590cc83c47b67eed4723459b0235e", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/NicholasTD07/swift-data-structure-and-algorithms/75f9a9b33a534cbcd96e65024b211d20b148c476/Archived on Wednesday, 1 September 2021/binary-search.swift", "visit_date": "2021-11-25T02:18:55.399830", "added": "2024-11-18T21:24:08.205168+00:00", "created": "2021-11-18T22:27:50", "int_score": 5, "score": 4.5625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0090.json.gz" }
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Apr 1 13:54:26 2021 @author: jasperhajonides """ import numpy as np def sample_data_time(n_trials=100, n_features=5, num_samples=200, n_classes = 5): """ Create sample time series dataset""" # n_features = 30 # n_classes = 5 # n_trials = 100 # num_samples = 100 max_theta = np.pi*5 thetas = np.linspace(0,max_theta,num_samples) x = np.zeros((n_trials*n_classes, n_features-1, len(thetas))) y = np.zeros(n_trials*n_classes) counter = 0 for i, cl in enumerate(np.arange(-np.pi, np.pi, np.pi*2/n_classes)): for trial in range(n_trials): for feat in range(1,n_features): x_temp = n_features/feat*np.sin(thetas+cl+np.random.rand()) + feat/n_features*np.cos(thetas+cl+np.random.rand()) # add noise # np.random.seed(42) for tp in range(num_samples): n = np.random.rand() * 50*tp/num_samples x[counter, feat-1, tp] = x_temp[tp] + n y[counter] = i counter += 1 return x, y
e83ef982ec99b17ebb3eee80758e19a17a4486a6
{ "blob_id": "e83ef982ec99b17ebb3eee80758e19a17a4486a6", "branch_name": "refs/heads/master", "committer_date": "2021-10-26T11:14:54", "content_id": "c78e1c1b917dae5785bee31c22d72109958bbcdf", "detected_licenses": [ "MIT" ], "directory_id": "cc38de5004f18267010920f5c3b3fe873ff48e27", "extension": "py", "filename": "simulate_data.py", "fork_events_count": 3, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 220514978, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1158, "license": "MIT", "license_type": "permissive", "path": "/simulate_data.py", "provenance": "stack-edu-0063.json.gz:58819", "repo_name": "jasperhajonides/temp_dec", "revision_date": "2021-10-26T11:14:54", "revision_id": "80a163c43cb30ac698a411d7fcb327d3f5de954e", "snapshot_id": "dedfad33d7982bb39c5221bb4a4c903343aee573", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/jasperhajonides/temp_dec/80a163c43cb30ac698a411d7fcb327d3f5de954e/simulate_data.py", "visit_date": "2023-08-29T14:38:24.104778", "added": "2024-11-18T18:59:40.696127+00:00", "created": "2021-10-26T11:14:54", "int_score": 3, "score": 2.890625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0081.json.gz" }
from collections import namedtuple import datetime import heapq from open511.utils import timezone from open511.utils import memoize_method Period = namedtuple('Period', 'start end') def text_to_date(s): return datetime.date(*[int(x) for x in s.split('-')]) if s else None def text_to_time(s): return datetime.time(*[int(x) for x in s.split(':')]) if s else None def _time_text_to_period(t): (start, _, end) = t.partition('-') return Period( text_to_time(start), text_to_time(end) ) class Schedule(object): """ Class for working with schedule components of an Open511 event. The constructor requires two arguments: an lxml Element for the <schedule> tag, and a tzinfo object (ideally from pytz) for the timezone of the event. """ def __init__(self, root, timezone): assert root.tag == 'schedules' self.root = root self.timezone = timezone self.recurring_schedules = [ RecurringScheduleComponent(el, timezone) for el in root.xpath('schedule') if el.xpath('start_date') ] @property @memoize_method def specific_dates(self): """A dict of dates -> [Period time tuples] representing exceptions to the base recurrence pattern.""" ex = {} for sd in self.root.xpath('schedule/specific_dates/specific_date'): bits = str(sd.text).split(' ') date = text_to_date(bits.pop(0)) ex.setdefault(date, []).extend([ _time_text_to_period(t) for t in bits ]) return ex def specific_dates_periods(self, range_start=datetime.date.min, range_end=datetime.date.max): """Returns a list of Period tuples for each period represented in a <specific_dates> schedule that falls between range_start and range_end.""" periods = [] for exception_date, exception_times in self.specific_dates.items(): if exception_date >= range_start and exception_date <= range_end: for exception_time in exception_times: periods.append( Period( self.timezone.localize(datetime.datetime.combine(exception_date, exception_time.start)), self.timezone.localize(datetime.datetime.combine(exception_date, exception_time.end)) ) ) periods.sort() return periods def to_timezone(self, dt): """Converts a datetime to the timezone of this Schedule.""" if timezone.is_aware(dt): return dt.astimezone(self.timezone) else: return timezone.make_aware(dt, self.timezone) def includes(self, query): """Does this schedule include the provided time? query should be a datetime (naive or timezone-aware)""" query = self.to_timezone(query) query_date = query.date() query_time = query.time() # Is the provided time an exception for this schedule? specific = self.specific_dates.get(query_date) if specific is not None: if len(specific) == 0: # Not in effect on this day return False for period in specific: if query_time >= period.start and query_time <= period.end: return True return False # It's not an exception. Is it within a recurring schedule? return any(sched.includes(query_date, query_time) for sched in self.recurring_schedules) def active_within_range(self, query_start, query_end): """Is this event ever active between query_start and query_end, which are (aware or naive) datetimes?""" query_start = self.to_timezone(query_start) query_end = self.to_timezone(query_end) for range in self.daily_periods(range_start=query_start.date(), range_end=query_end.date()): if ( ((range.start < query_start) and (range.end > query_end)) or (query_start <= range.start <= query_end) or (query_start <= range.end <= query_end)): return True return False def has_remaining_periods(self, after=None): """Is this schedule ever in effect at or after the given time? If no time is given, uses the current time.""" if after is None: after = timezone.now() after = self.to_timezone(after) periods = self.daily_periods(range_start=after.date()) return any(p for p in periods if p.end > after) def next_period(self, after=None): """Returns the next Period this event is in effect, or None if the event has no remaining periods.""" if after is None: after = timezone.now() after = self.to_timezone(after) return next((p for p in self.periods(range_start=after.date()) if p.end > after), None) def daily_periods(self, range_start=datetime.date.min, range_end=datetime.date.max): """Returns an iterator of Period tuples for every day this event is in effect, between range_start and range_end.""" specific = set(self.specific_dates.keys()) return heapq.merge(self.specific_dates_periods(range_start, range_end), *[ sched.daily_periods(range_start=range_start, range_end=range_end, exclude_dates=specific) for sched in self.recurring_schedules ]) def periods(self, range_start=datetime.date.min, range_end=datetime.date.max, max_continuous_days=60): """Returns an iterator of Period tuples for continuous stretches of time during which this event is in effect, between range_start and range_end. daily_periods returns one (or more) Period per day; if this event is continuously in effect for several days, this method will return a single Period for that time. However, Periods will be broken apart after max_continuous_days. This is because the algorithm currently works day-by-day, and so the algorithm would become (nearly) infinitely slow for events without an end date.""" current_period = None for period in self.daily_periods(range_start, range_end): if current_period is None: current_period = period else: if ( ((period.start < current_period.end) or (period.start - current_period.end) <= datetime.timedelta(minutes=1)) and (current_period.end - current_period.start) < datetime.timedelta(days=max_continuous_days)): # Merge current_period = Period(current_period.start, period.end) else: yield current_period current_period = period if current_period: yield current_period class RecurringScheduleComponent(object): def __init__(self, root, timezone): assert root.tag == 'schedule' self.root = root self.timezone = timezone def includes(self, query_date, query_time=None): """Does this schedule include the provided time? query_date and query_time are date and time objects, interpreted in this schedule's timezone""" if self.start_date and query_date < self.start_date: return False if self.end_date and query_date > self.end_date: return False if query_date.weekday() not in self.weekdays: return False if not query_time: return True if query_time >= self.period.start and query_time <= self.period.end: return True return False def daily_periods(self, range_start=datetime.date.min, range_end=datetime.date.max, exclude_dates=tuple()): """Returns an iterator of Period tuples for every day this schedule is in effect, between range_start and range_end.""" tz = self.timezone period = self.period weekdays = self.weekdays current_date = max(range_start, self.start_date) end_date = range_end if self.end_date: end_date = min(end_date, self.end_date) while current_date <= end_date: if current_date.weekday() in weekdays and current_date not in exclude_dates: yield Period( tz.localize(datetime.datetime.combine(current_date, period.start)), tz.localize(datetime.datetime.combine(current_date, period.end)) ) current_date += datetime.timedelta(days=1) @property @memoize_method def period(self): """A Period tuple representing the daily start and end time.""" start_time = self.root.findtext('start_time') if start_time: return Period(text_to_time(start_time), text_to_time(self.root.findtext('end_time'))) return Period(datetime.time(0, 0), datetime.time(23, 59)) @property def weekdays(self): """A set of integers representing the weekdays the schedule recurs on, with Monday = 0 and Sunday = 6.""" if not self.root.xpath('days'): return set(range(7)) return set(int(d) - 1 for d in self.root.xpath('days/day/text()')) @property @memoize_method def start_date(self): """Start date of event recurrence, as datetime.date or None.""" return text_to_date(self.root.findtext('start_date')) @property @memoize_method def end_date(self): """End date of event recurrence, as datetime.date or None.""" return text_to_date(self.root.findtext('end_date'))
5774aa3719ffe11d2b2306f7b01fcc18a0365ea0
{ "blob_id": "5774aa3719ffe11d2b2306f7b01fcc18a0365ea0", "branch_name": "refs/heads/master", "committer_date": "2014-05-27T02:17:27", "content_id": "15270f5fcec090a7dd783b69afe083deefc00a84", "detected_licenses": [ "MIT" ], "directory_id": "e6c56a8ac610011c9bd83372e2f5ec1bd516a166", "extension": "py", "filename": "schedule.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": 9816, "license": "MIT", "license_type": "permissive", "path": "/open511/utils/schedule.py", "provenance": "stack-edu-0058.json.gz:234706", "repo_name": "mehulsbhatt/open511", "revision_date": "2014-05-27T02:17:27", "revision_id": "09c882ca21166676d1ccac003c03f1d7b138d5e7", "snapshot_id": "657d8100801c3315491a93a29562619e8e33d55e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mehulsbhatt/open511/09c882ca21166676d1ccac003c03f1d7b138d5e7/open511/utils/schedule.py", "visit_date": "2017-05-26T08:39:38.041163", "added": "2024-11-18T19:58:34.797915+00:00", "created": "2014-05-27T02:17:27", "int_score": 3, "score": 2.9375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0076.json.gz" }
<?php declare(strict_types=1); /** * This file is part of beotie/psr7_request_dto_bridge * * As each files provides by the CSCFA, this file is licensed * under the MIT license. * * PHP version 7.1 * * @category Bridge * @package Beotie_Psr7_Request_Dto_Bridge * @author matthieu vallance <matthieu.vallance@cscfa.fr> * @license MIT <https://opensource.org/licenses/MIT> * @link http://cscfa.fr */ namespace Beotie\PSR7\DTOBridge\Selector\Builder; /** * SelectedElement builder * * This class is used to build the SelectedElement instances * * @category Bridge * @package Beotie_Psr7_Request_Dto_Bridge * @author matthieu vallance <matthieu.vallance@cscfa.fr> * @license MIT <https://opensource.org/licenses/MIT> * @link http://cscfa.fr */ class SelectedElementBuider implements SelectedElementBuilderInterface { use SelectedElementBuilderTrait; }
0cf6485f68834fc012126ce4f95eb289bb546589
{ "blob_id": "0cf6485f68834fc012126ce4f95eb289bb546589", "branch_name": "refs/heads/master", "committer_date": "2018-02-02T15:46:40", "content_id": "c7f457af113794edbf1b38bf9c09633d3c7dd764", "detected_licenses": [ "MIT" ], "directory_id": "c6f03ca8f44a79813fdcc78a9a590dab610db724", "extension": "php", "filename": "SelectedElementBuider.php", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 119566208, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 891, "license": "MIT", "license_type": "permissive", "path": "/Beotie/PSR7/DTOBridge/Selector/Builder/SelectedElementBuider.php", "provenance": "stack-edu-0052.json.gz:603222", "repo_name": "Beotie/beotie-psr7-request-dto-bridge", "revision_date": "2018-02-02T15:46:40", "revision_id": "2ee058e146b0f5c1d31ff3a0f5e5f04fc19b7c07", "snapshot_id": "9148052827e4e85bdbe0ad094b9c30e6c865d394", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Beotie/beotie-psr7-request-dto-bridge/2ee058e146b0f5c1d31ff3a0f5e5f04fc19b7c07/Beotie/PSR7/DTOBridge/Selector/Builder/SelectedElementBuider.php", "visit_date": "2021-05-08T19:20:17.413268", "added": "2024-11-18T22:13:05.579279+00:00", "created": "2018-02-02T15:46:40", "int_score": 2, "score": 2.375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0070.json.gz" }
from tkinter import * from tkinter import ttk import time import urllib.request const_up = 0 const_down = 2 const_right = 4 const_left = 6 const_diag_up_left = 91 const_diag_up_right = 90 const_diag_down_left = 93 const_diag_down_right = 92 const_center = 25 const_led_on = 95 const_led_off = 94 class command_sender(object): def __init__(self): pass def update_data(self, fqdn, username, password): self.url = "http://"+fqdn+"/decoder_control.cgi?user="+username+"&pwd="+password+"&command=" print(self.url) def send_movement(self, scale_num, mov_num): urllib.request.urlopen(self.url+str(mov_num)) print(scale_num) time.sleep(scale_num*0.01) urllib.request.urlopen(self.url+"1") def send_single_command(self, mov_num): urllib.request.urlopen(self.url+str(mov_num)) def send_command_to_camera(command_type, flip, fqdn, username, password): url = "http://"+fqdn+"/decoder_control.cgi?user="+username+"&pwd="+password+"&command=" if command_type == "LED_ON": pass #urllib.request.urlopen class main_program_gui(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.command_object = command_sender() self.init_ui() self.pack() def update_all(self): self.command_object.update_data(self.fqdn_var.get(),self.user_var.get(),self.pass_var.get()) for bttn in self.button_list: bttn.state(["!disabled"]) def send_up(self): if self.flip_var.get() == False: self.command_object.send_movement(self.scale_time.get(), const_up) else: self.command_object.send_movement(self.scale_time.get(), const_down) def send_down(self): if self.flip_var.get() == False: self.command_object.send_movement(self.scale_time.get(), const_down) else: self.command_object.send_movement(self.scale_time.get(), const_up) def send_left(self): if self.flip_var.get() == False: self.command_object.send_movement(self.scale_time.get(), const_left) else: self.command_object.send_movement(self.scale_time.get(), const_right) def send_right(self): if self.flip_var.get() == False: self.command_object.send_movement(self.scale_time.get(), const_right) else: self.command_object.send_movement(self.scale_time.get(), const_left) def send_diag_up_left(self): if self.flip_var.get() == False: self.command_object.send_movement(self.scale_time.get(), const_diag_up_left) else: self.command_object.send_movement(self.scale_time.get(), const_diag_down_right) def send_diag_up_right(self): if self.flip_var.get() == False: self.command_object.send_movement(self.scale_time.get(), const_diag_up_right) else: self.command_object.send_movement(self.scale_time.get(), const_diag_down_left) def send_diag_down_left(self): if self.flip_var.get() == False: self.command_object.send_movement(self.scale_time.get(), const_diag_down_left) else: self.command_object.send_movement(self.scale_time.get(), const_diag_up_right) def send_diag_down_right(self): if self.flip_var.get() == False: self.command_object.send_movement(self.scale_time.get(), const_diag_down_right) else: self.command_object.send_movement(self.scale_time.get(), const_diag_up_left) def send_center(self): self.command_object.send_single_command(const_center) def send_led_on(self): self.command_object.send_single_command(const_led_on) def send_led_off(self): self.command_object.send_single_command(const_led_off) def init_ui(self): self.parent.title("FI8918W PT Control") self.main_frame = ttk.Frame(self) self.button_list = [] self.button_list.append(ttk.Button(self.main_frame,text="\u2196",state="disabled",command=self.send_diag_up_left)) self.button_list.append(ttk.Button(self.main_frame,text="\u2191",state="disabled",command=self.send_up)) self.button_list.append(ttk.Button(self.main_frame,text="\u2197",state="disabled",command=self.send_diag_up_right)) self.button_list.append(ttk.Button(self.main_frame,text="\u2190",state="disabled",command=self.send_left)) self.button_list.append(ttk.Button(self.main_frame,text="\u2022",state="disabled",command=self.send_center)) self.button_list.append(ttk.Button(self.main_frame,text="\u2192",state="disabled",command=self.send_right)) self.button_list.append(ttk.Button(self.main_frame,text="\u2199",state="disabled",command=self.send_diag_down_left)) self.button_list.append(ttk.Button(self.main_frame,text="\u2193",state="disabled",command=self.send_down)) self.button_list.append(ttk.Button(self.main_frame,text="\u2198",state="disabled",command=self.send_diag_down_right)) self.button_list.append(ttk.Button(self.main_frame,text="ON",state="disabled",command=self.send_led_on)) self.button_list[9].grid(row=3,column=0) ttk.Label(self.main_frame,text="LED").grid(row=3,column=1) self.button_list.append(ttk.Button(self.main_frame,text="OFF",state="disabled",command=self.send_led_off)) self.button_list[10].grid(row=3,column=2) ttk.Label(self.main_frame,text="FQDN").grid(row=0,column=3) ttk.Label(self.main_frame,text="User").grid(row=1,column=3) ttk.Label(self.main_frame,text="Pass").grid(row=2,column=3) self.fqdn_var = StringVar() self.user_var = StringVar() self.pass_var = StringVar() self.flip_var = IntVar() self.fqdn_entry = ttk.Entry(self.main_frame,textvariable=self.fqdn_var) self.fqdn_entry.grid(row=0,column=4) self.user_entry = ttk.Entry(self.main_frame,textvariable=self.user_var) self.user_entry.grid(row=1,column=4) self.pass_entry = ttk.Entry(self.main_frame,textvariable=self.pass_var,show="*") self.pass_entry.grid(row=2,column=4) #ttk.Label(self.pack_frame,text="Flip").grid(row=0,column=0) self.flip_control = ttk.Checkbutton(self.main_frame, text="Flip", variable=self.flip_var) self.flip_control.grid(row=3,column=3) self.update_info = ttk.Button(self.main_frame, text="Update", command=self.update_all) self.update_info.grid(row=3,column=4) ttk.Label(self.main_frame, text="M. Am").grid(row=0,column=5) self.scale_time = ttk.Scale(self.main_frame, from_=10, to=200, orient="vertical") self.scale_time.grid(row=1,column=5, rowspan=4) c = 0 for i in range(0,3): for j in range(0,3): self.button_list[c].grid(row=i,column=j) c += 1 self.main_frame.pack() def update_all(): pass main_window = Tk() actual_program = main_program_gui(main_window) main_window.mainloop()
1fb12d40436a860a7cdb5c2d4bd57c2ffda15651
{ "blob_id": "1fb12d40436a860a7cdb5c2d4bd57c2ffda15651", "branch_name": "refs/heads/master", "committer_date": "2015-07-26T12:17:17", "content_id": "3f32bd269787f95d45cc546403bac6901805e95d", "detected_licenses": [ "MIT" ], "directory_id": "61a0095062c9da8e74d71169e3ca7ef35e49953f", "extension": "py", "filename": "main.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 39724448, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6345, "license": "MIT", "license_type": "permissive", "path": "/main.py", "provenance": "stack-edu-0064.json.gz:148660", "repo_name": "fabrizziop/foscam-control-gui", "revision_date": "2015-07-26T12:17:17", "revision_id": "dd11d80e8e9e6258d90d9b74942281511ea792cb", "snapshot_id": "814b4a4b4fb3067680b0d2e995f515b389e1b7a3", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/fabrizziop/foscam-control-gui/dd11d80e8e9e6258d90d9b74942281511ea792cb/main.py", "visit_date": "2021-01-02T22:51:21.096761", "added": "2024-11-18T23:10:59.427611+00:00", "created": "2015-07-26T12:17:17", "int_score": 2, "score": 2.3125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0082.json.gz" }
#include "h264.hpp" #include <cstring> namespace h264 { bool IterateAnnexB(const void* data, size_t len, const std::function<void(const void* data, size_t len)>& f) { auto ptr = reinterpret_cast<const uint8_t*>(data); while (true) { while (true) { if (!len) { return true; } else if (ptr[0] != 0) { return false; } else if (len >= 3 && ptr[0] == 0 && ptr[1] == 0 && ptr[2] == 1) { break; } ++ptr; --len; } ptr += 3; len -= 3; auto nalu = ptr; while (true) { if (!len || (len >= 3 && ptr[0] == 0 && ptr[1] == 0 && ptr[2] <= 1)) { f(nalu, ptr - nalu); break; } ++ptr; --len; } } } bool IterateAVCC(const void* data, size_t len, size_t naluSizeLength, const std::function<void(const void* data, size_t len)>& f) { if (naluSizeLength > 8 || naluSizeLength < 1) { return false; } auto ptr = reinterpret_cast<const uint8_t*>(data); while (len >= naluSizeLength) { size_t naluSize = 0; for (size_t i = 0; i < naluSizeLength; ++i) { naluSize = (naluSize << 8) | ptr[i]; } ptr += naluSizeLength; len -= naluSizeLength; if (len < naluSize) { return false; } f(ptr, naluSize); ptr += naluSize; len -= naluSize; } return true; } bool FilterAVCC(std::vector<uint8_t>* dest, const void* data, size_t len, size_t naluSizeLength, std::function<bool(unsigned int)> filter) { if (naluSizeLength > 8 || naluSizeLength < 1) { return false; } auto ptr = reinterpret_cast<const uint8_t*>(data); while (len >= naluSizeLength) { size_t naluSize = 0; for (size_t i = 0; i < naluSizeLength; ++i) { naluSize = (naluSize << 8) | ptr[i]; } const auto copyLen = naluSizeLength + naluSize; if (len < copyLen) { return false; } dest->resize(dest->size() + copyLen); auto destPtr = &(*dest)[dest->size() - copyLen]; std::memcpy(destPtr, ptr, copyLen); ptr += copyLen; len -= copyLen; } return true; } bool AVCCToAnnexB(std::vector<uint8_t>* dest, const void* data, size_t len, size_t naluSizeLength) { return IterateAVCC(data, len, naluSizeLength, [&](const void* data, size_t len) { dest->resize(dest->size() + 3 + len); auto ptr = &(*dest)[dest->size() - 3 - len]; *(ptr++) = 0; *(ptr++) = 0; *(ptr++) = 1; std::memcpy(ptr, data, len); }); } bool AnnexBToAVCC(std::vector<uint8_t>* dest, const void* data, size_t len, std::function<bool(unsigned int)> filter) { return IterateAnnexB(data, len, [&](const void* data, size_t len) { if (filter && !filter(*reinterpret_cast<const uint8_t*>(data) & 0x1f)) { return; } dest->resize(dest->size() + 4 + len); auto ptr = &(*dest)[dest->size() - 4 - len]; *(ptr++) = len >> 24; *(ptr++) = len >> 16; *(ptr++) = len >> 8; *(ptr++) = len; std::memcpy(ptr, data, len); }); } } // namespace h264
df0b8a89b473899ee619a36e36492bb1f81a4abe
{ "blob_id": "df0b8a89b473899ee619a36e36492bb1f81a4abe", "branch_name": "refs/heads/master", "committer_date": "2019-04-02T23:16:47", "content_id": "1bc97ff5c59b37bd8350210cab155198c5eefa00", "detected_licenses": [ "MIT" ], "directory_id": "5993545f475566a3ad6c64c34d5d87458abac510", "extension": "cpp", "filename": "h264.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": 3318, "license": "MIT", "license_type": "permissive", "path": "/lib/h26x/h264.cpp", "provenance": "stack-edu-0008.json.gz:183517", "repo_name": "alliance-archive/av", "revision_date": "2019-04-02T23:16:47", "revision_id": "d17dfd3b18685ae917b369ad891de225884da790", "snapshot_id": "484d4cb03f95bd458d195bb23f99ebf9aabfbc2b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/alliance-archive/av/d17dfd3b18685ae917b369ad891de225884da790/lib/h26x/h264.cpp", "visit_date": "2020-05-04T17:49:43.355596", "added": "2024-11-18T21:07:02.477937+00:00", "created": "2019-04-02T23:16:47", "int_score": 3, "score": 2.671875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0026.json.gz" }
import * as express from "express"; import ChatController from "../controller/chatController"; import Logger from '../server/logger'; import ProtectedRouter from "./protectedRouter"; const logger = new Logger("ChatRouter"); export default class ChatRouter{ constructor() { let router = express.Router(); let chatController = new ChatController(); router.post('/', chatController.chat.bind(chatController)); logger.info('register chat router'); return router; } }
24423c9f6318edb3b8a2303308d7cf7656389b36
{ "blob_id": "24423c9f6318edb3b8a2303308d7cf7656389b36", "branch_name": "refs/heads/master", "committer_date": "2018-03-19T03:09:19", "content_id": "6c7ab5a0b52e099873602edb4942187a0d72d846", "detected_licenses": [ "MIT" ], "directory_id": "a6beed5e44555c1593ee7a0f5c11d56d92961ada", "extension": "ts", "filename": "chatRouter.ts", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 74931920, "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 507, "license": "MIT", "license_type": "permissive", "path": "/WeiERP/WekaServer/routes/chatRouter.ts", "provenance": "stack-edu-0073.json.gz:624126", "repo_name": "hurungang/WeiERP", "revision_date": "2018-03-19T03:09:19", "revision_id": "8c8fadf2f5b23d509c2ce1999d5cd2c0c77d5a2f", "snapshot_id": "56e2c84a383250df7ee04c1e311ddce93b734c92", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/hurungang/WeiERP/8c8fadf2f5b23d509c2ce1999d5cd2c0c77d5a2f/WeiERP/WekaServer/routes/chatRouter.ts", "visit_date": "2020-06-19T00:27:59.396061", "added": "2024-11-19T03:11:59.710690+00:00", "created": "2018-03-19T03:09:19", "int_score": 2, "score": 2.203125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0091.json.gz" }
export class C8oTranslator { public static stringToJSON(jsonValueString): JSON { return JSON.parse(jsonValueString); } }
033f6312239c9f7d6ed56b1122dc8bbcdd70698c
{ "blob_id": "033f6312239c9f7d6ed56b1122dc8bbcdd70698c", "branch_name": "refs/heads/develop", "committer_date": "2023-06-15T08:10:37", "content_id": "6e78bdf62a1ca9034d8acd74617a999dc1c70d3c", "detected_licenses": [ "Apache-2.0" ], "directory_id": "662340200565d0f57e21e4825b3be731c301c5a7", "extension": "ts", "filename": "c8oTranslator.ts", "fork_events_count": 2, "gha_created_at": "2018-04-23T11:46:09", "gha_event_created_at": "2022-05-31T16:05:16", "gha_language": "TypeScript", "gha_license_id": "Apache-2.0", "github_id": 130688095, "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 137, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/c8o/c8oTranslator.ts", "provenance": "stack-edu-0073.json.gz:991092", "repo_name": "convertigo/c8osdk-js-core", "revision_date": "2023-06-15T08:10:37", "revision_id": "25eda1ccc4dfe612aae80defa4433cbe476415ab", "snapshot_id": "8b3e5470c97c37f7f5281eecb93694d8c25dde5e", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/convertigo/c8osdk-js-core/25eda1ccc4dfe612aae80defa4433cbe476415ab/src/c8o/c8oTranslator.ts", "visit_date": "2023-07-01T18:36:23.802252", "added": "2024-11-19T02:20:36.967607+00:00", "created": "2023-06-15T08:10:37", "int_score": 2, "score": 2.015625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0091.json.gz" }
# coding: utf-8 from __future__ import print_function import numpy as np from keras.models import Sequential from keras.layers.recurrent import GRU def understand_return_sequence(): """用来帮助理解 recurrent layer 中的 return_sequences 参数""" model_1 = Sequential() model_1.add(GRU(input_dim=256, output_dim=256, return_sequences=True)) model_1.compile(loss='mean_squared_error', optimizer='sgd') train_x = np.random.randn(100, 78, 256) train_y = np.random.randn(100, 78, 256) model_1.fit(train_x, train_y, verbose=0) model_2 = Sequential() model_2.add(GRU(input_dim=256, output_dim=256, return_sequences=False)) model_2.compile(loss='mean_squared_error', optimizer='sgd') train_x = np.random.randn(100, 78, 256) train_y = np.random.randn(100, 256) model_2.fit(train_x, train_y, verbose=0) inz = np.random.randn(100, 78, 256) rez_1 = model_1.predict_proba(inz, verbose=0) rez_2 = model_2.predict_proba(inz, verbose=0) print() print('=========== understand return_sequence =================') print('Input shape is: {}'.format(inz.shape)) print('Output shape of model with `return_sequences=True`: {}'.format(rez_1.shape)) print('Output shape of model with `return_sequences=False`: {}'.format(rez_2.shape)) print('====================== end =============================') def understand_variable_length_handle(): """用来帮助理解如何用 recurrent layer 处理变长序列""" model = Sequential() model.add(GRU(input_dim=256, output_dim=256, return_sequences=True)) model.compile(loss='mean_squared_error', optimizer='sgd') train_x = np.random.randn(100, 78, 256) train_y = np.random.randn(100, 78, 256) model.fit(train_x, train_y, verbose=0) inz_1 = np.random.randn(1, 78, 256) rez_1 = model.predict_proba(inz_1, verbose=0) inz_2 = np.random.randn(1, 87, 256) rez_2 = model.predict_proba(inz_2, verbose=0) print() print('=========== understand variable length =================') print('With `return_sequence=True`') print('Input shape is: {}, output shae is {}'.format(inz_1.shape, rez_1.shape)) print('Input shape is: {}, output shae is {}'.format(inz_2.shape, rez_2.shape)) print('====================== end =============================') def try_variable_length_train(): """变长序列训练实验 实验失败,这样得到的 train_x 和 train_y 的 dtype 是 object 类型, 取其 shape 得到的是 (100,) ,这将导致训练出错 """ model = Sequential() model.add(GRU(input_dim=256, output_dim=256, return_sequences=True)) model.compile(loss='mean_squared_error', optimizer='sgd') train_x = [] train_y = [] for i in range(100): seq_length = np.random.randint(78, 87 + 1) sequence = [] for _ in range(seq_length): sequence.append([np.random.randn() for _ in range(256)]) train_x.append(np.array(sequence)) train_y.append(np.array(sequence)) train_x = np.array(train_x) train_y = np.array(train_y) model.fit(np.array(train_x), np.array(train_y)) def try_variable_length_train_in_batch(): """变长序列训练实验(2)""" model = Sequential() model.add(GRU(input_dim=256, output_dim=256, return_sequences=True)) model.compile(loss='mean_squared_error', optimizer='sgd') # 分作两个 batch, 不同 batch 中的 sequence 长度不一样 seq_lens = [78, 87] for i in range(2): train_x = np.random.randn(20, seq_lens[i], 256) train_y = np.random.randn(20, seq_lens[i], 256) model.train_on_batch(train_x, train_y) if __name__ == '__main__': understand_return_sequence() understand_variable_length_handle()
d9d00bf3e4925a7535bbd7b63c40de40352ec479
{ "blob_id": "d9d00bf3e4925a7535bbd7b63c40de40352ec479", "branch_name": "refs/heads/master", "committer_date": "2017-12-16T04:36:52", "content_id": "c304fc2560acda4c267e553c8e2d1366a32037b0", "detected_licenses": [ "MIT" ], "directory_id": "d80ec8a8fc819a2f35d39db914ff3936f5a19906", "extension": "py", "filename": "understand.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": 3781, "license": "MIT", "license_type": "permissive", "path": "/demos/understand.py", "provenance": "stack-edu-0056.json.gz:367854", "repo_name": "heimagithub/soph", "revision_date": "2017-12-16T04:34:29", "revision_id": "46822f347795f51c3872a164fbbe416fa0e91807", "snapshot_id": "f400634c3b8a09b315a8e829589d36a3f3d49ce1", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/heimagithub/soph/46822f347795f51c3872a164fbbe416fa0e91807/demos/understand.py", "visit_date": "2020-03-19T13:47:22.801593", "added": "2024-11-18T21:37:18.828148+00:00", "created": "2017-12-16T04:34:29", "int_score": 3, "score": 3.265625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0074.json.gz" }
#!/usr/bin/env python """ -------------------------------------------------------------------------------- Created: Jackson Lee 7/8/14 This script reads in a fasta or fastq and filters for sequences greater or less than a threshold length Input fastq file @2402:1:1101:1392:2236/2 GATAGTCTTCGGCGCCATCGTCATCCTCTACACCCTCAAGGCGAGCGGCGCGATGGAGACAATCCAGTGGGGCATGCAGCAGGTGACACCGGACTCCCGGATCCA + @@CFFFFFGHHHHIJJIIJIHIJIIIIJIIGEIJJIJJJJJIIIJHFFDDBD8BBD>BCBCCDDDCDCCCDBDDDDDDDDDDD<CDDDDDDDDBBCDDBD<<BDD -------------------------------------------------------------------------------- usage: filter_fasta_by_len.py -i sequence.fasta -g filter_greater_than -l filter_less_than """ #------------------------------------------------------------------------------- #Header - Linkers, Libs, Constants from string import strip from Bio import SeqIO from argparse import ArgumentParser, RawDescriptionHelpFormatter #------------------------------------------------------------------------------- #function declarations def process_and_generate(input_iterator, threshold, greaterflag): """Reusable function that processes a record, then generates each record. input_iterator is an iterator that returns one record at a time process_function is a function that takes one record and does some processing on it """ for rec in input_iterator: if greaterflag: if len(rec.seq) <= threshold: yield rec else: if len(rec.seq) >= threshold: yield rec #------------------------------------------------------------------------------- #Body print "Running..." if __name__ == '__main__': parser = ArgumentParser(usage = "filter_fasta_by_len.py -i sequence.fasta -g filter_greater_than -l filter_less_than", description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument("-i", "--input_fastq", action="store", dest="inputfilename", help="fastq file of input sequences") parser.add_argument("-g", "--filter_greater_than", action="store", type=int, dest="greaterthan", help="filter out sequences greater than or equal to \ this size") parser.add_argument("-l", "--filter_less_than", action="store", type=int, dest="lessthan", help="filter out sequences less than or equal this size") options = parser.parse_args() mandatories = ["inputfilename"] for m in mandatories: if not options.__dict__[m]: print "\nError: Missing Arguments\n" parser.print_help() exit(-1) inputfilename = options.inputfilename left, __, right = inputfilename.rpartition('.') fasta =['fa','fasta','faa','fas', 'fna'] fastq =['fq','fastq'] if right in fasta: ext = "fasta" elif right in fastq: ext = "fastq" print "Processing read file: " + inputfilename with open(inputfilename,'U') as infile: parse_iterator = SeqIO.parse(infile, ext) if options.greaterthan == None and options.lessthan == None: print "\nError: Missing Comparison Value\n" parser.print_help() exit(-1) elif options.greaterthan == None and options.lessthan != None: lessthan = options.lessthan print "and filtering out sequences less than ", lessthan outputfilename = left + '.filtered.lessthan.' + str(lessthan) + "." + right with open(outputfilename, 'w') as outfile: record_generator = process_and_generate(parse_iterator, lessthan, False) SeqIO.write(record_generator, outfile, ext) elif options.greaterthan != None and options.lessthan == None: greaterthan = options.greaterthan print "and filtering out sequences greater than ", greaterthan outputfilename = left + '.filtered.greaterthan.' + str(greaterthan) + "." + right with open(outputfilename, 'w') as outfile: record_generator = process_and_generate(parse_iterator, greaterthan, True) SeqIO.write(record_generator, outfile, ext) elif options.greaterthan != None and options.lessthan != None: greaterthan = options.greaterthan lessthan = options.lessthan print "and filtering out sequences less than ", lessthan, " and greater than ", greaterthan outputfilename = left + '.filtered.greaterthan.' + str(greaterthan) + ".filtered.lessthan." + str(lessthan) + '.' + right with open(outputfilename, 'w') as outfile: pre_record_generator = process_and_generate(parse_iterator, greaterthan, True) record_generator = process_and_generate(pre_record_generator, lessthan, False) SeqIO.write(record_generator, outfile, ext) print "Done!"
3908b95a6975f7a91c3a0db8a1446ac5d94cbe59
{ "blob_id": "3908b95a6975f7a91c3a0db8a1446ac5d94cbe59", "branch_name": "refs/heads/main", "committer_date": "2017-01-04T01:20:07", "content_id": "c2bda254901ca4fa1b0b7dd625ad56b8178fb6f5", "detected_licenses": [ "MIT" ], "directory_id": "99cea225d17db0c119b498986a05d248b54540e7", "extension": "py", "filename": "filter_fasta_by_len.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 42123579, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5048, "license": "MIT", "license_type": "permissive", "path": "/filter_fasta_by_len.py", "provenance": "stack-edu-0065.json.gz:150322", "repo_name": "leejz/misc-scripts", "revision_date": "2017-01-04T01:20:07", "revision_id": "ab23af0bac5a5051df83fb9f59f23e7c413fd81a", "snapshot_id": "f558a2d8dff663b63a197a75fcff653b7c7fcc71", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/leejz/misc-scripts/ab23af0bac5a5051df83fb9f59f23e7c413fd81a/filter_fasta_by_len.py", "visit_date": "2020-06-14T15:55:52.658200", "added": "2024-11-18T23:55:42.428998+00:00", "created": "2017-01-04T01:20:07", "int_score": 3, "score": 3.125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0083.json.gz" }
package main /* import ( "net/http" "github.com/gorilla/websocket" "fmt" "time" "log" ) func ClientWebSocketHandler (w http.ResponseWriter, r *http.Request) { go func() { // Dial with Gorilla package. The x/net/websocket package has issues. fmt.Println("HERE") c, _, err := websocket.DefaultDialer.Dial("wss://wire-moraispgsi.c9users.io/websocket", nil) if err != nil { log.Fatal("dial:", err) fmt.Println("client: " + string(err.Error())) } // Clean up on exit from this goroutine defer c.Close() // Loop reading messages. Send each message to the channel. for { _, m, err := c.ReadMessage() if err != nil { log.Fatal("read:", err) return } fmt.Println("client: " + string(m)) } }() } func WebSocketHandler(w http.ResponseWriter, r *http.Request) { var conn, err = upgrader.Upgrade(w, r, nil) if err != nil { fmt.Println(err) return } go func(conn *websocket.Conn) { for { _, p, err := conn.ReadMessage() if err != nil { conn.Close() return } if string(p) == "create-socket" { sc.CreateSocket(true) json := []int64{} for _, id := range sc.GetSocketsIds() { json = append(json, id) } conn.WriteJSON(json) } fmt.Println("Mensagem recebida:" + string(p)) } }(conn) go func(conn *websocket.Conn) { ch := time.Tick(5 * time.Second) for range ch { if conn == nil { return } json := []int64{} for _, id := range sc.GetSocketsIds() { json = append(json, id) } conn.WriteJSON(json) } }(conn) // // Create channel to receive messages from all connections //messages := make(chan []byte) // Run a goroutine for each URL that you want to dial. } */
ce901207d43306341ae5790b9d5ba1a0489b2856
{ "blob_id": "ce901207d43306341ae5790b9d5ba1a0489b2856", "branch_name": "refs/heads/master", "committer_date": "2017-04-24T21:59:09", "content_id": "6c8cbe3327c2a2e66b263dc3867b8d6d26d53e73", "detected_licenses": [ "MIT" ], "directory_id": "7991a59d0e0f4d5113616531ffa9caf1a5d14868", "extension": "go", "filename": "handlers.go", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 89290729, "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 2149, "license": "MIT", "license_type": "permissive", "path": "/old/handlers.go", "provenance": "stack-edu-0018.json.gz:71760", "repo_name": "moraispgsi/wire", "revision_date": "2017-04-24T21:59:09", "revision_id": "82e75164aae410fa6927e0c37070e2b5851562a9", "snapshot_id": "848e5aeb09523ea886e7394d619e0cf7e8902408", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/moraispgsi/wire/82e75164aae410fa6927e0c37070e2b5851562a9/old/handlers.go", "visit_date": "2021-01-20T01:31:51.386274", "added": "2024-11-18T21:33:35.441878+00:00", "created": "2017-04-24T21:59:09", "int_score": 3, "score": 2.6875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0036.json.gz" }
<?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Models\Seat; use App\Models\Venue; use App\Models\hall; use App\Models\Hall_sanse; use App\Models\Seat_hall_sanse; use App\Models\Seatsection; class SeatController extends Controller { public function index(){ $venues=Venue::all(); return view('admin_seats.specification',compact(['venues'])); } public function find_venue_halls(Request $request){ $data=Hall::select('name','id')->where('venue_id',$request->id)->take(100)->get(); return response()->json($data); } public function find_hall_seatsection(Request $request){ $data=Seatsection::select('name','id')->where('hall_id',$request->id)->take(100)->get(); return response()->json($data); } public function insertseat(Request $request){ $rows=$request->get('horizontal'); $cols=$request->get('vertical'); // dd($cols); $venue=$request->get('venue'); $hall=$request->get('hall'); $seatsection=$request->get('seatsection'); for ($i=1;$i<=$rows;$i++){ for($j=1;$j<=$cols;$j++){ $seat= new Seat(); $seat->seat_row=$i; $seat->seat_col=$j; $seat->venue_id=$venue; $seat->hall_id=$hall; $seat->seatsection_id=$seatsection; $seat->save(); } } $all=Seat::where('seatsection_id',$seatsection)->where('hall_id',$hall) ->where('venue_id',$venue)->get(); $rows=$all->groupBy('seat_row')->count(); $columns=($all->count()/$rows); //save in Seat_hall_sanse table as well $halls=Hall_sanse::where('hall_id',$hall)->get(); // dd($halls); foreach($halls as $hall){ foreach($all as $single){ $s=new Seat_hall_sanse(); $s->seat_id=$single->id; $s->hall_sanse_id=$hall->id; $s->seatsection_id=$seatsection; $s->status_id=3; $s->save(); // $s=new Seat_hall_sanse(); // $s->seat_id=$single->id; // $s->hall_sanse_id=2; // $s->status_id=3; // $s->save(); } } return view('admin_seats.ui2')->with('all',$all)->with('columns',$columns); } public function make_seat_plan(Request $request){ $seats=Seat::all(); $deleted=$request->deletes; $forwarded=$request->forwards; // dd($deleted); // dd($forwarded); if($forwarded){ if(is_array($forwarded)){ foreach($forwarded as $forward){ $seat=Seat::where('id',$forward)->first(); // dd($seat); $seat['forward']='yes'; $seat->save(); } } else{ $seat=Seat::where('id',$forward)->first(); $seat['forward']='yes'; $seat->save(); } } if($deleted){ if(is_array($deleted)){ foreach($deleted as $delete){ $seat=Seat::where('id',$delete)->first(); // dd($seat); $seat->empty='yes'; $seat->save(); } } else{ $seat=Seat::find($deleted)->get(); $seat->empty='yes'; $seat->save(); } } // $a="successfull!"; // return response()->json($a); } public function final_seat_plan(){ $allseats=Seat::all(); $rows=$allseats->groupBy('seat_row')->count(); $columns=($allseats->count()/$rows); // dd($columns); $data=json_encode($columns); return view('seats.myseatplan4')->with('allseats',$allseats)->with('columns',$columns); } }
521bebaddd47de7d1aa079af50b855b8d1b053e8
{ "blob_id": "521bebaddd47de7d1aa079af50b855b8d1b053e8", "branch_name": "refs/heads/master", "committer_date": "2020-05-10T21:52:28", "content_id": "4e21980e250e070aa4fd22faf1759ed8074fe107", "detected_licenses": [ "MIT" ], "directory_id": "59c7134e1f4cf700d1ae979957b50859acb8afd2", "extension": "php", "filename": "SeatController.php", "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": "PHP", "length_bytes": 4013, "license": "MIT", "license_type": "permissive", "path": "/app/Http/Controllers/Admin/SeatController.php", "provenance": "stack-edu-0047.json.gz:587592", "repo_name": "fastlyos/ticketbama", "revision_date": "2020-05-10T21:52:28", "revision_id": "9cc5d629d619ede327ebf5b3a39900c43df4f486", "snapshot_id": "baf47e6cba59caf797bebc26fb10fdbc78188402", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/fastlyos/ticketbama/9cc5d629d619ede327ebf5b3a39900c43df4f486/app/Http/Controllers/Admin/SeatController.php", "visit_date": "2022-07-01T03:10:07.729845", "added": "2024-11-18T22:26:29.040636+00:00", "created": "2020-05-10T21:52:28", "int_score": 2, "score": 2.3125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0065.json.gz" }
// File generated from our OpenAPI spec declare module 'stripe' { namespace Stripe { namespace FinancialConnections { interface SessionCreateParams { /** * The account holder to link accounts for. */ account_holder: SessionCreateParams.AccountHolder; /** * List of data features that you would like to request access to. * * Possible values are `balances`, `transactions`, `ownership`, and `payment_method`. */ permissions: Array<SessionCreateParams.Permission>; /** * Specifies which fields in the response should be expanded. */ expand?: Array<string>; /** * Filters to restrict the kinds of accounts to collect. */ filters?: SessionCreateParams.Filters; /** * List of data features that you would like to retrieve upon account creation. */ prefetch?: Array<SessionCreateParams.Prefetch>; /** * For webview integrations only. Upon completing OAuth login in the native browser, the user will be redirected to this URL to return to your app. */ return_url?: string; } namespace SessionCreateParams { interface AccountHolder { /** * The ID of the Stripe account whose accounts will be retrieved. Should only be present if `type` is `account`. */ account?: string; /** * The ID of the Stripe customer whose accounts will be retrieved. Should only be present if `type` is `customer`. */ customer?: string; /** * Type of account holder to collect accounts for. */ type: AccountHolder.Type; } namespace AccountHolder { type Type = 'account' | 'customer'; } interface Filters { /** * List of countries from which to collect accounts. */ countries: Array<string>; } type Permission = | 'balances' | 'ownership' | 'payment_method' | 'transactions'; type Prefetch = 'balances' | 'ownership'; } interface SessionRetrieveParams { /** * Specifies which fields in the response should be expanded. */ expand?: Array<string>; } class SessionsResource { /** * To launch the Financial Connections authorization flow, create a Session. The session's client_secret can be used to launch the flow using Stripe.js. */ create( params: SessionCreateParams, options?: RequestOptions ): Promise<Stripe.Response<Stripe.FinancialConnections.Session>>; /** * Retrieves the details of a Financial Connections Session */ retrieve( id: string, params?: SessionRetrieveParams, options?: RequestOptions ): Promise<Stripe.Response<Stripe.FinancialConnections.Session>>; retrieve( id: string, options?: RequestOptions ): Promise<Stripe.Response<Stripe.FinancialConnections.Session>>; } } } }
b2bd991e8a61f19fb76519f85267cec060741bed
{ "blob_id": "b2bd991e8a61f19fb76519f85267cec060741bed", "branch_name": "refs/heads/master", "committer_date": "2023-08-31T20:25:58", "content_id": "04c01a0af789ef3b3975beb36c644189f16e2b34", "detected_licenses": [ "MIT" ], "directory_id": "babcd5bb85ce070577269c8f7eac55880049c67e", "extension": "ts", "filename": "SessionsResource.d.ts", "fork_events_count": 801, "gha_created_at": "2011-09-28T00:28:33", "gha_event_created_at": "2023-09-14T16:55:20", "gha_language": "TypeScript", "gha_license_id": "MIT", "github_id": 2471804, "is_generated": false, "is_vendor": true, "language": "TypeScript", "length_bytes": 3241, "license": "MIT", "license_type": "permissive", "path": "/types/FinancialConnections/SessionsResource.d.ts", "provenance": "stack-edu-0072.json.gz:900537", "repo_name": "stripe/stripe-node", "revision_date": "2023-08-31T20:25:58", "revision_id": "86da21e351d876bca8bd80417db7938130ec9ad0", "snapshot_id": "2b739af8c1e5bdec3ff142dca3cae7c61cf66723", "src_encoding": "UTF-8", "star_events_count": 3142, "url": "https://raw.githubusercontent.com/stripe/stripe-node/86da21e351d876bca8bd80417db7938130ec9ad0/types/FinancialConnections/SessionsResource.d.ts", "visit_date": "2023-09-05T05:56:10.876768", "added": "2024-11-19T03:13:25.013084+00:00", "created": "2023-08-31T20:25:58", "int_score": 3, "score": 2.515625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0090.json.gz" }
<?php error_reporting(E_ERROR | E_WARNING | E_PARSE); set_time_limit(0); require_once __DIR__."/curl.php"; $keyWord = "physician assistant"; $Location = "Orlando, FL"; $keyWord = urlencode($keyWord); $size = $_GET['size']; $Location = urlencode($Location); //$mkURL = "https://www.indeed.com/jobs?as_and={$keyWord}&as_phr=&as_any=&as_not=&as_ttl=&as_cmp=&jt=all&st=&as_src=&salary=&radius=100&l=Orlando%2C+FL&fromage=any&limit=100&sort=&psf=advsrch&from=advancedsearch"; $mkURL = $_GET['url']; if($size == true) { $curl = new curl; $name = $curl->get($mkURL); @$doc = new DOMDocument(); @$doc->loadHTML($name); $xpath = new DomXPath($doc); $count_div = $xpath->query("(//*[@id='searchCountPages'])"); foreach ($count_div as $element) { $page_count = $element->nodeValue; } echo $page_count; exit; } $curl = new curl; $name = $curl->get($mkURL); preg_match_all('/\d\]= {(.*?)};/', $name, $output_array); $outputArr = null; $sites = null; if (!empty($output_array) ) { foreach ($output_array[0] as $arr) { $Names = null; $exploded = explode("]= ", $arr); $outputArr[] = $exploded[1]; //json_decode($newJson, true); //$outputArr[] = json_decode(stripslashes($exploded[1]), true); preg_match('/title:\'(.*?)\'/',$exploded[1],$title); $Names['Title'] = stripslashes($title[1]); preg_match('/jk:\'(.*?)\'/',$exploded[1],$jk); preg_match("/\,efccid: \\'(.*?)\\'/", $exploded[1], $efccid); $Names['Link'] = "https://www.indeed.com/rc/clk?jk=".stripslashes($jk[1])."&fccid=".stripslashes($efccid[1])."&vjs=3"; preg_match('/loc:\'(.*?)\'/',$exploded[1],$loc); $Names['Description'] = stripslashes($loc[1]); $descriptionLink = "https://www.indeed.com/rpc/jobdescs?jks=".stripslashes($jk[1]); $DescContent = file_get_contents($descriptionLink); preg_match('/\":\"(.*?)\"\}/',$DescContent,$description); $Names['Description'] = strip_tags($description[1]); $Names['date'] = ""; $Names['Summary'] = ""; $Names['Email'] = ""; $Names['ContactAddress'] = ""; $Names['Time'] = ""; $sites[] = $Names; } } echo json_encode($sites); exit; $filename = 'indeed.csv'; //header("Content-type: text/csv"); //header("Content-Disposition: attachment; filename=$filename"); $output = fopen($filename, 'w'); $header = array_keys($sites[0]); fputcsv($output, $header); foreach($sites as $row) { fputcsv($output, $row); } fclose($output); echo "<a href='{$filename}'>{$filename}</a>";
59355297fe82911f8db7334d2f700f3c30456cb8
{ "blob_id": "59355297fe82911f8db7334d2f700f3c30456cb8", "branch_name": "refs/heads/master", "committer_date": "2020-04-10T11:10:35", "content_id": "7bd4731f7f06992c95cd3eef783558796e27f488", "detected_licenses": [ "MIT" ], "directory_id": "8bfbc58cdb0fec49fad1dec840ede84e6daf5a9d", "extension": "php", "filename": "indeed.php", "fork_events_count": 0, "gha_created_at": "2020-01-24T20:42:19", "gha_event_created_at": "2023-02-02T10:38:58", "gha_language": "PHP", "gha_license_id": null, "github_id": 236080038, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2650, "license": "MIT", "license_type": "permissive", "path": "/scrapper/indeed.php", "provenance": "stack-edu-0046.json.gz:604611", "repo_name": "mobeen7asif/seizeit", "revision_date": "2020-04-10T11:10:35", "revision_id": "8f05e40b5f80ede6bd2fffd7483138310e9e1933", "snapshot_id": "f6278b9617ac0a39d8215cec2763bf24f6f1f12e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mobeen7asif/seizeit/8f05e40b5f80ede6bd2fffd7483138310e9e1933/scrapper/indeed.php", "visit_date": "2023-02-04T00:17:56.726554", "added": "2024-11-18T22:39:48.111186+00:00", "created": "2020-04-10T11:10:35", "int_score": 2, "score": 2.328125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0064.json.gz" }
import { GRPCStatusCode } from "../../../src/driver/Common/GRPCStatusCode" import { InProcessFirestore } from "../../../src/driver/Firestore/InProcessFirestore" describe("InProcessFirestore create", () => { const db = new InProcessFirestore() beforeEach(() => { db.resetStorage() }) test("create new document", async () => { // When we create a new document; await db .collection("animals") .doc("tiger") .create({ description: "stripey" }) // Then the document should be created. const snapshot = await db .collection("animals") .doc("tiger") .get() expect(snapshot.exists).toBeTruthy() expect(snapshot.data()).toEqual({ description: "stripey" }) }) test("cannot create existing document", async () => { // Given there is an existing document; await db .collection("animals") .doc("tiger") .set({ description: "stripey" }) // When we create the same document; let error: Error | null = null try { await db .collection("animals") .doc("tiger") .create({ size: "large" }) } catch (err) { error = err as any } // Then the write should fail; expect(error).isFirestoreErrorWithCode( GRPCStatusCode.ALREADY_EXISTS, new RegExp("/documents/animals/tiger"), ) // And the document should not be changed. const snapshot = await db .collection("animals") .doc("tiger") .get() expect(snapshot.exists).toBeTruthy() expect(snapshot.data()).toEqual({ description: "stripey" }) }) })
a31038e7a6fa3e14691500588237b21e21f201cb
{ "blob_id": "a31038e7a6fa3e14691500588237b21e21f201cb", "branch_name": "refs/heads/master", "committer_date": "2022-10-06T12:12:20", "content_id": "35ff97c69401ec50974321fde501fc34f85cebbc", "detected_licenses": [ "MIT" ], "directory_id": "2470b9b94bc65a1f69abd4ba33f90c9442ca4456", "extension": "ts", "filename": "InProcessFirestore.create.test.ts", "fork_events_count": 1, "gha_created_at": "2019-09-14T18:10:45", "gha_event_created_at": "2023-03-01T10:29:46", "gha_language": "TypeScript", "gha_license_id": "MIT", "github_id": 208482711, "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1812, "license": "MIT", "license_type": "permissive", "path": "/tests/driver/Firestore/InProcessFirestore.create.test.ts", "provenance": "stack-edu-0072.json.gz:313243", "repo_name": "freetrade-io/ts-firebase-driver-testing", "revision_date": "2022-10-06T12:12:20", "revision_id": "72d69b249f3a6db0195d2d7079def46fc11ba5ce", "snapshot_id": "62d5ad95b540a52e5c1187871ed600f577874327", "src_encoding": "UTF-8", "star_events_count": 11, "url": "https://raw.githubusercontent.com/freetrade-io/ts-firebase-driver-testing/72d69b249f3a6db0195d2d7079def46fc11ba5ce/tests/driver/Firestore/InProcessFirestore.create.test.ts", "visit_date": "2023-03-02T21:06:46.086791", "added": "2024-11-18T20:06:31.857304+00:00", "created": "2022-10-06T12:12:20", "int_score": 3, "score": 2.71875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0090.json.gz" }
<?php namespace TgoH; #Base use pocketmine\plugin\PluginBase; use pocketmine\event\Listener; use pocketmine\Player; use pocketmine\Server; #Entity use pocketmine\entity\Entity; #etc use pocketmine\entity\Item as ItemEntity; use pocketmine\network\mcpe\protocol\ChangeDimensionPacket; use pocketmine\scheduler\PluginTask; #Commands use pocketmine\command\Command; use pocketmine\command\CommandSender; #Utils use pocketmine\utils\TextFormat as Color; use TgoH\utils\tunedConfig as Config; class Main extends PluginBase implements Listener{ const NAME = 'The gate of Hell', VERSION = '√3'; private $pk; public function onEnable(){ $this->initialize(); $this->makePacket(); $sec = new sec($this); $this->getServer()->getScheduler()->scheduleRepeatingTask($sec, 60); $this->getServer()->getPluginManager()->registerEvents($this,$this); $this->getLogger()->info(Color::GREEN.self::NAME." ".self::VERSION." が読み込まれました。"); } public function onCommand(CommandSender $s, Command $command, string $label, array $args): bool{ if (strtolower($label) === "hell") { if (isset($args[0])) { $target = $this->getServer()->getPlayer($args[0]); if (is_null($target)) { if (isset($this->black[strtolower($args[0])])) { $s->sendMessage("§4[TgoH] そのプレイヤーは既にブラックリストに登録されています"); }else { $s->sendMessage("§4[TgoH] 指定されたプレイヤーをブラックリストに登録しました"); $date = new \DateTime(); $date->setTimeZone(new \DateTimeZone('Asia/Tokyo')); $date_time = $date->format('Y-m-d H:i:s'); $tn = strtolower($args[0]); $this->black[$tn] = $date_time; $this->blackList->set($tn, $date_time); $this->blackList->save(); } }else { $tn = strtolower($target->getName()); $s->sendMessage("§4[TgoH] 指定されたプレイヤーをブラックリストに登録し、地獄の門を開きました。"); $this->theEnd($target); $date = new \DateTime(); $date->setTimeZone(new \DateTimeZone('Asia/Tokyo')); $date_time = $date->format('Y-m-d H:i:s'); $this->black[$tn] = $date_time; $this->blackList->set($tn, $date_time); $this->blackList->save(); $s->sendMessage("§4[TgoH] The end."); } }else { return false; } } return true; } private function theEnd($target){ $target->dataPacket($this->pk); } public function phantomKiller(){ foreach ($this->getServer()->getOnlinePlayers() as $p) { if (isset($this->black[strtolower($p->getName())])) { $this->theEnd($p); } } } public function onDisable(){ $this->getLogger()->info(Color::RED.self::NAME." が無効化されました。"); } /****************************************************************************/ //適当 private function initialize(){ $dir = $this->getDataFolder(); $black = "blackList.json"; // if(!file_exists($dir)) mkdir($dir); if(!file_exists($dir.$black)) file_put_contents($dir.$black, []); $this->blackList = new Config($dir.$black, Config::JSON); $this->black = $this->blackList->getAll(); } private function makePacket(){ $pk = new ChangeDimensionPacket(); $pk->dimension = -1; $pk->x = 0; $pk->y = 0; $pk->z = 0; $this->pk = $pk; } } class sec extends PluginTask{ function __construct($main){ parent::__construct($main); $this->main = $main; } function onRun(int $tick){ $this->main->phantomKiller(); } }
4a0d8391ce6b85b1b09983a9ff92478eb838ae24
{ "blob_id": "4a0d8391ce6b85b1b09983a9ff92478eb838ae24", "branch_name": "refs/heads/master", "committer_date": "2017-11-21T16:07:31", "content_id": "bd8325ab81e0dec4556cfcbc28d2d399f317b6b3", "detected_licenses": [ "MIT" ], "directory_id": "2fff5c6cc898655cd3ff8395d348c67fa3603cd9", "extension": "php", "filename": "Main.php", "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": "PHP", "length_bytes": 3746, "license": "MIT", "license_type": "permissive", "path": "/src/TgoH/Main.php", "provenance": "stack-edu-0052.json.gz:328848", "repo_name": "gragonvlad/TgoH", "revision_date": "2017-11-21T16:07:31", "revision_id": "9d5418409931bc6ae1e091e6e9042ce2be962d6b", "snapshot_id": "9d1007a2769b65cb112d14a61c409f77a61b6626", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/gragonvlad/TgoH/9d5418409931bc6ae1e091e6e9042ce2be962d6b/src/TgoH/Main.php", "visit_date": "2021-08-26T04:42:06.764822", "added": "2024-11-18T22:17:49.840853+00:00", "created": "2017-11-21T16:07:31", "int_score": 2, "score": 2.421875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0070.json.gz" }
<?php use Illuminate\Support\Facades\Route; //===============================FRONT END===================================== Route::get('/', 'HomeController@index'); Route::get('/home', 'HomeController@index'); //Side bar menu Cate and Brand Route::get('/brand/{brand_id}','Brand@getBrand'); Route::get('/danh-muc-san-pham/{category_id}','CategoryProduct@getCategory'); //Detail Route::get('/chi-tiet-san-pham/{produc_id}','Product@getProductDetail'); //Cart //Route::post('/save-cart','CartController@saveCart'); Route::post('/add-to-cart','CartController@addToCart'); Route::get('/check-out','CartController@showCart'); Route::get('/delete-cart/{session_id}','CartController@deleteCart'); Route::post('update-cart','CartController@updateCart'); Route::post('check-coupon','CartController@checkCoupon'); //product Route::get('/product','Product@getAllProduct'); //tim kiem Route::get('/tim-kiem','HomeController@search'); Route::post('/ket-qua-tim-kiem','HomeController@searchResult'); //send mail Route::get('/send-mail','MailController@sendMail'); // ===============================BACK END===================================== //Admin Route::get('/admin', 'AdminController@index'); Route::get('/dashboard', 'AdminController@dashboard'); Route::post('/admin-dashboard', 'AdminController@loginDashboard'); Route::get('/logout', 'AdminController@logOut'); // Category Route::get('/add-category', 'CategoryProduct@addCategory'); Route::get('/list-category', 'CategoryProduct@listCategory'); Route::post('/save-category', 'CategoryProduct@saveCategory'); Route::get('/unactive-category/{category_id}', 'CategoryProduct@unactiveCategory'); Route::get('/active-category/{category_id}', 'CategoryProduct@activeCategory'); Route::get('/edit-category/{category_id}', 'CategoryProduct@editCategory'); Route::get('/delete-category/{category_id}', 'CategoryProduct@deleteCategory'); Route::post('/update-category/{category_id}','CategoryProduct@updateCategory'); //Brand Route::get('/add-brand', 'Brand@addBrand'); Route::get('/list-brand', 'Brand@listBrand'); Route::post('/save-brand', 'Brand@saveBrand'); Route::get('/unactive-brand/{brand_id}', 'Brand@unactiveBrand'); Route::get('/active-brand/{brand_id}', 'Brand@activeBrand'); Route::get('/edit-brand/{brand_id}', 'Brand@editBrand'); Route::get('/delete-brand/{brand_id}', 'Brand@deleteBrand'); Route::post('/update-brand/{brand_id}','Brand@updateBrand'); //Product Route::get('/add-product', 'Product@addProduct'); Route::get('/list-product', 'Product@listProduct'); Route::post('/save-product', 'Product@saveProduct'); Route::get('/unactive-product/{product_id}', 'Product@unactiveProduct'); Route::get('/active-product/{product_id}', 'Product@activeProduct'); Route::get('/edit-product/{product_id}', 'Product@editProduct'); Route::get('/delete-product/{product_id}', 'Product@deleteProduct'); Route::post('/update-product/{product_id}','Product@updateProduct'); //Coupon Route::get('/add-coupon', 'CouponController@addCoupon'); Route::get('/list-coupon', 'CouponController@listCoupon'); Route::post('/save-coupon', 'CouponController@saveCoupon'); Route::get('/unactive-coupon/{cp_id}', 'CouponController@unactiveCoupon'); Route::get('/active-coupon/{cp_id}', 'CouponController@activeCoupon'); Route::get('/delete-coupon/{cp_id}', 'CouponController@deleteCoupon'); Route::post('/update-coupon/{cp_id}','CouponController@updateCoupon'); //Delivery Route::get('/delivery', 'DeliveryController@delivery'); Route::post('/select-delivery', 'DeliveryController@selectDelivery'); Route::post('/save-delivery', 'DeliveryController@saveDelivery'); Route::post('/select-feeship','DeliveryController@selectFeeship');
2e9f27352894cc2f471f48b2a25476765a6d1355
{ "blob_id": "2e9f27352894cc2f471f48b2a25476765a6d1355", "branch_name": "refs/heads/master", "committer_date": "2021-09-22T14:54:06", "content_id": "da1dc6c5a7daca09b91246e552d5720dc5c1b9f4", "detected_licenses": [ "MIT" ], "directory_id": "79648e78c36607d576ed56d277cc8351d62c501a", "extension": "php", "filename": "web.php", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 406062975, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 3700, "license": "MIT", "license_type": "permissive", "path": "/routes/web.php", "provenance": "stack-edu-0051.json.gz:207437", "repo_name": "mockingbitch/laravelweb", "revision_date": "2021-09-22T14:54:06", "revision_id": "b64d0a8eb90b9021d2b1c5fdb28a3a33ff3bb308", "snapshot_id": "13d9b9ada96e534bd8abd2abe49cda398c333f9a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mockingbitch/laravelweb/b64d0a8eb90b9021d2b1c5fdb28a3a33ff3bb308/routes/web.php", "visit_date": "2023-08-11T07:35:43.633145", "added": "2024-11-18T21:20:28.558672+00:00", "created": "2021-09-22T14:54:06", "int_score": 2, "score": 2.0625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0069.json.gz" }
import * as validator from "./validator"; import { Config, Result, SingleResult } from "./types"; import { vError } from "./error"; /** * Validator Schema * Test Case: "case:message:test" * You can use a "|" to add more Test Case to schema * eg. "isRequired:Field is required|hasMin:Field is greater than two:2" * * Sample Schema: { * email: "isEmail:Invalid email", * name: "hasMin:Is greater than 2 charaters:2|hasMax:Is lesser than 30 charaters:30" * } * * @param param0 */ export default function valid({ schema, single }: Config) { if (single && typeof schema == "object") return (v: any): Result => vError.badSchemaTypeObject; if (!single && typeof schema == "string") return (v: any): Result => vError.badSchemaTypeString; if (single) return value => validateSingle(schema, value); return value => validateMultiple(schema, value); } // Multiple export function validateMultiple(schema: any, value: any): Result { const errors = {}; for (let item in schema) { const { error } = validateSingle(schema[item], value[item]); if (error && error.length) errors[item] = error; } return { errors, valid: validator.isEmpty(errors) }; } // Single export function validateSingle(schema, value): SingleResult { let error = null; schema.split("|").forEach(op => { const [testCase, message, test] = op.split(":"); if (test) { if (!validator[testCase](value, test)) error = message; } else { if (!validator[testCase](value)) error = message; } }); return { error, valid: validator.isEmpty(error) }; }
c2820381b30d0ddf80e51743225b2789e0574c27
{ "blob_id": "c2820381b30d0ddf80e51743225b2789e0574c27", "branch_name": "refs/heads/master", "committer_date": "2020-02-27T04:07:54", "content_id": "bc80773071f92c1b0ef82b15f082cd665dce8949", "detected_licenses": [ "MIT" ], "directory_id": "83b3b08c55c01b8a0d925f0c73bfb697a65e228a", "extension": "ts", "filename": "index.ts", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 243418874, "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1583, "license": "MIT", "license_type": "permissive", "path": "/src/index.ts", "provenance": "stack-edu-0075.json.gz:681620", "repo_name": "GTime/valid", "revision_date": "2020-02-27T04:07:54", "revision_id": "e7d5b1e58426c0da4c481c68d298bf4924a8f28e", "snapshot_id": "777dcf5901c03c3ff46bba7cef2acd96b966ba8f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/GTime/valid/e7d5b1e58426c0da4c481c68d298bf4924a8f28e/src/index.ts", "visit_date": "2021-01-26T11:15:21.782603", "added": "2024-11-19T00:54:07.878151+00:00", "created": "2020-02-27T04:07:54", "int_score": 3, "score": 3.1875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0093.json.gz" }
using Aspekt.IO; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace TrixieCore { public class RedShieldAbility : BaseShieldAbility { public bool ShootRequiresFullCharge = true; public Beam.BeamStats beamSettings; public enum ChargeTypes { Chargeup, Cooldown, Deplete } public ChargeTypes ChargeType; public float ChargeupTime = 1f; public float CooldownTime = 1f; public Beam Beam; private float timer; protected override void Start() { base.Start(); Colour = EnergyTypes.Colours.Red; Beam.SetBeamSettings(beamSettings); Beam.Deactivate(); } public override void DisableAbility() { Beam.Deactivate(); } public override void ActivatePressed() { if (ShootRequiresFullCharge && !power.ShieldFullyCharged()) return; if (ChargeType == ChargeTypes.Chargeup) { state = States.Charging; } else if (ChargeType == ChargeTypes.Deplete) { state = States.Activating; Beam.Activate(); } } public override bool ActivateReleased() { shield.ChargeIndicator.StopCharge(); bool shootSuccess = false; if (state == States.Charged && shield.IsShielding()) { shootSuccess = true; ActivateShoot(); } if (ChargeType == ChargeTypes.Chargeup) { timer = 0f; if (state == States.Charging) { state = States.None; } } else if (ChargeType == ChargeTypes.Deplete) { state = States.None; Beam.Deactivate(); } return shootSuccess; } public override void ReturnShield() { if (state != States.Returning && shield.gameObject.activeSelf) { state = States.Returning; StartCoroutine(ReturnShieldRoutine()); } } public override void DisableShield() { if (state == States.Activating) { timer = 0f; } state = States.None; shield.ChargeIndicator.StopCharge(); Beam.Deactivate(); } public override void UpdateCharge(float deltaTime) { switch (state) { case States.None: if (ChargeType == ChargeTypes.Cooldown) { if (timer > CooldownTime) { state = States.Charged; } else { state = States.Charging; } } else { timer = 0f; } break; case States.Charging: timer += deltaTime; shield.ChargeIndicator.SetCharge(timer / (ChargeType == ChargeTypes.Chargeup ? ChargeupTime : CooldownTime)); TransitionIfCharged(); break; case States.Charged: break; case States.Activating: float shieldDistance = (transform.position - shield.CenterPoint.position).magnitude; //if (shieldDistance >= MaxBeamDistance) //{ // ReturnShield(); //} break; case States.Returning: break; default: break; } } private void ActivateShoot() { state = States.Activating; shield.ShieldCollider.isTrigger = true; body.isKinematic = false; // body.velocity = ShootSpeed * GetMoveDirection().normalized; anim.Play("Shoot", 0, 0f); } private IEnumerator ReturnShieldRoutine() { body.isKinematic = true; while (Vector2.Distance(transform.position, shield.CenterPoint.position) > 1f) { Vector2 distVector = (shield.CenterPoint.position - transform.position).normalized; //transform.position += new Vector3(distVector.x, distVector.y, 0f) * ShootSpeed * Time.deltaTime; // Ensure we don't overshoot the target position Vector2 newDistVector = shield.CenterPoint.position - transform.position; if (Mathf.Sign(newDistVector.x) != Mathf.Sign(distVector.x) || Mathf.Sign(newDistVector.y) != Mathf.Sign(distVector.y)) { transform.position = new Vector3(shield.CenterPoint.position.x, shield.CenterPoint.position.y, transform.position.z); } yield return null; } shield.ShieldCollider.isTrigger = false; state = States.None; if (ChargeType == ChargeTypes.Cooldown) { timer = 0f; } shield.OnReturn(); } private void TransitionIfCharged() { if (ChargeType == ChargeTypes.Chargeup && timer > ChargeupTime) { shield.ChargeIndicator.SetCharged(ChargeType == ChargeTypes.Cooldown); state = States.Charged; } else if (ChargeType == ChargeTypes.Cooldown && timer > CooldownTime) { shield.ChargeIndicator.SetCharged(ChargeType == ChargeTypes.Cooldown); state = States.Charged; } } private Vector2 GetMoveDirection() { Vector2 dir = Trixie.Instance.GetComponent<PlayerController>().GetMoveDirection(); if (dir.y > Mathf.Abs(dir.x)) { return Vector2.up; } else if (dir.y < -Mathf.Abs(dir.x)) { return Vector2.down; } else if (Trixie.Instance.IsFacingRight()) { return Vector2.right; } else { return Vector2.left; } } } }
afe624012796a7ed392de3eb54d94e8db991768b
{ "blob_id": "afe624012796a7ed392de3eb54d94e8db991768b", "branch_name": "refs/heads/master", "committer_date": "2020-05-18T03:00:35", "content_id": "4be7e761d228f0f606c0d55c3a7b8c9dca009060", "detected_licenses": [ "Apache-2.0" ], "directory_id": "f9e37c1f6c14f4986aa0aa2c8c45ea6e43289b13", "extension": "cs", "filename": "RedShieldAbility.cs", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 110308877, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 6657, "license": "Apache-2.0", "license_type": "permissive", "path": "/Assets/Scripts/Core/Player/Abilities/ShieldComponents/ShieldAbilities/RedShieldAbility.cs", "provenance": "stack-edu-0009.json.gz:438620", "repo_name": "Aspekt1024/Trixie", "revision_date": "2020-05-18T03:00:35", "revision_id": "8a5fb4a47452559508c73079c8aa1fd87bef3f04", "snapshot_id": "7b67bb1c04a9dc719ebb23c5df153504d9b91374", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/Aspekt1024/Trixie/8a5fb4a47452559508c73079c8aa1fd87bef3f04/Assets/Scripts/Core/Player/Abilities/ShieldComponents/ShieldAbilities/RedShieldAbility.cs", "visit_date": "2022-07-06T05:27:58.564440", "added": "2024-11-19T03:02:41.767996+00:00", "created": "2020-05-18T03:00:35", "int_score": 2, "score": 2.203125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0027.json.gz" }
define([ 'main/messageHandlers', 'main/serviceLoader', 'main/serviceController', 'rx', 'common/chromeApi' ], function (messageHandlers, serviceLoader, serviceController, Rx, chromeApi) { 'use strict'; describe('messageHandlers', function () { var port; var handler; var connectHandler; beforeEach(function () { spyOn(chromeApi, 'addMessageListener').andCallFake(function (handlerFunction) { handler = handlerFunction; }); spyOn(chromeApi, 'addConnectListener').andCallFake(function (onConnect) { connectHandler = onConnect; }); port = openPort('popup'); messageHandlers.init(); }); afterEach(function () { if (port.disconnectHandler) { port.disconnectHandler(port); } }); function openPort(portName) { var port = { name: portName, postMessage: function () {}, onDisconnect: { addListener: function () {} } }; spyOn(port.onDisconnect, 'addListener').andCallFake(function (onDisconnect) { port.disconnectHandler = onDisconnect; }); spyOn(port, 'postMessage'); return port; } describe('state', function () { it('should subscribe to state sequence on connect', function () { connectHandler(port); serviceController.activeProjects.onNext([{ name: 'service 1', items: [] }]); expect(port.postMessage).toHaveBeenCalled(); }); it('should unsubscribe from state changes on disconnect', function () { connectHandler(port); port.disconnectHandler(port); serviceController.activeProjects.onNext('test'); serviceController.activeProjects.onNext('test'); serviceController.activeProjects.onNext('test'); expect(port.postMessage.callCount).toBe(1); }); it('should unsubscribe from right channel', function () { var popupPort = openPort('popup'); var dashboardPort = openPort('dashboard'); connectHandler(popupPort); connectHandler(dashboardPort); popupPort.disconnectHandler(popupPort); serviceController.activeProjects.onNext('test'); serviceController.activeProjects.onNext('test'); serviceController.activeProjects.onNext('test'); expect(popupPort.postMessage.callCount).toBe(1); expect(dashboardPort.postMessage.callCount).toBe(4); }); it('should push message on event', function () { connectHandler(port); var lastMessage; messageHandlers.messages.subscribe(function (message) { lastMessage = message; }); serviceController.activeProjects.onNext([{ name: 'service 1', items: [] }]); expect(lastMessage).toBeDefined(); }); }); describe('availableProjects', function () { var CustomBuildService = function () {}; CustomBuildService.prototype.availableBuilds = function () {}; var service; var sendResponse; var request; var mockAvailableBuilds; beforeEach(function () { service = new CustomBuildService(); spyOn(serviceLoader, 'load').andCallFake(function () { return Rx.Observable.returnValue(new CustomBuildService()); }); sendResponse = jasmine.createSpy(); request = { name: 'availableProjects', serviceSettings: {} }; mockAvailableBuilds = spyOn(CustomBuildService.prototype, 'availableBuilds').andCallFake(function () { return Rx.Observable.never(); }); }); it('should create service', function () { handler(request, null, sendResponse); expect(serviceLoader.load).toHaveBeenCalled(); }); it('should call service', function () { handler(request, null, sendResponse); expect(service.availableBuilds).toHaveBeenCalled(); }); it('should send response back', function () { var serviceResponse = {}; var actualResponse; var sendResponse = function (response) { actualResponse = response; }; mockAvailableBuilds.andReturn(Rx.Observable.returnValue(serviceResponse)); handler(request, null, sendResponse); expect(actualResponse.projects).toBe(serviceResponse); }); it('should send error back', function () { var serviceError = {}; var actualResponse; var sendResponse = function (response) { actualResponse = response; }; mockAvailableBuilds.andReturn(Rx.Observable.throwException(serviceError)); handler(request, null, sendResponse); expect(actualResponse.error).toBe(serviceError); }); }); }); });
a4f8228e50dd628139fc4f48b3c1a663d1be33d9
{ "blob_id": "a4f8228e50dd628139fc4f48b3c1a663d1be33d9", "branch_name": "refs/heads/master", "committer_date": "2013-09-10T07:29:48", "content_id": "c4885c9d553f3155f72caa68808e071d49fdd41e", "detected_licenses": [ "Apache-2.0" ], "directory_id": "3564b0fa4cc3a9b74e6ec024d83bdc524093e9e8", "extension": "js", "filename": "messageHandlers.spec.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": 4345, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/main/messageHandlers.spec.js", "provenance": "stack-edu-0040.json.gz:65672", "repo_name": "vladshub/BuildReactor", "revision_date": "2013-09-10T07:29:48", "revision_id": "abeec5990602d256f6bba6195c02664580efb7ce", "snapshot_id": "258923c4ef12236af833ff6e04aefc33bc626ed6", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/vladshub/BuildReactor/abeec5990602d256f6bba6195c02664580efb7ce/src/main/messageHandlers.spec.js", "visit_date": "2021-01-17T07:39:05.322074", "added": "2024-11-19T00:40:08.992789+00:00", "created": "2013-09-10T07:29:48", "int_score": 2, "score": 2.28125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0058.json.gz" }
var express = require("express"), // bodyParser = require("body-parser"), async = require("async"), error = require("../middlewares/error.js"), Template = require("../models/templates.js"), Reference = require("../models/references"), Verify = require("./verify"), router = express.Router(); router.route("/") .get(Verify.verifyOrdinaryUser, function(req, res, next) { async.parallel({ "subject": function(callback) { Template.aggregate([{ $unwind: "$subjects" }, { $group: { _id: "$subjects", count: { $sum: 1 } } }, { $sort: { _id: 1 } }], function(err, results) { console.log(results); callback(null, results); }); }, "reference": function(callback) { Template.aggregate([{ $unwind: "$references" }, { $group: { _id: {textbook: "$references.textbook", chapter: "$references.chapter"}, count: { $sum: 1 } } }, { $sort: { "_id.textbook": 1, "_id.chapter": 1 } }], function(err, results) { console.log(results); callback(null, results); }); }, "createdBy": function(callback) { Template.aggregate([{ $group: { _id: "$createdBy", count: { $sum: 1 } } }], function(err, results) { console.log(results); callback(null, results); }); } }, function(err, results) { console.log(results); res.json(results); } ); }); module.exports = router;
7600f821b7c95c1fe68084aee96c97fdc3c19856
{ "blob_id": "7600f821b7c95c1fe68084aee96c97fdc3c19856", "branch_name": "refs/heads/master", "committer_date": "2017-03-02T15:30:33", "content_id": "d3db9509feb80474ebefad62ce1f06e7846614f0", "detected_licenses": [ "MIT" ], "directory_id": "853d6ee23f67779b1398c05b0b9bfa625ed27ac0", "extension": "js", "filename": "stats.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 81439094, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1477, "license": "MIT", "license_type": "permissive", "path": "/routes/stats.js", "provenance": "stack-edu-0032.json.gz:727487", "repo_name": "robinguo/engbooster", "revision_date": "2017-03-02T15:30:33", "revision_id": "f25d579a45580f198e2458b569f6238c069985a1", "snapshot_id": "5586264c332627f418dc443e105bb303072af491", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/robinguo/engbooster/f25d579a45580f198e2458b569f6238c069985a1/routes/stats.js", "visit_date": "2021-01-13T05:25:44.215914", "added": "2024-11-19T00:50:15.549194+00:00", "created": "2017-03-02T15:30:33", "int_score": 2, "score": 2, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0050.json.gz" }
"""Resize images in a folder using imagemagick command line tools. http://hakanu.net """ import glob import os def main(): print 'Started' images = glob.glob("/home/h/Desktop/all_karikatur_resized/*.jpg") counter = 0 for image in images: print 'Processing: ', image index = image[image.rfind('/') + 1:image.rfind('.jpg')] print 'index: ', index os.system("convert " + index + ".jpg -resize 128x128 resize_128_" + index + ".jpg") counter += 1 if counter % 100 == 0: print 'Completed: ', counter print '\n' main()
a7c3fa2562416f9955f8bbf9a051062270bcc452
{ "blob_id": "a7c3fa2562416f9955f8bbf9a051062270bcc452", "branch_name": "refs/heads/master", "committer_date": "2013-11-10T22:04:55", "content_id": "a9836284221d7bd240a52447bd76b631ea410043", "detected_licenses": [ "Apache-2.0" ], "directory_id": "d837ccb12582feadc50247cba04c87a623b00837", "extension": "py", "filename": "batch_image_resizer.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": 559, "license": "Apache-2.0", "license_type": "permissive", "path": "/batch_image_resizer2/batch_image_resizer.py", "provenance": "stack-edu-0060.json.gz:598329", "repo_name": "hakanu/scripts", "revision_date": "2013-11-10T22:04:55", "revision_id": "d0f1801d0f56bb9cd16f6fb76ce4124c42e11e44", "snapshot_id": "fe7c013fd18d63947583359d04cfc7a9fc11f4d6", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/hakanu/scripts/d0f1801d0f56bb9cd16f6fb76ce4124c42e11e44/batch_image_resizer2/batch_image_resizer.py", "visit_date": "2020-12-24T15:14:18.799738", "added": "2024-11-18T21:14:08.820637+00:00", "created": "2013-11-10T22:04:55", "int_score": 3, "score": 3.0625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0078.json.gz" }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 com.aliyun.oss.common.comm.io; import static com.aliyun.oss.common.utils.LogUtils.getLog; import java.io.IOException; import java.io.InputStream; public class RepeatableInputStream extends InputStream { private InputStream is = null; private int bufferSize = 0; private int bufferOffset = 0; private long bytesReadFromMark = 0; private byte[] buffer = null; public RepeatableInputStream(InputStream inputStream, int bufferSize) { if (inputStream == null) { throw new IllegalArgumentException("inputStream should not be null"); } this.is = inputStream; this.bufferSize = bufferSize; this.buffer = new byte[this.bufferSize]; } public void reset() throws IOException { if (bytesReadFromMark <= bufferSize) { getLog().debug("Reset after reading " + bytesReadFromMark + " bytes."); bufferOffset = 0; } else { throw new IOException("Input stream cannot be reset as " + this.bytesReadFromMark + " bytes have been written, exceeding the available buffer size of " + this.bufferSize); } } public boolean markSupported() { return true; } public synchronized void mark(int readlimit) { if (bytesReadFromMark <= bufferSize && buffer != null) { byte[] newBuffer = new byte[this.bufferSize]; System.arraycopy(buffer, bufferOffset, newBuffer, 0, (int) (bytesReadFromMark - bufferOffset)); this.buffer = newBuffer; this.bytesReadFromMark -= bufferOffset; this.bufferOffset = 0; } else { this.bufferOffset = 0; this.bytesReadFromMark = 0; this.buffer = new byte[this.bufferSize]; } } public int available() throws IOException { return is.available(); } public void close() throws IOException { is.close(); } public int read(byte[] out, int outOffset, int outLength) throws IOException { byte[] tmp = new byte[outLength]; if (bufferOffset < bytesReadFromMark && buffer != null) { int bytesFromBuffer = tmp.length; if (bufferOffset + bytesFromBuffer > bytesReadFromMark) { bytesFromBuffer = (int) bytesReadFromMark - bufferOffset; } System.arraycopy(buffer, bufferOffset, out, outOffset, bytesFromBuffer); bufferOffset += bytesFromBuffer; return bytesFromBuffer; } int count = is.read(tmp); if (count <= 0) { return count; } if (bytesReadFromMark + count <= bufferSize) { System.arraycopy(tmp, 0, buffer, (int) bytesReadFromMark, count); bufferOffset += count; } else if (buffer != null) { getLog().debug("Buffer size " + bufferSize + " has been exceeded and the input stream " + "will not be repeatable until the next mark. Freeing buffer memory"); buffer = null; } System.arraycopy(tmp, 0, out, outOffset, count); bytesReadFromMark += count; return count; } public int read() throws IOException { byte[] tmp = new byte[1]; int count = read(tmp); if (count != -1) { return tmp[0]; } else { return count; } } public InputStream getWrappedInputStream() { return is; } }
b14d9c9419cd0e7012f8b01018e21fa180eed35c
{ "blob_id": "b14d9c9419cd0e7012f8b01018e21fa180eed35c", "branch_name": "refs/heads/master", "committer_date": "2023-07-24T02:37:44", "content_id": "4c06de955f2444ae11efdb7f72680cb31bb9a0b9", "detected_licenses": [ "Apache-2.0" ], "directory_id": "1de856b1eaf5885f22a766c843df4899f06fd8a0", "extension": "java", "filename": "RepeatableInputStream.java", "fork_events_count": 1016, "gha_created_at": "2015-07-31T03:21:07", "gha_event_created_at": "2023-09-13T02:17:10", "gha_language": "Java", "gha_license_id": null, "github_id": 39984469, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4295, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/main/java/com/aliyun/oss/common/comm/io/RepeatableInputStream.java", "provenance": "stack-edu-0021.json.gz:697808", "repo_name": "aliyun/aliyun-oss-java-sdk", "revision_date": "2023-07-24T02:35:33", "revision_id": "3f0a1a8046aa9312fdd2030218367f4c719dcfad", "snapshot_id": "2b0c9556f81d732d33d2c5d4711bb4ead32441fc", "src_encoding": "UTF-8", "star_events_count": 1282, "url": "https://raw.githubusercontent.com/aliyun/aliyun-oss-java-sdk/3f0a1a8046aa9312fdd2030218367f4c719dcfad/src/main/java/com/aliyun/oss/common/comm/io/RepeatableInputStream.java", "visit_date": "2023-08-23T07:23:42.570369", "added": "2024-11-18T18:52:09.352469+00:00", "created": "2023-07-24T02:35:33", "int_score": 2, "score": 2.34375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0039.json.gz" }
package fsm.dao.impl; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import fsm.dao.GroupDao; import fsm.model.domain.Group; @Repository public class GroupDaoImpl implements GroupDao { @Autowired private SessionFactory sessionFactory; @Override public Integer addGroup(Group group) { Session session = sessionFactory.getCurrentSession(); Integer groupID = (Integer) session.save(group); return groupID; } @Override public void removeGroup(int groupId) { Session session = sessionFactory.getCurrentSession(); Group group = getGroupById(groupId); if (group != null) { session.delete(group); } } @Override public void updateGroup(Group group) { Session session = sessionFactory.getCurrentSession(); session.update(group); } @Override public Group getGroupById(int groupId) { Session session = sessionFactory.getCurrentSession(); Group group = (Group) session.get(Group.class, groupId); return group; } @Override public List<Group> getAllGroups() { Session session = sessionFactory.getCurrentSession(); Criteria criteria = session.createCriteria(Group.class); return criteria.list(); } }
0b31224f609348255539d0706f13ac7a47e03d58
{ "blob_id": "0b31224f609348255539d0706f13ac7a47e03d58", "branch_name": "refs/heads/master", "committer_date": "2016-12-24T18:55:29", "content_id": "27357f9b2a82d5c6cf6d50c975e91984fcd58e13", "detected_licenses": [ "MIT" ], "directory_id": "2047587ca9a2689d8bc20da32ad3952286ecd2f4", "extension": "java", "filename": "GroupDaoImpl.java", "fork_events_count": 0, "gha_created_at": "2020-07-18T18:54:01", "gha_event_created_at": "2020-07-18T18:54:01", "gha_language": null, "gha_license_id": null, "github_id": 280719511, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1341, "license": "MIT", "license_type": "permissive", "path": "/src/main/java/fsm/dao/impl/GroupDaoImpl.java", "provenance": "stack-edu-0024.json.gz:11017", "repo_name": "arpit006/FSM", "revision_date": "2016-12-24T18:55:29", "revision_id": "1acdab69c54845175551d660b6381f915a5e8aef", "snapshot_id": "b6739b6b235b72d28414b10c4568a80b8179e290", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/arpit006/FSM/1acdab69c54845175551d660b6381f915a5e8aef/src/main/java/fsm/dao/impl/GroupDaoImpl.java", "visit_date": "2021-06-08T20:32:01.547012", "added": "2024-11-18T21:30:20.399969+00:00", "created": "2016-12-24T18:55:29", "int_score": 2, "score": 2.40625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0042.json.gz" }
/* * Copyright 2013 Steve Jones. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.github.sjones4.youcan.youconfig.model; /** * */ public class ComponentInfo { private String type; private String partition; private String name; private String hostName; private String fullName; private String state; private String detail; public String getType() { return type; } public void setType( final String type ) { this.type = type; } public String getPartition() { return partition; } public void setPartition( final String partition ) { this.partition = partition; } public String getName() { return name; } public void setName( final String name ) { this.name = name; } public String getHostName() { return hostName; } public void setHostName( final String hostName ) { this.hostName = hostName; } public String getFullName() { return fullName; } public void setFullName( final String fullName ) { this.fullName = fullName; } public String getState() { return state; } public void setState( final String state ) { this.state = state; } public String getDetail() { return detail; } public void setDetail( final String detail ) { this.detail = detail; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getType() != null) sb.append("Type: " + getType() + ","); if (getPartition() != null) sb.append("Partition: " + getPartition() + ","); if (getName() != null) sb.append("Name: " + getName() + ","); if (getHostName() != null) sb.append("HostName: " + getHostName() + ","); if (getFullName() != null) sb.append("FullName: " + getFullName() + ","); if (getState() != null) sb.append("State: " + getState() + ","); if (getDetail() != null) sb.append("Detail: " + getDetail() ); sb.append("}"); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getType() == null) ? 0 : getType().hashCode()); hashCode = prime * hashCode + ((getPartition() == null) ? 0 : getPartition().hashCode()); hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode()); hashCode = prime * hashCode + ((getHostName() == null) ? 0 : getHostName().hashCode()); hashCode = prime * hashCode + ((getFullName() == null) ? 0 : getFullName().hashCode()); hashCode = prime * hashCode + ((getState() == null) ? 0 : getState().hashCode()); hashCode = prime * hashCode + ((getDetail() == null) ? 0 : getDetail().hashCode()); return hashCode; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ComponentInfo == false) return false; ComponentInfo other = (ComponentInfo)obj; if (other.getType() == null ^ this.getType() == null) return false; if (other.getType() != null && other.getType().equals(this.getType()) == false) return false; if (other.getPartition() == null ^ this.getPartition() == null) return false; if (other.getPartition() != null && other.getPartition().equals(this.getPartition()) == false) return false; if (other.getName() == null ^ this.getName() == null) return false; if (other.getName() != null && other.getName().equals(this.getName()) == false) return false; if (other.getHostName() == null ^ this.getHostName() == null) return false; if (other.getHostName() != null && other.getHostName().equals(this.getHostName()) == false) return false; if (other.getFullName() == null ^ this.getFullName() == null) return false; if (other.getFullName() != null && other.getFullName().equals(this.getFullName()) == false) return false; if (other.getState() == null ^ this.getState() == null) return false; if (other.getState() != null && other.getState().equals(this.getState()) == false) return false; if (other.getDetail() == null ^ this.getDetail() == null) return false; if (other.getDetail() != null && other.getDetail().equals(this.getDetail()) == false) return false; return true; } }
decc3c969173e2a223fa5e1b2814238ed631c82f
{ "blob_id": "decc3c969173e2a223fa5e1b2814238ed631c82f", "branch_name": "refs/heads/master", "committer_date": "2016-11-12T00:12:25", "content_id": "c6fd116354bc4ac5279687a8a178747de3540dd2", "detected_licenses": [ "Apache-2.0" ], "directory_id": "aa29e430671ba3a25b6617abc1f4ded9fb64be41", "extension": "java", "filename": "ComponentInfo.java", "fork_events_count": 0, "gha_created_at": "2016-12-02T20:09:02", "gha_event_created_at": "2016-12-02T20:09:02", "gha_language": null, "gha_license_id": null, "github_id": 75427207, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4692, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/main/java/com/github/sjones4/youcan/youconfig/model/ComponentInfo.java", "provenance": "stack-edu-0021.json.gz:591169", "repo_name": "sangmin/you-are-sdk", "revision_date": "2016-11-12T00:12:25", "revision_id": "bb86d6023094a26e0b85c3b83795536f5c4a9679", "snapshot_id": "0d2157f23f8879651fbfc229008489384f5bc690", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/sangmin/you-are-sdk/bb86d6023094a26e0b85c3b83795536f5c4a9679/src/main/java/com/github/sjones4/youcan/youconfig/model/ComponentInfo.java", "visit_date": "2020-06-13T09:25:23.660755", "added": "2024-11-19T00:38:37.545568+00:00", "created": "2016-11-12T00:12:25", "int_score": 2, "score": 2.15625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0039.json.gz" }
using UnityEngine; using System.Collections; using UnityEngine.UI; public class ToggleEditColor : MonoBehaviour { public Color pressedColor; public Color normalColor; public Image theImageComponent; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public void OnPressToggleButton(bool status) { if (status) { theImageComponent.color = pressedColor; } else { theImageComponent.color = normalColor; } } }
6f749fd12407ee035cd004a36695c341dc109857
{ "blob_id": "6f749fd12407ee035cd004a36695c341dc109857", "branch_name": "refs/heads/master", "committer_date": "2020-08-31T15:52:11", "content_id": "e2bc96029fdadf0c0ec71fa2c05b6b9c1236dfa9", "detected_licenses": [ "MIT" ], "directory_id": "47199ef7a97ff1a77025a123e206e532c76376fc", "extension": "cs", "filename": "ToggleEditColor.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": 501, "license": "MIT", "license_type": "permissive", "path": "/Assets/CrosswordStarterPack/scripts/Utilities/ToggleEditColor.cs", "provenance": "stack-edu-0014.json.gz:325925", "repo_name": "Shah-Rana/Crosswords", "revision_date": "2020-08-31T15:52:11", "revision_id": "285598b347a12ce8576d5c318f4bbd55ab2e4bf7", "snapshot_id": "7278da52c08df909c6f4fb9f405ae0d3eed7dae2", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Shah-Rana/Crosswords/285598b347a12ce8576d5c318f4bbd55ab2e4bf7/Assets/CrosswordStarterPack/scripts/Utilities/ToggleEditColor.cs", "visit_date": "2022-12-08T14:59:43.595478", "added": "2024-11-18T21:42:35.699784+00:00", "created": "2020-08-31T15:52:11", "int_score": 2, "score": 2.046875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0032.json.gz" }
--- layout: post title: "SFPC: Day 05 - Open Frameworks Workshop, Troubleshooting git" date: 2016-10-14 14:16:00 -0400 categories: SFPC, Robby Kraft, Open Frameworks, git, Hiro Nakamura, project idea, command line, rotate image, EXIF --- Today was our fifth day at SFPC. It was an off day but our TA, [Robby Kraft](www.robbykraft.com) was kind enough to lead a really great [Open Frameworks](http://openframeworks.cc/) workshop with some of us today. ![Impromptu Open Frameworks workshop at SFPC](/images/IMG_4215.JPG) ------ Last night I went to [Babycastles](http://www.babycastles.com/) for the first time. Two of the people in game collective [Kokoromi](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=2&cad=rja&uact=8&ved=0ahUKEwiYgu6Jp9vPAhUGPT4KHaxLDnMQ6F4IJDAB&url=https%3A%2F%2Ftwitter.com%2FKOKOROMI%3Fref_src%3Dtwsrc%255Egoogle%257Ctwcamp%255Eserp%257Ctwgr%255Eauthor&usg=AFQjCNGFmpMOmdmV9y91YzScBoO5HzW-SQ&sig2=b1h_KTJWfsQYtWda5Db2RQ) were celebrating the Playstation 4 of their VR game [Super Hypercube](http://superhypercube.com/), which had been almost a decade in the making. Also, Lauren Gardner was there and showed some of us [Hack Manhattan's](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwi4pezDp9vPAhXGHD4KHWMuDGwQFggdMAA&url=https%3A%2F%2Fhackmanhattan.com%2F&usg=AFQjCNE30eUdtwCuasTeucARJxU2lajsWQ&sig2=eNnGAVJAdF2CwN4eNOM3aA&bvm=bv.135974163,d.cWw) space, which is connected to the same floor as Babycastles. ![Image from Babycastles.](/images/IMG_4202.JPG) -------- At 10am this morning, a few of us arrived for an Open Frameworks workshop initially suggested by Ruby. It took a bit to get Ofx installed on everyone's machines, but that's usually how workshops go. Some of us decided to pair program and we got started. We created a sketch called "Text Rain", in the workshop: ![Robby Kraft's OF Workshop Sketch Projection Example](/images/textRain_robby.gif) My classmate Hiroshi took it a step further and added some finesse. [You can find the code for his version of the sketch here.](https://github.com/5up-okamura/of-sketch-bouncing-text) ![Hiro Nakamura OF Workshop Sketch Projection](/images/textRain_hiro.gif) **Summation:** And so - I can *finally* run and (somewhat)debug a project in Open Frameworks. This is a wonderful feeling. **Project Idea:** I'd like to build a Raspberry Pi camera that incorporates some of this Open Frameworks computer vision stuff. Robby said that he had a project like that when he was a student at SFPC last year. [Check it out here: Crowdsourced Turing Machine.](https://vimeo.com/146826524) Spent 2-3 hours trying to push to my blog repo, messing with a git error: remote: error: GH001: Large files detected. You may want to try Git Large File Storage - https://git-lfs.github.com. remote: error: Trace: fd6343c9c8bff756b49d7b539776ea83 remote: error: See http://git.io/iEPt8g for more information. remote: error: File images/IMG_4174.MOV is 168.86 MB; this exceeds GitHub's file size limit of 100.00 MB To https://github.com/alexdwagner/alexdwagner.github.io.git ! [remote rejected] master -> master (pre-receive hook declined) All I want to do is update my blog. All... I... Want... To... Do... :( -------- **1 Hour Later...** I figured it out. You can use: git reset --hard HEAD~1 to revoke your last commit. Phew. **Also...** Sometimes, the iPhone takes pictures with the wrong image orientation, ie when you import the image, your portrait-framed image has been accidentally rotated into landscape. You can use this command in the terminal: sips -r 270 [fileName] Now to do some freelance work and then go home. One last thing to mention is that I met [Dan Shiffman](https://shiffman.net) today! He was recording a live stream tutorial for his [Coding Rainbow channel](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwihr9ni-N3PAhWGOz4KHd_OBDsQFggpMAA&url=http%3A%2F%2Fcodingrainbow.com%2F&usg=AFQjCNHdpl-aKFD2f8jMXWpwhpncDu1_zg&sig2=3qpFfzrilTCRPQoI-OuorQ&bvm=bv.135974163,d.cWw) on Youtube and he was nice enough to chat with us for 10 minutes or so. He will be here next Tuesday and said he would give us a tour of his video setup here at SFPC. --- **For lunch:** Salmon Teriyaki at Sushi West with Bryan and Ruby. We talked about Japan, possible projects we are considering, and weekend plans. **For dinner:** ?. It's 2:57p at the time of this writing. Looking forward to tomorrow, which is a Saturday! Moving into a new place with Dannie, Agustin, and Baku this weekend. Bed Stuy is much closer to the city than Ditmas Park! But it is going to be further away from my internship at Eyebeam! Overall a good move! Good day!! ------ **Code from the Open Frameworks workshop:** [ofapp.h](http://pastebin.com/qbXSqCuK), [ofapp.cpp](http://pastebin.com/LMz2rQHb) **[Paper Notes for the Day](https://www.dropbox.com/s/tjhlhoe6938u7a4/IMG_4221.JPG?dl=0)**
c7aadee1678cb8e34e2d7e9b1e57a277d9c1c518
{ "blob_id": "c7aadee1678cb8e34e2d7e9b1e57a277d9c1c518", "branch_name": "refs/heads/master", "committer_date": "2019-01-12T20:40:25", "content_id": "c0c9a0cee7a4863111285515fb065fb34f053175", "detected_licenses": [ "MIT" ], "directory_id": "5f6f710c48031e87f89b6bdf55c870917b5afaee", "extension": "md", "filename": "2016-10-14-Day-Five-at-SFPC.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": 4996, "license": "MIT", "license_type": "permissive", "path": "/_posts/2016-10-14-Day-Five-at-SFPC.md", "provenance": "stack-edu-markdown-0007.json.gz:291258", "repo_name": "alexdwagner/sfpc-blog-2016", "revision_date": "2019-01-12T20:40:25", "revision_id": "9f5c21140f2acbb808a89cb2ca5705f2d8462b99", "snapshot_id": "51e8022be7a0cc118c7ca50207dfbcc0b4906871", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/alexdwagner/sfpc-blog-2016/9f5c21140f2acbb808a89cb2ca5705f2d8462b99/_posts/2016-10-14-Day-Five-at-SFPC.md", "visit_date": "2023-05-01T17:00:55.029453", "added": "2024-11-19T03:11:34.110692+00:00", "created": "2019-01-12T20:40:25", "int_score": 3, "score": 2.953125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0007.json.gz" }
<?php // This file is auto-generated, don't edit it. Thanks. namespace AlibabaCloud\SDK\SDK_DATA_1598238000612\Models; use AlibabaCloud\Tea\Model; class UpgradeOapiProcessTemplateParams extends Model { protected $_name = [ 'processCode' => 'process_code', 'formComponentId' => 'form_component_id', 'detailComponentId' => 'detail_component_id', 'userid' => 'userid', ]; public function validate() { Model::validateRequired('processCode', $this->processCode, true); Model::validateRequired('formComponentId', $this->formComponentId, true); Model::validateRequired('userid', $this->userid, true); } public function toMap() { $res = []; if (null !== $this->processCode) { $res['process_code'] = $this->processCode; } if (null !== $this->formComponentId) { $res['form_component_id'] = $this->formComponentId; } if (null !== $this->detailComponentId) { $res['detail_component_id'] = $this->detailComponentId; } if (null !== $this->userid) { $res['userid'] = $this->userid; } return $res; } /** * @param array $map * @return UpgradeOapiProcessTemplateParams */ public static function fromMap($map = []) { $model = new self(); if(isset($map['process_code'])){ $model->processCode = $map['process_code']; } if(isset($map['form_component_id'])){ $model->formComponentId = $map['form_component_id']; } if(isset($map['detail_component_id'])){ $model->detailComponentId = $map['detail_component_id']; } if(isset($map['userid'])){ $model->userid = $map['userid']; } return $model; } /** * @description 流程code * @var string */ public $processCode; /** * @description 数组或金额类组件id * @var string */ public $formComponentId; /** * @description 明细组件id * @var string */ public $detailComponentId; /** * @description 其实是staffId * @var string */ public $userid; }
3330fce00cd81a9cc95b26e88ef630038121d70f
{ "blob_id": "3330fce00cd81a9cc95b26e88ef630038121d70f", "branch_name": "refs/heads/master", "committer_date": "2020-08-27T06:23:31", "content_id": "31a7b03e68e3d4606ba7bb5dc9f7142ac25b5059", "detected_licenses": [ "Apache-2.0" ], "directory_id": "35270dbaa9b3baf1f005459e0ff9fe11b09844f8", "extension": "php", "filename": "UpgradeOapiProcessTemplateParams.php", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 290694028, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2236, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/Models/UpgradeOapiProcessTemplateParams.php", "provenance": "stack-edu-0048.json.gz:29167", "repo_name": "sdk-team/dingtalk-php-test", "revision_date": "2020-08-27T06:23:31", "revision_id": "d6cb744c6942f8eb11cb0d3fb443dd3b3f87062c", "snapshot_id": "c2ad1c8cc5f3b6872940b6f76845417c20d5723b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/sdk-team/dingtalk-php-test/d6cb744c6942f8eb11cb0d3fb443dd3b3f87062c/src/Models/UpgradeOapiProcessTemplateParams.php", "visit_date": "2022-07-30T05:47:40.401015", "added": "2024-11-18T21:32:08.848291+00:00", "created": "2020-08-27T06:23:31", "int_score": 3, "score": 2.53125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0066.json.gz" }
package fi.aalto.dmg.frame.bolts; import backtype.storm.topology.BasicOutputCollector; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.topology.base.BaseBasicBolt; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Tuple; import fi.aalto.dmg.frame.functions.MapPartitionFunction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created by yangjun.wang on 31/10/15. */ public class MapPartitionBolt<T, R> extends BaseBasicBolt { private static final Logger logger = LoggerFactory.getLogger(MapPartitionBolt.class); private static final long serialVersionUID = -3273118129502437891L; MapPartitionFunction<T, R> fun; public MapPartitionBolt(MapPartitionFunction<T, R> function) { this.fun = function; } @Override public void execute(Tuple input, BasicOutputCollector collector) { } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { declarer.declare(new Fields()); } }
d400bbf78ceb859fda040c5484803d4dff5b9f56
{ "blob_id": "d400bbf78ceb859fda040c5484803d4dff5b9f56", "branch_name": "refs/heads/master", "committer_date": "2017-11-09T12:30:36", "content_id": "f627b9486c17d5a44aad90785e5a84a5d5262051", "detected_licenses": [ "Apache-2.0" ], "directory_id": "81e8f4b7f6845dc360e5930dc1cb1585a35b7a29", "extension": "java", "filename": "MapPartitionBolt.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": 1015, "license": "Apache-2.0", "license_type": "permissive", "path": "/StreamBench/storm/src/main/java/fi/aalto/dmg/frame/bolts/MapPartitionBolt.java", "provenance": "stack-edu-0029.json.gz:24212", "repo_name": "CJECNU/StreamBench", "revision_date": "2017-11-09T12:30:36", "revision_id": "a598a6637f6efc3c4a953d18375d3f34d311aa97", "snapshot_id": "a5a8ac8ad4e25efd46a1bffc69ed8623ba559d23", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/CJECNU/StreamBench/a598a6637f6efc3c4a953d18375d3f34d311aa97/StreamBench/storm/src/main/java/fi/aalto/dmg/frame/bolts/MapPartitionBolt.java", "visit_date": "2020-03-07T20:04:57.355404", "added": "2024-11-18T22:58:33.305758+00:00", "created": "2017-11-09T12:30:36", "int_score": 2, "score": 2.03125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0047.json.gz" }
import DataType from "@ui5/webcomponents-base/dist/types/DataType.js"; /** * @lends sap.ui.webcomponents.main.types.ToastPlacement.prototype * @public */ const ToastPlacements = { /** * <code>ui5-toast</code> is placed at the <code>TopStart</code> position of its container. * @public * @type {TopStart} */ TopStart: "TopStart", /** * <code>ui5-toast</code> is placed at the <code>TopCenter</code> position of its container. * @public * @type {TopCenter} */ TopCenter: "TopCenter", /** * <code>ui5-toast</code> is placed at the <code>TopEnd</code> position of its container. * @public * @type {TopEnd} */ TopEnd: "TopEnd", /** * <code>ui5-toast</code> is placed at the <code>MiddleStart</code> position of its container. * @public * @type {MiddleStart} */ MiddleStart: "MiddleStart", /** * <code>ui5-toast</code> is placed at the <code>MiddleCenter</code> position of its container. * @public * @type {MiddleCenter} */ MiddleCenter: "MiddleCenter", /** * <code>ui5-toast</code> is placed at the <code>MiddleEnd</code> position of its container. * @public * @type {MiddleEnd} */ MiddleEnd: "MiddleEnd", /** * <code>ui5-toast</code> is placed at the <code>BottomStart</code> position of its container. * @public * @type {BottomStart} */ BottomStart: "BottomStart", /** * <code>ui5-toast</code> is placed at the <code>BottomCenter</code> position of its container. * Default placement (no selection) * @public * @type {BottomCenter} */ BottomCenter: "BottomCenter", /** * <code>ui5-toast</code> is placed at the <code>BottomEnd</code> position of its container. * @public * @type {BottomEnd} */ BottomEnd: "BottomEnd", }; /** * @class * Defines where the <code>ui5-toast</code> will be placed. * @constructor * @author SAP SE * @alias sap.ui.webcomponents.main.types.ToastPlacement * @public * @enum {string} */ class ToastPlacement extends DataType { static isValid(value) { return !!ToastPlacements[value]; } } ToastPlacement.generataTypeAcessors(ToastPlacements); export default ToastPlacement;
d30dcf2a66d7f1cefae119ff1c5b619ed51d889c
{ "blob_id": "d30dcf2a66d7f1cefae119ff1c5b619ed51d889c", "branch_name": "refs/heads/master", "committer_date": "2020-03-09T08:04:48", "content_id": "a66cd8b8a36c128fc3678cb74e288d6152e8e029", "detected_licenses": [ "Apache-2.0", "MIT" ], "directory_id": "6fb917d317c353121d526d1d7d4a48a0da9a39a1", "extension": "js", "filename": "ToastPlacement.js", "fork_events_count": 0, "gha_created_at": "2019-02-26T08:02:23", "gha_event_created_at": "2019-02-26T08:02:23", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 172665188, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2116, "license": "Apache-2.0,MIT", "license_type": "permissive", "path": "/packages/main/src/types/ToastPlacement.js", "provenance": "stack-edu-0033.json.gz:641545", "repo_name": "MarcusNotheis/ui5-webcomponents", "revision_date": "2020-03-09T08:04:48", "revision_id": "c9253a6e7eaf768cceed1ff7188ab52b5c70d9eb", "snapshot_id": "cc2fbb15d24d3bd1290997f5bea736aa9a189738", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/MarcusNotheis/ui5-webcomponents/c9253a6e7eaf768cceed1ff7188ab52b5c70d9eb/packages/main/src/types/ToastPlacement.js", "visit_date": "2022-04-22T08:59:15.392011", "added": "2024-11-19T01:11:41.397373+00:00", "created": "2020-03-09T08:04:48", "int_score": 2, "score": 2.015625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0051.json.gz" }
/*Copyright (c) 2017 The Paradox Game Converters Project 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.*/ #ifndef V2FACTORY_H_ #define V2FACTORY_H_ #include <deque> #include <vector> #include <map> #include <memory> using namespace std; class Object; struct V2FactoryType { V2FactoryType(shared_ptr<Object> factory); string name; bool requireCoastal; string requireTech; string requiredInvention; map<string,float> inputs; string outputGoods; }; class V2Factory { public: V2Factory(const V2FactoryType* _type) : type(_type) { level = 1; }; void output(FILE* output) const; void increaseLevel(); bool requiresCoastal() const { return type->requireCoastal; } string getRequiredTech() const { return type->requireTech; } string getRequiredInvention() const { return type->requiredInvention; } string getTypeName() const { return type->name; } map<string,float> getInputs() const { return type->inputs; }; string getOutputGoods() const { return type->outputGoods; }; private: const V2FactoryType* type; int level; }; class V2FactoryFactory { public: V2FactoryFactory(); deque<V2Factory*> buildFactories() const; private: void loadRequiredTechs(string filename); void loadRequiredInventions(string filename); vector<pair<V2FactoryType*, int>> factoryCounts; map<string, V2FactoryType*> factoryTypes; map<string, string> factoryTechReqs; map<string, string> factoryInventionReqs; }; #endif // V2FACTORY_H_
f80f355ef5a20690adb7d20751cb89e8631be939
{ "blob_id": "f80f355ef5a20690adb7d20751cb89e8631be939", "branch_name": "refs/heads/master", "committer_date": "2020-03-28T21:18:56", "content_id": "bc34fe4df7e05977a11b1c19cec88ecf8abfe433", "detected_licenses": [ "MIT" ], "directory_id": "7276439b533f4874955c872f478627a243631728", "extension": "h", "filename": "V2Factory.h", "fork_events_count": 38, "gha_created_at": "2015-06-05T19:10:11", "gha_event_created_at": "2018-12-23T17:15:26", "gha_language": "C++", "gha_license_id": "MIT", "github_id": 36950594, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2554, "license": "MIT", "license_type": "permissive", "path": "/EU4toV2/Source/V2World/V2Factory.h", "provenance": "stack-edu-0002.json.gz:517764", "repo_name": "ParadoxGameConverters/paradoxGameConverters", "revision_date": "2020-03-28T21:18:56", "revision_id": "a994edeb4618c2e60bc1b1e26327fe504f94aa06", "snapshot_id": "406ff200abad3d43e7f4ad57a88311b2074ccacc", "src_encoding": "UTF-8", "star_events_count": 71, "url": "https://raw.githubusercontent.com/ParadoxGameConverters/paradoxGameConverters/a994edeb4618c2e60bc1b1e26327fe504f94aa06/EU4toV2/Source/V2World/V2Factory.h", "visit_date": "2021-06-03T15:31:51.717844", "added": "2024-11-18T21:29:51.327704+00:00", "created": "2020-03-28T21:18:56", "int_score": 2, "score": 2.09375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0020.json.gz" }
<?php namespace Checkout\Issuing\Cards\Enrollment; class SecurityQuestionThreeDSEnrollmentRequest extends ThreeDSEnrollmentRequest { /** * @var SecurityPair */ public $security_pair; }
5e391319850f13605c8c8f68ea8fa229324ef04a
{ "blob_id": "5e391319850f13605c8c8f68ea8fa229324ef04a", "branch_name": "refs/heads/master", "committer_date": "2023-08-24T15:50:06", "content_id": "98b6263858e2df289058219e39cb8f22705a385b", "detected_licenses": [ "MIT" ], "directory_id": "dd893e1354e63730b70cb41645126557eeaccdf7", "extension": "php", "filename": "SecurityQuestionThreeDSEnrollmentRequest.php", "fork_events_count": 40, "gha_created_at": "2019-01-31T11:52:24", "gha_event_created_at": "2023-09-07T11:00:16", "gha_language": "PHP", "gha_license_id": "MIT", "github_id": 168517219, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 205, "license": "MIT", "license_type": "permissive", "path": "/lib/Checkout/Issuing/Cards/Enrollment/SecurityQuestionThreeDSEnrollmentRequest.php", "provenance": "stack-edu-0053.json.gz:628902", "repo_name": "checkout/checkout-sdk-php", "revision_date": "2023-08-22T08:13:08", "revision_id": "ebd50b50525d8c9ea8b54f8568752172337d14e0", "snapshot_id": "02cbdb2628ac9bac42d521fbbde2fc156e4684ef", "src_encoding": "UTF-8", "star_events_count": 38, "url": "https://raw.githubusercontent.com/checkout/checkout-sdk-php/ebd50b50525d8c9ea8b54f8568752172337d14e0/lib/Checkout/Issuing/Cards/Enrollment/SecurityQuestionThreeDSEnrollmentRequest.php", "visit_date": "2023-09-01T10:46:10.995561", "added": "2024-11-19T03:21:51.930906+00:00", "created": "2023-08-22T08:13:08", "int_score": 2, "score": 2.015625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0071.json.gz" }
import { inspect } from '../../jsutils/inspect.js'; import { GraphQLError } from '../../error/GraphQLError.js'; import type { InputValueDefinitionNode } from '../../language/ast.js'; import { Kind } from '../../language/kinds.js'; import { print } from '../../language/printer.js'; import type { ASTVisitor } from '../../language/visitor.js'; import type { GraphQLArgument } from '../../type/definition.js'; import { isRequiredArgument, isType } from '../../type/definition.js'; import { specifiedDirectives } from '../../type/directives.js'; import type { SDLValidationContext, ValidationContext, } from '../ValidationContext.js'; /** * Provided required arguments * * A field or directive is only valid if all required (non-null without a * default value) field arguments have been provided. */ export function ProvidedRequiredArgumentsRule( context: ValidationContext, ): ASTVisitor { return { // eslint-disable-next-line new-cap ...ProvidedRequiredArgumentsOnDirectivesRule(context), Field: { // Validate on leave to allow for deeper errors to appear first. leave(fieldNode) { const fieldDef = context.getFieldDef(); if (!fieldDef) { return false; } const providedArgs = new Set( // FIXME: https://github.com/graphql/graphql-js/issues/2203 /* c8 ignore next */ fieldNode.arguments?.map((arg) => arg.name.value), ); for (const argDef of fieldDef.args) { if (!providedArgs.has(argDef.name) && isRequiredArgument(argDef)) { const argTypeStr = inspect(argDef.type); context.reportError( new GraphQLError( `Field "${fieldDef.name}" argument "${argDef.name}" of type "${argTypeStr}" is required, but it was not provided.`, { nodes: fieldNode }, ), ); } } }, }, }; } /** * @internal */ export function ProvidedRequiredArgumentsOnDirectivesRule( context: ValidationContext | SDLValidationContext, ): ASTVisitor { const requiredArgsMap = new Map< string, Map<string, GraphQLArgument | InputValueDefinitionNode> >(); const schema = context.getSchema(); const definedDirectives = schema?.getDirectives() ?? specifiedDirectives; for (const directive of definedDirectives) { requiredArgsMap.set( directive.name, new Map( directive.args.filter(isRequiredArgument).map((arg) => [arg.name, arg]), ), ); } const astDefinitions = context.getDocument().definitions; for (const def of astDefinitions) { if (def.kind === Kind.DIRECTIVE_DEFINITION) { // FIXME: https://github.com/graphql/graphql-js/issues/2203 /* c8 ignore next */ const argNodes = def.arguments ?? []; requiredArgsMap.set( def.name.value, new Map( argNodes .filter(isRequiredArgumentNode) .map((arg) => [arg.name.value, arg]), ), ); } } return { Directive: { // Validate on leave to allow for deeper errors to appear first. leave(directiveNode) { const directiveName = directiveNode.name.value; const requiredArgs = requiredArgsMap.get(directiveName); if (requiredArgs != null) { // FIXME: https://github.com/graphql/graphql-js/issues/2203 /* c8 ignore next */ const argNodes = directiveNode.arguments ?? []; const argNodeMap = new Set(argNodes.map((arg) => arg.name.value)); for (const [argName, argDef] of requiredArgs.entries()) { if (!argNodeMap.has(argName)) { const argType = isType(argDef.type) ? inspect(argDef.type) : print(argDef.type); context.reportError( new GraphQLError( `Directive "@${directiveName}" argument "${argName}" of type "${argType}" is required, but it was not provided.`, { nodes: directiveNode }, ), ); } } } }, }, }; } function isRequiredArgumentNode(arg: InputValueDefinitionNode): boolean { return arg.type.kind === Kind.NON_NULL_TYPE && arg.defaultValue == null; }
32dd3dadb114ca047f417808c61c5d5fc3e6b2dd
{ "blob_id": "32dd3dadb114ca047f417808c61c5d5fc3e6b2dd", "branch_name": "refs/heads/main", "committer_date": "2023-08-25T15:12:25", "content_id": "72d104b852f9ffe48d782d8c319f9ec1fbfce72b", "detected_licenses": [ "MIT" ], "directory_id": "124a9f679b33d466db29e4b93c13488462d9db7a", "extension": "ts", "filename": "ProvidedRequiredArgumentsRule.ts", "fork_events_count": 2601, "gha_created_at": "2015-06-30T12:16:50", "gha_event_created_at": "2023-09-11T07:52:41", "gha_language": "TypeScript", "gha_license_id": "MIT", "github_id": 38307428, "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4271, "license": "MIT", "license_type": "permissive", "path": "/src/validation/rules/ProvidedRequiredArgumentsRule.ts", "provenance": "stack-edu-0075.json.gz:972378", "repo_name": "graphql/graphql-js", "revision_date": "2023-08-25T15:12:25", "revision_id": "fe65bc8be6813d03870ba0d7faffa733c1ba7351", "snapshot_id": "7d974443e0189b8b4a19d2621f691b68045d59dc", "src_encoding": "UTF-8", "star_events_count": 21404, "url": "https://raw.githubusercontent.com/graphql/graphql-js/fe65bc8be6813d03870ba0d7faffa733c1ba7351/src/validation/rules/ProvidedRequiredArgumentsRule.ts", "visit_date": "2023-08-28T09:37:55.272907", "added": "2024-11-18T23:04:54.120870+00:00", "created": "2023-08-25T15:12:25", "int_score": 3, "score": 2.703125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0093.json.gz" }
import logging from pathlib import Path from dataclasses import dataclass import pygame as pg import chess.settings as s from chess.utils.coords import Coords from chess.utils.typewriter import TypewriterConfig, Typewriter from chess.panels.panel import Panel logger = logging.getLogger(Path(__file__).stem) @dataclass(eq=False) class Wood(Panel): def __post_init__(self): super().__post_init__() self.draw_margin() self.draw_legend() def draw_legend(self): letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] config = TypewriterConfig( size=22, color=s.WHITE, padding=10, surface_color=s.DARKGREY ) tp = Typewriter( surface=self.image, config=config ) for i, l in enumerate(letters, start=1): num_w, num_h = tp.get_text_size(str(i)) l_w, l_h = tp.get_text_size(l) tp.type( text=str(i), coords=Coords( x=s.TILESIZE // 2 - num_w // 2, y=s.TILESIZE * 2 * i - num_h // 2 ) ) tp.type( text=l, coords=Coords( x=i * s.TILESIZE * 2 - l_w // 2, y=self.image.get_height() - s.TILESIZE + l_h // 4 ) ) def draw_margin(self): m_px = 4 margin = pg.Rect( s.TILESIZE - m_px, s.TILESIZE - m_px, 2 * (s.TILESIZE * 8 + m_px), 2 * (s.TILESIZE * 8 + m_px) ) pg.draw.rect(self.image, s.GREEN, margin)
79c128dd562fc53c84d4b70a7b9bf0f23e0e3a56
{ "blob_id": "79c128dd562fc53c84d4b70a7b9bf0f23e0e3a56", "branch_name": "refs/heads/master", "committer_date": "2019-11-21T18:36:07", "content_id": "a540ed8784328c21fa65d7d2e97f1d9bfd2ef1fd", "detected_licenses": [ "MIT" ], "directory_id": "c306cc350cf1ae216dee882f0244f70aac50a9ac", "extension": "py", "filename": "wood.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 214688595, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1648, "license": "MIT", "license_type": "permissive", "path": "/chess/panels/game/wood.py", "provenance": "stack-edu-0058.json.gz:96243", "repo_name": "cuiqui/chrisis", "revision_date": "2019-11-21T18:36:07", "revision_id": "d824bde0bc4a3b9def86550f5bae0db6398f971e", "snapshot_id": "55e20d369dab796cb8b7872a2565dfba7bab1007", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/cuiqui/chrisis/d824bde0bc4a3b9def86550f5bae0db6398f971e/chess/panels/game/wood.py", "visit_date": "2020-08-12T04:25:12.178964", "added": "2024-11-19T01:02:37.597805+00:00", "created": "2019-11-21T18:36:07", "int_score": 3, "score": 2.78125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0076.json.gz" }
# About this assignment We had to make choose and implement a game from a given list The game I chose: Connect4. The game is described [here](https://en.wikipedia.org/wiki/Connect_Four) ## Config You can configure the project settings from the `settings.properties` file You can modify: * `ui` = oneOf(`console`, `gui`) * `difficulty` = integer, how many moves ahead should the AI go(max - 2, it can go further but the algorithm needs a lot of refactoring) * `width` = integer, the width of the board * `height` = integer, the height of the boad ### Requirements (the exact problem statement) * You will be given one of the problems below to solve. * Use object oriented programming and layered architecture * All modules with the exception of the UI will be covered with specification and PyUnit test cases. * The program must protect itself against the user’s invalid input. ### BONUS POSSIBILITY (0.2P) * In addition to the console-based user interface required, also implement a graphical user interface (GUI) for the program. * To receive the bonus, both user interfaces (menu-based and graphical) must use the same program layers. You have to be able to start the application with either user interface. We do not expect you to implement optimal play on the part of the computer player. However, it should still employ a strategy when making its moves in order to attempt to win the game and provide an entertaining opponent for the human player. Minimally, the computer player should make its moves close to the area where stones have been placed, it should move to win the game whenever possible and should block the human player’s attempts at 1-move victory, whenever possible
541eaa071669750d4044bdc5f8c4e2a1d30dcff9
{ "blob_id": "541eaa071669750d4044bdc5f8c4e2a1d30dcff9", "branch_name": "refs/heads/master", "committer_date": "2018-02-19T00:09:58", "content_id": "fc8f4a0fe34f344adf24967573d326068d352e3f", "detected_licenses": [ "MIT" ], "directory_id": "7fc6531cc84baa03ad94555a4afaa01d760c16a6", "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": 122001522, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1726, "license": "MIT", "license_type": "permissive", "path": "/connect4/README.md", "provenance": "stack-edu-markdown-0013.json.gz:184122", "repo_name": "alexnaiman/Fundamentals-Of-Programming---Lab-assignments", "revision_date": "2018-02-19T00:09:58", "revision_id": "ef066e6036e20b9c686799f507f10e15e50e3285", "snapshot_id": "d53732aea8ea97b48aae235d0e6facbae5623c93", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/alexnaiman/Fundamentals-Of-Programming---Lab-assignments/ef066e6036e20b9c686799f507f10e15e50e3285/connect4/README.md", "visit_date": "2021-04-28T15:56:04.657101", "added": "2024-11-18T23:10:56.686054+00:00", "created": "2018-02-19T00:09:58", "int_score": 3, "score": 3.203125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0013.json.gz" }
# Created to Taq Karim # https://dev.to/taqkarim/extending-simplenamespace-for-nested-dictionaries-58e8 from types import SimpleNamespace class RecursiveNamespace(SimpleNamespace): @staticmethod def map_entry(entry): if isinstance(entry, dict): return RecursiveNamespace(**entry) return entry def get(self, key: str, default=None): return getattr(self, key, default) def __init__(self, **kwargs): super().__init__(**kwargs) for key, val in kwargs.items(): if type(val) == dict: setattr(self, key, RecursiveNamespace(**val)) elif type(val) == list: setattr(self, key, list(map(self.map_entry, val))) def __contains__(self, attr): return hasattr(self, attr)
301b43b8e8bbffe6015c00338ccb401d4c38c6d1
{ "blob_id": "301b43b8e8bbffe6015c00338ccb401d4c38c6d1", "branch_name": "refs/heads/main", "committer_date": "2021-03-18T11:36:32", "content_id": "bd607befbfb6fd828384a58a5b42585cb96969f8", "detected_licenses": [ "MIT" ], "directory_id": "6c99321d9f8a1c286fee9139ae079cb6dd56513c", "extension": "py", "filename": "recursive_namespace.py", "fork_events_count": 0, "gha_created_at": "2020-12-21T12:41:28", "gha_event_created_at": "2021-03-18T11:36:35", "gha_language": "C++", "gha_license_id": "MIT", "github_id": 323333045, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 798, "license": "MIT", "license_type": "permissive", "path": "/python/tests/utils/recursive_namespace.py", "provenance": "stack-edu-0058.json.gz:119334", "repo_name": "etkeys/cs417-in-python", "revision_date": "2021-03-17T01:49:25", "revision_id": "1d6d11ac2ed2bc738f388571238677077581af86", "snapshot_id": "0a3651d077cedc3779cce07f83705738d2dbb43b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/etkeys/cs417-in-python/1d6d11ac2ed2bc738f388571238677077581af86/python/tests/utils/recursive_namespace.py", "visit_date": "2023-03-20T17:20:46.220137", "added": "2024-11-18T19:38:17.585456+00:00", "created": "2021-03-17T01:49:25", "int_score": 3, "score": 3.171875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0076.json.gz" }
#Bioshock Physics Unlocker Simple patcher which lets you adjust Bioshock's physics timestep. [Video comparison](https://www.youtube.com/watch?v=PKNRgX93TCc) This has been tested with the Steam release of the game, and should also work for the version 1.0 & 1.1 retail releases. I have heard that it does not work with the Direct2Drive release of the game, presumably due to some form of DRM. ##Usage 1. Download the [latest release](https://github.com/TurtleHx/Bioshock-Physics-Unlocker/releases/latest). 2. Extract the `BioshockPhysicsUnlocker.exe` file into your Bioshock directory, typically: `C:\Program Files (x86)\Steam\steamapps\common\bioshock\Builds\Release`. 3. Run the executable and enter your desired physics framerate. ##License MIT
be0e941962d3360e9d0abddb58a3aebffff0b28d
{ "blob_id": "be0e941962d3360e9d0abddb58a3aebffff0b28d", "branch_name": "refs/heads/master", "committer_date": "2016-01-16T22:31:30", "content_id": "975b5bd8bebc15c4db66e436043c951e2ad48a60", "detected_licenses": [ "MIT" ], "directory_id": "6e08606933f04142e6e9853ec1554c276d4e5dd3", "extension": "md", "filename": "README.md", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 47251681, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 751, "license": "MIT", "license_type": "permissive", "path": "/README.md", "provenance": "stack-edu-markdown-0015.json.gz:216203", "repo_name": "TurtleHx/Bioshock-Physics-Unlocker", "revision_date": "2016-01-16T22:30:16", "revision_id": "974a4d2f9d34e2fea079ccaf13110fe569f3e1b7", "snapshot_id": "6e43a0ee482956551604c75dc3e529c48030d320", "src_encoding": "UTF-8", "star_events_count": 64, "url": "https://raw.githubusercontent.com/TurtleHx/Bioshock-Physics-Unlocker/974a4d2f9d34e2fea079ccaf13110fe569f3e1b7/README.md", "visit_date": "2021-01-10T15:21:20.895646", "added": "2024-11-18T23:14:44.564624+00:00", "created": "2016-01-16T22:30:16", "int_score": 3, "score": 3.125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0015.json.gz" }
package com.sflpro.notifier.services.device; import com.sflpro.notifier.db.entities.device.UserDevice; import com.sflpro.notifier.services.device.dto.UserDeviceDto; import javax.annotation.Nonnull; /** * User: Ruben Dilanyan * Company: SFL LLC * Date: 12/24/15 * Time: 6:44 PM */ public interface UserDeviceService { /** * Gets user device for id * * @param userDeviceId * @return userDevice */ @Nonnull UserDevice getUserDeviceById(@Nonnull final Long userDeviceId); /** * Creates user device * * @param userId * @param userDeviceDto * @return userDevice */ @Nonnull UserDevice createUserDevice(@Nonnull final Long userId, @Nonnull final UserDeviceDto userDeviceDto); /** * Get user device for user id and uuid * * @param userId * @param uuId * @return userDevice */ @Nonnull UserDevice getUserDeviceByUuId(@Nonnull final Long userId, @Nonnull final String uuId); /** * Checks if user device exists for user id and uuid * * @param userId * @param uuId * @return */ @Nonnull boolean checkIfUserDeviceExistsForUuId(@Nonnull final Long userId, @Nonnull final String uuId); /** * Gets or creates user device for provided DTO * * @param userId * @param userDeviceDto * @return userDevice */ @Nonnull UserDevice getOrCreateUserDevice(@Nonnull final Long userId, @Nonnull final UserDeviceDto userDeviceDto); }
45bf4fc17599297e42567fa3406abea26872ac22
{ "blob_id": "45bf4fc17599297e42567fa3406abea26872ac22", "branch_name": "refs/heads/master", "committer_date": "2019-11-01T10:32:48", "content_id": "6e1090344b29546953864472ee568d7faf649172", "detected_licenses": [ "Apache-2.0" ], "directory_id": "ed7c857d45a8cdef182af5a5e85fff5226609cfe", "extension": "java", "filename": "UserDeviceService.java", "fork_events_count": 0, "gha_created_at": "2020-01-20T13:31:55", "gha_event_created_at": "2020-01-20T13:31:56", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 235108405, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1524, "license": "Apache-2.0", "license_type": "permissive", "path": "/core/core-services/src/main/java/com/sflpro/notifier/services/device/UserDeviceService.java", "provenance": "stack-edu-0028.json.gz:376654", "repo_name": "Biacode/notifier", "revision_date": "2019-11-01T10:32:48", "revision_id": "388e5ce88e042fda125ff30ec9211b41837808cb", "snapshot_id": "f705263eae7307e8a6f4e49582eba8456d72e0c3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Biacode/notifier/388e5ce88e042fda125ff30ec9211b41837808cb/core/core-services/src/main/java/com/sflpro/notifier/services/device/UserDeviceService.java", "visit_date": "2020-12-15T12:52:00.476561", "added": "2024-11-18T23:12:43.460611+00:00", "created": "2019-11-01T10:32:48", "int_score": 2, "score": 2.234375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0046.json.gz" }
from openflix import app from flask import abort, Response, request import requests from http import HTTPStatus as status import logging class YGGTracker: def __init__(self, **options): self.load_config(options) self.ygg_tracker_url = None self.session = requests.Session() app.add_url_rule(self.config["path"], view_func=self.announce, subdomain=self.config["subdomain"]) def get_url(self): domain = self.config['subdomain'] + "." + app.config["SERVER_NAME"] return domain + self.config['path'] def exchange_url(self, url): self.ygg_tracker_url = url return self.get_url() def load_config(self, options): options.setdefault("hide_complete", True) options.setdefault("timeout", 5) options.setdefault("path", "/announce") options.setdefault("subdomain", "p2p") self.config = options def get_ygg_tracker(self): if self.ygg_tracker_url is None: from . import ygg self.ygg_tracker_url = ygg.exchange_url(self.get_url()) def hide_download(self, query_string): params = query_string.split("&") for i, param in enumerate(params): key, _, _ = param.partition("=") if key == "downloaded": params[i] = "downloaded=0" break return "&".join(params) def announce(self): response = abort(status.INTERNAL_SERVER_ERROR) self.get_ygg_tracker() if self.ygg_tracker_url is None: return response headers = dict(request.headers) args = str(request.query_string) headers.pop("Host", None) if self.config["hide_complete"]: args = self.hide_download(args) for _ in range(self.config["max_retry"]): try: resp = self.session.get( url=f"{self.ygg_tracker_url}?{args}", headers=headers, cookies=request.cookies, timeout=self.config["timeout"] ) except requests.Timeout: continue except Exception as e: logging.error(e) else: response = (resp.content, resp.status_code, resp.raw.headers) break else: logging.error("maximum announce try exceeded") return response
02d45f9d5d7a593541cbc7b0e028cb040e69139a
{ "blob_id": "02d45f9d5d7a593541cbc7b0e028cb040e69139a", "branch_name": "refs/heads/master", "committer_date": "2020-05-23T08:55:23", "content_id": "9963be9c5dd8faf21978c9584a168d1f0b4e6118", "detected_licenses": [ "MIT" ], "directory_id": "1d8c6bf3893964773b1cefac14103c17e458adaf", "extension": "py", "filename": "tracker.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": 2558, "license": "MIT", "license_type": "permissive", "path": "/openflix/providers/ygg/tracker.py", "provenance": "stack-edu-0056.json.gz:320413", "repo_name": "matthieu-jqm/OpenFlix", "revision_date": "2020-05-23T08:55:23", "revision_id": "cf2cadca1a919091c327afffed26c3280449def5", "snapshot_id": "a594c985ada079a80c85d13363c587403b21d15d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/matthieu-jqm/OpenFlix/cf2cadca1a919091c327afffed26c3280449def5/openflix/providers/ygg/tracker.py", "visit_date": "2022-07-28T02:03:56.327469", "added": "2024-11-18T21:55:55.722637+00:00", "created": "2020-05-23T08:55:23", "int_score": 2, "score": 2.328125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0074.json.gz" }
<?php namespace Pidev\FrontBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Contacter * * @ORM\Table(name="contacter") * @ORM\Entity */ class Contacter { /** * @var integer * * @ORM\Column(name="id_parent", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="NONE") */ private $idParent; /** * @var \Babysitter * * @ORM\Id * @ORM\GeneratedValue(strategy="NONE") * @ORM\OneToOne(targetEntity="Babysitter") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="id_babysitter", referencedColumnName="id_babysitter") * }) */ private $idBabysitter; }
ab34b86a538b9e2f4a12dbfe871c4ee5a582767d
{ "blob_id": "ab34b86a538b9e2f4a12dbfe871c4ee5a582767d", "branch_name": "refs/heads/master", "committer_date": "2016-09-16T10:36:19", "content_id": "9dd05e7c3b5e5034c6195e827b83f580bc9db332", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "directory_id": "958680d3b2fa0ce046075282684167ec68be9b9f", "extension": "php", "filename": "Contacter.php", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 68371163, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 668, "license": "MIT,BSD-3-Clause", "license_type": "permissive", "path": "/src/Pidev/FrontBundle/Entity/Contacter.php", "provenance": "stack-edu-0052.json.gz:224077", "repo_name": "TZ92/baby-sittingFinal", "revision_date": "2016-09-16T10:36:19", "revision_id": "cbbafb407a5a26717390d7e9189e1623ec490368", "snapshot_id": "6dae567eca34f219cf89bddfa05b98d259c8c805", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/TZ92/baby-sittingFinal/cbbafb407a5a26717390d7e9189e1623ec490368/src/Pidev/FrontBundle/Entity/Contacter.php", "visit_date": "2021-01-17T19:09:14.998142", "added": "2024-11-18T22:39:03.197037+00:00", "created": "2016-09-16T10:36:19", "int_score": 2, "score": 2.25, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0070.json.gz" }
using System.Collections.Generic; using System.Text; namespace XUnity.AutoTranslator.Plugin.Core.Batching { public class TranslationBatch { public TranslationBatch() { Trackers = new List<TranslationLineTracker>(); } public List<TranslationLineTracker> Trackers { get; private set; } public bool IsEmpty => Trackers.Count == 0; public int TotalLinesCount { get; set; } public void Add( TranslationJob job ) { var lines = new TranslationLineTracker( job ); Trackers.Add( lines ); TotalLinesCount += lines.LinesCount; } public bool MatchWithTranslations( string allTranslations ) { var lines = allTranslations.Split( '\n' ); if( lines.Length != TotalLinesCount ) return false; int current = 0; foreach( var tracker in Trackers ) { var builder = new StringBuilder( 32 ); for( int i = 0 ; i < tracker.LinesCount ; i++ ) { var translation = lines[ current++ ]; builder.Append( translation ); // ADD NEW LINE IF NEEDED if( !( i == tracker.LinesCount - 1 ) ) // if not last line { builder.Append( '\n' ); } } var fullTranslation = builder.ToString(); tracker.RawTranslatedText = fullTranslation; } return true; } public string GetFullTranslationKey() { var builder = new StringBuilder(); for( int i = 0 ; i < Trackers.Count ; i++ ) { var tracker = Trackers[ i ]; builder.Append( tracker.Job.Key.GetDictionaryLookupKey() ); if( !( i == Trackers.Count - 1 ) ) { builder.Append( '\n' ); } } return builder.ToString(); } } }
a92a7c378c383f458970e6128cfd8e47f1b25462
{ "blob_id": "a92a7c378c383f458970e6128cfd8e47f1b25462", "branch_name": "refs/heads/master", "committer_date": "2019-01-11T21:16:38", "content_id": "1e3487a33b456003f9d8e9c7caa86413cf4b23f4", "detected_licenses": [ "MIT" ], "directory_id": "4289d2a1ebfedb1ba00963bec2756d4e8ac00274", "extension": "cs", "filename": "TranslationBatch.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": 1928, "license": "MIT", "license_type": "permissive", "path": "/src/XUnity.AutoTranslator.Plugin.Core/Batching/TranslationBatch.cs", "provenance": "stack-edu-0009.json.gz:474615", "repo_name": "emmauss/XUnity.AutoTranslator", "revision_date": "2019-01-11T21:16:38", "revision_id": "571c8cfe6ba3f187a6764c8b8346ac24c41e920e", "snapshot_id": "78ddc1d2b7b7fc79eab73e4b032f7714103f0415", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/emmauss/XUnity.AutoTranslator/571c8cfe6ba3f187a6764c8b8346ac24c41e920e/src/XUnity.AutoTranslator.Plugin.Core/Batching/TranslationBatch.cs", "visit_date": "2020-04-17T18:49:07.194449", "added": "2024-11-19T01:37:13.284541+00:00", "created": "2019-01-11T21:16:38", "int_score": 3, "score": 2.609375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0027.json.gz" }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreatePersonasTable extends Migration { public function up() { Schema::create('personas', function (Blueprint $table) { $table->bigIncrements('id'); $table->enum('tipo_persona', ['Juridico', 'Natural']); $table->timestamps(); }); } public function down() { Schema::dropIfExists('personas'); } }
07fb03ae20928ff85f9b1819eadde7196b39d99d
{ "blob_id": "07fb03ae20928ff85f9b1819eadde7196b39d99d", "branch_name": "refs/heads/master", "committer_date": "2020-02-26T15:29:40", "content_id": "4fa6b8e68f13d1621893488f1c3e6bf22a4ef157", "detected_licenses": [ "MIT" ], "directory_id": "da2628c87e1004dae06652c6cc0a1a3e94debb93", "extension": "php", "filename": "2020_01_26_161011_create_personas_table.php", "fork_events_count": 0, "gha_created_at": "2020-01-25T01:33:21", "gha_event_created_at": "2023-02-02T11:00:15", "gha_language": "PHP", "gha_license_id": null, "github_id": 236111824, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 524, "license": "MIT", "license_type": "permissive", "path": "/database/migrations/2020_01_26_161011_create_personas_table.php", "provenance": "stack-edu-0053.json.gz:818295", "repo_name": "projectsparquesoft/fomix", "revision_date": "2020-02-26T15:29:40", "revision_id": "d2376c85df493c3bc9e9058ba32c6231b7884162", "snapshot_id": "f95926d34c8848b52dd2e3a395edbb82b32a8e55", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/projectsparquesoft/fomix/d2376c85df493c3bc9e9058ba32c6231b7884162/database/migrations/2020_01_26_161011_create_personas_table.php", "visit_date": "2023-02-05T08:14:40.839704", "added": "2024-11-19T03:21:26.030385+00:00", "created": "2020-02-26T15:29:40", "int_score": 2, "score": 2.5, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0071.json.gz" }
# tree printing +-- YAML [4 lines] +-- Heading [h1] - Setup | \-- Chunk [r, 1 opt, 1 lines] - setup \-- Heading [h1] - Content +-- Heading [h2] - R Markdown | +-- Markdown [6 lines] | +-- Chunk [r, 1 lines] - cars | \-- Chunk [r, 1 lines] - unnamed-chunk-1 \-- Heading [h2] - Including Plots +-- Markdown [2 lines] +-- Chunk [r, 1 opt, 1 lines] - pressure \-- Markdown [2 lines] --- +-- YAML [2 lines] +-- Heading [h3] - Load packages | \-- Chunk [r, 1 opt, 2 lines] - load-packages +-- Heading [h3] - Exercise 1 | +-- Markdown [2 lines] | \-- Heading [h4] - Solution | \-- Markdown [5 lines] +-- Heading [h3] - Exercise 2 | +-- Markdown [2 lines] | \-- Heading [h4] - Solution | +-- Markdown [2 lines] | +-- Chunk [r, 2 opts, 5 lines] - plot-dino | +-- Markdown [2 lines] | \-- Chunk [r, 2 lines] - cor-dino \-- Heading [h3] - Exercise 3 +-- Markdown [2 lines] \-- Heading [h4] - Solution +-- Chunk [r, 2 opts, 5 lines] - plot-star \-- Chunk [r, 2 lines] - cor-star --- +-- YAML [2 lines] +-- Heading [h3] - Load packages | \-- Chunk [r, 1 opt, 2 lines] - load-packages +-- Heading [h3] - Exercise 1 | +-- Markdown [2 lines] | \-- Heading [h4] - Solution | \-- Markdown [2 lines] +-- Heading [h3] - Exercise 2 | +-- Markdown [2 lines] | \-- Heading [h4] - Solution | +-- Markdown [4 lines] | +-- Chunk [r, 2 opts, 5 lines] - plot-dino | +-- Markdown [2 lines] | \-- Chunk [r, 2 lines] - cor-dino \-- Heading [h3] - Exercise 3 +-- Markdown [2 lines] \-- Heading [h4] - Solution +-- Markdown [4 lines] +-- Chunk [r, 1 lines] - plot-star +-- Markdown [2 lines] \-- Chunk [r, 1 lines] - cor-star --- +-- YAML [2 lines] +-- Heading [h3] - H3 +-- Heading [h2] - H2 | \-- Heading [h3] - H3 - Part 2 \-- Heading [h1] - H1 --- +-- YAML [1 lines] +-- Heading [h2] - R Markdown | +-- Markdown [4 lines] | \-- Chunk [r, 1 lines] - cars \-- Heading [h2] - Pandoc Raw Attribute Chunk +-- Markdown [2 lines] \-- Raw Attr Chunk [html, 5 lines]
c76300888185635a35adceca671bc02f58fa0acd
{ "blob_id": "c76300888185635a35adceca671bc02f58fa0acd", "branch_name": "refs/heads/master", "committer_date": "2021-08-16T17:45:54", "content_id": "cb41ff0c7498b39d0cdb06458be1ac0e6c5dd207", "detected_licenses": [ "MIT" ], "directory_id": "a217b8339f1e3ca17df8e2a4756882bba1817665", "extension": "md", "filename": "print_tree.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": 2405, "license": "MIT", "license_type": "permissive", "path": "/tests/testthat/_snaps/print_tree.md", "provenance": "stack-edu-markdown-0008.json.gz:137235", "repo_name": "rossellhayes/parsermd", "revision_date": "2021-08-16T17:45:54", "revision_id": "d54a911a2c30e344e3cd633f98009ba4d4c32442", "snapshot_id": "49a38639c13f74ced2ce9c1e4cceb88868637dba", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/rossellhayes/parsermd/d54a911a2c30e344e3cd633f98009ba4d4c32442/tests/testthat/_snaps/print_tree.md", "visit_date": "2023-07-28T13:05:14.632533", "added": "2024-11-19T00:40:04.980926+00:00", "created": "2021-08-16T17:45:54", "int_score": 2, "score": 2.265625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0008.json.gz" }
<?php //--- Day 2: Inventory Management System --- // //You stop falling through time, catch your breath, and check the screen on the device. "Destination reached. Current Year: 1518. Current Location: North Pole Utility Closet 83N10." You made it! Now, to find those anomalies. // //Outside the utility closet, you hear footsteps and a voice. "...I'm not sure either. But now that so many people have chimneys, maybe he could sneak in that way?" Another voice responds, "Actually, we've been working on a new kind of suit that would let him fit through tight spaces like that. But, I heard that a few days ago, they lost the prototype fabric, the design plans, everything! Nobody on the team can even seem to remember important details of the project!" // //"Wouldn't they have had enough fabric to fill several boxes in the warehouse? They'd be stored together, so the box IDs should be similar. Too bad it would take forever to search the warehouse for two similar box IDs..." They walk too far away to hear any more. // //Late at night, you sneak to the warehouse - who knows what kinds of paradoxes you could cause if you were discovered - and use your fancy wrist device to quickly scan every box and produce a list of the likely candidates (your puzzle input). // //To make sure you didn't miss any, you scan the likely candidate boxes again, counting the number that have an ID containing exactly two of any letter and then separately counting those with exactly three of any letter. You can multiply those two counts together to get a rudimentary checksum and compare it to what your device predicts. // //For example, if you see the following box IDs: // // abcdef contains no letters that appear exactly two or three times. // bababc contains two a and three b, so it counts for both. // abbcde contains two b, but no letter appears exactly three times. // abcccd contains three c, but no letter appears exactly two times. // aabcdd contains two a and two d, but it only counts once. // abcdee contains two e. // ababab contains three a and three b, but it only counts once. // //Of these box IDs, four of them contain a letter which appears exactly twice, and three of them contain a letter which appears exactly three times. Multiplying these together produces a checksum of 4 * 3 = 12. // //What is the checksum for your list of box IDs? $myFile= "input"; $data=file($myFile); function getCheckSum($data) { $twice = 0; $thrice = 0; forEach($data as $box){ $stringLength=strlen($box); $twiceInString=0; $thriceInString=0; while($stringLength>0){ $box=str_replace($box[0], '', $box); $newLength=strlen($box); if($stringLength-$newLength===2){ $twiceInString=1; } elseif($stringLength-$newLength===3){ $thriceInString=1; } $stringLength=$newLength; } $twice=$twice+$twiceInString; $thrice=$thrice+$thriceInString; } return($thrice*$twice); } echo ('D2P1 The checksum is: '.getCheckSum($data)."\n"); //--- Part Two --- // //Confident that your list of box IDs is complete, you're ready to find the boxes full of prototype fabric. // //The boxes will have IDs which differ by exactly one character at the same position in both strings. For example, given the following box IDs: // //abcde //fghij //klmno //pqrst //fguij //axcye //wvxyz // //The IDs abcde and axcye are close, but they differ by two characters (the second and fourth). However, the IDs fghij and fguij differ by exactly one character, the third (h and u). Those must be the correct boxes. // //What letters are common between the two correct box IDs? (In the example above, this is found by removing the differing character from either ID, producing fgij.) function getCommonLetters($data){ for($i=0; $i<strlen($data[$i]); $i++){ $alteredData=array(); foreach($data as $box){ $box=($i===0?'':substr($box, $i-1, $i)).($i===strlen($box)?'':substr($box, $i+1)); $alteredData[]=$box; } echo(count(array_unique($alteredData))-count($alteredData)); if(count(array_unique($alteredData))<count($alteredData)){ return(array_search(2, array_count_values($alteredData))); } } } echo ('D2P2 The letters in common are: '.getCommonLetters($data));
e1d8ee73449f4fa11804dc181e3d62146e97508c
{ "blob_id": "e1d8ee73449f4fa11804dc181e3d62146e97508c", "branch_name": "refs/heads/master", "committer_date": "2022-10-27T04:08:26", "content_id": "ac8c4af1604af82ba0d74e6c97ca58b7853a8e01", "detected_licenses": [ "Apache-2.0" ], "directory_id": "9fca4dee8d06675eff33994092c5803f27758367", "extension": "php", "filename": "day-2.php", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 225247485, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 4201, "license": "Apache-2.0", "license_type": "permissive", "path": "/adventOfCode2018/day-2/day-2.php", "provenance": "stack-edu-0049.json.gz:927591", "repo_name": "Johnthe-dev/advent-of-code-2019", "revision_date": "2022-10-27T04:08:26", "revision_id": "a0bd4cea7a9db1625ca10c905bdfa94480240c5a", "snapshot_id": "990280ef97f7669e02854ff707ba53162daae5b4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Johnthe-dev/advent-of-code-2019/a0bd4cea7a9db1625ca10c905bdfa94480240c5a/adventOfCode2018/day-2/day-2.php", "visit_date": "2022-10-29T18:37:01.627493", "added": "2024-11-19T00:51:08.789509+00:00", "created": "2022-10-27T04:08:26", "int_score": 3, "score": 2.859375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0067.json.gz" }
/** * Created by 斌 on 2017/4/6. */ const router = require('express').Router(); const fs = require('fs'); const path = require('path'); const formidable = require('formidable'); let dataDir = path.resolve(__dirname, '../') + '/data', vacationPhotoDir = dataDir + '/vacation-photo'; fs.existsSync(dataDir) || fs.mkdirSync(dataDir); fs.existsSync(vacationPhotoDir) || fs.mkdirSync(vacationPhotoDir); router.get(`/vacation-photo`, (req, res) => { let now = new Date(); res.render(`contest/vacation-photo`, { year: now.getFullYear(), month: now.getMonth() }) }); module.exports = router;
8eb2e74fbe11a115b748b87777e3b82581485d9a
{ "blob_id": "8eb2e74fbe11a115b748b87777e3b82581485d9a", "branch_name": "refs/heads/master", "committer_date": "2021-07-14T00:14:05", "content_id": "49182a8c4c35c497d5b598abaf6dac27c77549fe", "detected_licenses": [ "MIT" ], "directory_id": "4811d337e12a75da0e23662185097417043611c9", "extension": "js", "filename": "vacation-photo.js", "fork_events_count": 0, "gha_created_at": "2017-04-03T14:12:00", "gha_event_created_at": "2022-03-16T00:18:48", "gha_language": "JavaScript", "gha_license_id": "MIT", "github_id": 87081778, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 622, "license": "MIT", "license_type": "permissive", "path": "/express/meadowlark/site/route/vacation-photo.js", "provenance": "stack-edu-0038.json.gz:295753", "repo_name": "imuntil/nodejs", "revision_date": "2021-07-14T00:14:05", "revision_id": "90905eb836aaabe61fd522da92ac44a81c7ee9be", "snapshot_id": "a5039d2f6c45939b9fe7b8763fa4d4a252b96039", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/imuntil/nodejs/90905eb836aaabe61fd522da92ac44a81c7ee9be/express/meadowlark/site/route/vacation-photo.js", "visit_date": "2022-03-29T19:13:31.835003", "added": "2024-11-19T00:03:25.742846+00:00", "created": "2021-07-14T00:14:05", "int_score": 2, "score": 2.078125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0056.json.gz" }
""" Tag map shortcuts hook tests. """ # pylint: disable=missing-docstring import uuid from datetime import datetime from dateutil.tz import tzutc from taskw.task import Task from taskw.utils import DATE_FORMAT from twpm.hooks import tag_map_hook NOW = datetime.now().replace(tzinfo=tzutc()) def test_tag_map(): test_task = Task( { "description": "test task 1", "status": "pending", "tags": ["tag1", "n", "@w", "@h", "ne"], "modified": NOW.strftime(DATE_FORMAT), "entry": NOW.strftime(DATE_FORMAT), "uuid": str(uuid.uuid4()), } ) tag_map_hook.main(test_task) assert test_task['description'] == "test task 1" assert test_task['tags'] == ["tag1", "next", "@work", "@home", "ne"] def test_tag_map_no_tags(): test_task = Task( { "description": "test task 2", "entry": NOW.strftime(DATE_FORMAT), "modified": NOW.strftime(DATE_FORMAT), "status": "pending", "uuid": str(uuid.uuid4()), } ) tag_map_hook.main(test_task) assert test_task['description'] == "test task 2" assert test_task.get('tags') is None
cbbe454f6656f7a5cdf46621ac2b0ba67ce82990
{ "blob_id": "cbbe454f6656f7a5cdf46621ac2b0ba67ce82990", "branch_name": "refs/heads/develop", "committer_date": "2022-11-08T06:35:46", "content_id": "178ba679bdb2080f4f007133af73a1865a9e02c2", "detected_licenses": [ "MIT" ], "directory_id": "38ed6b899f688db2724b278f71d1553f1d60378e", "extension": "py", "filename": "test_tag_map_hook.py", "fork_events_count": 0, "gha_created_at": "2018-08-19T03:05:48", "gha_event_created_at": "2022-09-14T00:09:11", "gha_language": "Python", "gha_license_id": "MIT", "github_id": 145268893, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1211, "license": "MIT", "license_type": "permissive", "path": "/tests/hooks/test_tag_map_hook.py", "provenance": "stack-edu-0060.json.gz:583845", "repo_name": "Fongshway/twpm", "revision_date": "2022-11-08T05:33:28", "revision_id": "dc3119aba788b900aba0efaf87aa0a48697a424c", "snapshot_id": "81a68a7ad7c09909a9205b17953d8f4dc1507ab8", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/Fongshway/twpm/dc3119aba788b900aba0efaf87aa0a48697a424c/tests/hooks/test_tag_map_hook.py", "visit_date": "2022-12-20T10:48:38.505168", "added": "2024-11-19T02:41:58.134370+00:00", "created": "2022-11-08T05:33:28", "int_score": 2, "score": 2.40625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0078.json.gz" }
package com.didactilab.jsjvm.client.classfile; public enum JavaVersion { J2SE_8 (0x34, "J2SE 8"), J2SE_7 (0x33, "J2SE 7"), J2SE_6_0(0x32, "J2SE 6.0"), J2SE_5_0(0x31, "J2SE 5.0"), JDK_1_4 (0x30, "JDK 1.4"), JDK_1_3 (0x2F, "JDK 1.3"), JDK_1_2 (0x2E, "JDK 1.2"), JDK_1_1 (0x2D, "JDK 1.1"), UNKNOWN (0x00, "UNKNOWN"); private final int majorVersion; private final String name; private JavaVersion(int majorVersion, String name) { this.majorVersion = majorVersion; this.name = name; } public int getMajorVersion() { return majorVersion; } public String getName() { return name; } @Override public String toString() { return name; } public static JavaVersion valueOf(int version) { for (JavaVersion v : values()) { if (v.majorVersion == version) { return v; } } return UNKNOWN; } }
633bcf9b5780b321cb2b9151df58038007e8452f
{ "blob_id": "633bcf9b5780b321cb2b9151df58038007e8452f", "branch_name": "refs/heads/master", "committer_date": "2015-06-24T14:09:45", "content_id": "7bd84b46801aa229df8af3cdff8291fdd0d1a7aa", "detected_licenses": [ "Apache-2.0" ], "directory_id": "7ee393fac18ff92176878f5c864163a02a817f7f", "extension": "java", "filename": "JavaVersion.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 37462936, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 839, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/com/didactilab/jsjvm/client/classfile/JavaVersion.java", "provenance": "stack-edu-0028.json.gz:686528", "repo_name": "Albatarm/jsjvm", "revision_date": "2015-06-24T14:09:45", "revision_id": "faafdc77cb705a13b19e93446e972f7060f65a28", "snapshot_id": "f650ff11fd66b6757b1a8d97612c617477aa7408", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Albatarm/jsjvm/faafdc77cb705a13b19e93446e972f7060f65a28/src/com/didactilab/jsjvm/client/classfile/JavaVersion.java", "visit_date": "2021-01-01T06:55:38.683225", "added": "2024-11-19T02:31:29.483554+00:00", "created": "2015-06-24T14:09:45", "int_score": 3, "score": 2.5625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0046.json.gz" }
import gettext from .command import Command from utils.text import millify, trim_string from utils.time import seconds_to_hhmmss _ = gettext.gettext class CommandServerDosh(Command): def __init__(self, server): Command.__init__(self, server, admin_only=False, requires_patch=False) self.help_text = _("Usage: !server_dosh\n" "Desc: Shows total dosh earned on this server") def execute(self, username, args, user_flags): args, err = self.parse_args(username, args, user_flags) if err: return err if args.help: return self.format_response(self.help_text, args) dosh = self.server.database.server_dosh() return self.format_response( _("£{} has been earned on this server").format(millify(dosh)), args ) class CommandServerKills(Command): def __init__(self, server): Command.__init__(self, server, admin_only=False, requires_patch=False) self.help_text = _("Usage: !server_kills\n" "Desc: Shows total ZEDs killed on this server") def execute(self, username, args, user_flags): args, err = self.parse_args(username, args, user_flags) if err: return err if args.help: return self.format_response(self.help_text, args) kills = self.server.database.server_kills() return self.format_response( _("{} ZEDs have been killed on this server") .format(millify(kills)), args ) class CommandKills(Command): def __init__(self, server): Command.__init__(self, server, admin_only=False, requires_patch=False) self.help_text = _("Usage: !kills USERNAME\n" "\tUSERNAME - User to get kill stats for\n" "Desc: Shows kill statistics for a player, " "username can be omitted to get personal stats") self.parser.add_argument("username", nargs="*") def execute(self, username, args, user_flags): args, err = self.parse_args(username, args, user_flags) if err: return err if args.help: return self.format_response(self.help_text, args) if args.username: username = " ".join(args.username) player = self.server.get_player_by_username(username) if not player: return self.format_response( _("Player {} not in game").format(username), args ) pos_kills = self.server.database.rank_kills(player.steam_id) return self.format_response( _("You've killed a total of {} ZEDs (#{}), and {} this game") .format( str(player.total_kills), str(pos_kills), str(player.kills) ), args ) class CommandDosh(Command): def __init__(self, server): Command.__init__(self, server, admin_only=False, requires_patch=False) self.help_text = _("Usage: !dosh USERNAME\n" "\tUSERNAME - User to get dosh stats for\n" "Desc: Shows dosh statistics for a player, " "username can be omitted to get personal stats") self.parser.add_argument("username", nargs="*") def execute(self, username, args, user_flags): args, err = self.parse_args(username, args, user_flags) if err: return err if args.help: return self.format_response(self.help_text, args) if args.username: username = " ".join(args.username) player = self.server.get_player_by_username(username) if not player: return self.format_response(_("Player not in game"), args) pos_dosh = self.server.database.rank_dosh(player.steam_id) return self.format_response( _("You've earned a total of £{} dosh (#{}), and £{} this" " game") .format( str(player.total_dosh), str(pos_dosh), str(player.game_dosh) ), args ) class CommandTopKills(Command): def __init__(self, server): Command.__init__(self, server, admin_only=False, requires_patch=False) self.help_text = _("Usage: !top_kills\n" "Desc: Show the global kills leaderboard") def execute(self, username, args, user_flags): args, err = self.parse_args(username, args, user_flags) if err: return err if args.help: return self.format_response(self.help_text, args) records = self.server.database.top_kills() message = _("Top 5 players by total kills:\n") for player in records[:5]: username = trim_string(player['username'], 20) kills = millify(player['score']) message += "\t{}\t- {}\n".format( kills, username ) return self.format_response(message[:-1], args) class CommandTopDosh(Command): def __init__(self, server): Command.__init__(self, server, admin_only=False, requires_patch=False) self.help_text = _("Usage: !top_dosh\n" "Desc: Shows the global dosh leaderboard") def execute(self, username, args, user_flags): args, err = self.parse_args(username, args, user_flags) if err: return err if args.help: return self.format_response(self.help_text, args) records = self.server.database.top_dosh() message = _("Top 5 players by Dosh earned:\n") for player in records[:5]: username = trim_string(player['username'], 20) dosh = millify(player['score']) message += "\t£{}\t- {}\n".format( dosh, username ) return self.format_response(message[:-1], args) class CommandTopTime(Command): def __init__(self, server): Command.__init__(self, server, admin_only=False, requires_patch=False) self.help_text = _("Usage: !top_time\n" "Desc: Shows the global play time leaderboard") def execute(self, username, args, user_flags): args, err = self.parse_args(username, args, user_flags) if err: return err if args.help: return self.format_response(self.help_text, args) records = self.server.database.top_time() message = _("Top 5 players by play time:\n") for player in records[:5]: username = trim_string(player['username'], 20) time = seconds_to_hhmmss(player['score']) message += "\t{}\t- {}\n".format( time, username ) return self.format_response(message[:-1], args) class CommandScoreboard(Command): def __init__(self, server): Command.__init__(self, server, admin_only=False, requires_patch=False) self.help_text = _("Usage: !scoreboard\n" "Desc: Shows full player scoreboard") def execute(self, username, args, user_flags): args, err = self.parse_args(username, args, user_flags) if err: return err if args.help: return self.format_response(self.help_text, args) message = _("Scoreboard (name, kills, dosh):\n") self.server.players.sort( key=lambda player: player.kills, reverse=True ) for player in self.server.players: username = trim_string(player.username, 20) dosh = millify(player.dosh) kills = player.kills message += _("{}\t- {} Kills, £{}\n").format( username, kills, dosh ) return self.format_response(message[:-1], args) class CommandTopWaveKills(Command): def __init__(self, server): Command.__init__(self, server, admin_only=False, requires_patch=True) self.help_text = _("Usage: !top_wave_kills\n" "Desc: Shows who killed the most ZEDs in this " "wave") def execute(self, username, args, user_flags): args, err = self.parse_args(username, args, user_flags) if err: return err if args.help: return self.format_response(self.help_text, args) if not self.server.players: return self.format_response(_("No players in game"), args) self.server.players.sort( key=lambda player: player.wave_kills, reverse=True ) top = self.server.players[0] return self.format_response( _("Player {} killed the most ZEDs this wave: {}").format( top.username, millify(top.wave_kills) ), args ) class CommandTopWaveDosh(Command): def __init__(self, server): Command.__init__(self, server, admin_only=False, requires_patch=True) self.help_text = _("Usage: !top_wave_dosh\n" "Desc: Shows who earned the most dosh this wave") def execute(self, username, args, user_flags): args, err = self.parse_args(username, args, user_flags) if err: return err if args.help: return self.format_response(self.help_text, args) if not self.server.players: return None self.server.players.sort( key=lambda player: player.wave_dosh, reverse=True ) top = self.server.players[0] return self.format_response( _("Player {} earned the most Dosh this wave: £{}").format( top.username, millify(top.wave_dosh) ), args )
2c65daf196aef9b9d8dea789c8412d31bf89b88a
{ "blob_id": "2c65daf196aef9b9d8dea789c8412d31bf89b88a", "branch_name": "refs/heads/master", "committer_date": "2020-12-23T10:58:37", "content_id": "43547ec99fd89f2b318b901d38b3d13f812d413a", "detected_licenses": [ "MIT" ], "directory_id": "9deab1365af45b135921eeb2c573c1afc577478e", "extension": "py", "filename": "player_commands.py", "fork_events_count": 10, "gha_created_at": "2017-09-22T12:13:36", "gha_event_created_at": "2021-01-24T11:45:57", "gha_language": "Python", "gha_license_id": "MIT", "github_id": 104470697, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9926, "license": "MIT", "license_type": "permissive", "path": "/magicked_admin/chatbot/commands/player_commands.py", "provenance": "stack-edu-0065.json.gz:496656", "repo_name": "th3-z/kf2-magicked-admin", "revision_date": "2020-12-23T10:58:37", "revision_id": "0d8330fa752de6fc3526d9dc47d81e455160b86d", "snapshot_id": "341b9577e1300cabb64f3e3e25762acb4004b454", "src_encoding": "UTF-8", "star_events_count": 16, "url": "https://raw.githubusercontent.com/th3-z/kf2-magicked-admin/0d8330fa752de6fc3526d9dc47d81e455160b86d/magicked_admin/chatbot/commands/player_commands.py", "visit_date": "2022-08-27T17:18:40.499207", "added": "2024-11-18T22:43:30.346450+00:00", "created": "2020-12-23T10:58:37", "int_score": 3, "score": 2.65625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0083.json.gz" }
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * 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 com.tencentcloudapi.postgres.v20170312.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class DBInstanceNetInfo extends AbstractModel{ /** * DNS domain name */ @SerializedName("Address") @Expose private String Address; /** * Ip */ @SerializedName("Ip") @Expose private String Ip; /** * Connection port address */ @SerializedName("Port") @Expose private Long Port; /** * Network type. 1: inner (private network address), 2: public (public network address) */ @SerializedName("NetType") @Expose private String NetType; /** * Network connection status. Valid values: `initing` (never enabled before), `opened` (enabled), `closed` (disabled), `opening` (enabling), `closing` (disabling) */ @SerializedName("Status") @Expose private String Status; /** * VPC ID Note: this field may return `null`, indicating that no valid values can be obtained. */ @SerializedName("VpcId") @Expose private String VpcId; /** * Subnet ID Note: this field may return `null`, indicating that no valid values can be obtained. */ @SerializedName("SubnetId") @Expose private String SubnetId; /** * Database connection protocol type. Valid values: `postgresql`, `mssql` (MSSQL-compatible) Note: This field may return null, indicating that no valid values can be obtained. */ @SerializedName("ProtocolType") @Expose private String ProtocolType; /** * Get DNS domain name * @return Address DNS domain name */ public String getAddress() { return this.Address; } /** * Set DNS domain name * @param Address DNS domain name */ public void setAddress(String Address) { this.Address = Address; } /** * Get Ip * @return Ip Ip */ public String getIp() { return this.Ip; } /** * Set Ip * @param Ip Ip */ public void setIp(String Ip) { this.Ip = Ip; } /** * Get Connection port address * @return Port Connection port address */ public Long getPort() { return this.Port; } /** * Set Connection port address * @param Port Connection port address */ public void setPort(Long Port) { this.Port = Port; } /** * Get Network type. 1: inner (private network address), 2: public (public network address) * @return NetType Network type. 1: inner (private network address), 2: public (public network address) */ public String getNetType() { return this.NetType; } /** * Set Network type. 1: inner (private network address), 2: public (public network address) * @param NetType Network type. 1: inner (private network address), 2: public (public network address) */ public void setNetType(String NetType) { this.NetType = NetType; } /** * Get Network connection status. Valid values: `initing` (never enabled before), `opened` (enabled), `closed` (disabled), `opening` (enabling), `closing` (disabling) * @return Status Network connection status. Valid values: `initing` (never enabled before), `opened` (enabled), `closed` (disabled), `opening` (enabling), `closing` (disabling) */ public String getStatus() { return this.Status; } /** * Set Network connection status. Valid values: `initing` (never enabled before), `opened` (enabled), `closed` (disabled), `opening` (enabling), `closing` (disabling) * @param Status Network connection status. Valid values: `initing` (never enabled before), `opened` (enabled), `closed` (disabled), `opening` (enabling), `closing` (disabling) */ public void setStatus(String Status) { this.Status = Status; } /** * Get VPC ID Note: this field may return `null`, indicating that no valid values can be obtained. * @return VpcId VPC ID Note: this field may return `null`, indicating that no valid values can be obtained. */ public String getVpcId() { return this.VpcId; } /** * Set VPC ID Note: this field may return `null`, indicating that no valid values can be obtained. * @param VpcId VPC ID Note: this field may return `null`, indicating that no valid values can be obtained. */ public void setVpcId(String VpcId) { this.VpcId = VpcId; } /** * Get Subnet ID Note: this field may return `null`, indicating that no valid values can be obtained. * @return SubnetId Subnet ID Note: this field may return `null`, indicating that no valid values can be obtained. */ public String getSubnetId() { return this.SubnetId; } /** * Set Subnet ID Note: this field may return `null`, indicating that no valid values can be obtained. * @param SubnetId Subnet ID Note: this field may return `null`, indicating that no valid values can be obtained. */ public void setSubnetId(String SubnetId) { this.SubnetId = SubnetId; } /** * Get Database connection protocol type. Valid values: `postgresql`, `mssql` (MSSQL-compatible) Note: This field may return null, indicating that no valid values can be obtained. * @return ProtocolType Database connection protocol type. Valid values: `postgresql`, `mssql` (MSSQL-compatible) Note: This field may return null, indicating that no valid values can be obtained. */ public String getProtocolType() { return this.ProtocolType; } /** * Set Database connection protocol type. Valid values: `postgresql`, `mssql` (MSSQL-compatible) Note: This field may return null, indicating that no valid values can be obtained. * @param ProtocolType Database connection protocol type. Valid values: `postgresql`, `mssql` (MSSQL-compatible) Note: This field may return null, indicating that no valid values can be obtained. */ public void setProtocolType(String ProtocolType) { this.ProtocolType = ProtocolType; } public DBInstanceNetInfo() { } /** * NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy, * and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy. */ public DBInstanceNetInfo(DBInstanceNetInfo source) { if (source.Address != null) { this.Address = new String(source.Address); } if (source.Ip != null) { this.Ip = new String(source.Ip); } if (source.Port != null) { this.Port = new Long(source.Port); } if (source.NetType != null) { this.NetType = new String(source.NetType); } if (source.Status != null) { this.Status = new String(source.Status); } if (source.VpcId != null) { this.VpcId = new String(source.VpcId); } if (source.SubnetId != null) { this.SubnetId = new String(source.SubnetId); } if (source.ProtocolType != null) { this.ProtocolType = new String(source.ProtocolType); } } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "Address", this.Address); this.setParamSimple(map, prefix + "Ip", this.Ip); this.setParamSimple(map, prefix + "Port", this.Port); this.setParamSimple(map, prefix + "NetType", this.NetType); this.setParamSimple(map, prefix + "Status", this.Status); this.setParamSimple(map, prefix + "VpcId", this.VpcId); this.setParamSimple(map, prefix + "SubnetId", this.SubnetId); this.setParamSimple(map, prefix + "ProtocolType", this.ProtocolType); } }
736353d730b155ac867c405bd212c860308b2d0b
{ "blob_id": "736353d730b155ac867c405bd212c860308b2d0b", "branch_name": "refs/heads/master", "committer_date": "2023-09-01T04:04:14", "content_id": "c13db1f9bbe5595324c718fb285adbbc8fb147f3", "detected_licenses": [ "Apache-2.0" ], "directory_id": "9410ef0fbb317ace552b6f0a91e0b847a9a841da", "extension": "java", "filename": "DBInstanceNetInfo.java", "fork_events_count": 4, "gha_created_at": "2019-12-28T06:13:51", "gha_event_created_at": "2022-05-25T06:54:45", "gha_language": "Java", "gha_license_id": "Apache-2.0", "github_id": 230567388, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 8678, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/main/java/com/tencentcloudapi/postgres/v20170312/models/DBInstanceNetInfo.java", "provenance": "stack-edu-0029.json.gz:272866", "repo_name": "TencentCloud/tencentcloud-sdk-java-intl-en", "revision_date": "2023-09-01T04:04:14", "revision_id": "6ca868a8de6803a6c9f51af7293d5e6dad575db6", "snapshot_id": "274de822748bdb9b4077e3b796413834b05f1713", "src_encoding": "UTF-8", "star_events_count": 7, "url": "https://raw.githubusercontent.com/TencentCloud/tencentcloud-sdk-java-intl-en/6ca868a8de6803a6c9f51af7293d5e6dad575db6/src/main/java/com/tencentcloudapi/postgres/v20170312/models/DBInstanceNetInfo.java", "visit_date": "2023-09-04T05:18:35.048202", "added": "2024-11-18T22:56:06.086560+00:00", "created": "2023-09-01T04:04:14", "int_score": 2, "score": 2.0625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0047.json.gz" }