hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
98 values
lang
stringclasses
21 values
max_stars_repo_path
stringlengths
3
945
max_stars_repo_name
stringlengths
4
118
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
368k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
945
max_issues_repo_name
stringlengths
4
118
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
945
max_forks_repo_name
stringlengths
4
135
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
5
1.05M
avg_line_length
float64
1
1.03M
max_line_length
int64
2
1.03M
alphanum_fraction
float64
0
1
9d199b0011771855cd69d876fc7807a16afd234c
1,049
html
HTML
site/layouts/partials/reader/main_how_it_works.html
larrylai0121/ponddy-website-ai
5b08906e0dd7f55cc8e7a34f2c09af18ce5c7897
[ "MIT" ]
1
2018-12-19T08:14:03.000Z
2018-12-19T08:14:03.000Z
site/layouts/partials/reader/main_how_it_works.html
larrylai0121/ponddy-website-ai
5b08906e0dd7f55cc8e7a34f2c09af18ce5c7897
[ "MIT" ]
null
null
null
site/layouts/partials/reader/main_how_it_works.html
larrylai0121/ponddy-website-ai
5b08906e0dd7f55cc8e7a34f2c09af18ce5c7897
[ "MIT" ]
1
2019-01-19T06:40:09.000Z
2019-01-19T06:40:09.000Z
<section class="content how-it-works"> <div class="container"> <div class="row product"> <div class="col-md-6 product-pictures no-gutters"> <img src="{{.show.mac_image | absURL }}" class="mac" id="mac"> <img src="{{.show.iphone_image | absURL }}" class="iPhone-Xs"> </div> <div class="col-md-6 description"> <h6> {{.title}} </h6> <div class="icons"> {{ range .icons }} <img src="{{.url | absURL}}"> {{ end }} </div> <p> {{ .description }} </p> </div> </div> <div class="row justify-content-center align-self-center no-gutters"> <div class="col-md-12 features"> {{ range .feature_icons }} <img src="{{.url | absURL}}"> {{ end }} </div> </div> </div> </section>
32.78125
78
0.391802
9bffe734cf6ccb66beb1bed9bae8dd667b117f22
3,731
js
JavaScript
spec/jasmine/OwnerSpec.js
fossabot/thinx-device-api
d6ef10e7938039e3879b2fa87c2c05c51c7d17e3
[ "MIT" ]
null
null
null
spec/jasmine/OwnerSpec.js
fossabot/thinx-device-api
d6ef10e7938039e3879b2fa87c2c05c51c7d17e3
[ "MIT" ]
null
null
null
spec/jasmine/OwnerSpec.js
fossabot/thinx-device-api
d6ef10e7938039e3879b2fa87c2c05c51c7d17e3
[ "MIT" ]
null
null
null
describe("Owner", function() { var generated_key_hash = null; var User = require('../../lib/thinx/owner'); var envi = require("./_envi.json"); var owner = envi.oid; var avatar_image = envi.test_avatar; var email = envi.email; var test_info = envi.test_info; var activation_key; var reset_key; // activation key is provided by e-mail for security, // cimrman@thinx.cloud receives his activation token in response // and must not be used in production environment it("should be able to create owner profile", function(done) { var body = { first_name: "Jára", last_name: "Cimrman", email: email, owner: "cimrman" }; User.create(body, true, function(success, response) { if (response.toString().indexOf("already_exists") !== -1) { expect(success).toBe(false); } else { expect(success).toBe(true); } expect(response).toBeDefined(); if (response.indexOf("username_already_exists" !== -1)) { done(); } if (response) { console.log("Activation response: " + response); this.activation_key = response; // store activation token for next step } console.log(JSON.stringify(response)); done(); }); }, 10000); it("should be able to update owner avatar", function(done) { var body = { avatar: avatar_image }; User.update(owner, body, function(success, response) { console.log("avatar update response: " + JSON.stringify(response)); if (success === false) { console.log(response); } expect(success).toBe(true); done(); }); }, 10000); it("should be able to fetch owner profile", function(done) { User.profile(owner, function(success, response) { expect(response).toBeDefined(); expect(success).toBe(true); if (success === false) { console.log("profile fetch response: " + JSON.stringify(response)); } done(); }); }, 10000); it("should be able to update owner info", function(done) { var body = { info: test_info }; User.update(owner, body, function(success, response) { console.log(JSON.stringify( response)); expect(success).toBe(true); done(); }); }, 10000); // This expects activated account and e-mail fetch support it("should be able to activate owner", function(done) { User.activate(owner, activation_key, function(success, response) { expect(success).toBe(true); expect(response).toBeDefined(); console.log(JSON.stringify(response)); done(); }); }, 10000); it("should be able to begin reset owner password", function(done) { User.password_reset_init(email, function(success, response) { if (success === false) { console.log(response); } expect(success).toBe(true); expect(response).toBeDefined(); console.log(JSON.stringify(response)); if (response) { this.reset_key = response; // store reset token for next step expect(this.reset_key).toBeDefined(); } done(); }); }, 10000); // async version fails it("should be able to set owner password", function() { var body = { password: "tset", rpassword: "tset", owner: owner, reset_key: this.reset_key }; User.set_password(body, function(success, response) { expect(this.reset_key).toBeDefined(); if (success === false) { console.log("Password set result: " + response); } expect(success).toBe(true); expect(response).toBeDefined(); console.log(JSON.stringify(response)); }); }); });
28.052632
79
0.600643
d5c3f62442802851e7a244d4f30ffd6178daa85c
2,618
c
C
server/src/services/pathogenomics/src/files_metadata.c
TGAC/grassroots-api
9692dcb428fc7a2a93b22a8510abff05deda1234
[ "Apache-2.0" ]
2
2017-12-30T14:39:48.000Z
2019-11-20T23:49:38.000Z
server/src/services/pathogenomics/src/files_metadata.c
TGAC/grassroots-api
9692dcb428fc7a2a93b22a8510abff05deda1234
[ "Apache-2.0" ]
null
null
null
server/src/services/pathogenomics/src/files_metadata.c
TGAC/grassroots-api
9692dcb428fc7a2a93b22a8510abff05deda1234
[ "Apache-2.0" ]
null
null
null
/* ** Copyright 2014-2016 The Earlham Institute ** ** 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. */ /* * files_metadata.c * * Created on: 3 Mar 2016 * Author: tyrrells */ #include "files_metadata.h" #include "string_utils.h" #include "pathogenomics_utils.h" const char *InsertFilesData (MongoTool *tool_p, json_t *values_p, PathogenomicsServiceData *data_p) { const char *error_s = NULL; const char * const key_s = PG_ID_S; const char *id_s = GetJSONString (values_p, key_s); if (id_s) { /* Create a json doc with "files"=values_p and PG_ID_S=id_s */ json_t *doc_p = json_object (); if (doc_p) { if (json_object_set_new (doc_p, PG_ID_S, json_string (id_s)) == 0) { if (json_object_del (values_p, key_s) != 0) { PrintErrors (STM_LEVEL_WARNING, __FILE__, __LINE__, "Failed to remove %s from files", key_s); } if (json_object_set (doc_p, PG_FILES_S, values_p) == 0) { error_s = InsertOrUpdateMongoData (tool_p, doc_p, NULL, NULL, PG_ID_S, NULL, NULL); /* char *date_s = ConcatenateStrings (PG_FILES_S, PG_LIVE_DATE_SUFFIX_S); if (date_s) { if (AddPublishDateToJSON (doc_p, date_s)) { error_s = InsertOrUpdateMongoData (tool_p, doc_p, NULL, NULL, PG_ID_S, NULL, NULL); } else { error_s = "Failed to add current date to files data"; } FreeCopiedString (date_s); } else { error_s = "Failed to make files date key"; } */ } else { error_s = "Failed to add values to new files data"; } } /* if (json_object_set_new (doc_p, PG_ID_S, json_string (id_s)) == 0) */ else { error_s = "Failed to add id to new v data"; } json_decref (doc_p); } /* if (doc_p) */ else { error_s = "Failed to create files data to add"; } } /* if (id_s) */ else { error_s = "Failed to get ID value"; } return error_s; }
25.920792
102
0.60084
c07d45d6f80667cedbb846720c0824bb96b80062
1,415
html
HTML
_legacy/tools/0.3.0/src/test/resources/cpptest/input/gendoc/CODSTA-CPP-36.html
cittools/checking-rules-extractor
4c40b856ce8bb0a8e2fa862a0ba2f6c85f851a57
[ "MIT" ]
null
null
null
_legacy/tools/0.3.0/src/test/resources/cpptest/input/gendoc/CODSTA-CPP-36.html
cittools/checking-rules-extractor
4c40b856ce8bb0a8e2fa862a0ba2f6c85f851a57
[ "MIT" ]
null
null
null
_legacy/tools/0.3.0/src/test/resources/cpptest/input/gendoc/CODSTA-CPP-36.html
cittools/checking-rules-extractor
4c40b856ce8bb0a8e2fa862a0ba2f6c85f851a57
[ "MIT" ]
null
null
null
<HTML> <HEAD> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <LINK REL="stylesheet" HREF="book.css" TYPE="text/css"> <TITLE> Avoid using global variables, global functions, and class in file outside namespaces </TITLE> </HEAD> <BODY BGCOLOR=#FFFFFF> <STRONG> Avoid using global variables, global functions, and class in file outside namespaces [CODSTA-CPP-36-3] </STRONG> <BR><BR> <STRONG> DESCRIPTION </STRONG> <PRE> This rule detects the use of global variables, classes, and global functions outside of namespaces. </PRE> <STRONG> BENEFITS </STRONG> <PRE> Prevents the use of global variables, classes, and global functions outside namespaces. All data and functions in a file should be inside one or more namespaces. </PRE> <STRONG> EXAMPLE </STRONG> <PRE> int var = 0; // Violation void globalfoo( ) { // Violation } class A { // Violation int i; void foo( ); }; </PRE> <STRONG> REPAIR </STRONG> <PRE> namespace name1 { int var = 0; // OK void globalfoo( ) { // OK } class A { // OK int i; void foo(); }; } </PRE> <STRONG> REFERENCES </STRONG> <PRE> 1. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS Chapter 4.11 Namespaces, AV Rule 98 2. MISRA C++:2008 Guidelines for the use of the C++ language in critical systems, Chapter 6, Section 7, Rule 7-3-1 </PRE> </BODY> </HTML>
15.898876
102
0.657244
fbb483cfb58e821bc01c4423c6cb3f64b88c6298
4,305
sql
SQL
mysql-pawolanmwen_alwaysdata_net.sql
BettaSplendid/Neo_Noodcat
849e1f938ad5a1af2f177da618f84f4e6136cdff
[ "MIT" ]
null
null
null
mysql-pawolanmwen_alwaysdata_net.sql
BettaSplendid/Neo_Noodcat
849e1f938ad5a1af2f177da618f84f4e6136cdff
[ "MIT" ]
null
null
null
mysql-pawolanmwen_alwaysdata_net.sql
BettaSplendid/Neo_Noodcat
849e1f938ad5a1af2f177da618f84f4e6136cdff
[ "MIT" ]
null
null
null
-- phpMyAdmin SQL Dump -- version 5.1.1 -- https://www.phpmyadmin.net/ -- -- Host: mysql-pawolanmwen.alwaysdata.net -- Generation Time: Feb 04, 2022 at 10:39 AM -- Server version: 10.4.22-MariaDB -- PHP Version: 7.4.19 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `pawolanmwen_gp2` -- CREATE DATABASE IF NOT EXISTS `pawolanmwen_gp2` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci; USE `pawolanmwen_gp2`; -- -------------------------------------------------------- -- -- Table structure for table `Bar` -- CREATE TABLE `Bar` ( `id` int(11) NOT NULL, `enseigne` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `adress` varchar(100) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `Bar` -- INSERT INTO `Bar` (`id`, `enseigne`, `adress`) VALUES (1, 'b', 'a'), (2, 'bbbb', 'aazzaazaz'), (3, 'Bar vol', 'ASCENT'), (4, 'Bar vol', 'ASCENT'), (5, 'Bar vol', 'ASCENT'), (6, 'Bar vol', 'ASCENT'), (7, 'Bar vol', 'ASCENT'), (8, 'Bar vol', 'ASCENT'); -- -------------------------------------------------------- -- -- Table structure for table `Cat` -- CREATE TABLE `Cat` ( `id` int(11) NOT NULL, `puceNum` int(11) NOT NULL, `description` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `statut` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `Cat` -- INSERT INTO `Cat` (`id`, `puceNum`, `description`, `statut`) VALUES (1, 222, 'Default description', NULL); -- -------------------------------------------------------- -- -- Table structure for table `Reservation` -- CREATE TABLE `Reservation` ( `id` int(11) NOT NULL, `ReservationTime` datetime NOT NULL, `cashier_id` int(11) DEFAULT NULL, `cat_id` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `User` -- CREATE TABLE `User` ( `id` int(11) NOT NULL, `lastname` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `firstname` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `email` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `password` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `dateInscription` date NOT NULL, `type` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `identityCard` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Indexes for dumped tables -- -- -- Indexes for table `Bar` -- ALTER TABLE `Bar` ADD PRIMARY KEY (`id`); -- -- Indexes for table `Cat` -- ALTER TABLE `Cat` ADD PRIMARY KEY (`id`); -- -- Indexes for table `Reservation` -- ALTER TABLE `Reservation` ADD PRIMARY KEY (`id`), ADD KEY `IDX_C454C6822EDB0489` (`cashier_id`), ADD KEY `IDX_C454C682E6ADA943` (`cat_id`); -- -- Indexes for table `User` -- ALTER TABLE `User` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `emailConstraint` (`email`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `Bar` -- ALTER TABLE `Bar` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9; -- -- AUTO_INCREMENT for table `Cat` -- ALTER TABLE `Cat` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `Reservation` -- ALTER TABLE `Reservation` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `User` -- ALTER TABLE `User` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; -- -- Constraints for dumped tables -- -- -- Constraints for table `Reservation` -- ALTER TABLE `Reservation` ADD CONSTRAINT `FK_C454C6822EDB0489` FOREIGN KEY (`cashier_id`) REFERENCES `User` (`id`), ADD CONSTRAINT `FK_C454C682E6ADA943` FOREIGN KEY (`cat_id`) REFERENCES `Cat` (`id`); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
24.460227
105
0.66597
40c6a6caf1d9d769d9189ccc84e3cfc6cc94ff3c
103
sql
SQL
migrations/1615409192551_alter_small_group_mentors_users_foreign_key/down.sql
rcos/rcos-ap
5ea4072f0593fe034a90fdc44baae22ae94863e6
[ "MIT" ]
null
null
null
migrations/1615409192551_alter_small_group_mentors_users_foreign_key/down.sql
rcos/rcos-ap
5ea4072f0593fe034a90fdc44baae22ae94863e6
[ "MIT" ]
2
2021-01-05T18:14:53.000Z
2021-01-11T07:21:18.000Z
migrations/1615409192551_alter_small_group_mentors_users_foreign_key/down.sql
rcos/rcos-ap
5ea4072f0593fe034a90fdc44baae22ae94863e6
[ "MIT" ]
null
null
null
-- Drop user_id column from small_group_mentors. ALTER TABLE small_group_mentors DROP COLUMN user_id;
25.75
52
0.834951
0b8f097eaf823137c79c39a4fcd3c6e49316ae19
8,456
py
Python
src/sadie/renumbering/clients/g3.py
jwillis0720/pybody
2d7c68650ac1ef5f3003ccb67171898eac1f63eb
[ "MIT" ]
null
null
null
src/sadie/renumbering/clients/g3.py
jwillis0720/pybody
2d7c68650ac1ef5f3003ccb67171898eac1f63eb
[ "MIT" ]
null
null
null
src/sadie/renumbering/clients/g3.py
jwillis0720/pybody
2d7c68650ac1ef5f3003ccb67171898eac1f63eb
[ "MIT" ]
null
null
null
from functools import lru_cache from itertools import product from pathlib import Path from typing import Optional, List, Tuple from pydantic import validate_arguments import pyhmmer import requests as r from yarl import URL from sadie.typing import Species, Chain, Source class G3: """API Wrapper with OpenAPI found here https://g3.jordanrwillis.com/docs""" # TODO: most likely make this an import data_folder = Path(__file__).parent.parent / "data" segments = {"V", "D", "J"} chains = {"H", "K", "L"} def __init__(self): self.base_url = URL("https://g3.jordanrwillis.com/api/v1") self.not_usable_species = [ "pig", "cow", "cat", # missing L "alpaca", # missing L and K "rhesus", # TODO: breaks tests; fix and fall back on numbering for now "dog", # TODO: viable but does not match. Need to check if diff species of dog from G3 ] self.alphabet = pyhmmer.easel.Alphabet.amino() self.builder = pyhmmer.plan7.Builder(self.alphabet, architecture="hand") self.background = pyhmmer.plan7.Background(self.alphabet) @property @lru_cache(maxsize=1) def sources(self): resp = r.get(self.base_url) resp.raise_for_status() return resp.json()["components"]["schemas"]["SourceName"]["enum"] @property @lru_cache(maxsize=1) def species(self): resp = r.get(self.base_url) resp.raise_for_status() species = resp.json()["components"]["schemas"]["CommonName"]["enum"] return [single_species for single_species in species if single_species not in self.not_usable_species] @lru_cache(maxsize=None) @validate_arguments def __get_gene_resp( self, source: Source = "imgt", species: Species = "human", segment: str = "V", limit: Optional[int] = None, ) -> str: segment = segment.upper() if segment not in self.segments: raise ValueError(f"{segment} is not a valid segment from {self.segments}") params = { "source": source, "common": species, "segment": segment, "limit": limit if limit else "-1", } resp = r.get(self.base_url / "genes", params=params) resp.raise_for_status() return resp @validate_arguments def get_gene( self, source: Source = "imgt", species: Species = "human", chain: Chain = "H", segment: str = "V", limit: Optional[int] = None, ) -> str: resp = self.__get_gene_resp(source=source, species=species, segment=segment, limit=limit) return [x for x in resp.json() if x["gene"][2].lower() == chain.lower()] def get_stockholm_pairs( self, source: Source = "imgt", chain: Chain = "H", species: Species = "human", limit: Optional[int] = None, ) -> List[Tuple[str, str]]: sub_v = self.get_gene(source=source, species=species, chain=chain, segment="V", limit=limit) sub_j = self.get_gene(source=source, species=species, chain=chain, segment="J", limit=limit) stockholm_pairs = [] for merge in product(sub_v, sub_j): v_seg = merge[0] j_seg = merge[1] if v_seg["receptor"] not in ["IG"]: continue functional = v_seg["imgt"]["imgt_functional"] v_part = v_seg["imgt"]["sequence_gapped_aa"].replace(".", "-")[:108].ljust(108).replace(" ", "-") # if v_part[0] == "-": # continue cdr3_part = j_seg["imgt"]["cdr3_aa"] fwr4_part = j_seg["imgt"]["fwr4_aa"] v_name = v_seg["gene"] j_name = j_seg["gene"] name = f"{species}_{v_name}_{j_name}" # why? if functional != "F": continue # H rules if chain.strip().lower() in "H": if len(cdr3_part[-3:] + fwr4_part) == 13: fwr4_part += "-" # K rules if chain.strip().lower() in "k": if len(cdr3_part[-3:] + fwr4_part) in [12, 13]: fwr4_part += "-" # # L rules if chain.strip().lower() == "l": if len(cdr3_part[-3:] + fwr4_part) == 12: fwr4_part += "-" # todo: alt fwr4_part based on it's size and who's askin multiplier = 128 - (len(v_part) + len(cdr3_part[-3:] + fwr4_part)) align = v_part + "-" * multiplier + cdr3_part[-3:] + fwr4_part # sanity check if chains rules are working assert len(align) == 128 stockholm_pairs.append((name, align)) return stockholm_pairs # def get_msa( # self, # source: Source = "imgt", # species: Species = "human", # chain: Chain = "H", # limit: Optional[int] = None, # ) -> str: # stockholm_pairs = self.get_stockholm_pairs(source=source, chain=chain, species=species, limit=limit) # sequences = [] # for name, align in stockholm_pairs: # sequence = pyhmmer.easel.TextSequence(name=name.encode(), sequence=align) # sequences.append(sequence) # if not sequences: # return None # return pyhmmer.easel.TextMSA(name=f"{species}_{chain}".encode(), sequences=sequences).digitize(self.alphabet) @lru_cache(maxsize=None) def build_stockholm( self, source: Source = "imgt", species: Species = "human", chain: Chain = "H", limit: Optional[int] = None, ) -> Path: """ Get a stockholm file in string format for the given species and chain. Parameters ---------- source : str, optional Source of gene data, by default "imgt" options: 'imgt' or 'custom' species : str, optional species selected from avaliabe, by default "human" chain : str, optional chain for seq, by default "H" options: 'H', 'k', 'l' -> heavy, kappa light Returns ------- str stockholm file in string format """ sto_path = self.data_folder / f"stockholms/{species}_{chain}.sto" sto_pairs = self.get_stockholm_pairs(source=source, chain=chain, species=species, limit=limit) if not sto_pairs: return head = f"# STOCKHOLM 1.0\n#=GF ID {species}_{chain}\n" body = "\n".join([f"{name}\t{ali}" for name, ali in sto_pairs]) tail = "\n#=GC RF" + "\t" + "x" * 128 + "\n//\n" # TODO: hand arch needs a parsed file -- will be refactored to handle digital directly with open(sto_path, "w") as outfile: outfile.write(head + body + tail) return sto_path @lru_cache(maxsize=None) def build_hmm( self, source: Source = "imgt", species: Species = "human", chain: Chain = "H", limit: Optional[int] = None, ) -> Path: sto_path = self.build_stockholm(source=source, chain=chain, species=species, limit=limit) if not sto_path: return hmm_path = self.data_folder / f"hmms/{species}_{chain}.hmm" with pyhmmer.easel.MSAFile(sto_path, digital=True, alphabet=self.alphabet, format="stockholm") as msa_file: msa = next(msa_file) hmm, _, _ = self.builder.build_msa(msa, self.background) with open(hmm_path, "wb") as output_file: hmm.write(output_file) return hmm_path @lru_cache(maxsize=None) def get_hmm( self, source: Source = "imgt", species: Species = "human", chain: Chain = "H", limit: Optional[int] = None, prioritize_cached_hmm: bool = False, ): hmm_path = self.data_folder / f"hmms/{species}_{chain}.hmm" if prioritize_cached_hmm is True: if hmm_path.is_file() is False: hmm_path = self.build_hmm(source=source, chain=chain, species=species, limit=limit) else: hmm_path = self.build_hmm(source=source, chain=chain, species=species, limit=limit) if not hmm_path: return with pyhmmer.plan7.HMMFile(hmm_path) as hmm_file: hmm = next(hmm_file) return hmm
33.555556
119
0.561968
bd3cf7545eeff5a2b64cbeba0e6971ebcf7758ee
386
rs
Rust
openraft/src/engine/mod.rs
datafuselabs/openraft
3718311cecf9166afb6b846d9d85698ae365822d
[ "Apache-2.0", "MIT" ]
446
2021-12-29T06:28:40.000Z
2022-03-31T12:21:12.000Z
openraft/src/engine/mod.rs
datafuselabs/openraft
3718311cecf9166afb6b846d9d85698ae365822d
[ "Apache-2.0", "MIT" ]
135
2021-12-29T04:51:43.000Z
2022-03-21T02:57:56.000Z
openraft/src/engine/mod.rs
datafuselabs/openraft
3718311cecf9166afb6b846d9d85698ae365822d
[ "Apache-2.0", "MIT" ]
48
2021-12-29T19:08:39.000Z
2022-03-28T06:05:03.000Z
mod command; mod engine_impl; mod log_id_list; #[cfg(test)] mod elect_test; #[cfg(test)] mod handle_vote_req_test; #[cfg(test)] mod handle_vote_resp_test; #[cfg(test)] mod initialize_test; #[cfg(test)] mod log_id_list_test; #[cfg(test)] mod purge_log_test; #[cfg(test)] mod testing; pub(crate) use command::Command; pub(crate) use engine_impl::Engine; pub use log_id_list::LogIdList;
24.125
39
0.751295
90a8feec75fa8b831be4458a88c167175ba9e791
5,695
py
Python
apps/netconfig/manager.py
eocho1105/developer-badge-2018-apps
dfc4cb8fd95c15328ff28684fdfc7057002430f8
[ "Apache-2.0" ]
9
2018-12-25T06:57:39.000Z
2019-09-29T00:29:16.000Z
apps/netconfig/manager.py
eocho1105/developer-badge-2018-apps
dfc4cb8fd95c15328ff28684fdfc7057002430f8
[ "Apache-2.0" ]
1
2019-04-11T07:23:04.000Z
2019-04-11T08:05:29.000Z
apps/netconfig/manager.py
eocho1105/developer-badge-2018-apps
dfc4cb8fd95c15328ff28684fdfc7057002430f8
[ "Apache-2.0" ]
9
2018-12-25T06:57:41.000Z
2019-09-29T00:29:20.000Z
import machine import network import time import ugfx import util from home.launcher import ButtonGroup, Button, Display class ConfigManager(Display): def __init__(self, parent=None): self.parent = parent super().__init__() def reload(self): if self.parent: self.parent.reload() else: self.destroy() self.main() def kb_handler(self, keycode): if keycode == 13: # GKEY_ENTER text = self.kb_input.text() self.kb.destroy() self.kb_input.destroy() self.kb_callback(text) def get_input(self, label, callback): ugfx.input_attach(ugfx.BTN_B, util.reboot) w = self.create_window() edit_size = 40 ugfx.Textbox(5, 0, w.width() - 12, edit_size, text=label, parent=w).enabled(False) self.kb_input = ugfx.Textbox(5, 7 + edit_size, w.width() - 12, edit_size, parent=w) self.kb = ugfx.Keyboard(5, edit_size * 2 + 12, w.width() - 12, w.height() - edit_size * 2 - 20, parent=w) self.kb_callback = callback self.kb.set_keyboard_callback(self.kb_handler) def get_status(self, interface): for stat in dir(network): if stat.startswith('STAT_'): if getattr(network, stat) == interface.status(): return stat.replace('STAT_', '') def teardown(self, pressed=True): if pressed and self.window and self.window.enabled() != 0: self.window.hide() self.window.destroy() ugfx.poll() class WifiConfig(ConfigManager): def __init__(self, parent=None): self.sta_if = network.WLAN(network.STA_IF) self.ap_if = network.WLAN(network.AP_IF) self.saved_config = None super().__init__(parent) def scan(self): if not self.sta_if.active(): self.sta_if.active(True) self.create_status_box() self.set_status('Scanning..') self.scan_configs = self.sta_if.scan() self.close_status_box() def connect_network(self, ssid, pw=None, timeout=15): self.create_window() self.window.text(10, 10, 'Connecting to {}'.format(ssid), ugfx.BLACK) if not self.sta_if.active(): self.sta_if.active(True) else: self.sta_if.active(False) time.sleep(0.3) self.sta_if.active(True) self.create_status_box() self.sta_if.connect(ssid, pw) tried = 0 while self.get_status(self.sta_if) != 'GOT_IP' and tried < timeout: self.set_status(self.get_status(self.sta_if)) time.sleep(0.2) tried += 0.2 if self.get_status(self.sta_if) == 'GOT_IP': self.set_status('Connected!') config = util.Config('network') config['sta_if'] = { 'ssid': ssid, 'password': pw, } config.save() time.sleep(1) self.set_status('Network configuration saved.') time.sleep(1) util.reboot() else: self.set_status('Connection failed.') def network_selected(self, pressed): if not pressed: return scan_config = self.scan_configs[self.scan_list.selected_index()] self.saved_config = scan_config ugfx.input_attach(ugfx.BTN_A, None) self.scan_list.destroy() if scan_config[4] == 0: self.connect_network(scan_config[0].decode('utf-8')) else: self.get_password() def list_network(self): w = self.create_window() self.scan() self.scan_list = ugfx.List(10, 10, w.width() - 20, w.height() - 20, parent = w) self.scan_list.visible(False) for scan_config in self.scan_configs: ap_name = '{} {}'.format( '@' if scan_config[4] else ' ', scan_config[0].decode('utf-8') ) self.scan_list.add_item(ap_name) print(scan_config) self.scan_list.visible(True) ugfx.input_attach(ugfx.BTN_A, self.network_selected) ugfx.input_attach(ugfx.BTN_B, util.reboot) def pw_callback(self, pw): self.connect_network(self.saved_config[0].decode('utf-8'), pw) def get_password(self): self.get_input('Input password', self.pw_callback) class WebreplConfig(ConfigManager): CONFIG = '/webrepl_cfg.py' def pw_callback(self, passwd): with open(self.CONFIG, "w") as f: f.write("PASS = %r\n" % passwd) self.create_window() self.create_status_box() self.set_status('Webrepl password saved.') time.sleep(1) util.reboot() def main(self): ugfx.input_attach(ugfx.BTN_A, None) self.get_input('New password (4-9 chars)', self.pw_callback) class Status(Display): menus = ['WiFi', 'Webrepl'] def title(self): self.window.text(60, 20, 'Network config', ugfx.HTML2COLOR(0x01d7dd)) def main(self): self.create_window() self.title() self.btngroup = ButtonGroup(self.window, 80, 110, 140, 40, 10) self.widgets.append(self.btngroup) sta_if = network.WLAN(network.STA_IF) ugfx.Label(40, 60, 240, 30, text=sta_if.ifconfig()[0], parent=self.window) for menu in self.menus: self.btngroup.add(menu, getattr(self, menu)) self.btngroup.end() def WiFi(self, data=None): self.destroy() m = WifiConfig(self) m.list_network() def Webrepl(self, data=None): self.destroy() w = WebreplConfig(self) w.main()
30.61828
113
0.581914
b6547d823a4623674b8a149e48c214dea25c006a
772
rb
Ruby
spec/grpc_mock_spec.rb
eisuke/grpc_mock
b2a5bd1868c0df18ad3e4dc537a4b5db58df5a8b
[ "MIT" ]
null
null
null
spec/grpc_mock_spec.rb
eisuke/grpc_mock
b2a5bd1868c0df18ad3e4dc537a4b5db58df5a8b
[ "MIT" ]
null
null
null
spec/grpc_mock_spec.rb
eisuke/grpc_mock
b2a5bd1868c0df18ad3e4dc537a4b5db58df5a8b
[ "MIT" ]
null
null
null
require 'examples/hello/hello_client' RSpec.describe GrpcMock do describe '.enable!' do let(:client) do HelloClient.new end before do described_class.disable_net_connect! described_class.enable! end it { expect { client.send_message('hello!') } .to raise_error(GrpcMock::NetConnectNotAllowedError) } context 'to GrpcMock.diable!' do before do described_class.disable! end it { expect { client.send_message('hello!') } .to raise_error(GRPC::Unavailable) } context 'to GrpcMock.enable!' do before do described_class.enable! end it { expect { client.send_message('hello!') } .to raise_error(GrpcMock::NetConnectNotAllowedError) } end end end end
23.393939
108
0.654145
90df72772a6b330fe80dd309ac7a128cbf3a93a6
12,901
py
Python
optimal_stopping/run/run_algo.py
AYUSH-ISHAN/OptStopRandNN
8c02d2d1971e8a6e13dbc2cf008c33fe7cca49ed
[ "MIT" ]
9
2021-04-30T10:08:53.000Z
2022-03-26T18:08:59.000Z
optimal_stopping/run/run_algo.py
AYUSH-ISHAN/OptStopRandNN
8c02d2d1971e8a6e13dbc2cf008c33fe7cca49ed
[ "MIT" ]
null
null
null
optimal_stopping/run/run_algo.py
AYUSH-ISHAN/OptStopRandNN
8c02d2d1971e8a6e13dbc2cf008c33fe7cca49ed
[ "MIT" ]
4
2021-09-28T09:10:16.000Z
2022-03-13T12:50:17.000Z
# Lint as: python3 """ Main module to run the algorithms. """ import os import atexit import csv import itertools import multiprocessing import socket import random import time import psutil # absl needs to be upgraded to >= 0.10.0, otherwise joblib might not work from absl import app from absl import flags import numpy as np import shutil from optimal_stopping.utilities import configs_getter from optimal_stopping.algorithms.backward_induction import DOS from optimal_stopping.payoffs import payoff from optimal_stopping.algorithms.backward_induction import LSM from optimal_stopping.algorithms.backward_induction import RLSM from optimal_stopping.algorithms.backward_induction import RRLSM from optimal_stopping.data import stock_model from optimal_stopping.algorithms.backward_induction import NLSM from optimal_stopping.algorithms.reinforcement_learning import RFQI from optimal_stopping.algorithms.reinforcement_learning import FQI from optimal_stopping.algorithms.reinforcement_learning import LSPI from optimal_stopping.run import write_figures import joblib # GLOBAL CLASSES class SendBotMessage: def __init__(self): pass @staticmethod def send_notification(text, *args, **kwargs): print(text) try: from telegram_notifications import send_bot_message as SBM except Exception: SBM = SendBotMessage() NUM_PROCESSORS = multiprocessing.cpu_count() if 'ada-' in socket.gethostname() or 'arago' in socket.gethostname(): SERVER = True NB_JOBS = int(NUM_PROCESSORS) - 1 else: SERVER = False NB_JOBS = int(NUM_PROCESSORS) - 1 SEND = False if SERVER: SEND = True FLAGS = flags.FLAGS flags.DEFINE_list("nb_stocks", None, "List of number of Stocks") flags.DEFINE_list("algos", None, "Name of the algos to run.") flags.DEFINE_bool("print_errors", False, "Set to True to print errors if any.") flags.DEFINE_integer("nb_jobs", NB_JOBS, "Number of CPUs to use parallelly") flags.DEFINE_bool("generate_pdf", False, "Whether to generate latex tables") _CSV_HEADERS = ['algo', 'model', 'payoff', 'drift', 'volatility', 'mean', 'speed', 'correlation', 'hurst', 'nb_stocks', 'nb_paths', 'nb_dates', 'spot', 'strike', 'dividend', 'maturity', 'nb_epochs', 'hidden_size', 'factors', 'ridge_coeff', 'train_ITM_only', 'use_path', 'price', 'duration'] _PAYOFFS = { "MaxPut": payoff.MaxPut, "MaxCall": payoff.MaxCall, "GeometricPut": payoff.GeometricPut, "BasketCall": payoff.BasketCall, "Identity": payoff.Identity, "Max": payoff.Max, "Mean": payoff.Mean, } _STOCK_MODELS = { "BlackScholes": stock_model.BlackScholes, "FractionalBlackScholes": stock_model.FractionalBlackScholes, "FractionalBrownianMotion": stock_model.FractionalBrownianMotion, 'FractionalBrownianMotionPathDep': stock_model.FractionalBrownianMotionPathDep, "Heston": stock_model.Heston, } _ALGOS = { "LSM": LSM.LeastSquaresPricer, "LSMLaguerre": LSM.LeastSquarePricerLaguerre, "LSMRidge": LSM.LeastSquarePricerRidge, "FQI": FQI.FQIFast, "FQILaguerre": FQI.FQIFastLaguerre, "LSPI": LSPI.LSPI, # TODO: this is a slow version -> update similar to FQI "NLSM": NLSM.NeuralNetworkPricer, "DOS": DOS.DeepOptimalStopping, "RLSM": RLSM.ReservoirLeastSquarePricerFast, "RLSMRidge": RLSM.ReservoirLeastSquarePricerFastRidge, "RRLSM": RRLSM.ReservoirRNNLeastSquarePricer, "RFQI": RFQI.FQI_ReservoirFast, "RRFQI": RFQI.FQI_ReservoirFastRNN, } _NUM_FACTORS = { "RRLSMmix": 3, "RRLSM": 2, "RLSM": 1, } def init_seed(): random.seed(0) np.random.seed(0) def _run_algos(): fpath = os.path.join(os.path.dirname(__file__), "../../output/metrics_draft", f'{int(time.time()*1000)}.csv') tmp_dirpath = f'{fpath}.tmp_results' os.makedirs(tmp_dirpath, exist_ok=True) atexit.register(shutil.rmtree, tmp_dirpath) tmp_files_idx = 0 delayed_jobs = [] nb_stocks_flag = [int(nb) for nb in FLAGS.nb_stocks or []] for config_name, config in configs_getter.get_configs(): print(f'Config {config_name}', config) config.algos = [a for a in config.algos if FLAGS.algos is None or a in FLAGS.algos] if nb_stocks_flag: config.nb_stocks = [a for a in config.nb_stocks if a in nb_stocks_flag] combinations = list(itertools.product( config.algos, config.dividends, config.maturities, config.nb_dates, config.nb_paths, config.nb_stocks, config.payoffs, config.drift, config.spots, config.stock_models, config.strikes, config.volatilities, config.mean, config.speed, config.correlation, config.hurst, config.nb_epochs, config.hidden_size, config.factors, config.ridge_coeff, config.train_ITM_only, config.use_path)) # random.shuffle(combinations) for params in combinations: for i in range(config.nb_runs): tmp_file_path = os.path.join(tmp_dirpath, str(tmp_files_idx)) tmp_files_idx += 1 delayed_jobs.append(joblib.delayed(_run_algo)( tmp_file_path, *params, fail_on_error=FLAGS.print_errors) ) print(f"Running {len(delayed_jobs)} tasks using " f"{FLAGS.nb_jobs}/{NUM_PROCESSORS} CPUs...") joblib.Parallel(n_jobs=FLAGS.nb_jobs)(delayed_jobs) print(f'Writing results to {fpath}...') with open(fpath, "w") as csvfile: writer = csv.DictWriter(csvfile, fieldnames=_CSV_HEADERS) writer.writeheader() for idx in range(tmp_files_idx): tmp_file_path = os.path.join(tmp_dirpath, str(idx)) try: with open(tmp_file_path, "r") as read_f: csvfile.write(read_f.read()) except FileNotFoundError: pass return fpath def _run_algo( metrics_fpath, algo, dividend, maturity, nb_dates, nb_paths, nb_stocks, payoff, drift, spot, stock_model, strike, volatility, mean, speed, correlation, hurst, nb_epochs, hidden_size=10, factors=(1.,1.,1.), ridge_coeff=1., train_ITM_only=True, use_path=False, fail_on_error=False): """ This functions runs one algo for option pricing. It is called by _run_algos() which is called in main(). Below the inputs are listed which have to be specified in the config that is passed to main(). Args: metrics_fpath: file path, automatically generated & passed by _run_algos() algo (str): the algo to train. See dict _ALGOS above. dividend (float): the dividend of the stock model. maturity (float): the maturity of the option. nb_dates (int): number of equidistance dates at which option can be exercised up to maturity. nb_paths (int): number of paths that are simulated from stock model. Half is used to learn the weigths, half to estimate the option price. nb_stocks (int): number of stocks used for the option (e.g. max call). payoff (str): see dict _PAYOFFS. drift (float): the drift of the stock model spot (float): the value of the stocks at t=0. stock_model (str): see dict _STOCK_MODELS. strike (float): the strike price of the option, if used by the payoff. volatility (float): the volatility of the stock model. mean (float): parameter for Heston stock model. speed (float): parameter for Heston stock model. correlation (float): parameter for Heston stock model. hurst (float): in (0,1) the hurst parameter for the FractionalBrownianMotion and FractionalBrownianMotionPathDep stock models. nb_epochs (int): number of epochs to train the algos which are based on iterative updates (FQI, RFQI etc.) or SGD (NLSM, DOS). Otherwise unused. hidden_size (int): the number of nodes in the hidden layers of NN based algos. factors (list of floats, optional. Contains scaling coeffs for the randomized NN (i.e. scaling of the randomly sampled and fixed weights -> changes the std of the sampling distribution). Depending on the algo, the factors are used differently. See there directly. ridge_coeff (float, regression coeff for the algos using Ridge regression. train_ITM_only (bool): whether to train weights on all paths or only on those where payoff is positive (i.e. where it makes sense to stop). This should be set to False when using FractionalBrownianMotion with Identity payoff, since there the payoff can actually become negative and therefore training on those paths is important. use_path (bool): for DOS algo only. If true, the algo uses the entire path up to the current time of the stock (instead of the current value only) as input. This is used for Non-Markovian stock models, i.e. FractionalBrownianMotion, where the decisions depend on the history. fail_on_error (bool): whether to continue when errors occure or not. Automatically passed from _run_algos(), with the value of FLAGS.print_errors. """ print(algo, spot, volatility, maturity, nb_paths, '... ', end="") payoff_ = _PAYOFFS[payoff](strike) stock_model_ = _STOCK_MODELS[stock_model]( drift=drift, volatility=volatility, mean=mean, speed=speed, hurst=hurst, correlation=correlation, nb_stocks=nb_stocks, nb_paths=nb_paths, nb_dates=nb_dates, spot=spot, dividend=dividend, maturity=maturity) if algo in ['NLSM']: pricer = _ALGOS[algo](stock_model_, payoff_, nb_epochs=nb_epochs, hidden_size=hidden_size, train_ITM_only=train_ITM_only) elif algo in ["DOS"]: pricer = _ALGOS[algo](stock_model_, payoff_, nb_epochs=nb_epochs, hidden_size=hidden_size, use_path=use_path) elif algo in ["RLSM", "RRLSM", "RRFQI", "RFQI",]: pricer = _ALGOS[algo](stock_model_, payoff_, nb_epochs=nb_epochs, hidden_size=hidden_size, factors=factors, train_ITM_only=train_ITM_only) elif algo in ["RLSMRidge"]: pricer = _ALGOS[algo](stock_model_, payoff_, nb_epochs=nb_epochs, hidden_size=hidden_size, factors=factors, train_ITM_only=train_ITM_only, ridge_coeff=ridge_coeff) elif algo in ["LSM", "LSMLaguerre"]: pricer = _ALGOS[algo](stock_model_, payoff_, nb_epochs=nb_epochs, train_ITM_only=train_ITM_only) elif algo in ["LSMRidge"]: pricer = _ALGOS[algo](stock_model_, payoff_, nb_epochs=nb_epochs, train_ITM_only=train_ITM_only, ridge_coeff=ridge_coeff) else: pricer = _ALGOS[algo](stock_model_, payoff_, nb_epochs=nb_epochs) t_begin = time.time() try: price = pricer.price() duration = time.time() - t_begin except BaseException as err: if fail_on_error: raise print(err) return metrics_ = {} metrics_['algo'] = algo metrics_['model'] = stock_model metrics_['payoff'] = payoff metrics_['drift'] = drift metrics_['volatility'] = volatility metrics_['mean'] = mean metrics_['speed'] = speed metrics_['correlation'] = correlation metrics_['hurst'] = hurst metrics_['nb_stocks'] = nb_stocks metrics_['nb_paths'] = nb_paths metrics_['nb_dates'] = nb_dates metrics_['spot'] = spot metrics_['strike'] = strike metrics_['dividend'] = dividend metrics_['maturity'] = maturity metrics_['price'] = price metrics_['duration'] = duration metrics_['hidden_size'] = hidden_size metrics_['factors'] = factors metrics_['ridge_coeff'] = ridge_coeff metrics_['nb_epochs'] = nb_epochs metrics_['train_ITM_only'] = train_ITM_only metrics_['use_path'] = use_path print("price: ", price, "duration: ", duration) with open(metrics_fpath, "w") as metrics_f: writer = csv.DictWriter(metrics_f, fieldnames=_CSV_HEADERS) writer.writerow(metrics_) def main(argv): del argv try: if SEND: SBM.send_notification( text='start running AMC2 with config:\n{}'.format(FLAGS.configs), chat_id="-399803347" ) filepath = _run_algos() if FLAGS.generate_pdf: write_figures.write_figures() write_figures.generate_pdf() if SEND: time.sleep(1) SBM.send_notification( text='finished', files=[filepath], chat_id="-399803347" ) except Exception as e: if SEND: SBM.send_notification( text='ERROR\n{}'.format(e), chat_id="-399803347" ) else: print('ERROR\n{}'.format(e)) if __name__ == "__main__": app.run(main)
35.442308
80
0.674211
becc5dc2c2130b0ed001068df686239c246c1ee2
188
sql
SQL
DeleteOlddata.sql
mkaraki/CCS
809994055ba411de3d8ce61b33c922ceda3b7021
[ "Apache-2.0" ]
null
null
null
DeleteOlddata.sql
mkaraki/CCS
809994055ba411de3d8ce61b33c922ceda3b7021
[ "Apache-2.0" ]
null
null
null
DeleteOlddata.sql
mkaraki/CCS
809994055ba411de3d8ce61b33c922ceda3b7021
[ "Apache-2.0" ]
null
null
null
DELETE FROM ChatLog WHERE senttime < UNIX_TIMESTAMP() - 259200; DELETE FROM Rooms WHERE lastjoin < UNIX_TIMESTAMP() - 604800; DELETE FROM Users WHERE lastlogin < UNIX_TIMESTAMP() - 604800;
62.666667
63
0.781915
75f3d2a03973059e0f931eea074d316497ebe746
7,321
php
PHP
vufind/web/sys/MaterialsRequest/MaterialsRequest.php
MarmotLibraryNetwork/Pika
f6c03bf1025d0b1da63fcd1219829a34500357a7
[ "Unlicense" ]
5
2018-10-11T11:18:54.000Z
2021-08-20T14:06:17.000Z
vufind/web/sys/MaterialsRequest/MaterialsRequest.php
MarmotLibraryNetwork/Pika
f6c03bf1025d0b1da63fcd1219829a34500357a7
[ "Unlicense" ]
9
2019-04-30T16:00:52.000Z
2022-01-12T22:50:36.000Z
vufind/web/sys/MaterialsRequest/MaterialsRequest.php
MarmotLibraryNetwork/Pika
f6c03bf1025d0b1da63fcd1219829a34500357a7
[ "Unlicense" ]
4
2019-02-11T23:32:53.000Z
2019-05-15T19:38:00.000Z
<?php /** * Copyright (C) 2020 Marmot Library Network * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ /** * Table Definition for Materials Request */ require_once 'DB/DataObject.php'; class MaterialsRequest extends DB_DataObject { public $__table = 'materials_request'; // table name // Note: if table column names are changed, data for class MaterialsRequestFieldsToDisplay will need updated. public $id; public $libraryId; public $title; public $season; public $magazineTitle; public $magazineDate; public $magazineVolume; public $magazineNumber; public $magazinePageNumbers; public $author; public $format; public $formatId; public $subFormat; public $ageLevel; public $bookType; public $isbn; public $upc; public $issn; public $oclcNumber; public $publisher; public $publicationYear; public $abridged; public $about; public $comments; public $status; public $phone; public $email; public $dateCreated; public $createdBy; public $dateUpdated; public $emailSent; public $holdsCreated; public $placeHoldWhenAvailable; public $illItem; public $holdPickupLocation; public $bookmobileStop; public $assignedTo; //Dynamic properties setup by joins public $numRequests; public $description; public $userId; public $firstName; public $lastName; function keys() { return array('id'); } static function getFormats(){ require_once ROOT_DIR . '/sys/MaterialsRequest/MaterialsRequestFormats.php'; $availableFormats = array(); $customFormats = new MaterialsRequestFormats(); global $library; $requestLibrary = $library; if (UserAccount::isLoggedIn()) { $user = UserAccount::getLoggedInUser(); $homeLibrary = $user->getHomeLibrary(); if (isset($homeLibrary)) { $requestLibrary = $homeLibrary; } } $customFormats->libraryId = $requestLibrary->libraryId; if ($customFormats->count() == 0 ) { // Default Formats to use when no custom formats are created. /** @var MaterialsRequestFormats[] $defaultFormats */ $defaultFormats = MaterialsRequestFormats::getDefaultMaterialRequestFormats($requestLibrary->libraryId); $availableFormats = array(); global $configArray; foreach ($defaultFormats as $index => $materialRequestFormat){ $format = $materialRequestFormat->format; if (isset($configArray['MaterialsRequestFormats'][$format]) && $configArray['MaterialsRequestFormats'][$format] == false){ // dont add this format } else { $availableFormats[$format] = $materialRequestFormat->formatLabel; } } } else { $customFormats->orderBy('weight'); $availableFormats = $customFormats->fetchAll('format', 'formatLabel'); } return $availableFormats; } public function getFormatObject() { if (!empty($this->libraryId) && !empty($this->format)) { require_once ROOT_DIR . '/sys/MaterialsRequest/MaterialsRequestFormats.php'; $format = new MaterialsRequestFormats(); $format->format = $this->format; $format->libraryId = $this->libraryId; if ($format->find(1)) { return $format; } else { foreach (MaterialsRequestFormats::getDefaultMaterialRequestFormats($this->libraryId) as $defaultFormat) { if ($this->format == $defaultFormat->format) { return $defaultFormat; } } } } return false; } static $materialsRequestEnabled = null; static function enableMaterialsRequest($forceReload = false){ if (MaterialsRequest::$materialsRequestEnabled != null && $forceReload == false){ return MaterialsRequest::$materialsRequestEnabled; } global $configArray; global $library; //First make sure we are enabled in the config file if (!empty($configArray['MaterialsRequest']['enabled'])){ $enableMaterialsRequest = $configArray['MaterialsRequest']['enabled']; //Now check if the library allows material requests if ($enableMaterialsRequest){ if (isset($library) && $library->enableMaterialsRequest == 0){ $enableMaterialsRequest = false; }elseif (UserAccount::isLoggedIn()){ // $homeLibrary = Library::getPatronHomeLibrary(); $homeLibrary = UserAccount::getUserHomeLibrary(); if (is_null($homeLibrary)){ $enableMaterialsRequest = false; }elseif ($homeLibrary->enableMaterialsRequest == 0){ $enableMaterialsRequest = false; }elseif (isset($library) && $homeLibrary->libraryId != $library->libraryId){ $enableMaterialsRequest = false; }elseif (!empty($configArray['MaterialsRequest']['allowablePatronTypes'])){ //Check to see if we need to do additional restrictions by patron type $allowablePatronTypes = $configArray['MaterialsRequest']['allowablePatronTypes']; if (!preg_match("/^$allowablePatronTypes$/i", UserAccount::getUserPType())){ $enableMaterialsRequest = false; } } } } }else{ $enableMaterialsRequest = false; } MaterialsRequest::$materialsRequestEnabled = $enableMaterialsRequest; return $enableMaterialsRequest; } function getHoldLocationName($locationId) { require_once ROOT_DIR . '/sys/Location/Location.php'; $holdLocation = new Location(); if ($holdLocation->get($locationId)) { return $holdLocation->displayName; } return false; } function getRequestFormFields($libraryId, $isStaffRequest = false) { require_once ROOT_DIR . '/sys/MaterialsRequest/MaterialsRequestFormFields.php'; $formFields = new MaterialsRequestFormFields(); $formFields->libraryId = $libraryId; $formFields->orderBy('weight'); /** @var MaterialsRequestFormFields[] $fieldsToSortByCategory */ $fieldsToSortByCategory = $formFields->fetchAll(); // If no values set get the defaults. if (empty($fieldsToSortByCategory)) { $fieldsToSortByCategory = $formFields::getDefaultFormFields($libraryId); } if (!$isStaffRequest){ foreach ($fieldsToSortByCategory as $fieldKey => $fieldDetails){ if (in_array($fieldDetails->fieldType, array('assignedTo','createdBy','libraryCardNumber','id','status'))){ unset($fieldsToSortByCategory[$fieldKey]); } } } // If we use another interface variable that is sorted by category, this should be a method in the Interface class $requestFormFields = array(); if ($fieldsToSortByCategory) { foreach ($fieldsToSortByCategory as $formField) { if (!array_key_exists($formField->formCategory, $requestFormFields)) { $requestFormFields[$formField->formCategory] = array(); } $requestFormFields[$formField->formCategory][] = $formField; } } return $requestFormFields; } function getAuthorLabelsAndSpecialFields($libraryId) { require_once ROOT_DIR . '/sys/MaterialsRequest/MaterialsRequestFormats.php'; return MaterialsRequestFormats::getAuthorLabelsAndSpecialFields($libraryId); } }
32.829596
126
0.719574
b22ed2b92bf59799a82e5bc23fa18f9678a389e2
853
sql
SQL
Sample/SQL Server 2016 Demo/16.Advanced Analytics/01.R スクリプトの実行.sql
MasayukiOzawa/SQLServer-Util
7dd1f9ab411955b85026c78e6e901ea4c57788f8
[ "MIT" ]
64
2016-06-15T07:39:40.000Z
2022-03-22T02:19:50.000Z
Sample/SQL Server 2016 Demo/16.Advanced Analytics/01.R スクリプトの実行.sql
MasayukiOzawa/SQLServer-Util
7dd1f9ab411955b85026c78e6e901ea4c57788f8
[ "MIT" ]
1
2016-09-24T17:41:04.000Z
2016-11-09T01:31:17.000Z
Sample/SQL Server 2016 Demo/16.Advanced Analytics/01.R スクリプトの実行.sql
MasayukiOzawa/SQLServer-Util
7dd1f9ab411955b85026c78e6e901ea4c57788f8
[ "MIT" ]
20
2017-03-07T19:20:00.000Z
2022-03-22T02:34:50.000Z
-- インスタンスインストール時にAdvanced Analytics Extensions をインストール -- RRO-3.2.2-for-RRE-7.5.0-Windows.exe のインストール -- Revolution-R-Enterprise-Node-SQL-7.5.0-Windows.exe のインストール -- R スクリプト実行の有効化 EXEC sp_configure 'external scripts enabled', 1 RECONFIGURE GO -- "C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\R_SERVICES\library\RevoScaleR\rxLibs\x64\RegisterRExt.exe" /install -- SQL Server の再起動 USE [DemoDB] GO DROP TABLE IF EXISTS MyData CREATE TABLE MyData ([Col1] int not null) ON [PRIMARY] INSERT INTO MyData VALUES (1); INSERT INTO MyData Values (10); INSERT INTO MyData Values (100) ; GO execute sp_execute_external_script @language = N'R' , @script = N' SQLOut <- SQLIn;' , @input_data_1 = N' SELECT 12 as Col;' , @input_data_1_name = N'SQLIn' , @output_data_1_name = N'SQLOut' WITH RESULT SETS (([NewColName] int NOT NULL));
27.516129
129
0.737397
48cb5b235a754f7111f01fa2074ef491d9585db8
1,504
lua
Lua
samples/projects/IsometricComposer/main.lua
jsykes/million-tile-engine
a23fc96b17c37e3991bed8e934e0ae1cc94df9aa
[ "MIT" ]
12
2017-02-12T23:38:00.000Z
2021-04-20T11:09:59.000Z
samples/projects/IsometricComposer/main.lua
jsykes/million-tile-engine
a23fc96b17c37e3991bed8e934e0ae1cc94df9aa
[ "MIT" ]
2
2017-02-20T04:20:32.000Z
2018-05-01T08:36:30.000Z
samples/projects/IsometricComposer/main.lua
jsykes/million-tile-engine
a23fc96b17c37e3991bed8e934e0ae1cc94df9aa
[ "MIT" ]
8
2017-02-18T14:46:18.000Z
2021-06-23T19:46:26.000Z
-- MTE "CASTLE DEMO" ---------------------------------------------------------- local composer = require("composer") local myData = require("IsometricComposer.mydata") myData.prevMap = "IsoMap3" myData.nextMap = "IsoMap1" --SETUP D-PAD ------------------------------------------------------------ myData.controlGroup = display.newGroup() myData.DpadBack = display.newImageRect(myData.controlGroup, "IsometricComposer/Dpad2.png", 120, 120) myData.DpadBack.x = Screen.Left + myData.DpadBack.width*0.5 + 10 myData.DpadBack.y = Screen.Bottom - myData.DpadBack.height*0.5 - 10 myData.DpadBack:toFront() local function move( event ) if event.phase == "began" then display.getCurrentStage():setFocus(event.target, event.id) event.target.isFocus = true end if event.phase == "began" or event.phase == "moved" then local dirX = event.x - event.target.x local dirY = event.y - event.target.y local angle = math.deg(math.atan(dirY/dirX)) if dirX < 0 then angle = 90 + (90 - (angle * -1)) end angle = angle + 90 angle = math.round(angle / 45) * 45 myData.movement = tostring(angle) elseif event.phase == "ended" or event.phase == "cancelled" then myData.movement = nil display.getCurrentStage():setFocus( event.target, nil ) event.target.isFocus = false end return true end myData.DpadBack:addEventListener("touch", move) composer.gotoScene("IsometricComposer.scene")
34.976744
100
0.613032
62fc9a6630c7777d643f878b93a9da4de6a75d36
5,295
sql
SQL
Banco_dados/cria_banco_praticas_GS.sql
dvictori/GarantiaSafBancodeDados
add99117ac450605b0fa491bd97661fa5483223e
[ "MIT" ]
null
null
null
Banco_dados/cria_banco_praticas_GS.sql
dvictori/GarantiaSafBancodeDados
add99117ac450605b0fa491bd97661fa5483223e
[ "MIT" ]
null
null
null
Banco_dados/cria_banco_praticas_GS.sql
dvictori/GarantiaSafBancodeDados
add99117ac450605b0fa491bd97661fa5483223e
[ "MIT" ]
null
null
null
-- tabela dos sistemas CREATE TABLE sistema ( id_sistema INTEGER PRIMARY KEY NOT NULL, nome TEXT, descricao TEXT, complexidade TEXT, referencias TEXT, cartilha TEXT ); CREATE TABLE sistema_midia ( id_midia INTEGER PRIMARY KEY NOT NULL, id_sistema INTEGER, tipo INTEGER, arquivo TEXT, FOREIGN key(id_sistema) REFERENCES sistema(id_sistema) ); -- quais espécies vegetais entram em cada sistema CREATE TABLE sistema_especie ( id_sistema_especie INTEGER PRIMARY KEY NOT NULL, id_sistema INTEGER, id_especie INTEGER, posicao_especie TEXT, espacamento_entreplantas REAL, espacamento_entrelinhas REAL, FOREIGN KEY("id_especie") REFERENCES "especie_vegetal"("id_especie") ON DELETE NO ACTION, FOREIGN KEY("id_sistema") REFERENCES "sistema"("id_sistema") ON DELETE NO ACTION ); CREATE TABLE especie_vegetal ( id_especie INTEGER PRIMARY KEY NOT NULL, nome_cientifico TEXT, estrato TEXT, resiliencia INTEGER, ciclo_min INTEGER, ciclo_max INTEGER, alimento_humano TEXT, medicinal TEXT, bioma_caract TEXT ); CREATE TABLE nome_popular ( id_nome_pop INTEGER PRIMARY KEY NOT NULL, id_especie INTEGER NOT NULL, nome_pop TEXT NOT NULL, FOREIGN KEY(id_especie) REFERENCES especie_vegetal(id_especie) ON DELETE NO ACTION ); -- pragas que atacam as especies vegetais CREATE TABLE praga ( id_praga INTEGER PRIMARY KEY NOT NULL, praga_cientifico TEXT, descricao_praga TEXT, descricao_sintoma TEXT, foto TEXT -- será que não é possível ter só uma tabela de midia ); CREATE TABLE praga_pop ( id_praga_pop INTEGER PRIMARY KEY NOT NULL, id_praga INTEGER, praga_pop TEXT, FOREIGN KEY(id_praga) REFERENCES praga(id_praga) ON DELETE NO ACTION ); CREATE TABLE praga_especie ( id INTEGER PRIMARY KEY NOT NULL, id_praga INTEGER, id_especie INTEGER, FOREIGN KEY (id_praga) REFERENCES praga(id_praga), FOREIGN KEY (id_especie) REFERENCES especie_vegetal(id_especie) ); CREATE TABLE controle_praga ( id_ctrl_biologico INTEGER PRIMARY KEY NOT NULL, id_praga INTEGER, insumo_ctrl TEXT, descricao_crtl TEXT, biologico INTEGER, -- bolean? FOREIGN KEY(id_praga) REFERENCES praga(id_praga) ON DELETE NO ACTION ); -- sistema pode ter animais CREATE TABLE sistema_animal ( id_sistema_animal INTEGER PRIMARY KEY NOT NULL, id_sistema INTEGER, id_animal INTEGER, funcao_animal, ciclo, FOREIGN KEY(id_sistema) REFERENCES sistema(id_sistema), FOREIGN KEY(id_animal) REFERENCES animal(id_animal) ); -- não sei se precisa detalhar nome cientifico CREATE TABLE animal ( id_animal INTEGER PRIMARY KEY NOT NULL, nome TEXT, raca TEXT, exigencia_alimentacao TEXT ); CREATE TABLE patogeno ( id_patogeno INTEGER PRIMARY KEY NOT NULL, id_animal INTEGER, nome_cientifico TEXT, descricao TEXT, sintoma TEXT, foto TEXT, FOREIGN KEY(id_animal) REFERENCES animal(id_animal) ); CREATE TABLE patogeno_pop ( id_patogeno_pop INTEGER PRIMARY KEY NOT NULL, id_patogeno INTEGER, nome_popular TEXT, FOREIGN KEY(id_patogeno) REFERENCES patogeno(id_patogeno) ON DELETE NO ACTION ); CREATE TABLE controle_patogeno ( id_ctrl INTEGER PRIMARY KEY NOT NULL, id_patogeno INTEGER, insumo_ctrl TEXT, descricao_crtl TEXT, biologico INTEGER, -- bolean? FOREIGN KEY(id_patogeno) REFERENCES patogeno(id_patogeno) ON DELETE NO ACTION ); -- manejo de cultivo CREATE TABLE sitema_manejo_cultivo ( id INTEGER PRIMARY KEY NOT NULL, id_sistema INTEGER, id_manejo_cultivo INTEGER, epoca INTEGER, FOREIGN KEY(id_sistema) REFERENCES sistema(id_sistema), FOREIGN KEY(id_manejo_cultivo) REFERENCES manejo_cultivo(id) ); CREATE TABLE manejo_cultivo ( id INTEGER PRIMARY KEY NOT NULL, tipo TEXT, descricao_manejo TEXT, epoca INTEGER, periodicidade INTEGER, duracao_operacao INTEGER ); -- manejo do solo CREATE TABLE sistema_manejo_solo ( id INTEGER PRIMARY KEY NOT NULL, id_sistema INTEGER, id_manejo_solo INTEGER, epoca INTEGER, FOREIGN KEY(id_sistema) REFERENCES sistema(id_sistema), FOREIGN KEY(id_manejo_solo) REFERENCES manejo_solo(id) ); CREATE TABLE manejo_solo ( id INTEGER PRIMARY KEY NOT NULL, tipo TEXT, descricao TEXT, implemento TEXT, insumo TEXT, correcao TEXT ); -- solos que o sistema pode ser implantado CREATE TABLE sistema_solo ( id INTEGER PRIMARY KEY NOT NULL, id_sistema INTEGER, id_solo INTEGER, FOREIGN KEY(id_sistema) REFERENCES sistema(id_sistema), FOREIGN KEY(id_solo) REFERENCES solo(id) ); CREATE TABLE solo ( id INTEGER PRIMARY KEY NOT NULL, tipo_solo TEXT, granulometria TEXT, acidez TEXT, retencao_agua TEXT, potencialidades TEXT, deficiencias TEXT, classe_zarc INTEGER ); -- ZARC - identifica época de plantio -- da cultura principal do sistema -- Considera risco de 20%. -- Se município não tiver janela, vai p/ risco de 30% CREATE TABLE zarc ( id INTEGER PRIMARY KEY NOT NULL, id_sistema INTEGER, id_solo INTEGER, id_municipio INTEGER, inicio_plantio INTEGER, fim_plantio INTEGER, FOREIGN KEY(id_sistema) REFERENCES sistema(id_sistema), FOREIGN KEY(id_solo) REFERENCES solo(id), FOREIGN KEY(id_municipio) REFERENCES municipio(geocodigo) ); CREATE TABLE municipio ( geocodigo INTEGER PRIMARY KEY NOT NULL, nome TEXT, uf TEXT, bioma TEXT, geometria TEXT -- depois vira geom );
25.214286
91
0.767328
db167f96055486f988ff76c895a20ed6b9d3e956
1,203
sql
SQL
store/postgres/migrations/2018-07-10-061659_create_history_tables/up.sql
Tumble17/graph-node
a4315a33652391f453031a5412b6c51ba4ce084c
[ "Apache-2.0", "MIT" ]
1,811
2018-08-01T00:52:11.000Z
2022-03-31T17:56:57.000Z
store/postgres/migrations/2018-07-10-061659_create_history_tables/up.sql
Tumble17/graph-node
a4315a33652391f453031a5412b6c51ba4ce084c
[ "Apache-2.0", "MIT" ]
1,978
2018-08-01T17:00:43.000Z
2022-03-31T23:59:29.000Z
store/postgres/migrations/2018-07-10-061659_create_history_tables/up.sql
Tumble17/graph-node
a4315a33652391f453031a5412b6c51ba4ce084c
[ "Apache-2.0", "MIT" ]
516
2018-08-01T05:26:27.000Z
2022-03-31T14:04:19.000Z
/************************************************************** * CREATE TABLES **************************************************************/ -- Stores the metadata from each SQL transaction CREATE TABLE IF NOT EXISTS event_meta_data ( id SERIAL PRIMARY KEY, db_transaction_id BIGINT NOT NULL UNIQUE, db_transaction_time TIMESTAMP NOT NULL, op_id SMALLINT NOT NULL, source VARCHAR DEFAULT NULL ); -- Stores the row level data and changes (1 or more per SQL transaction) CREATE TABLE IF NOT EXISTS entity_history ( id SERIAL PRIMARY KEY, event_id BIGINT NOT NULL, entity_id VARCHAR NOT NULL, subgraph VARCHAR NOT NULL, entity VARCHAR NOT NULL, data_before JSONB, data_after JSONB, reversion BOOLEAN NOT NULL DEFAULT FALSE ); /************************************************************** * ADD FOREIGN KEYS **************************************************************/ -- Define relationship between event_meta_data and entity_history ALTER TABLE entity_history ADD CONSTRAINT entity_history_event_id_fkey FOREIGN KEY (event_id) REFERENCES event_meta_data(id) MATCH FULL ON DELETE CASCADE ON UPDATE CASCADE;
33.416667
72
0.583541
8d226633baae5f0d076ac90f6da2871f04a75e2e
1,837
sql
SQL
data/dzproject.dump.sqlite.sql
adrien-desfourneaux/DzProjectModule
fa39aca1ed2b2762fbf600af74a093cced6d3d6f
[ "MIT" ]
null
null
null
data/dzproject.dump.sqlite.sql
adrien-desfourneaux/DzProjectModule
fa39aca1ed2b2762fbf600af74a093cced6d3d6f
[ "MIT" ]
null
null
null
data/dzproject.dump.sqlite.sql
adrien-desfourneaux/DzProjectModule
fa39aca1ed2b2762fbf600af74a093cced6d3d6f
[ "MIT" ]
null
null
null
INSERT INTO project ( project_id, display_name, begin_date, end_date ) VALUES ( 1, 'Projet non débuté', strftime('%s', 'now', 'start of day', '-1 hour', '+6 months'), strftime('%s', 'now', 'start of day', '-1 hour', '+1 year') ); INSERT INTO project ( project_id, display_name, begin_date, end_date ) VALUES ( 2, "Projet qui débute aujourd'hui", strftime('%s', 'now', 'start of day', '-1 hour'), strftime('%s', 'now', 'start of day', '-1 hour', '+2 years') ); INSERT INTO project ( project_id, display_name, begin_date, end_date ) VALUES ( 3, 'Projet actif 1', strftime('%s', 'now', 'start of day', '-1 hour', '-1 day'), strftime('%s', 'now', 'start of day', '-1 hour', '+3 years') ); INSERT INTO project ( project_id, display_name, begin_date, end_date ) VALUES ( 4, 'Projet actif 2', strftime('%s', 'now', 'start of day', '-1 hour', '-1 day'), strftime('%s', 'now', 'start of day', '-1 hour', '+3 years') ); INSERT INTO project ( project_id, display_name, begin_date, end_date ) VALUES ( 5, "Projet qui se termine aujourd'hui", strftime('%s', 'now', 'start of day', '-1 hour', '-1 day'), strftime('%s', 'now', 'start of day', '-1 hour') ); INSERT INTO project ( project_id, display_name, begin_date, end_date ) VALUES ( 6, 'Projet terminé', strftime('%s', 'now', 'start of day', '-1 hour', '-2 days'), strftime('%s', 'now', 'start of day', '-1 hour', '-1 day') ); INSERT INTO project ( project_id, display_name, begin_date, end_date ) VALUES ( 7, 'Project actif 1 de Jean Michel', strftime('%s', 'now', 'start of day', '-1 hour', '-1 day'), strftime('%s', 'now', 'start of day', '-1 hour', '+3 years') );
21.869048
66
0.55362
f38ffb325097c5ebb3a59569d2510bff323cbeda
4,008
swift
Swift
ARLoad/ShareViewController.swift
DenisZubkov/ARClient
18538255507841088e5f39201ba25d0a5b395472
[ "MIT" ]
null
null
null
ARLoad/ShareViewController.swift
DenisZubkov/ARClient
18538255507841088e5f39201ba25d0a5b395472
[ "MIT" ]
null
null
null
ARLoad/ShareViewController.swift
DenisZubkov/ARClient
18538255507841088e5f39201ba25d0a5b395472
[ "MIT" ]
null
null
null
// // ShareViewController.swift // ARLoad // // Created by Dennis Zubkoff on 08.02.2020. // Copyright © 2020 Denis Zubkov. All rights reserved. // import UIKit import Social import MobileCoreServices import CoreData class ShareViewController: SLComposeServiceViewController { private var urlString: String? private var textString: String? let store = CoreDataStack.store override func viewDidLoad() { super.viewDidLoad() var imageFound = false for item in self.extensionContext!.inputItems as! [NSExtensionItem] { for provider in item.attachments! { if provider.hasItemConformingToTypeIdentifier(kUTTypeURL as String) { // This is an image. We'll load it, then place it in our image view. provider.loadItem(forTypeIdentifier: kUTTypeURL as String, options: nil, completionHandler: { (usdzURL, error) in OperationQueue.main.addOperation { if let usdzURL = usdzURL as? URL { var alert: UIAlertController! let filename = NSString(string: usdzURL.path).lastPathComponent guard filename.contains(".usdz") else { alert = UIAlertController(title: "Неверный формат", message: "По адресу \(usdzURL.absoluteString) нет USDZ файла", preferredStyle: .alert) let cancelAction = UIAlertAction(title: "OK", style: .destructive) { (action) in self.cancelBarButton() } alert.addAction(cancelAction) self.present(alert, animated: true) return } self.urlString = usdzURL.absoluteString self.placeholder = "Ввведите название для объекта:" //self.textView.text = usdzURL.lastPathComponent } } }) imageFound = true break } } if (imageFound) { // We only handle one image, so stop looking for more. break } } } @IBAction func cancelBarButton() { self.extensionContext!.completeRequest(returningItems: self.extensionContext!.inputItems, completionHandler: nil) } override func isContentValid() -> Bool { // Do validation of contentText and/or NSExtensionContext attachments here return true } override func didSelectPost() { guard let urlString = urlString, let url = URL(string: urlString) else { return } do { let data = try Data(contentsOf: url) let filename = url.lastPathComponent let comment = self.textView.text ?? "No comment" let name = filename.replacingOccurrences(of: ".usdz", with: "") store.storeLoadObject(name: name, url: url, data: data, date: Date(), filename: filename, comment: comment) } catch { print("No Data") } // Inform the host that we're done, so it un-blocks its UI. Note: Alternatively you could call super's -didSelectPost, which will similarly complete the extension context. self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil) } override func configurationItems() -> [Any]! { // To add configuration options via table cells at the bottom of the sheet, return an array of SLComposeSheetConfigurationItem here. return [] } }
41.75
179
0.533184
2a5e27e24c9ed38dacebc890eac45fdef560118d
2,028
java
Java
BlockTraceClient/src/main/java/me/alexanderhodes/blocktrace/client/model/ShipmentType.java
alexanderhodes/blocktrace
d014c2b25bff4b40b26363f8112e2c679e315a05
[ "Apache-2.0" ]
1
2022-03-02T13:42:29.000Z
2022-03-02T13:42:29.000Z
BlockTraceClient/src/main/java/me/alexanderhodes/blocktrace/client/model/ShipmentType.java
alexanderhodes/blocktrace
d014c2b25bff4b40b26363f8112e2c679e315a05
[ "Apache-2.0" ]
null
null
null
BlockTraceClient/src/main/java/me/alexanderhodes/blocktrace/client/model/ShipmentType.java
alexanderhodes/blocktrace
d014c2b25bff4b40b26363f8112e2c679e315a05
[ "Apache-2.0" ]
null
null
null
package me.alexanderhodes.blocktrace.client.model; import java.io.Serializable; /** * Created by alexa on 23.09.2017. */ public class ShipmentType implements Serializable { private static final long serialVersionUID = 1L; private long id; private String name; private int height; private int width; private int length; private double weight; private Product product; public ShipmentType () { } public ShipmentType (long id, String name, int height, int width, int length, double weight, Product product) { this.id = id; this.name = name; this.height = height; this.width = width; this.length = length; this.weight = weight; this.product = product; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getLength() { return length; } public void setLength(int length) { this.length = length; } public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; } public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ShipmentType that = (ShipmentType) o; return id == that.id; } @Override public int hashCode() { return (int) (id ^ (id >>> 32)); } }
19.314286
115
0.577416
e9370ec7dd5429f4e4d55962d8fc2dba44f2b5f7
1,029
go
Go
internal/app/controller/auth.go
Clivern/Hamster
b318bc4c138d091150185038992ca3ea13aa5e05
[ "MIT" ]
44
2018-10-02T21:11:46.000Z
2020-09-26T23:41:34.000Z
internal/app/controller/auth.go
Clivern/Hamster
b318bc4c138d091150185038992ca3ea13aa5e05
[ "MIT" ]
47
2018-09-23T19:30:21.000Z
2022-03-26T15:14:29.000Z
internal/app/controller/auth.go
Clivern/Hamster
b318bc4c138d091150185038992ca3ea13aa5e05
[ "MIT" ]
4
2018-11-27T14:30:03.000Z
2020-07-06T19:45:01.000Z
// Copyright 2018 Clivern. All rights reserved. // Use of this source code is governed by the MIT // license that can be found in the LICENSE file. package controller import ( "github.com/clivern/hamster/internal/app/pkg/github" "github.com/gin-gonic/gin" "os" ) // Auth controller func Auth(c *gin.Context) { githubOauth := &github.OAuthApp{ ClientID: os.Getenv("GithubAppClientID"), RedirectURI: os.Getenv("GithubAppRedirectURI"), AllowSignup: os.Getenv("GithubAppAllowSignup"), Scope: os.Getenv("GithubAppScope"), ClientSecret: os.Getenv("GithubAppClientSecret"), } state, err := c.Cookie("gh_oauth_state") if err == nil && state != "" { githubOauth.SetState(state) } ok, err := githubOauth.FetchAccessToken( c.DefaultQuery("code", ""), c.DefaultQuery("state", ""), ) if ok && err == nil { c.JSON(200, gin.H{ "status": "ok", "accessToken": githubOauth.GetAccessToken(), }) } else { c.JSON(200, gin.H{ "status": "not ok", "error": err.Error(), }) } }
21.893617
53
0.655977
e72cc58a2bf8c954d6b8c47a1f01168119cf53ee
251
js
JavaScript
reducers/index.js
EnzoAliatis/Little-boy
2196a3490e54332d87fbef10a156f64da0b57c09
[ "MIT" ]
21
2019-01-21T23:31:28.000Z
2019-03-18T17:20:23.000Z
reducers/index.js
EnzoAliatis/Little-boy
2196a3490e54332d87fbef10a156f64da0b57c09
[ "MIT" ]
2
2019-02-03T18:11:25.000Z
2019-02-04T20:50:34.000Z
reducers/index.js
EnzoAliatis/Little-boy
2196a3490e54332d87fbef10a156f64da0b57c09
[ "MIT" ]
null
null
null
import { combineReducers } from 'redux' import navigation from './navigation' import diaSemana from './diaSemana' import infoUser from './infoUser' const reducer = combineReducers({ navigation, diaSemana, infoUser }) export default reducer
15.6875
39
0.749004
fffd689592239c1c891cca7d922ae74ccde02a1d
902
html
HTML
manuscript/page-176/body.html
marvindanig/strange-case-of-dr-jekyll-and-mr-hyde
5cea7c3602de61d09775ae12b91f4caf9a503572
[ "CECILL-B" ]
2
2018-10-22T03:46:08.000Z
2019-01-19T23:03:27.000Z
manuscript/page-176/body.html
marvindanig/the-strange-case-of-dr-jekyll-and-mr-hyde
5cea7c3602de61d09775ae12b91f4caf9a503572
[ "CECILL-B" ]
null
null
null
manuscript/page-176/body.html
marvindanig/the-strange-case-of-dr-jekyll-and-mr-hyde
5cea7c3602de61d09775ae12b91f4caf9a503572
[ "CECILL-B" ]
null
null
null
<div class="leaf flex"><div class="inner justify"><p>The pleasures which I made haste to seek in my disguise were, as I have said, undignified; I would scarce use a harder term. But in the hands of Edward Hyde, they soon began to turn toward the monstrous. When I would come back from these excursions, I was often plunged into a kind of wonder at my vicarious depravity. This familiar that I called out of my own soul, and sent forth alone to do his good pleasure, was a being inherently malign and villainous; his every act and thought centred on self; drinking pleasure with bestial avidity from any degree of torture to another; relentless like a man of stone. Henry Jekyll stood at times aghast before the acts of Edward Hyde; but the situation was apart from ordinary laws, and insidiously relaxed the grasp of conscience. It was Hyde, after all, and Hyde alone, that was guilty.</p></div> </div>
902
902
0.782705
f07fc415bef3771ca87fd201519c50fb72b463fd
2,965
js
JavaScript
web/src/pages/HomePage/HomePage.js
zackmckenna/hackathon-7-13
a1367ea3d198e1aabedf7931928acc2886d9e75a
[ "MIT" ]
null
null
null
web/src/pages/HomePage/HomePage.js
zackmckenna/hackathon-7-13
a1367ea3d198e1aabedf7931928acc2886d9e75a
[ "MIT" ]
null
null
null
web/src/pages/HomePage/HomePage.js
zackmckenna/hackathon-7-13
a1367ea3d198e1aabedf7931928acc2886d9e75a
[ "MIT" ]
null
null
null
import { useState } from 'react' import { Link } from '@redwoodjs/router' import WikiCell from 'src/components/WikiCell' import PrettySearchButton from 'src/components/PrettySearchButton' import NavLayout from 'src/layouts/NavLayout' import PrettyHeader from 'src/components/PrettyHeader/PrettyHeader' import PrettyInput from 'src/components/PrettyInput/PrettyInput' const HomePage = () => { const [searchParam, setSearchParam] = useState(null) const [searchParamInput, setSearchParamInput] = useState('') const handleSearchParamInputChange = (e) => { e.preventDefault() setSearchParamInput(e.target.value) } const handleSubmitSearchParam = () => { setSearchParam(searchParamInput) setSearchParamInput('') } return ( <> <NavLayout handleSubmitSearchParam={handleSubmitSearchParam} handleSearchParamInputChange={handleSearchParamInputChange} > <section className="hero is-bold is-fullwidth is-fullheight is-primary"> <div className="hero-body"> <div className="container"> <h1 className="title is-size-1 has-text-centered">prettypedia</h1> <h2 className="subtitle has-text-centered">pretty. simple.</h2> {!searchParam && ( <div> <div className="column is-half is-offset-one-quarter" > <PrettyInput handleSubmitSearchParam={handleSubmitSearchParam} handleSearchParamInputChange={ handleSearchParamInputChange } /> </div> <div className="column has-text-centered"> <PrettySearchButton handleSubmitSearchParam={handleSubmitSearchParam} /> </div> </div> )} <div className="column m-b-3"> {searchParam && <WikiCell searchParam={searchParam} />} </div> <div className="column"> {searchParam && ( <div className="column is-half is-offset-one-quarter"> <div className="navbar-item"> <input placeholder="search again" onChange={(e) => handleSearchParamInputChange(e)} className="input m-r-1 has-addons" ></input> <a onClick={() => handleSubmitSearchParam()} className="button is-info" > <strong>Search</strong> </a> </div> </div> )} </div> </div> </div> </section> </NavLayout> </> ) } export default HomePage
34.08046
80
0.51602
98b637335b5806f30c0d480c004d4cfd363cf456
3,070
html
HTML
doc/html/protocol_m_b_progress_h_u_d_delegate-p.html
sunnycmf/MBProgressHUD
b45bc95c7098881910cac09c5b6b687b6312dda7
[ "MIT" ]
1
2015-08-29T09:04:55.000Z
2015-08-29T09:04:55.000Z
doc/html/protocol_m_b_progress_h_u_d_delegate-p.html
sunnycmf/MBProgressHUD
b45bc95c7098881910cac09c5b6b687b6312dda7
[ "MIT" ]
null
null
null
doc/html/protocol_m_b_progress_h_u_d_delegate-p.html
sunnycmf/MBProgressHUD
b45bc95c7098881910cac09c5b6b687b6312dda7
[ "MIT" ]
null
null
null
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>MBProgressHUD: &lt; MBProgressHUDDelegate &gt; Protocol Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"> <link href="doxygen.css" rel="stylesheet" type="text/css"> </head><body> <!-- Generated by Doxygen 1.5.8 --> <div class="navigation" id="top"> <div class="tabs"> <ul> <li><a href="index.html"><span>Main&nbsp;Page</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> </ul> </div> <div class="tabs"> <ul> <li><a href="annotated.html"><span>Class&nbsp;List</span></a></li> <li><a href="hierarchy.html"><span>Class&nbsp;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&nbsp;Members</span></a></li> </ul> </div> </div> <div class="contents"> <h1>&lt; MBProgressHUDDelegate &gt; Protocol Reference</h1><!-- doxytag: class="MBProgressHUDDelegate-p" -->Defines callback methods for <a class="el" href="interface_m_b_progress_h_u_d.html" title="Displays a simple HUD window containing a UIActivityIndicatorView and two optional...">MBProgressHUD</a> delegates. <a href="#_details">More...</a> <p> <code>#import &lt;<a class="el" href="_m_b_progress_h_u_d_8h-source.html">MBProgressHUD.h</a>&gt;</code> <p> Inherited by HudDemoViewController. <p> <p> <a href="protocol_m_b_progress_h_u_d_delegate-p-members.html">List of all members.</a><table border="0" cellpadding="0" cellspacing="0"> <tr><td></td></tr> <tr><td colspan="2"><br><h2>Public Member Functions</h2></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="anchor" name="249e40d64d6df30f2bf2f7fce209b9c7"></a><!-- doxytag: member="MBProgressHUDDelegate&#45;p::hudWasHidden" ref="249e40d64d6df30f2bf2f7fce209b9c7" args="()" --> (void)&nbsp;</td><td class="memItemRight" valign="bottom">- <a class="el" href="protocol_m_b_progress_h_u_d_delegate-p.html#249e40d64d6df30f2bf2f7fce209b9c7">hudWasHidden</a></td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">A callback function that is called after the hud was fully hidden from the screen. <br></td></tr> </table> <hr><a name="_details"></a><h2>Detailed Description</h2> Defines callback methods for <a class="el" href="interface_m_b_progress_h_u_d.html" title="Displays a simple HUD window containing a UIActivityIndicatorView and two optional...">MBProgressHUD</a> delegates. <hr>The documentation for this protocol was generated from the following file:<ul> <li>/Users/matej/Documents/Xcode/HudDemo/Classes/<a class="el" href="_m_b_progress_h_u_d_8h-source.html">MBProgressHUD.h</a></ul> </div> <hr size="1"><address style="text-align: right;"><small>Generated on Tue Jul 21 18:54:32 2009 for MBProgressHUD by&nbsp; <a href="http://www.doxygen.org/index.html"> <img src="doxygen.png" alt="doxygen" align="middle" border="0"></a> 1.5.8 </small></address> </body> </html>
60.196078
316
0.705537
dec0bee2fa0a4d5c95cd810ba014607abab7c339
8,800
rs
Rust
lib/rust/ensogl/core/src/display/scene/dom.rs
luna/luna
a1bf0974ceec6e1a47f371956598f81d18596e88
[ "Apache-2.0" ]
3,834
2015-01-05T08:24:37.000Z
2020-06-23T08:20:38.000Z
lib/rust/ensogl/core/src/display/scene/dom.rs
luna/luna
a1bf0974ceec6e1a47f371956598f81d18596e88
[ "Apache-2.0" ]
808
2015-02-19T03:43:32.000Z
2020-06-23T12:25:47.000Z
lib/rust/ensogl/core/src/display/scene/dom.rs
luna/luna
a1bf0974ceec6e1a47f371956598f81d18596e88
[ "Apache-2.0" ]
147
2015-02-06T09:39:34.000Z
2020-06-17T09:23:51.000Z
//! This module defines a DOM management utilities. use crate::display::object::traits::*; use crate::prelude::*; use web::traits::*; use crate::display::camera::camera2d::Projection; use crate::display::camera::Camera2d; use crate::display::symbol::dom::eps; use crate::display::symbol::dom::inverse_y_translation; use crate::display::symbol::DomSymbol; #[cfg(target_arch = "wasm32")] use crate::system::gpu::data::JsBufferView; use crate::system::web; #[cfg(target_arch = "wasm32")] use wasm_bindgen::prelude::wasm_bindgen; use web::HtmlDivElement; // =================== // === Js Bindings === // =================== #[cfg(target_arch = "wasm32")] mod js { use super::*; #[wasm_bindgen(inline_js = " function arr_to_css_matrix3d(a) { return `matrix3d(${a.join(',')})` } export function setup_perspective(dom, perspective) { dom.style.perspective = perspective + 'px'; } export function setup_camera_orthographic(dom, matrix_array) { dom.style.transform = arr_to_css_matrix3d(matrix_array); } export function setup_camera_perspective (dom, near, matrix_array) { let translateZ = 'translateZ(' + near + 'px)'; let matrix3d = arr_to_css_matrix3d(matrix_array); let transform = translateZ + matrix3d + 'translate(50%,50%)'; dom.style.transform = transform; } ")] extern "C" { // Setup perspective CSS 3D projection on DOM. #[allow(unsafe_code)] pub fn setup_perspective(dom: &web::JsValue, znear: &web::JsValue); // Setup Camera orthographic projection on DOM. #[allow(unsafe_code)] pub fn setup_camera_orthographic(dom: &web::JsValue, matrix_array: &web::JsValue); // Setup Camera perspective projection on DOM. #[allow(unsafe_code)] pub fn setup_camera_perspective( dom: &web::JsValue, near: &web::JsValue, matrix_array: &web::JsValue, ); } } #[cfg(target_arch = "wasm32")] #[allow(unsafe_code)] fn setup_camera_perspective(dom: &web::JsValue, near: f32, matrix: &Matrix4<f32>) { // Views to WASM memory are only valid as long the backing buffer isn't // resized. Check documentation of IntoFloat32ArrayView trait for more // details. unsafe { let matrix_array = matrix.js_buffer_view(); js::setup_camera_perspective(dom, &near.into(), &matrix_array) } } #[cfg(target_arch = "wasm32")] #[allow(unsafe_code)] fn setup_camera_orthographic(dom: &web::JsValue, matrix: &Matrix4<f32>) { // Views to WASM memory are only valid as long the backing buffer isn't // resized. Check documentation of IntoFloat32ArrayView trait for more // details. unsafe { let matrix_array = matrix.js_buffer_view(); js::setup_camera_orthographic(dom, &matrix_array) } } #[cfg(not(target_arch = "wasm32"))] mod js { use super::*; pub fn setup_perspective(_dom: &web::JsValue, _znear: &web::JsValue) {} } #[cfg(not(target_arch = "wasm32"))] fn setup_camera_perspective(_dom: &web::JsValue, _near: f32, _matrix: &Matrix4<f32>) {} #[cfg(not(target_arch = "wasm32"))] fn setup_camera_orthographic(_dom: &web::JsValue, _matrix: &Matrix4<f32>) {} // ============= // === Utils === // ============= /// Inverts Matrix Y coordinates. It's equivalent to scaling by (1.0, -1.0, 1.0). pub fn invert_y(mut m: Matrix4<f32>) -> Matrix4<f32> { // Negating the second column to invert Y. m.row_part_mut(1, 4).iter_mut().for_each(|a| *a = -*a); m } // ==================== // === DomSceneData === // ==================== /// Internal representation for `DomScene`. #[derive(Clone, Debug)] pub struct DomSceneData { /// The root dom element of this scene. pub dom: HtmlDivElement, /// The child div of the `dom` element with view-projection Css 3D transformations applied. pub view_projection_dom: HtmlDivElement, logger: Logger, } impl DomSceneData { /// Constructor. pub fn new(dom: HtmlDivElement, view_projection_dom: HtmlDivElement, logger: Logger) -> Self { Self { dom, view_projection_dom, logger } } } // ================ // === DomScene === // ================ /// `DomScene` is a renderer for `DomSymbol`s. It integrates with other rendering contexts, /// such as WebGL, by placing two HtmlElements in front and behind of the Canvas element, /// allowing the move `DomSymbol`s between these two layers, mimicking z-index ordering. /// /// Each DomScene is essentially an HTML `div` element covering the whole screen. /// It ignores all pointer events by setting `pointer-events: none`. /// See https://github.com/enso-org/enso/blob/develop/lib/rust/ensogl/doc/mouse-handling.md for details. /// We also set `position: absolute` because it is required for `z-index` property to work. /// /// To make use of its functionalities, the API user can create a `Css3dSystem` by using /// the `DomScene::new_system` method which creates and manages instances of /// `DomSymbol`s. #[derive(Clone, CloneRef, Debug, Shrinkwrap)] pub struct DomScene { data: Rc<DomSceneData>, } impl DomScene { /// Constructor. pub fn new(logger: impl AnyLogger) -> Self { let logger = Logger::new_sub(logger, "DomScene"); let dom = web::document.create_div_or_panic(); let view_projection_dom = web::document.create_div_or_panic(); dom.set_class_name("dom-scene-layer"); // z-index works on positioned elements only. dom.set_style_or_warn("position", "absolute"); dom.set_style_or_warn("top", "0px"); dom.set_style_or_warn("overflow", "hidden"); dom.set_style_or_warn("overflow", "hidden"); dom.set_style_or_warn("width", "100%"); dom.set_style_or_warn("height", "100%"); // We ignore pointer events to avoid stealing them from other DomScenes. // See https://github.com/enso-org/enso/blob/develop/lib/rust/ensogl/doc/mouse-handling.md. dom.set_style_or_warn("pointer-events", "none"); view_projection_dom.set_class_name("view_projection"); view_projection_dom.set_style_or_warn("width", "100%"); view_projection_dom.set_style_or_warn("height", "100%"); view_projection_dom.set_style_or_warn("transform-style", "preserve-3d"); dom.append_or_warn(&view_projection_dom); let data = DomSceneData::new(dom, view_projection_dom, logger); let data = Rc::new(data); Self { data } } /// Gets the number of children DomSymbols. pub fn children_number(&self) -> u32 { self.data.dom.children().length() } /// Sets the z-index of this DOM element. pub fn set_z_index(&self, z: i32) { self.data.dom.set_style_or_warn("z-index", z.to_string()); } /// Sets the CSS property `filter: grayscale({value})` on this element. A value of 0.0 displays /// the element normally. A value of 1.0 will make the element completely gray. pub fn filter_grayscale(&self, value: f32) { self.data.dom.set_style_or_warn("filter", format!("grayscale({})", value)); } /// Creates a new instance of DomSymbol and adds it to parent. pub fn manage(&self, object: &DomSymbol) { let dom = object.dom(); let data = &self.data; if object.is_visible() { self.view_projection_dom.append_or_warn(dom); } object.display_object().set_on_hide(f_!(dom.remove())); object.display_object().set_on_show(f__!([data,dom] { data.view_projection_dom.append_or_warn(&dom) })); } /// Update the objects to match the new camera's point of view. This function should be called /// only after camera position change. pub fn update_view_projection(&self, camera: &Camera2d) { if self.children_number() == 0 { return; } let trans_cam = camera.transform_matrix().try_inverse(); let trans_cam = trans_cam.expect("Camera's matrix is not invertible."); let trans_cam = trans_cam.map(eps); let trans_cam = inverse_y_translation(trans_cam); let half_dim = camera.screen().height / 2.0; let fovy_slope = camera.half_fovy_slope(); let near = half_dim / fovy_slope; match camera.projection() { Projection::Perspective { .. } => { js::setup_perspective(&self.data.dom, &near.into()); setup_camera_perspective(&self.data.view_projection_dom, near, &trans_cam); } Projection::Orthographic => { setup_camera_orthographic(&self.data.view_projection_dom, &trans_cam); } } } }
35.059761
104
0.635682
667feb4336fae34632eef1b8d84cfa11f1cb2c55
1,181
sql
SQL
data/gl/postgres/subdivisions_PL.postgres.sql
timshadel/subdivision-list
869415cee0886e34a1cb44e8a545a2e5a82aeb8c
[ "MIT" ]
26
2017-04-14T16:15:13.000Z
2021-11-20T17:41:39.000Z
data/gl/postgres/subdivisions_PL.postgres.sql
timshadel/subdivision-list
869415cee0886e34a1cb44e8a545a2e5a82aeb8c
[ "MIT" ]
null
null
null
data/gl/postgres/subdivisions_PL.postgres.sql
timshadel/subdivision-list
869415cee0886e34a1cb44e8a545a2e5a82aeb8c
[ "MIT" ]
15
2018-05-23T14:36:47.000Z
2021-11-04T08:26:20.000Z
CREATE TABLE subdivision_PL (id VARCHAR(6) NOT NULL, name VARCHAR(255), level VARCHAR(64) NOT NULL, PRIMARY KEY(id)); INSERT INTO "subdivision_PL" ("id", "name", "level") VALUES (E'PL-WP', E'Gran Polonia', E'voivodship'); INSERT INTO "subdivision_PL" ("id", "name", "level") VALUES (E'PL-KP', E'Cuiavia-Pomerania', E'voivodship'); INSERT INTO "subdivision_PL" ("id", "name", "level") VALUES (E'PL-MA', E'Pequena Polonia', E'voivodship'); INSERT INTO "subdivision_PL" ("id", "name", "level") VALUES (E'PL-DS', E'Baixa Silesia', E'voivodship'); INSERT INTO "subdivision_PL" ("id", "name", "level") VALUES (E'PL-LU', E'Voivodato de Lublin', E'voivodship'); INSERT INTO "subdivision_PL" ("id", "name", "level") VALUES (E'PL-LB', E'Lubusz', E'voivodship'); INSERT INTO "subdivision_PL" ("id", "name", "level") VALUES (E'PL-OP', E'Opole', E'voivodship'); INSERT INTO "subdivision_PL" ("id", "name", "level") VALUES (E'PL-SL', E'Voivodía da Silesia', E'voivodship'); INSERT INTO "subdivision_PL" ("id", "name", "level") VALUES (E'PL-WN', E'Varmia e Masuria', E'voivodship'); INSERT INTO "subdivision_PL" ("id", "name", "level") VALUES (E'PL-ZP', E'Pomerania Occidental', E'voivodship');
90.846154
117
0.677392
85c7ef14d55f006a8af50d72b515058588436044
655
js
JavaScript
src/router/index.js
cplasabas/davoh_admin
902111965776ad24f79d511be1fa1d45889dce95
[ "MIT" ]
null
null
null
src/router/index.js
cplasabas/davoh_admin
902111965776ad24f79d511be1fa1d45889dce95
[ "MIT" ]
null
null
null
src/router/index.js
cplasabas/davoh_admin
902111965776ad24f79d511be1fa1d45889dce95
[ "MIT" ]
null
null
null
import Vue from 'vue'; import store from '@/store/store'; import Router from 'vue-router'; import paths from './paths'; import NProgress from 'nprogress'; import 'nprogress/nprogress.css'; Vue.use(Router); const router = new Router({ base: '/', mode: 'history', linkActiveClass: 'active', routes: paths }); // router guards router.beforeEach((to, from, next) => { if (!to.name) { next({ path: '/404' }); } else if ((to.meta.requiresAuth && !store.state.isUserLogged) || (to.meta.requiresAdmin && store.state.user.type === 2)) { next({ path: '/403' }); } else { next(); } }); export default router;
19.848485
68
0.60916
33abd84ad6f622d8dabdc15fae57ce95b5458d47
5,692
swift
Swift
VisionSample/Controllers/ViewController.swift
davidiny/ShoeSleuth
2a1909f7b941d27085cafb8a588e4602f877a197
[ "MIT" ]
1
2019-12-06T02:30:13.000Z
2019-12-06T02:30:13.000Z
VisionSample/Controllers/ViewController.swift
davidiny/ShoeSleuth
2a1909f7b941d27085cafb8a588e4602f877a197
[ "MIT" ]
null
null
null
VisionSample/Controllers/ViewController.swift
davidiny/ShoeSleuth
2a1909f7b941d27085cafb8a588e4602f877a197
[ "MIT" ]
null
null
null
// // ViewController.swift // VisionSample // // Created by chris on 19/06/2017. // Copyright © 2017 MRM Brand Ltd. All rights reserved. // import UIKit import AVFoundation import Vision class ViewController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate { // video capture session let session = AVCaptureSession() // preview layer var previewLayer: AVCaptureVideoPreviewLayer! // queue for processing video frames let captureQueue = DispatchQueue(label: "captureQueue") // overlay layer var gradientLayer: CAGradientLayer! // vision request var visionRequests = [VNRequest]() var recognitionThreshold : Float = 0.25 @IBOutlet weak var thresholdStackView: UIStackView! @IBOutlet weak var threshholdLabel: UILabel! @IBOutlet weak var threshholdSlider: UISlider! @IBOutlet weak var previewView: UIView! @IBOutlet weak var resultView: UILabel! override func viewDidLoad() { super.viewDidLoad() // get hold of the default video camera guard let camera = AVCaptureDevice.default(for: .video) else { fatalError("No video camera available") } do { // add the preview layer previewLayer = AVCaptureVideoPreviewLayer(session: session) previewView.layer.addSublayer(previewLayer) // add a slight gradient overlay so we can read the results easily gradientLayer = CAGradientLayer() gradientLayer.colors = [ UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.7).cgColor, UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.0).cgColor, ] gradientLayer.locations = [0.0, 0.3] self.previewView.layer.addSublayer(gradientLayer) // create the capture input and the video output let cameraInput = try AVCaptureDeviceInput(device: camera) let videoOutput = AVCaptureVideoDataOutput() videoOutput.setSampleBufferDelegate(self, queue: captureQueue) videoOutput.alwaysDiscardsLateVideoFrames = true videoOutput.videoSettings = [kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA] session.sessionPreset = .high // wire up the session session.addInput(cameraInput) session.addOutput(videoOutput) // make sure we are in portrait mode let conn = videoOutput.connection(with: .video) conn?.videoOrientation = .portrait // Start the session session.startRunning() // set up the vision model guard let resNet50Model = try? VNCoreMLModel(for: ShoeSleuthModel().model) else { fatalError("Could not load model") } // set up the request using our vision model let classificationRequest = VNCoreMLRequest(model: resNet50Model, completionHandler: handleClassifications) classificationRequest.imageCropAndScaleOption = .centerCrop visionRequests = [classificationRequest] } catch { fatalError(error.localizedDescription) } updateThreshholdLabel() } func updateThreshholdLabel () { self.threshholdLabel.text = "Threshold: " + String(format: "%.2f", recognitionThreshold) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() previewLayer.frame = self.previewView.bounds; gradientLayer.frame = self.previewView.bounds; let orientation: UIDeviceOrientation = UIDevice.current.orientation; switch (orientation) { case .portrait: previewLayer?.connection?.videoOrientation = .portrait case .landscapeRight: previewLayer?.connection?.videoOrientation = .landscapeLeft case .landscapeLeft: previewLayer?.connection?.videoOrientation = .landscapeRight case .portraitUpsideDown: previewLayer?.connection?.videoOrientation = .portraitUpsideDown default: previewLayer?.connection?.videoOrientation = .portrait } } func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) { guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return } connection.videoOrientation = .portrait var requestOptions:[VNImageOption: Any] = [:] if let cameraIntrinsicData = CMGetAttachment(sampleBuffer, kCMSampleBufferAttachmentKey_CameraIntrinsicMatrix, nil) { requestOptions = [.cameraIntrinsics: cameraIntrinsicData] } // for orientation see kCGImagePropertyOrientation let imageRequestHandler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, orientation: .upMirrored, options: requestOptions) do { try imageRequestHandler.perform(self.visionRequests) } catch { print(error) } } @IBAction func userTapped(sender: Any) { self.thresholdStackView.isHidden = !self.thresholdStackView.isHidden } @IBAction func sliderValueChanged(slider: UISlider) { self.recognitionThreshold = slider.value updateThreshholdLabel() } func handleClassifications(request: VNRequest, error: Error?) { if let theError = error { print("Error: \(theError.localizedDescription)") return } guard let observations = request.results else { print("No results") return } let classifications = observations[0...2] // top 4 results .flatMap({ $0 as? VNClassificationObservation }) .flatMap({$0.confidence > recognitionThreshold ? $0 : nil}) .map({ "\($0.identifier) \(String(format:"%.2f", $0.confidence))" }) .joined(separator: "\n") DispatchQueue.main.async { self.resultView.text = classifications } } }
34.289157
130
0.694308
e52bd12107e35b84a6202129ae95bd6a73fb6739
360
tsx
TypeScript
src/components/Header.tsx
zrh617/PocketBookkeeping
e51a2d9f33ee930d4bc94fc71ab9739607f4f966
[ "MIT" ]
null
null
null
src/components/Header.tsx
zrh617/PocketBookkeeping
e51a2d9f33ee930d4bc94fc71ab9739607f4f966
[ "MIT" ]
null
null
null
src/components/Header.tsx
zrh617/PocketBookkeeping
e51a2d9f33ee930d4bc94fc71ab9739607f4f966
[ "MIT" ]
null
null
null
import React from 'react'; import styled from 'styled-components'; const Head = styled.div` line-height: 40px; background:cadetblue; ` const Content = styled.div` text-align: center; font-size: 20px; padding: 10px 0; color: #fff; ` export const Header = () => { return( <Head> <Content> 口袋记账 </Content> </Head> ) }
15.652174
39
0.611111
6db06acdd68081b851b2d8e309c6e9996878ec04
326
swift
Swift
Atsam/Preference/IPreference.swift
IniongunIsaac/Atsam-iOS
fa7f0471913aed0d09aea2e59196827207b584ce
[ "Unlicense" ]
null
null
null
Atsam/Preference/IPreference.swift
IniongunIsaac/Atsam-iOS
fa7f0471913aed0d09aea2e59196827207b584ce
[ "Unlicense" ]
null
null
null
Atsam/Preference/IPreference.swift
IniongunIsaac/Atsam-iOS
fa7f0471913aed0d09aea2e59196827207b584ce
[ "Unlicense" ]
null
null
null
// // IPreference.swift // Tiv Bible // // Created by Isaac Iniongun on 22/05/2020. // Copyright © 2020 Iniongun Group. All rights reserved. // import Foundation protocol IPreference { var isDBInitialized: Bool { get set } var stayAwake: Bool { get set } var appVersion: String { get } }
16.3
57
0.631902
3f1ffcb38be42b9cce6fc6e2c14e350512319ddf
1,697
sql
SQL
config/database/migrations/000010_create_migrations_table.up.sql
MohammedAl-Mahdawi/bnkr
2ee08790d729719ca3dd91ae712e4bba6903d8c8
[ "MIT" ]
3
2021-06-20T20:40:15.000Z
2022-01-11T06:42:34.000Z
config/database/migrations/000010_create_migrations_table.up.sql
MohammedAl-Mahdawi/bnkr
2ee08790d729719ca3dd91ae712e4bba6903d8c8
[ "MIT" ]
null
null
null
config/database/migrations/000010_create_migrations_table.up.sql
MohammedAl-Mahdawi/bnkr
2ee08790d729719ca3dd91ae712e4bba6903d8c8
[ "MIT" ]
null
null
null
CREATE TABLE IF NOT EXISTS public.migrations ( id bigserial NOT NULL, created_at timestamptz NULL, updated_at timestamptz NULL, deleted_at timestamptz NULL, started_at timestamptz NULL, completed_at timestamptz NULL, "name" text NOT NULL, "user" int8 NOT NULL, timezone text NULL, emails text NULL, src_type text NOT NULL, dest_type text NOT NULL, src_access text NOT NULL, dest_access text NOT NULL, dest_bucket text NULL, src_bucket text NULL, src_files_path text NULL, src_s3_access_key text NULL, src_s3_secret_key text NULL, src_s3_file text NULL, src_ssh_host text NULL, src_ssh_port text NULL, src_ssh_user text NULL, src_ssh_key text NULL, src_kubeconfig text NULL, src_db_password text NULL, src_db_port text NULL, src_db_name text NULL, src_db_user text NULL, src_db_host text NULL, src_pod_label text NULL, src_container text NULL, src_pod_name text NULL, src_region text NULL, src_uri text NULL, dest_files_path text NULL, dest_s3_access_key text NULL, dest_s3_secret_key text NULL, dest_region text NULL, dest_storage_directory text NULL, dest_ssh_host text NULL, dest_ssh_port text NULL, dest_ssh_user text NULL, dest_ssh_key text NULL, dest_kubeconfig text NULL, dest_db_password text NULL, dest_db_port text NULL, dest_db_name text NULL, dest_db_user text NULL, dest_db_host text NULL, dest_pod_label text NULL, dest_container text NULL, dest_pod_name text NULL, dest_uri text NULL, status text NULL, "output" text NULL, CONSTRAINT migrations_pkey PRIMARY KEY (id) ); CREATE INDEX IF NOT EXISTS idx_migrations_deleted_at ON public.migrations USING btree (deleted_at);
28.283333
99
0.773718
8304acf2e3b53b1816684efc13cde37061ad4ea5
337
sql
SQL
orcas_core/build_source/orcas_db_objects/packages/h_pa_orcas_clean.sql
llsand/orcas
273bb591432d8bdbd535ccd3086e18e927ee9b38
[ "Apache-2.0" ]
null
null
null
orcas_core/build_source/orcas_db_objects/packages/h_pa_orcas_clean.sql
llsand/orcas
273bb591432d8bdbd535ccd3086e18e927ee9b38
[ "Apache-2.0" ]
null
null
null
orcas_core/build_source/orcas_db_objects/packages/h_pa_orcas_clean.sql
llsand/orcas
273bb591432d8bdbd535ccd3086e18e927ee9b38
[ "Apache-2.0" ]
null
null
null
CREATE OR REPLACE package pa_orcas_clean authid current_user is /** * Loescht alle DDL daten zu der Tabelle, bis auf Saplten und die Tabelle selbst. */ procedure clean_table( p_table_name in varchar2 ); /** * Loescht alle DDL daten zu allen Tabelle, bis auf Saplten und die Tabellen selbst. */ procedure clean_all_tables; end; /
21.0625
84
0.756677
a9fe2f1c4a41a16f102ec8128fdd6a2aaad0b58b
99
sql
SQL
microservices/ga/datamgr/dev/db/organizationAdmin.sql
shgayle/templates
d62a6bde70768ea02f14a3f145bbe024a1f73033
[ "Apache-2.0" ]
null
null
null
microservices/ga/datamgr/dev/db/organizationAdmin.sql
shgayle/templates
d62a6bde70768ea02f14a3f145bbe024a1f73033
[ "Apache-2.0" ]
null
null
null
microservices/ga/datamgr/dev/db/organizationAdmin.sql
shgayle/templates
d62a6bde70768ea02f14a3f145bbe024a1f73033
[ "Apache-2.0" ]
null
null
null
{{define "dev/db/organizationAdmin.sql"}} CREATE USER IF NOT EXISTS {{.OrgSQLSafe}}Admin; {{end}}
19.8
47
0.707071
86427ff283a01ca0a4ea30a3536c33d5a8d7b3be
1,029
rs
Rust
crates/mun_codegen/src/ir/adt.rs
joshuawarner32/mun
519b8b10e9c9d93c94af1ea4e6e3899b85f6f537
[ "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
crates/mun_codegen/src/ir/adt.rs
joshuawarner32/mun
519b8b10e9c9d93c94af1ea4e6e3899b85f6f537
[ "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
crates/mun_codegen/src/ir/adt.rs
joshuawarner32/mun
519b8b10e9c9d93c94af1ea4e6e3899b85f6f537
[ "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
//use crate::ir::module::Types; use inkwell::context::Context; use crate::ir::try_convert_any_to_basic; use crate::{CodeGenParams, CodegenContext}; use inkwell::types::{BasicTypeEnum, StructType}; pub(super) fn gen_struct_decl<'ink, D: hir::HirDatabase>(context: &'ink Context, db: &mut CodegenContext<'ink, D>, s: hir::Struct) -> StructType<'ink> { let struct_type = db.struct_ty(context, s); if struct_type.is_opaque() { let field_types: Vec<BasicTypeEnum> = s .fields(db.hir_db()) .iter() .map(|field| { let field_type = field.ty(db.hir_db()); try_convert_any_to_basic(db.type_ir( context, field_type, CodeGenParams { make_marshallable: false, }, )) .expect("could not convert field type") }) .collect(); struct_type.set_body(&field_types, false); } struct_type }
34.3
152
0.550049
f0e7349c2b633b411ca8d58d4269d5af44a19dc4
434
kt
Kotlin
Compose/CryptoCurrencyApp/app/src/main/java/com/example/cryptocurrency/data/remote/CoinPaprikaApi.kt
PierreVieira/AndroidApps
a59c8149dfe04893701ba9afa3454e1a32a4b453
[ "MIT" ]
null
null
null
Compose/CryptoCurrencyApp/app/src/main/java/com/example/cryptocurrency/data/remote/CoinPaprikaApi.kt
PierreVieira/AndroidApps
a59c8149dfe04893701ba9afa3454e1a32a4b453
[ "MIT" ]
null
null
null
Compose/CryptoCurrencyApp/app/src/main/java/com/example/cryptocurrency/data/remote/CoinPaprikaApi.kt
PierreVieira/AndroidApps
a59c8149dfe04893701ba9afa3454e1a32a4b453
[ "MIT" ]
null
null
null
package com.example.cryptocurrency.data.remote import com.example.cryptocurrency.data.remote.dto.CoinDto import com.example.cryptocurrency.data.remote.dto.coinDetail.CoinDetailDto import retrofit2.http.GET import retrofit2.http.Path interface CoinPaprikaApi { @GET("v1/coins") suspend fun getCoins(): List<CoinDto> @GET("/v1/coins/{coinId}") suspend fun getCoinById(@Path("coinId") coinId: String): CoinDetailDto }
28.933333
74
0.774194
b9a2daa4c2149a1bbcfc778e13f309d3e25a2893
1,084
h
C
msf_localization_ros/src/include/msf_localization_ros/ros_imu_input_interface.h
Ahrovan/msf_localization
a78ba2473115234910789617e9b45262ebf1d13d
[ "BSD-3-Clause" ]
1
2021-02-27T15:23:13.000Z
2021-02-27T15:23:13.000Z
msf_localization_ros/src/include/msf_localization_ros/ros_imu_input_interface.h
Ahrovan/msf_localization
a78ba2473115234910789617e9b45262ebf1d13d
[ "BSD-3-Clause" ]
null
null
null
msf_localization_ros/src/include/msf_localization_ros/ros_imu_input_interface.h
Ahrovan/msf_localization
a78ba2473115234910789617e9b45262ebf1d13d
[ "BSD-3-Clause" ]
null
null
null
#ifndef _ROS_IMU_INPUT_INTERFACE_H #define _ROS_IMU_INPUT_INTERFACE_H // ROS Msg sensor_msgs::Imu #include <sensor_msgs/Imu.h> // Time Stamp #include "time_stamp/time_stamp.h" #include "msf_localization_ros/ros_input_interface.h" #include "msf_localization_core/imu_input_core.h" #include "pugixml/pugixml.hpp" class RosImuInputInterface : public RosInputInterface, public ImuInputCore { public: RosImuInputInterface(ros::NodeHandle* nh, tf::TransformBroadcaster *tf_transform_broadcaster, MsfLocalizationCore* msf_localization_core_ptr); ~RosImuInputInterface(); public: int setInputCommandRos(const sensor_msgs::ImuConstPtr& msg); // Subscriber protected: std::string imu_topic_name_; protected: ros::Subscriber imu_topic_subs_; void imuTopicCallback(const sensor_msgs::ImuConstPtr& msg); public: int setImuTopicName(const std::string imu_topic_name); public: int open(); public: int publish(); public: int readConfig(const pugi::xml_node& input, std::shared_ptr<ImuInputStateCore>& init_state_core); }; #endif
18.066667
146
0.76845
719fed96c6b50df7fdac3467a48cc6d0ef98bf01
154
ts
TypeScript
src/core/tags/embed.ts
the-yamiteru/susskind
c19176d3506264e4788c8a87aa436a27d54eeaf1
[ "MIT" ]
null
null
null
src/core/tags/embed.ts
the-yamiteru/susskind
c19176d3506264e4788c8a87aa436a27d54eeaf1
[ "MIT" ]
16
2021-08-18T20:18:54.000Z
2021-08-23T20:56:52.000Z
src/core/tags/embed.ts
the-yamiteru/susskind
c19176d3506264e4788c8a87aa436a27d54eeaf1
[ "MIT" ]
null
null
null
import { DoubleTag } from "../utils"; export const Embed = DoubleTag<{ height?: number; src: string; type?: string; width?: number; }>("embed");
17.111111
37
0.623377
0bd46f530ce829b26b935590a2340424d2f14991
379
js
JavaScript
demos/01-installation/app.js
Remi-Potvin/node-advanced-2020
889979942a4c5b13f4089c4d7d28b639c60f1962
[ "MIT" ]
null
null
null
demos/01-installation/app.js
Remi-Potvin/node-advanced-2020
889979942a4c5b13f4089c4d7d28b639c60f1962
[ "MIT" ]
null
null
null
demos/01-installation/app.js
Remi-Potvin/node-advanced-2020
889979942a4c5b13f4089c4d7d28b639c60f1962
[ "MIT" ]
null
null
null
const express = require('express'); const app = express(); //Définition d'une route app.get('/', (req,res,next) => { console.log(req.hostname); res.send('Hello world') }) app.get('/users/:name/:id', (req,res) => { // res.send('user' + req.params.name) res.json(req.params) }) app.listen(8001,()=> { console.log('Application started and listening on port 8001'); })
19.947368
64
0.633245
e8eddcc6db8f095a1b5c31a80b5070f8e6370b63
4,995
swift
Swift
EnglishCommunity-swift-master/EnglishCommunity-swift/Classes/Module/Profile/Controller/Message/JFMessageListViewController.swift
BobJing/Just-a-test
2016b0f5b87b2686820a6bc9e2405fa77617dc69
[ "MIT" ]
3
2016-10-10T02:48:28.000Z
2017-12-28T16:30:55.000Z
EnglishCommunity-swift-master/EnglishCommunity-swift/Classes/Module/Profile/Controller/Message/JFMessageListViewController.swift
BobJing/Just-a-test
2016b0f5b87b2686820a6bc9e2405fa77617dc69
[ "MIT" ]
null
null
null
EnglishCommunity-swift-master/EnglishCommunity-swift/Classes/Module/Profile/Controller/Message/JFMessageListViewController.swift
BobJing/Just-a-test
2016b0f5b87b2686820a6bc9e2405fa77617dc69
[ "MIT" ]
null
null
null
// // JFMessageListViewController.swift // BaoKanIOS // // Created by zhoujianfeng on 16/5/23. // Copyright © 2016年 六阿哥. All rights reserved. // import UIKit import MJRefresh class JFMessageListViewController: UITableViewController { var messageRecords = [JFMessageRecord]() let messageRecordIdentifier = "messageRecordIdentifier" var pageIndex = 1 override func viewDidLoad() { super.viewDidLoad() title = "消息中心" tableView.backgroundColor = COLOR_ALL_BG tableView.separatorStyle = .None tableView.registerClass(JFMessageRecordCell.classForCoder(), forCellReuseIdentifier: messageRecordIdentifier) tableView.mj_header = setupHeaderRefresh(self, action: #selector(updateNewData)) tableView.mj_footer = setupFooterRefresh(self, action: #selector(loadMoreData)) tableView.mj_header.beginRefreshing() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(false, animated: true) } /** 下拉加载最新数据 */ @objc private func updateNewData() { loadNews(1, method: 0) } /** 上拉加载更多数据 */ @objc private func loadMoreData() { pageIndex += 1 loadNews(pageIndex, method: 1) } /** 根据分类id、页码加载数据 - parameter pageIndex: 当前页码 - parameter method: 加载方式 0下拉加载最新 1上拉加载更多 */ private func loadNews(pageIndex: Int, method: Int) { JFMessageRecord.getMessageList(pageIndex) { (messageRecords) in self.tableView.mj_header.endRefreshing() self.tableView.mj_footer.endRefreshing() guard let messageRecords = messageRecords else { return } if method == 0 { self.messageRecords = messageRecords } else { self.messageRecords += messageRecords } self.tableView.reloadData() } } } // MARK: - Table view data source extension JFMessageListViewController { override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return messageRecords.count } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let messageRecord = messageRecords[indexPath.row] if Int(messageRecord.rowHeight) == 0 { let cell = tableView.dequeueReusableCellWithIdentifier(messageRecordIdentifier) as! JFMessageRecordCell let height = cell.getRowHeight(messageRecord) messageRecord.rowHeight = height } return messageRecord.rowHeight } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(messageRecordIdentifier) as! JFMessageRecordCell cell.messageRecord = messageRecords[indexPath.row] cell.delegate = self return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) let messageRecord = messageRecords[indexPath.row] if messageRecord.type == "tweet" { JFProgressHUD.showWithStatus("正在加载") JFTweet.loadTrendsDetail(messageRecord.sourceId, finished: { (tweet) in JFProgressHUD.dismiss() guard let tweet = tweet else { return } let detailVc = JFTweetDetailViewController() detailVc.tweet = tweet self.navigationController?.pushViewController(detailVc, animated: true) }) } else { JFProgressHUD.showWithStatus("正在加载") JFVideoInfo.loadVideoInfoDetail(messageRecord.sourceId, finished: { (videoInfo) in JFProgressHUD.dismiss() guard let videoInfo = videoInfo else { return } let playerVc = JFPlayerViewController() playerVc.videoInfo = videoInfo self.navigationController?.pushViewController(playerVc, animated: true) }) } } } // MARK: - JFMessageRecordCellDelegate extension JFMessageListViewController: JFMessageRecordCellDelegate { func messageRecordCell(cell: JFMessageRecordCell, didTappedAvatarButton button: UIButton) { guard let byUser = cell.messageRecord?.byUser else { return } let otherUser = JFOtherUserViewController() otherUser.userId = byUser.id navigationController?.pushViewController(otherUser, animated: true) } }
32.861842
118
0.624424
76e75997a039e6db92c66038c239d4c38bf5ceec
954
h
C
src/rendering/utility/containers/VertexAttributeInfo.h
halfmvsq/antropy
41e6f485a3914bae6a5ad90d60578b028b573d01
[ "Apache-2.0" ]
null
null
null
src/rendering/utility/containers/VertexAttributeInfo.h
halfmvsq/antropy
41e6f485a3914bae6a5ad90d60578b028b573d01
[ "Apache-2.0" ]
null
null
null
src/rendering/utility/containers/VertexAttributeInfo.h
halfmvsq/antropy
41e6f485a3914bae6a5ad90d60578b028b573d01
[ "Apache-2.0" ]
null
null
null
#ifndef VERTEX_ATTRIBUTE_INFO_H #define VERTEX_ATTRIBUTE_INFO_H #include "rendering/utility/gl/GLBufferTypes.h" #include "rendering/utility/gl/GLDrawTypes.h" class VertexAttributeInfo { public: VertexAttributeInfo( BufferComponentType componentType, BufferNormalizeValues normalizeValues, int numComponents, int strideInBytes, int offsetInBytes, uint64_t vertexCount ); BufferComponentType componentType() const; BufferNormalizeValues normalizeValues() const; int numComponents() const; int strideInBytes() const; int offsetInBytes() const; uint64_t vertexCount() const; void setVertexCount( uint64_t n ); private: BufferComponentType m_componentType; BufferNormalizeValues m_normalizeValues; int m_numComponents; int m_strideInBytes; int m_offsetInBytes; uint64_t m_vertexCount; }; #endif // VERTEX_ATTRIBUTE_INFO_H
23.85
50
0.725367
9a2997f80da149a91a4f8af2760a28405c4708ca
2,287
css
CSS
src/assets/thirdIcon/iconfont.css
CrazyJack262/vue-admin-jack
38d9f33457c5f36f2aa270fadd886b892e23b857
[ "MIT" ]
5
2020-07-02T07:17:47.000Z
2021-02-23T09:30:05.000Z
src/assets/thirdIcon/iconfont.css
CrazyJack262/vue-admin-jack
38d9f33457c5f36f2aa270fadd886b892e23b857
[ "MIT" ]
null
null
null
src/assets/thirdIcon/iconfont.css
CrazyJack262/vue-admin-jack
38d9f33457c5f36f2aa270fadd886b892e23b857
[ "MIT" ]
1
2020-09-29T15:56:49.000Z
2020-09-29T15:56:49.000Z
@font-face {font-family: "iconfont"; src: url('iconfont.eot?t=1592384894566'); /* IE9 */ src: url('iconfont.eot?t=1592384894566#iefix') format('embedded-opentype'), /* IE6-IE8 */ url('data:application/x-font-woff2;charset=utf-8;base64,d09GMgABAAAAAAOUAAsAAAAAB+QAAANIAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHEIGVgCDHAqDIIJmATYCJAMQCwoABCAFhG0HRRvVBsiemjwJACiQAFC7gZMJBE//a6933swuB1ElBSRNSH9dkGUBZT35CtNTzwpI9f/fWpvDPGkaHu3EEm5prfqfWbubfbP/LCKarUQemUgmRAjN00UlO4E1hP/nmOlSPL/N5lJNlUV7A5xF6sA6cU0T3UAOzG8Yu4nyIM5DgJhG8mTWrDvRyAAGmCaAnD7BbTKQEmM1sUKI4JesNaQHj9C1undAN/+9fGOWhODwFDB3/dFdj2x87CPN5XPspgiY4ykBbRMoMAWCgRwvVR+kO3RPoZvYGdzDPAghIQ7G6umjfF5iAIHUMvfxj+dQEB8pOgVgjuhR+DiLyRD4mCXDwcdiFArwQiQhd+TNgBEZW3+gIOi4+kprvsSfxobitvLyw+yOJw6QG0yOHL4fpfu1V1Udg4cnw5JVVl4abX+WexqnjuDanoumuOxFUqDUoqHcet424fA9mwdGKzoM3MZPZfKL7PJWrmtDfcTlBuLCtiHxsuGkYHg4G4rTtqfVNvosKWp/UafZUMM9Tdslr7GuXKnqmta9yeJEbaRbNpXxtein5eXMP7hetKZxZ/w6ezYLXq44str4+0cW31mYO3qT+gdzS94P17asTzSv3Hx7xcrJl+C6/zYcDTsxsmPRq/XXRq/5r8qfW4c9L+/kEW/9Fs4DEvW6+wd5CrNXQEDv67bf9jec+15bbo4v+R0mBsCH8f93ZWOe0U5I3j2zNfMnMVuWmcsGEjObgxme1lh+q1McEBMDv8YPpXyOIapoHQ1CSEUMjoAGUEKakIadAh4Jc8AnZDnETGZ/c0IZkm7EImASlwIIxTyDo5DXoBTzjjTsB3hU8gU+xaIQs1XK9kwYJyfi1RfBRvCo06GBK+oMyXAoiFWAN2JbJtkcZ4BMAxutTJuR9e1DHeQYC9ImryIyyqSo0T3hMohjQRMpQnCx6CMmS6XpR8veVHRFjQyxGglggwAeFIcOlAAXQR1GqyNDue8rAJwGMTaypqRDaQBIUoL+KRWKlFsg9wX1ViXXck1KE04VBGFQGBJBDcqeoARi6BZQkvJRIYALUsTv4UxYoiRVYm0FxflFtSfcBMSAl5g4UTHxCKYehhgQBqce8LyCK5JO79QjXoCEAA==') format('woff2'), url('iconfont.woff?t=1592384894566') format('woff'), url('iconfont.ttf?t=1592384894566') format('truetype'), /* chrome, firefox, opera, Safari, Android, iOS 4.2+ */ url('iconfont.svg?t=1592384894566#iconfont') format('svg'); /* iOS 4.1- */ } .iconfont { font-family: "iconfont" !important; font-size: 16px; font-style: normal; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } [class^="el-third-icon"], [class*=" el-third-icon"]/*这里有空格*/ { font-family: "iconfont" !important; font-size: 14px; font-style: normal; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } .el-third-icon-delete:before { content: "\e61a"; } .el-third-icon-add-copy:before { content: "\e62a"; } .el-third-icon-edit:before { content: "\e62e"; }
60.184211
1,301
0.831657
40e44163d610e4ed85228af51784dd8b8fc44616
387
py
Python
src/test/resources/beta_1_1_1/Sample.py
hyamamoto/hackerrank-core
e38abdf2b9466ce5f064136bf73f7fb7f2b96c65
[ "MS-PL", "Naumen", "Condor-1.1", "Apache-1.1" ]
1
2015-10-01T09:11:01.000Z
2015-10-01T09:11:01.000Z
src/test/resources/beta_1_1_1/Sample.py
hyamamoto/hackerrank-core
e38abdf2b9466ce5f064136bf73f7fb7f2b96c65
[ "MS-PL", "Naumen", "Condor-1.1", "Apache-1.1" ]
1
2021-06-04T01:03:42.000Z
2021-06-04T01:03:42.000Z
src/test/resources/beta_1_1_1/Sample.py
hyamamoto/hackerrank-core
e38abdf2b9466ce5f064136bf73f7fb7f2b96c65
[ "MS-PL", "Naumen", "Condor-1.1", "Apache-1.1" ]
2
2015-10-01T09:11:04.000Z
2016-08-31T07:49:14.000Z
#!/bin/python #If player is X, I'm the first player. #If player is O, I'm the second player. player = raw_input() #Read the board now. The board is a 3x3 array filled with X, O or _. board = [] for i in xrange(0, 3): board.append(raw_input()) #Proceed with processing and print 2 integers separated by a single space. #Example: print random.randint(0, 2), random.randint(0, 2)
22.764706
74
0.697674
bdcd94bfd06332f98de1f6147352bd6c45dd291f
202
kt
Kotlin
app/src/main/java/com/ilab/yougetmobiledl/model/BangumiDualStream.kt
zhushenwudi/YougetMobileDL
1755a1e5971a017b0f44c4df3e9491ae46a8d2fc
[ "MIT" ]
null
null
null
app/src/main/java/com/ilab/yougetmobiledl/model/BangumiDualStream.kt
zhushenwudi/YougetMobileDL
1755a1e5971a017b0f44c4df3e9491ae46a8d2fc
[ "MIT" ]
null
null
null
app/src/main/java/com/ilab/yougetmobiledl/model/BangumiDualStream.kt
zhushenwudi/YougetMobileDL
1755a1e5971a017b0f44c4df3e9491ae46a8d2fc
[ "MIT" ]
null
null
null
package com.ilab.yougetmobiledl.model data class BangumiDualStream( val code: Int, val message: String, val result: DualStream? ) { fun isSuccess() = message == "success" && code == 0 }
22.444444
55
0.668317
0bf6e2eae5393de54821d836bd3c0929a3aa9d74
500
js
JavaScript
src/store/index.js
blueYufisher/syb_index
8f8c22090cdd7762704d5354b5ac1bb243133515
[ "MIT" ]
null
null
null
src/store/index.js
blueYufisher/syb_index
8f8c22090cdd7762704d5354b5ac1bb243133515
[ "MIT" ]
null
null
null
src/store/index.js
blueYufisher/syb_index
8f8c22090cdd7762704d5354b5ac1bb243133515
[ "MIT" ]
null
null
null
import Vue from 'vue' import Vuex from 'vuex' import mutations from './mutations' import action from './action' Vue.use(Vuex) const state = { login: false, // 是否登录 user: null, // 用户信息 cartList: [], // 加入购物车列表 showMoveImg: false, // 显示飞入图片 elLeft: 0, elTop: 0, moveImgUrl: null, cartPositionT: 0, // 购物车位置 cartPositionL: 0, receiveInCart: false, // 是否进入购物车 showCart: false, // 是否显示购物车, searchType: '全站' } export default new Vuex.Store({ state, action, mutations })
18.518519
35
0.658
40fbc750a19b0f3f087c51579d5851b22624c038
1,866
py
Python
source/_static/code/aiyagari/aiyagari_compute_equilibrium.py
tuttugu-ryo/lecture-source-py
9ce84044c2cc421775ea63a004556d7ae3b4e504
[ "BSD-3-Clause" ]
56
2017-05-09T10:45:23.000Z
2022-01-20T20:33:27.000Z
source/_static/code/aiyagari/aiyagari_compute_equilibrium.py
tuttugu-ryo/lecture-source-py
9ce84044c2cc421775ea63a004556d7ae3b4e504
[ "BSD-3-Clause" ]
7
2017-06-30T01:52:46.000Z
2019-05-01T20:09:47.000Z
source/_static/code/aiyagari/aiyagari_compute_equilibrium.py
tuttugu-ryo/lecture-source-py
9ce84044c2cc421775ea63a004556d7ae3b4e504
[ "BSD-3-Clause" ]
117
2017-04-25T16:09:17.000Z
2022-03-23T02:30:29.000Z
A = 1.0 N = 1.0 α = 0.33 β = 0.96 δ = 0.05 def r_to_w(r): """ Equilibrium wages associated with a given interest rate r. """ return A * (1 - α) * (A * α / (r + δ))**(α / (1 - α)) def rd(K): """ Inverse demand curve for capital. The interest rate associated with a given demand for capital K. """ return A * α * (N / K)**(1 - α) - δ def prices_to_capital_stock(am, r): """ Map prices to the induced level of capital stock. Parameters: ---------- am : Household An instance of an aiyagari_household.Household r : float The interest rate """ w = r_to_w(r) am.set_prices(r, w) aiyagari_ddp = DiscreteDP(am.R, am.Q, β) # Compute the optimal policy results = aiyagari_ddp.solve(method='policy_iteration') # Compute the stationary distribution stationary_probs = results.mc.stationary_distributions[0] # Extract the marginal distribution for assets asset_probs = asset_marginal(stationary_probs, am.a_size, am.z_size) # Return K return np.sum(asset_probs * am.a_vals) # Create an instance of Household am = Household(a_max=20) # Use the instance to build a discrete dynamic program am_ddp = DiscreteDP(am.R, am.Q, am.β) # Create a grid of r values at which to compute demand and supply of capital num_points = 20 r_vals = np.linspace(0.005, 0.04, num_points) # Compute supply of capital k_vals = np.empty(num_points) for i, r in enumerate(r_vals): k_vals[i] = prices_to_capital_stock(am, r) # Plot against demand for capital by firms fig, ax = plt.subplots(figsize=(11, 8)) ax.plot(k_vals, r_vals, lw=2, alpha=0.6, label='supply of capital') ax.plot(k_vals, rd(k_vals), lw=2, alpha=0.6, label='demand for capital') ax.grid() ax.set_xlabel('capital') ax.set_ylabel('interest rate') ax.legend(loc='upper right') plt.show()
25.916667
76
0.661308
1b0c480acd6fd08cd8813e281f33194b2a19b3c7
3,748
sql
SQL
drawSQL-mysql-export-2022-04-04.sql
Javier-Alfonso-DS/S13_T01_Relational_Databases
f29e15a023a757ff48d87ab290079ed7d4d3aac7
[ "MIT" ]
null
null
null
drawSQL-mysql-export-2022-04-04.sql
Javier-Alfonso-DS/S13_T01_Relational_Databases
f29e15a023a757ff48d87ab290079ed7d4d3aac7
[ "MIT" ]
null
null
null
drawSQL-mysql-export-2022-04-04.sql
Javier-Alfonso-DS/S13_T01_Relational_Databases
f29e15a023a757ff48d87ab290079ed7d4d3aac7
[ "MIT" ]
null
null
null
CREATE TABLE `ShoppingTable`( `id` INT UNSIGNED NOT NULL, `ProviderId` INT UNSIGNED NOT NULL, `ProductId` INT UNSIGNED NOT NULL, `EstablishmentId` INT UNSIGNED NOT NULL ); ALTER TABLE `ShoppingTable` ADD PRIMARY KEY `shoppingtable_id_primary`(`id`); ALTER TABLE `ShoppingTable` ADD INDEX `shoppingtable_providerid_index`(`ProviderId`); ALTER TABLE `ShoppingTable` ADD INDEX `shoppingtable_productid_index`(`ProductId`); ALTER TABLE `ShoppingTable` ADD INDEX `shoppingtable_establishmentid_index`(`EstablishmentId`); CREATE TABLE `ProviderTable`( `id` INT UNSIGNED NOT NULL, `Name` TEXT NOT NULL, `Address` TEXT NOT NULL ); ALTER TABLE `ProviderTable` ADD PRIMARY KEY `providertable_id_primary`(`id`); CREATE TABLE `ProductsTable`( `id` INT UNSIGNED NOT NULL, `Name` TEXT NOT NULL, `TypeOfProductId` INT UNSIGNED NOT NULL, `ProviderId` INT UNSIGNED NOT NULL ); ALTER TABLE `ProductsTable` ADD PRIMARY KEY `productstable_id_primary`(`id`); ALTER TABLE `ProductsTable` ADD INDEX `productstable_typeofproductid_index`(`TypeOfProductId`); ALTER TABLE `ProductsTable` ADD INDEX `productstable_providerid_index`(`ProviderId`); CREATE TABLE `TypeOfProducts`( `id` INT UNSIGNED NOT NULL, `Name` TEXT NOT NULL, `Description` TEXT NOT NULL ); ALTER TABLE `TypeOfProducts` ADD PRIMARY KEY `typeofproducts_id_primary`(`id`); CREATE TABLE `EstablismentTable`( `id` INT UNSIGNED NOT NULL, `Name` TEXT NOT NULL, `Location` TEXT NOT NULL, `Area` TEXT NOT NULL, `EmployeesId` INT UNSIGNED NOT NULL, `CostumersId` INT UNSIGNED NOT NULL ); ALTER TABLE `EstablismentTable` ADD PRIMARY KEY `establismenttable_id_primary`(`id`); ALTER TABLE `EstablismentTable` ADD INDEX `establismenttable_employeesid_index`(`EmployeesId`); ALTER TABLE `EstablismentTable` ADD INDEX `establismenttable_costumersid_index`(`CostumersId`); CREATE TABLE `EmployeesTable`( `id` INT UNSIGNED NOT NULL, `Name` TEXT NOT NULL, `Surnames` TEXT NOT NULL, `StartDate` DATETIME NOT NULL, `EstablismentId` INT NOT NULL, `Address` TEXT NOT NULL, `PhoneNumber` INT NOT NULL, `DNI` INT NOT NULL, `DNI_letter` TEXT NOT NULL, `DateOfBirth` DATE NOT NULL ); ALTER TABLE `EmployeesTable` ADD PRIMARY KEY `employeestable_id_primary`(`id`); ALTER TABLE `EmployeesTable` ADD INDEX `employeestable_establismentid_index`(`EstablismentId`); CREATE TABLE `CustomersTable`( `id` INT UNSIGNED NOT NULL, `Name` TEXT NOT NULL, `Surnames` TEXT NOT NULL, `NIF` TEXT NOT NULL, `Address` TEXT NOT NULL ); ALTER TABLE `CustomersTable` ADD PRIMARY KEY `customerstable_id_primary`(`id`); ALTER TABLE `ShoppingTable` ADD CONSTRAINT `shoppingtable_productid_foreign` FOREIGN KEY(`ProductId`) REFERENCES `ProductsTable`(`id`); ALTER TABLE `ProductsTable` ADD CONSTRAINT `productstable_typeofproductid_foreign` FOREIGN KEY(`TypeOfProductId`) REFERENCES `TypeOfProducts`(`id`); ALTER TABLE `ProductsTable` ADD CONSTRAINT `productstable_providerid_foreign` FOREIGN KEY(`ProviderId`) REFERENCES `ProviderTable`(`id`); ALTER TABLE `ShoppingTable` ADD CONSTRAINT `shoppingtable_providerid_foreign` FOREIGN KEY(`ProviderId`) REFERENCES `ProviderTable`(`id`); ALTER TABLE `ShoppingTable` ADD CONSTRAINT `shoppingtable_establishmentid_foreign` FOREIGN KEY(`EstablishmentId`) REFERENCES `EstablismentTable`(`id`); ALTER TABLE `EstablismentTable` ADD CONSTRAINT `establismenttable_employeesid_foreign` FOREIGN KEY(`EmployeesId`) REFERENCES `EmployeesTable`(`id`); ALTER TABLE `EstablismentTable` ADD CONSTRAINT `establismenttable_costumersid_foreign` FOREIGN KEY(`CostumersId`) REFERENCES `CustomersTable`(`id`);
40.301075
143
0.746798
9817414a9711cd08d62b79465128286ad882b617
497
sql
SQL
db/remove_mms_schema_objects.sql
camsys/transam_mms
20257120a8b3de3092a69058537632db6d13a44f
[ "MIT" ]
null
null
null
db/remove_mms_schema_objects.sql
camsys/transam_mms
20257120a8b3de3092a69058537632db6d13a44f
[ "MIT" ]
null
null
null
db/remove_mms_schema_objects.sql
camsys/transam_mms
20257120a8b3de3092a69058537632db6d13a44f
[ "MIT" ]
null
null
null
DROP TABLE IF EXISTS maintenance_activity_types ; DROP TABLE IF EXISTS maintenance_repeat_interval_types ; DROP TABLE IF EXISTS maintenance_service_interval_types ; DROP TABLE IF EXISTS maintenance_schedules ; DROP TABLE IF EXISTS maintenance_activities ; DROP TABLE IF EXISTS maintenance_events ; DROP TABLE IF EXISTS assets_maintenance_schedules ; DROP TABLE IF EXISTS maintenance_providers ; DROP TABLE IF EXISTS maintenance_service_orders ; DROP TABLE IF EXISTS assets_maintenance_providers ;
23.666667
55
0.859155
5a36d2f774a3e4bdcdd8f5240b5175eb79371396
11,630
rs
Rust
src/node.rs
cyberfined/splay-tree-rs
22380e21748433dbf62bf40b253895ea8dfa8eac
[ "WTFPL" ]
null
null
null
src/node.rs
cyberfined/splay-tree-rs
22380e21748433dbf62bf40b253895ea8dfa8eac
[ "WTFPL" ]
null
null
null
src/node.rs
cyberfined/splay-tree-rs
22380e21748433dbf62bf40b253895ea8dfa8eac
[ "WTFPL" ]
null
null
null
#[cfg(feature = "recursive_debug")] use std::fmt; use std::mem; use std::fmt::Debug; use std::ptr::NonNull; use std::cmp::Ordering; pub(crate) type NodePtr<K, V> = Option<NonNull<Node<K, V>>>; /// Splay tree's node. #[cfg_attr(not(feature = "recursive_debug"), derive(Debug))] pub struct Node<K: Ord, V> { key: K, value: V, pub(crate) left: NodePtr<K, V>, pub(crate) right: NodePtr<K, V>, pub(crate) parent: NodePtr<K, V>, } #[cfg(feature = "recursive_debug")] impl<K: Ord + Debug, V: Debug> Debug for Node<K, V> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { self.print_tree_prefix(f, String::from(""), String::from("")) } } #[cfg(feature = "recursive_debug")] impl<K: Ord + Debug, V: Debug> Node<K, V> { fn print_tree_prefix( &self, f: &mut fmt::Formatter<'_>, prefix: String, c_prefix: String ) -> Result<(), fmt::Error> { f.write_fmt(format_args!("{}{:?}({:?})\n", prefix, self.key, self.value))?; let right_c_prefix; if let Some(left) = self.left() { right_c_prefix = c_prefix.clone(); let (new_prefix, new_c_prefix) = if self.right.is_some() { (c_prefix.clone() + "├── ", c_prefix + "│ ") } else { (c_prefix.clone() + "└── ", c_prefix + " ") }; left.print_tree_prefix(f, new_prefix, new_c_prefix)?; } else { right_c_prefix = c_prefix; } if let Some(right) = self.right() { let new_prefix = right_c_prefix.clone() + "└── "; let new_c_prefix = right_c_prefix + " "; right.print_tree_prefix(f, new_prefix, new_c_prefix)?; } Ok(()) } } impl<K: Ord, V> Node<K, V> { #[inline] pub(crate) fn new(key: K, value: V) -> Self { Node { key: key, value: value, left: None, right: None, parent: None, } } /// Returns a mutable reference to the node's parent, or `None` if the node is a root. /// /// This operation should compute in *O*(1) time. #[inline] pub fn parent_mut(&mut self) -> Option<&mut Self> { self.parent.map(|mut p| unsafe { p.as_mut() }) } /// Returns a reference to the node's parent, or `None` if the node is a root. /// /// This operation should compute in *O*(1) time. #[inline] pub fn parent(&self) -> Option<&Self> { self.parent.map(|p| unsafe { p.as_ref() }) } /// Returns a mutable reference to the node's left child, or `None` /// if the node doesn't have one. /// /// This operation should compute in *O*(1) time. #[inline] pub fn left_mut(&mut self) -> Option<&mut Self> { self.left.map(|mut l| unsafe { l.as_mut() }) } /// Returns a reference to the node's left child, or `None` /// if the node doesn't have one. /// /// This operation should compute in *O*(1) time. #[inline] pub fn left(&self) -> Option<&Self> { self.left.map(|l| unsafe { l.as_ref() }) } /// Returns a mutable reference to the node's right child, or `None` /// if the node doesn't have one. /// /// This operation should compute in *O*(1) time. #[inline] pub fn right_mut(&mut self) -> Option<&mut Self> { self.right.map(|mut r| unsafe { r.as_mut() }) } /// Returns a reference to the node's right child, or `None` /// if the node doesn't have one. /// /// This operation should compute in *O*(1) time. #[inline] pub fn right(&self) -> Option<&Self> { self.right.map(|r| unsafe { r.as_ref() }) } /// Returns a reference to the node's key. #[inline] pub fn key(&self) -> &K { &self.key } /// Returns a mutable reference to the node's value. #[inline] pub fn value_mut(&mut self) -> &mut V { &mut self.value } /// Returns a reference to the node's value. #[inline] pub fn value(&self) -> &V { &self.value } /// Returns `true` if the node is a root. #[inline] pub fn is_root(&self) -> bool { self.parent.is_none() } /// Returns `true` if the node is a left child. #[inline] pub fn is_left(&self) -> bool { if let Some(parent) = self.parent() { parent.left.map(|l| unsafe { mem::transmute::<*mut Self, *const Self>(l.as_ptr()) == self }).unwrap_or(false) } else { false } } /// Returns `true` if the node is a right child. #[inline] pub fn is_right(&self) -> bool { if let Some(parent) = self.parent() { parent.right.map(|l| unsafe { mem::transmute::<*mut Self, *const Self>(l.as_ptr()) == self }).unwrap_or(false) } else { false } } #[inline] pub(crate) unsafe fn ref_into_box(&mut self) -> Box<Self> { Box::from_raw(self) } #[inline] pub(crate) fn insert_child<'a>( &'a mut self, key: K, value: V ) -> Option<&'a mut Self> { match key.cmp(&self.key) { Ordering::Less if self.left.is_none() => { let node = Node { key: key, value: value, parent: Some(self.into()), left: None, right: None, }; let node_ptr = Box::leak(Box::new(node)).into(); self.left = Some(node_ptr); self.left_mut() }, Ordering::Equal => { self.value = value; Some(self) }, Ordering::Greater if self.right.is_none() => { let node = Node { key: key, value: value, parent: Some(self.into()), left: None, right: None, }; let node_ptr = Box::leak(Box::new(node)).into(); self.right = Some(node_ptr); self.right_mut() }, _ => None, } } #[inline] pub(crate) fn splay(&mut self) -> NodePtr<K, V> { loop { if let Some(new_root) = self.splay_step() { return Some(new_root) } } } fn splay_step(&mut self) -> NodePtr<K, V> { let self_ptr = self.into(); let is_left = self.is_left(); if let Some(splay_type) = self.splay_type() { match splay_type { SplayType::Zig => { self.parent_mut().map(|p| if is_left { p.rotate_right(); } else { p.rotate_left(); } ); }, SplayType::ZigZig => { self.parent_mut().map(|p| if is_left { p.parent_mut().map(|g| g.rotate_right()); p.rotate_right(); } else { p.parent_mut().map(|g| g.rotate_left()); p.rotate_left(); } ); }, SplayType::ZigZag => { if is_left { self.parent_mut().map(|p| p.rotate_right()); self.parent_mut().map(|g| g.rotate_left()); } else { self.parent_mut().map(|p| p.rotate_left()); self.parent_mut().map(|g| g.rotate_right()); } }, } } if self.is_root() { Some(self_ptr) } else { None } } #[inline] pub(crate) fn merge(&mut self, right: &mut Self) -> NodePtr<K, V> { let left_max = self.find_max(); let res = left_max.splay(); right.parent = res; left_max.right = Some(right.into()); res } #[inline] pub(crate) fn find_max(&mut self) -> &mut Self { let mut cur_node = self; loop { let ptr: *const Self = cur_node; cur_node = if let Some(next) = cur_node.right_mut() { next } else { break unsafe { &mut *mem::transmute::<*const Self, *mut Self>(ptr) }; } } } #[inline] pub(crate) fn find_min(&mut self) -> &mut Self { let mut cur_node = self; loop { let ptr: *const Self = cur_node; cur_node = if let Some(next) = cur_node.left_mut() { next } else { break unsafe { &mut *mem::transmute::<*const Self, *mut Self>(ptr) }; } } } #[inline] fn rotate_left(&mut self) { let self_ptr = self.into(); let parent_ptr = self.parent; let right_ptr = self.right; let right = match self.right_mut() { Some(ptr) => ptr, None => return, }; let left_ptr = right.left; right.parent = parent_ptr; right.left = Some(self_ptr); let is_left = self.is_left(); if let Some(parent) = self.parent_mut() { if is_left { parent.left = right_ptr; } else { parent.right = right_ptr; } } self.parent = right_ptr; self.right = left_ptr; self.right_mut().map(|mut r| { r.parent = Some(self_ptr); r }); } #[inline] fn rotate_right(&mut self) { let self_ptr = self.into(); let parent_ptr = self.parent; let left_ptr = self.left; let left = match self.left_mut() { Some(ptr) => ptr, None => return, }; let right_ptr = left.right; left.parent = parent_ptr; left.right = Some(self_ptr); let is_left = self.is_left(); if let Some(parent) = self.parent_mut() { if is_left { parent.left = left_ptr; } else { parent.right = left_ptr; } } self.parent = left_ptr; self.left = right_ptr; self.left_mut().map(|mut l| l.parent = Some(self_ptr)); } #[inline] fn splay_type(&self) -> Option<SplayType> { if self.parent()?.is_root() { Some(SplayType::Zig) } else if (self.is_left() && self.parent()?.is_left()) || (self.is_right() && self.parent()?.is_right()) { Some(SplayType::ZigZig) } else if !self.parent()?.is_root() { Some(SplayType::ZigZag) } else { None } } pub(crate) fn free(&mut self) { match self.left { Some(left_ptr) => { let mut left_box = unsafe { Box::from_raw(left_ptr.as_ptr()) }; left_box.free(); }, None => {}, } match self.right { Some(right_ptr) => { let mut right_box = unsafe { Box::from_raw(right_ptr.as_ptr()) }; right_box.free(); }, None => {}, } } } #[derive(Debug, PartialEq)] enum SplayType { Zig, ZigZig, ZigZag } #[cfg(test)] mod tests;
28.091787
90
0.463199
fc1d21d0626822cf2477edb44c26f4a13eada425
2,196
sql
SQL
old_ddl/run/truncate_tables.sql
datarttu/sujuikoDB
4e206395683b9670e0a7c82e86f366e756176bfb
[ "MIT" ]
1
2020-05-27T07:17:02.000Z
2020-05-27T07:17:02.000Z
old_ddl/run/truncate_tables.sql
datarttu/sujuikoDB
4e206395683b9670e0a7c82e86f366e756176bfb
[ "MIT" ]
102
2020-04-30T14:21:49.000Z
2021-11-10T15:06:12.000Z
old_ddl/run/truncate_tables.sql
datarttu/sujuikoDB
4e206395683b9670e0a7c82e86f366e756176bfb
[ "MIT" ]
1
2021-04-01T07:35:13.000Z
2021-04-01T07:35:13.000Z
/* * TRUNCATE commands in correct order: * execute these to revert to a certain state in the data import process. * WARNING: Executing the entire script will empty all the tables! * Normally you will want to pick just the necessary commands. * Consider BEGINning a transaction first and only then executing these. */ -- obs schema: TO DO. -- sched schema, template side; obs.journeys needs to be empty first. TRUNCATE TABLE sched.segment_times; TRUNCATE TABLE sched.template_timestamps; TRUNCATE TABLE sched.templates CASCADE; -- sched schema, pattern side. TRUNCATE TABLE sched.segments; TRUNCATE TABLE sched.patterns CASCADE; -- stage_gtfs schema, templates and patterns TRUNCATE TABLE stage_gtfs.template_timestamps; TRUNCATE TABLE stage_gtfs.template_stops; TRUNCATE TABLE stage_gtfs.templates CASCADE; TRUNCATE TABLE stage_gtfs.pattern_stops CASCADE; TRUNCATE TABLE stage_gtfs.pattern_paths; TRUNCATE TABLE stage_gtfs.patterns CASCADE; TRUNCATE TABLE stage_gtfs.stop_pairs; TRUNCATE TABLE stage_gtfs.stop_pair_paths; -- nw schema TRUNCATE TABLE nw.stops; TRUNCATE TABLE nw.nodes CASCADE; TRUNCATE TABLE nw.links_vertices_pgr; TRUNCATE TABLE nw.links CASCADE; -- stage_nw schema TRUNCATE TABLE stage_nw.snapped_stops; TRUNCATE TABLE stage_nw.contracted_nw; TRUNCATE TABLE stage_nw.contracted_edges_to_merge; TRUNCATE TABLE stage_nw.contracted_arr; TRUNCATE TABLE stage_nw.raw_nw_vertices_pgr; TRUNCATE TABLE stage_nw.raw_nw; -- sched schema, routes TRUNCATE TABLE sched.routes CASCADE; -- stage_osm schema, combined_lines TRUNCATE TABLE stage_osm.combined_lines; -- stage_gtfs schema, GTFS staging stuff TRUNCATE TABLE stage_gtfs.normalized_stop_times; TRUNCATE TABLE stage_gtfs.trips_with_dates; TRUNCATE TABLE stage_gtfs.shape_lines; TRUNCATE TABLE stage_gtfs.stops_with_mode; -- Original gtfs tables TRUNCATE TABLE stage_gtfs.calendar; TRUNCATE TABLE stage_gtfs.calendar_dates; TRUNCATE TABLE stage_gtfs.stop_times; TRUNCATE TABLE stage_gtfs.shapes; TRUNCATE TABLE stage_gtfs.trips; TRUNCATE TABLE stage_gtfs.stops; TRUNCATE TABLE stage_gtfs.routes; -- Original OSM data TRUNCATE TABLE stage_gtfs.raw_tram_lines; TRUNCATE TABLE stage_gtfs.raw_bus_lines;
32.294118
81
0.821494
adbda06cc0ba7b022823973e6e57108eb973fa4f
5,541
pkb
SQL
sources/packages/bmap_builder.pkb
jgebal/bitmap_set_index
7c7a2961055deacfa240d5c56425d31c75185a66
[ "MIT" ]
2
2016-08-31T11:34:19.000Z
2017-03-29T09:53:25.000Z
sources/packages/bmap_builder.pkb
jgebal/bitmap_set_index
7c7a2961055deacfa240d5c56425d31c75185a66
[ "MIT" ]
null
null
null
sources/packages/bmap_builder.pkb
jgebal/bitmap_set_index
7c7a2961055deacfa240d5c56425d31c75185a66
[ "MIT" ]
null
null
null
ALTER SESSION SET PLSQL_WARNINGS = 'ENABLE:ALL'; ALTER SESSION SET PLSQL_CODE_TYPE = NATIVE; / ALTER SESSION SET PLSQL_OPTIMIZE_LEVEL = 3; / CREATE OR REPLACE PACKAGE BODY bmap_builder AS PROCEDURE initialize( p_int_aarray IN OUT NOCOPY BIN_INT_ARRAY, p_height BINARY_INTEGER := C_BITMAP_HEIGHT ) IS BEGIN FOR i IN 1 .. p_height LOOP p_int_aarray( i ) := NULL; END LOOP; END initialize; PROCEDURE initialize( p_int_matrix IN OUT NOCOPY BIN_INT_MATRIX, p_height BINARY_INTEGER := C_BITMAP_HEIGHT ) IS x bmap_segment_builder.BIN_INT_LIST := bmap_segment_builder.BIN_INT_LIST(); BEGIN p_int_matrix := BIN_INT_MATRIX(); FOR i IN 1 .. p_height LOOP p_int_matrix.EXTEND; p_int_matrix( i ) := x; END LOOP; END initialize; PROCEDURE store_bmap_segment( p_stor_table_name VARCHAR2, p_bitmap_key INTEGER, p_segment_H_pos BINARY_INTEGER, p_segment_V_pos BINARY_INTEGER, p_segment bmap_segment_builder.BIN_INT_LIST ) IS BEGIN IF p_segment_H_pos IS NOT NULL AND p_segment_V_pos IS NOT NULL AND p_bitmap_key IS NOT NULL THEN bmap_persist.insert_segment( p_stor_table_name, p_bitmap_key, p_segment_V_pos, p_segment_H_pos, bmap_segment_builder.encode_and_convert( p_segment ) ); END IF; END store_bmap_segment; PROCEDURE flush_bmap_segments( p_stor_table_name VARCHAR2, p_bitmap_key INTEGER, p_segment_value_list IN OUT NOCOPY BIN_INT_MATRIX, p_segment_H_pos_lst IN OUT NOCOPY BIN_INT_ARRAY, p_segment_V_pos BINARY_INTEGER := 1 ) IS v_parent_segment_H_pos BINARY_INTEGER; BEGIN store_bmap_segment( p_stor_table_name, p_bitmap_key, p_segment_H_pos_lst( p_segment_V_pos ), p_segment_V_pos, p_segment_value_list( p_segment_V_pos ) ); IF p_segment_V_pos < C_BITMAP_HEIGHT THEN flush_bmap_segments( p_stor_table_name, p_bitmap_key, p_segment_value_list, p_segment_H_pos_lst, p_segment_V_pos + 1 ); ELSE PRAGMA INLINE (initialize, 'YES'); initialize( p_segment_H_pos_lst ); PRAGMA INLINE (initialize, 'YES'); initialize( p_segment_value_list ); END IF; END flush_bmap_segments; PROCEDURE build_or_store_bmap_segment( p_stor_table_name VARCHAR2, p_bitmap_key INTEGER, p_bit_pos INTEGER, p_processing_segm_H_pos_lst IN OUT NOCOPY BIN_INT_ARRAY, p_segment_int_list IN OUT NOCOPY BIN_INT_MATRIX, p_current_segment_V_pos BINARY_INTEGER := 1 ) IS v_new_segment_H_pos BINARY_INTEGER := CEIL( p_bit_pos / C_SEGMENT_CAPACITY ); v_is_segment_change BOOLEAN; v_is_new_bmap BOOLEAN; BEGIN v_is_new_bmap := p_processing_segm_H_pos_lst( p_current_segment_V_pos ) IS NULL; v_is_segment_change := ( p_processing_segm_H_pos_lst( p_current_segment_V_pos )!= v_new_segment_H_pos ); IF v_is_new_bmap OR v_is_segment_change THEN --build parent segment IF p_current_segment_V_pos < C_BITMAP_HEIGHT THEN build_or_store_bmap_segment( p_stor_table_name, p_bitmap_key, v_new_segment_H_pos, p_processing_segm_H_pos_lst, p_segment_int_list, p_current_segment_V_pos + 1 ); END IF; --save currently build segment, if a new segment is to be processed now IF v_is_segment_change THEN store_bmap_segment( p_stor_table_name, p_bitmap_key, p_processing_segm_H_pos_lst( p_current_segment_V_pos ), p_current_segment_V_pos, p_segment_int_list( p_current_segment_V_pos ) ); p_segment_int_list( p_current_segment_V_pos ).DELETE; END IF; END IF; --add segment element to segment elements list p_segment_int_list( p_current_segment_V_pos ).EXTEND; p_segment_int_list( p_current_segment_V_pos )( p_segment_int_list( p_current_segment_V_pos ).LAST ) := MOD( p_bit_pos-1, C_SEGMENT_CAPACITY ) + 1; p_processing_segm_H_pos_lst( p_current_segment_V_pos ) := v_new_segment_H_pos; END build_or_store_bmap_segment; PROCEDURE build_bitmaps( p_bit_list_crsr SYS_REFCURSOR, p_stor_table_name VARCHAR2 ) IS v_segment_value_list BIN_INT_MATRIX; v_bitmap_key_lst VARCHAR2_LIST; v_bit_elem_list INT_LIST; v_segment_H_pos_lst BIN_INT_ARRAY; v_prev_bmap_key VARCHAR2(4000); BEGIN PRAGMA INLINE (initialize, 'YES'); initialize( v_segment_value_list ); PRAGMA INLINE (initialize, 'YES'); initialize( v_segment_H_pos_lst ); LOOP FETCH p_bit_list_crsr BULK COLLECT INTO v_bitmap_key_lst, v_bit_elem_list LIMIT bmap_segment_builder.C_SEGMENT_CAPACITY; FOR i IN 1 .. v_bit_elem_list.COUNT LOOP IF v_bitmap_key_lst(i) != v_prev_bmap_key THEN flush_bmap_segments( p_stor_table_name, v_prev_bmap_key, v_segment_value_list, v_segment_H_pos_lst ); END IF; build_or_store_bmap_segment( p_stor_table_name, v_bitmap_key_lst(i), v_bit_elem_list(i), v_segment_H_pos_lst, v_segment_value_list ); v_prev_bmap_key := v_bitmap_key_lst(i); END LOOP; IF v_bit_elem_list.COUNT < bmap_segment_builder.C_SEGMENT_CAPACITY OR CARDINALITY( v_bit_elem_list ) = 0 THEN flush_bmap_segments( p_stor_table_name, v_prev_bmap_key, v_segment_value_list, v_segment_H_pos_lst ); END IF; EXIT WHEN p_bit_list_crsr%NOTFOUND; END LOOP; END build_bitmaps; END bmap_builder; / SHOW ERRORS /
42.953488
192
0.724598
9bed0f94a69cbd9b54991a9893483808cdd9531c
4,410
js
JavaScript
resources/js/src/util/forms/mixins/Create.js
michee1367/ibuzz_front_original
a53fe95a2f4d7d73ed3665c403d213e62d4f9c1c
[ "MIT" ]
null
null
null
resources/js/src/util/forms/mixins/Create.js
michee1367/ibuzz_front_original
a53fe95a2f4d7d73ed3665c403d213e62d4f9c1c
[ "MIT" ]
null
null
null
resources/js/src/util/forms/mixins/Create.js
michee1367/ibuzz_front_original
a53fe95a2f4d7d73ed3665c403d213e62d4f9c1c
[ "MIT" ]
null
null
null
import Axios from 'axios'; import MixinLoadable from "../../mixins/MixinLoadable"; import { BModal } from 'bootstrap-vue'; import { BOverlay } from 'bootstrap-vue' import RenderToken from "../../mixins/RenderToken"; import loaderData from "../../mixins/loaderData"; import { postMethod } from "../../request"; export default { mixins:[MixinLoadable, RenderToken, loaderData], components : { 'b-modal':BModal, 'b-overlay':BOverlay, }, props : { }, created(){ }, mounted (){ }, data(){ return { lErrors:{}, loading:false, api_token:"", } }, computed:{ /** * @returns {String} */ url(){ return "/api" }, /** * * @returns */ host(){ //return "http://api.ibuzz.ltd" //process.env.MIX_VAR return process.env.MIX_API_HOST // }, /** * */ formDataConcrete(){ return {}; }, isMultipart() { return true } /** * errors:{ get(){ return this.lErrors; }, set(errors){ this.lErrors = errors } }*/ }, methods : { loadResources(api_token){ this.api_token = api_token; }, setResult(data){ }, setReject(err){ }, submit(){ let me = this; let data = this.formDataConcrete; let formData = {}; let contentType = "" //console.log(data) let url = this.host + this.url+"?api_token="+me.api_token; if (this.isMultipart) { formData = new FormData(); contentType = "multipart/form-data" for (const key in data) { if (data.hasOwnProperty(key)) { let el = data[key]; el = el === "null" || el === null?"":el; //console.log(el) formData.append(key, el); } } } else { contentType = "application/json" formData = data } me.loading = true let promise = postMethod(url, formData, { 'Content-Type': contentType, 'Authorization': me.bearerToken }) /*let promise = Axios.post( url, formData, { headers: { 'Content-Type': contentType, 'Authorization': me.bearerToken } } )*/ .then( ({data}) => { me.errors = {}; //console.log(data) me.setResult(data); me.loading = false } ) this.errorResolver(promise) .catch( (errors) => { if (errors.errors) { errors = errors.errors } me.setReject(errors) me.loading = false } ) } } }
31.056338
95
0.297279
53d00c9cddb9f9a315f59b5f47824b3d3cd434c6
5,378
java
Java
src/main/java/org/whitesource/jenkins/model/WhiteSourceDescriptor.java
slaboure/whitesource-plugin
c89430ad6e787f64a048d02d37be3d1ad48710e3
[ "Apache-2.0" ]
4
2017-11-23T19:01:50.000Z
2019-04-26T19:53:22.000Z
src/main/java/org/whitesource/jenkins/model/WhiteSourceDescriptor.java
slaboure/whitesource-plugin
c89430ad6e787f64a048d02d37be3d1ad48710e3
[ "Apache-2.0" ]
6
2018-08-23T13:15:47.000Z
2021-12-09T19:27:09.000Z
src/main/java/org/whitesource/jenkins/model/WhiteSourceDescriptor.java
slaboure/whitesource-plugin
c89430ad6e787f64a048d02d37be3d1ad48710e3
[ "Apache-2.0" ]
11
2017-07-19T14:15:28.000Z
2021-10-01T12:14:48.000Z
package org.whitesource.jenkins.model; import hudson.util.Secret; import org.whitesource.jenkins.WhiteSourcePublisher; import org.whitesource.jenkins.pipeline.WhiteSourcePipelineStep; /** * Holds global configuration of the plugin * * @author artiom.petrov */ public class WhiteSourceDescriptor { /* --- Members --- */ private String serviceUrl; private Secret apiToken; private Secret userKey; private String checkPolicies; private boolean globalForceUpdate; private boolean failOnError; private boolean overrideProxySettings; private String server; private String port; private String userName; private Secret password; private String connectionTimeout; private String connectionRetries; private String connectionRetriesInterval; /* --- Constructors --- */ public WhiteSourceDescriptor(WhiteSourcePublisher.DescriptorImpl descriptor) { this.serviceUrl = descriptor.getServiceUrl(); this.apiToken = descriptor.getApiToken(); this.userKey = descriptor.getUserKey(); this.checkPolicies = descriptor.getCheckPolicies(); this.globalForceUpdate = descriptor.isGlobalForceUpdate(); this.failOnError = descriptor.isFailOnError(); this.overrideProxySettings = descriptor.isOverrideProxySettings(); this.server = descriptor.getServer(); this.port = descriptor.getPort(); this.userName = descriptor.getUserName(); this.password = descriptor.getPassword(); this.connectionTimeout = descriptor.getConnectionTimeout(); this.connectionRetries = descriptor.getConnectionRetries() == null ? "1" : descriptor.getConnectionRetries(); this.connectionRetriesInterval = descriptor.getConnectionRetriesInterval() == null ? "30" : descriptor.getConnectionRetries(); } public WhiteSourceDescriptor(WhiteSourcePipelineStep.DescriptorImpl descriptor) { this.serviceUrl = descriptor.getServiceUrl(); this.apiToken = descriptor.getApiToken(); this.userKey = descriptor.getUserKey(); this.checkPolicies = descriptor.getCheckPolicies(); this.globalForceUpdate = descriptor.isGlobalForceUpdate(); this.failOnError = descriptor.isFailOnError(); this.overrideProxySettings = descriptor.isOverrideProxySettings(); this.server = descriptor.getServer(); this.port = descriptor.getPort(); this.userName = descriptor.getUserName(); this.password = descriptor.getPassword(); this.connectionTimeout = descriptor.getConnectionTimeout(); this.connectionRetries = descriptor.getConnectionRetries() == null ? "1" : descriptor.getConnectionRetries(); this.connectionRetriesInterval = descriptor.getConnectionRetriesInterval() == null ? "30" : descriptor.getConnectionRetries(); } /* --- Getters / Setters --- */ public String getServiceUrl() { return serviceUrl; } public void setServiceUrl(String serviceUrl) { this.serviceUrl = serviceUrl; } public Secret getApiToken() { return apiToken; } public void setApiToken(Secret apiToken) { this.apiToken = apiToken; } public Secret getUserKey() { return userKey; } public void setUserKey(Secret userKey) { this.userKey = userKey; } public String getCheckPolicies() { return checkPolicies; } public void setCheckPolicies(String checkPolicies) { this.checkPolicies = checkPolicies; } public boolean isGlobalForceUpdate() { return globalForceUpdate; } public void setGlobalForceUpdate(boolean globalForceUpdate) { this.globalForceUpdate = globalForceUpdate; } public boolean isFailOnError() { return failOnError; } public void setFailOnError(boolean failOnError) { this.failOnError = failOnError; } public boolean isOverrideProxySettings() { return overrideProxySettings; } public void setOverrideProxySettings(boolean overrideProxySettings) { this.overrideProxySettings = overrideProxySettings; } public String getServer() { return server; } public void setServer(String server) { this.server = server; } public String getPort() { return port; } public void setPort(String port) { this.port = port; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Secret getPassword() { return password; } public void setPassword(Secret password) { this.password = password; } public String getConnectionTimeout() { return connectionTimeout; } public void setConnectionTimeout(String connectionTimeout) { this.connectionTimeout = connectionTimeout; } public String getConnectionRetries() { return connectionRetries; } public void setConnectionRetries(String connectionRetries) { this.connectionRetries = connectionRetries; } public String getConnectionRetriesInterval() { return connectionRetriesInterval; } public void setConnectionRetriesInterval(String connectionRetriesInterval) { this.connectionRetriesInterval = connectionRetriesInterval; } }
30.556818
135
0.693752
7fd0727796e97824c52b4339f561f3c14e317159
3,926
go
Go
pkg/websocketutil/client.go
giantswarm/confetti-backend
63952dd0e5259104d2f92dd94685973448275c17
[ "Apache-2.0" ]
null
null
null
pkg/websocketutil/client.go
giantswarm/confetti-backend
63952dd0e5259104d2f92dd94685973448275c17
[ "Apache-2.0" ]
8
2020-12-14T16:03:27.000Z
2021-09-20T04:08:50.000Z
pkg/websocketutil/client.go
giantswarm/confetti-backend
63952dd0e5259104d2f92dd94685973448275c17
[ "Apache-2.0" ]
1
2021-10-20T18:56:30.000Z
2021-10-20T18:56:30.000Z
package websocketutil import ( "sync" "time" "github.com/atreugo/websocket" "github.com/giantswarm/microerror" ) const ( // Time allowed to write a message to the peer. writeWait = 10 * time.Second // Time allowed to read the next pong message from the peer. pongWait = 60 * time.Second // Send pings to peer with this period. Must be less than pongWait. pingPeriod = (pongWait * 9) / 10 // Maximum message size allowed from peer. maxMessageSize = 512 ) type ClientConfig struct { // Hub is the web socket hub that this client belongs to. Hub Hub // Connection is the websocket connection. Connection *websocket.Conn } // Client is a middleman between the websocket connection and the hub. // // Taken from https://github.com/fasthttp/websocket/blob/master/_examples/chat/fasthttp/client.go // and modified to match our need. type Client struct { hub Hub conn *websocket.Conn // send is the buffered channel of outbound messages. send chan []byte // wg is a waiting group that synchronizes // the writer and reader goroutines. // It makes sure that the writer goroutine // will be closed before the request goroutine // is terminated. wg sync.WaitGroup } func NewClient(config ClientConfig) (*Client, error) { if config.Hub == nil { return nil, microerror.Maskf(invalidConfigError, "%T.Hub must not be empty", config) } if config.Connection == nil { return nil, microerror.Maskf(invalidConfigError, "%T.Connection must not be empty", config) } c := &Client{ hub: config.Hub, conn: config.Connection, send: make(chan []byte, 256), } c.registerToHub() return c, nil } func (c *Client) Emit(payload []byte) bool { select { case c.send <- payload: default: return false } return true } // GetUserValue retrieves a value from the connection context. func (c *Client) GetUserValue(key string) interface{} { return c.conn.UserValue(key) } // SaveUserValue saves a value into the connection context. func (c *Client) SaveUserValue(key string, value interface{}) { c.conn.SetUserValue(key, value) } func (c *Client) registerToHub() { c.wg.Add(1) c.hub.RegisterClient(c) go c.writePump() c.readPump() c.wg.Wait() } // readPump pumps messages from the websocket connection to the hub. // // The application runs readPump in a per-connection goroutine. The application // ensures that there is at most one reader on a connection by executing all // reads from this goroutine. func (c *Client) readPump() { defer func() { c.hub.UnregisterClient(c) c.conn.Close() }() c.conn.SetReadLimit(maxMessageSize) _ = c.conn.SetReadDeadline(time.Now().Add(pongWait)) c.conn.SetPongHandler(func(string) error { return c.conn.SetReadDeadline(time.Now().Add(pongWait)) }) var err error var message []byte for { _, message, err = c.conn.ReadMessage() if err != nil { return } clientMessage := ClientMessage{ Client: c, Payload: message, } c.hub.SendMessage(clientMessage) } } // writePump pumps messages from the hub to the websocket connection. // // A goroutine running writePump is started for each connection. The // application ensures that there is at most one writer to a connection by // executing all writes from this goroutine. func (c *Client) writePump() { ticker := time.NewTicker(pingPeriod) defer func() { ticker.Stop() c.conn.Close() c.wg.Done() }() for { select { case message, ok := <-c.send: _ = c.conn.SetWriteDeadline(time.Now().Add(writeWait)) if !ok { // The hub closed the channel. _ = c.conn.WriteMessage(CloseMessage, []byte{}) return } w, err := c.conn.NextWriter(TextMessage) if err != nil { return } _, _ = w.Write(message) if err := w.Close(); err != nil { return } case <-ticker.C: _ = c.conn.SetWriteDeadline(time.Now().Add(writeWait)) if err := c.conn.WriteMessage(PingMessage, nil); err != nil { return } } } }
22.306818
97
0.694345
dd036956b2642af10209fa3716e42d337ec6fa4c
772
go
Go
utils/substring.go
Daedliy/tsc-language-server
49f9001d8e2293495a0d9117259a5ad806c97498
[ "MIT" ]
1
2020-10-21T23:06:19.000Z
2020-10-21T23:06:19.000Z
utils/substring.go
Daedliy/tsc-language-server
49f9001d8e2293495a0d9117259a5ad806c97498
[ "MIT" ]
5
2021-04-03T01:11:51.000Z
2021-11-03T21:52:46.000Z
utils/substring.go
Daedliy/tsc-language-server
49f9001d8e2293495a0d9117259a5ad806c97498
[ "MIT" ]
5
2020-11-25T14:45:42.000Z
2021-11-03T17:11:52.000Z
package utils import "math" // Substring will return a substring of given length from a given index. If // the from index is bigger than the length of the string, it will return an // empty string. If the given length would result in an OOB error, the function // will return the substring up to the length of the string. If the from index // or the length is a negative value, it will return an empty string. If the // length is 0, it will return everything starting from the provided index to // the end of the string. func Substring(str string, from int, length int) string { if from > len(str) || from < 0 || length < 0 { return "" } if length == 0 { return str[from:] } to := int(math.Min(float64(from+length), float64(len(str)))) return str[from:to] }
32.166667
79
0.709845
6616025c340fcb373f83e711f7b78b5a51cc4142
7,608
swift
Swift
Tests/SwiftStringTests/StringURLTests.swift
neilabdev/SwiftString
8017b12c3e20cf8fe4f9b5538a3aaf89562036c2
[ "MIT" ]
127
2016-09-21T05:23:34.000Z
2021-07-30T02:14:05.000Z
Tests/SwiftStringTests/StringURLTests.swift
keshavakarthik/SwiftString
eb1c723503736a8c5d24a4e7408d69e5f06b3094
[ "MIT" ]
5
2016-12-16T04:35:38.000Z
2018-08-06T11:08:11.000Z
Tests/SwiftStringTests/StringURLTests.swift
keshavakarthik/SwiftString
eb1c723503736a8c5d24a4e7408d69e5f06b3094
[ "MIT" ]
39
2016-09-21T01:05:33.000Z
2020-09-01T07:21:32.000Z
// // StringURLTests.swift // SwiftString // // Created by thislooksfun on 1/3/17. // // import XCTest @testable import SwiftString class StringURLTests: XCTestCase { let rootPathToDir = "/foo/bar/baz/" let rootPathToDirNoTrail = "/foo/bar/baz" let rootPathToFile = "/foo/bar/baz.txt" let rootPathSingleLetters = "/f/b/z" let relPathToDir = "foo/bar/baz/" let relPathToDirNoTrail = "foo/bar/baz" let relPathToFile = "foo/bar/baz.txt" let relPathSingleLetters = "f/b/z" let randomString = "Quick brown fox, or something." func testParent() { let resultRootPathToDir = rootPathToDir.parent XCTAssertNotNil(resultRootPathToDir) XCTAssertEqual(resultRootPathToDir, "/foo/bar") let resultRootPathToDirNoTrail = rootPathToDirNoTrail.parent XCTAssertNotNil(resultRootPathToDirNoTrail) XCTAssertEqual(resultRootPathToDirNoTrail, "/foo/bar") let resultRootPathToFile = rootPathToFile.parent XCTAssertNotNil(resultRootPathToFile) XCTAssertEqual(resultRootPathToFile, "/foo/bar") let resultRootPathSingleLetters = rootPathSingleLetters.parent XCTAssertNotNil(resultRootPathSingleLetters) XCTAssertEqual(resultRootPathSingleLetters, "/f/b") let resultRelPathToDir = relPathToDir.parent XCTAssertNotNil(resultRelPathToDir) XCTAssertEqual(resultRelPathToDir, "foo/bar") let resultRelPathToDirNoTrail = relPathToDirNoTrail.parent XCTAssertNotNil(resultRelPathToDirNoTrail) XCTAssertEqual(resultRelPathToDirNoTrail, "foo/bar") let resultRelPathToFile = relPathToFile.parent XCTAssertNotNil(resultRelPathToFile) XCTAssertEqual(resultRelPathToFile, "foo/bar") let resultRelPathSingleLetters = relPathSingleLetters.parent XCTAssertNotNil(resultRelPathSingleLetters) XCTAssertEqual(resultRelPathSingleLetters, "f/b") let resultRandomString = randomString.parent XCTAssertNil(resultRandomString) } func testFile() { let resultRootPathToDir = rootPathToDir.file XCTAssertNotNil(resultRootPathToDir) XCTAssertEqual(resultRootPathToDir, "baz") let resultRootPathToDirNoTrail = rootPathToDirNoTrail.file XCTAssertNotNil(resultRootPathToDirNoTrail) XCTAssertEqual(resultRootPathToDirNoTrail, "baz") let resultRootPathToFile = rootPathToFile.file XCTAssertNotNil(resultRootPathToFile) XCTAssertEqual(resultRootPathToFile, "baz.txt") let resultRootPathSingleLetters = rootPathSingleLetters.file XCTAssertNotNil(resultRootPathSingleLetters) XCTAssertEqual(resultRootPathSingleLetters, "z") let resultRelPathToDir = relPathToDir.file XCTAssertNotNil(resultRelPathToDir) XCTAssertEqual(resultRelPathToDir, "baz") let resultRelPathToDirNoTrail = relPathToDirNoTrail.file XCTAssertNotNil(resultRelPathToDirNoTrail) XCTAssertEqual(resultRelPathToDirNoTrail, "baz") let filetRelPathToFile = relPathToFile.file XCTAssertNotNil(filetRelPathToFile) XCTAssertEqual(filetRelPathToFile, "baz.txt") let resultRelPathSingleLetters = relPathSingleLetters.file XCTAssertNotNil(resultRelPathSingleLetters) XCTAssertEqual(resultRelPathSingleLetters, "z") let resultRandomString = randomString.file XCTAssertNil(resultRandomString) } func testFileName() { let resultRootPathToDir = rootPathToDir.fileName XCTAssertNotNil(resultRootPathToDir) XCTAssertEqual(resultRootPathToDir, "baz") let resultRootPathToDirNoTrail = rootPathToDirNoTrail.fileName XCTAssertNotNil(resultRootPathToDirNoTrail) XCTAssertEqual(resultRootPathToDirNoTrail, "baz") let resultRootPathToFile = rootPathToFile.fileName XCTAssertNotNil(resultRootPathToFile) XCTAssertEqual(resultRootPathToFile, "baz") let resultRootPathSingleLetters = rootPathSingleLetters.fileName XCTAssertNotNil(resultRootPathSingleLetters) XCTAssertEqual(resultRootPathSingleLetters, "z") let resultRelPathToDir = relPathToDir.fileName XCTAssertNotNil(resultRelPathToDir) XCTAssertEqual(resultRelPathToDir, "baz") let resultRelPathToDirNoTrail = relPathToDirNoTrail.fileName XCTAssertNotNil(resultRelPathToDirNoTrail) XCTAssertEqual(resultRelPathToDirNoTrail, "baz") let filetRelPathToFile = relPathToFile.fileName XCTAssertNotNil(filetRelPathToFile) XCTAssertEqual(filetRelPathToFile, "baz") let resultRelPathSingleLetters = relPathSingleLetters.fileName XCTAssertNotNil(resultRelPathSingleLetters) XCTAssertEqual(resultRelPathSingleLetters, "z") let resultRandomString = randomString.fileName XCTAssertNil(resultRandomString) } func testExtension() { let resultRootPathToDir = rootPathToDir.extension XCTAssertNil(resultRootPathToDir) let resultRootPathToDirNoTrail = rootPathToDirNoTrail.extension XCTAssertNil(resultRootPathToDirNoTrail) let resultRootPathToFile = rootPathToFile.extension XCTAssertNotNil(resultRootPathToFile) XCTAssertEqual(resultRootPathToFile, "txt") let resultRootPathSingleLetters = rootPathSingleLetters.extension XCTAssertNil(resultRootPathSingleLetters) let resultRelPathToDir = relPathToDir.extension XCTAssertNil(resultRelPathToDir) let resultRelPathToDirNoTrail = relPathToDirNoTrail.extension XCTAssertNil(resultRelPathToDirNoTrail) let filetRelPathToFile = relPathToFile.extension XCTAssertNotNil(filetRelPathToFile) XCTAssertEqual(filetRelPathToFile, "txt") let resultRelPathSingleLetters = relPathSingleLetters.extension XCTAssertNil(resultRelPathSingleLetters) let resultRandomString = randomString.extension XCTAssertNil(resultRandomString) } func testCleanPath() { var testStringA = "/foo/bar//baz/..////data.txt" testStringA.cleanPath() XCTAssertEqual(testStringA, "/foo/bar/data.txt") var testStringB = "../foo/bar//baz/..///..//data.txt" testStringB.cleanPath() XCTAssertEqual(testStringB, "../foo/data.txt") } func testCleanedPath() { let testStringA = "/foo/bar//baz/..///data.txt" XCTAssertEqual(testStringA.cleanedPath(), "/foo/bar/data.txt") let testStringB = "../foo/bar//baz/..///..//data.txt" XCTAssertEqual(testStringB.cleanedPath(), "../foo/data.txt") } func testJoinVararg() { var base1 = "/foo/bar" base1.join("/baz", "..", "/..//data.txt") XCTAssertEqual(base1, "/foo/data.txt") var base2 = "/foo/bar/" base2.join("baz/", "..", "//data.txt") XCTAssertEqual(base2, "/foo/bar/data.txt") } func testJoinArray() { var base1 = "/foo/bar" base1.join(paths: ["/baz", "..", "/..//data.txt"]) XCTAssertEqual(base1, "/foo/data.txt") var base2 = "/foo/bar/" base2.join(paths: ["baz/", "..", "//data.txt"]) XCTAssertEqual(base2, "/foo/bar/data.txt") } func testJoiningVararg() { let base1 = "/foo/bar" XCTAssertEqual(base1.joining("/baz", "..", "/..//data.txt"), "/foo/data.txt") let base2 = "/foo/bar/" XCTAssertEqual(base2.joining("baz/", "..", "//data.txt"), "/foo/bar/data.txt") } func testJoiningArray() { let base1 = "/foo/bar" XCTAssertEqual(base1.joining(paths: ["/baz", "..", "/..//data.txt"]), "/foo/data.txt") let base2 = "/foo/bar/" XCTAssertEqual(base2.joining(paths: ["baz/", "..", "//data.txt"]), "/foo/bar/data.txt") } static var allTests : [(String, (StringURLTests) -> () throws -> Void)] { return [ ("testParent", testParent), ("testFile", testFile), ("testFileName", testFileName), ("testExtension", testExtension), ("testCleanPath", testCleanPath), ("testCleanedPath", testCleanedPath), ("testJoinVararg", testJoinVararg), ("testJoinArray", testJoinArray), ("testJoiningVararg", testJoiningVararg), ("testJoiningArray", testJoiningArray), ] } }
31.966387
89
0.757755
4931e6514e71eb7af6593209020b44d2e4b0aed9
3,824
swift
Swift
SwiftTweaks/StringOptionViewController.swift
turlodales/SwiftTweaks
7c06030f1db8acce3b641218ff16feab7ff20e2f
[ "MIT" ]
null
null
null
SwiftTweaks/StringOptionViewController.swift
turlodales/SwiftTweaks
7c06030f1db8acce3b641218ff16feab7ff20e2f
[ "MIT" ]
null
null
null
SwiftTweaks/StringOptionViewController.swift
turlodales/SwiftTweaks
7c06030f1db8acce3b641218ff16feab7ff20e2f
[ "MIT" ]
null
null
null
// // StringOptionViewController.swift // SwiftTweaks // // Created by Bryan Clark on 6/22/17. // Copyright © 2017 Khan Academy. All rights reserved. // import Foundation import UIKit internal protocol StringOptionViewControllerDelegate: AnyObject { func stringOptionViewControllerDidPressDismissButton(_ tweakSelectionViewController: StringOptionViewController) } /// Allows the user to select an option for a StringListOption value. internal class StringOptionViewController: UITableViewController { fileprivate let tweak: Tweak<StringOption> fileprivate let tweakStore: TweakStore fileprivate unowned var delegate: StringOptionViewControllerDelegate fileprivate var currentOption: String { didSet { tweakStore.setValue( .stringList( value: StringOption(value: currentOption), defaultValue: tweak.defaultValue, options: tweak.options ?? [] ), forTweak: AnyTweak(tweak: tweak) ) self.tableView.reloadData() } } fileprivate static let cellIdentifier = "TweakSelectionViewControllerCellIdentifier" init(anyTweak: AnyTweak, tweakStore: TweakStore, delegate: StringOptionViewControllerDelegate) { assert(anyTweak.tweakViewDataType == .stringList, "Can only choose a string list value in this UI.") self.tweak = anyTweak.tweak as! Tweak<StringOption> self.tweakStore = tweakStore self.delegate = delegate self.currentOption = tweakStore.currentValueForTweak(self.tweak).value super.init(style: UITableView.Style.plain) self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: StringOptionViewController.cellIdentifier) self.tableView.reloadData() title = tweak.tweakName toolbarItems = [ UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), UIBarButtonItem(title: TweaksViewController.dismissButtonTitle, style: .done, target: self, action: #selector(self.dismissButtonTapped)) ] self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Reset", style: .plain, target: self, action: #selector(StringOptionViewController.restoreDefaultValue)) self.navigationItem.rightBarButtonItem?.tintColor = AppTheme.Colors.controlDestructive } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tweak.options?.count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = self.tableView.dequeueReusableCell(withIdentifier: StringOptionViewController.cellIdentifier)! let option = tweak.options![indexPath.row].value cell.textLabel?.text = option cell.accessoryType = (option == self.currentOption) ? .checkmark : .none return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.currentOption = tweak.options![indexPath.row].value self.navigationController?.popViewController(animated: true) } // MARK: Events @objc private func dismissButtonTapped() { delegate.stringOptionViewControllerDidPressDismissButton(self) } @objc private func restoreDefaultValue() { let confirmationAlert = UIAlertController(title: "Reset This Tweak?", message: "Your other tweaks will be left alone. The default value is \(tweak.defaultValue.value)", preferredStyle: .actionSheet) confirmationAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) confirmationAlert.addAction(UIAlertAction(title: "Reset Tweak", style: .destructive, handler: { _ in self.currentOption = self.tweak.defaultValue.value })) present(confirmationAlert, animated: true, completion: nil) } }
36.419048
200
0.774582
e521c74c42dc73065210ed20f0c9331b19ff28a3
3,196
html
HTML
_site/notes/quicksort.html
switchkiller/switchkiller.github.io
7ec0b6390ef3665d8448a0a3e914aafb9ace36de
[ "MIT" ]
null
null
null
_site/notes/quicksort.html
switchkiller/switchkiller.github.io
7ec0b6390ef3665d8448a0a3e914aafb9ace36de
[ "MIT" ]
null
null
null
_site/notes/quicksort.html
switchkiller/switchkiller.github.io
7ec0b6390ef3665d8448a0a3e914aafb9ace36de
[ "MIT" ]
null
null
null
<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1" /><title>Quicksort</title><meta name="twitter:card" content="summary" /><meta name="twitter:site" content="@varunnurab" /><meta name="twitter:title" content="Quicksort" /><meta name="twitter:description" content="Quick Sort"><meta name="description" content="Quick Sort"><meta name="google-site-verification" content="epFgX0s_0RM3CdjwFcsewfXzPov2g8s9ZBOLyaIUH-o"><link rel="icon" href="/assets/favicon.png"><link rel="apple-touch-icon" href="/assets/touch-icon.png"><link rel="stylesheet" href="//code.cdn.mozilla.net/fonts/fira.css"><link rel="stylesheet" href="/assets/core.css"><link rel="canonical" href="/notes/quicksort"><link rel="alternate" type="application/atom+xml" title="Barun." href="/feed.xml" /></head><body><aside class="logo"> <a href="/"> <img src="http://www.gravatar.com/avatar/6f91bf41cec90b8d64bffc5853f26b12.png?s=80" class="gravatar"> </a> <span class="logo-prompt">Back to Home</span></aside><main> <noscript><style> article .footnotes { display: block; }</style></noscript><article><div class="center"><h1>Quicksort</h1><time>August 9, 2015</time></div><div class="divider"></div><h1 id="quick-sort">Quick Sort</h1><p>You might have learnt a lot about quicksort sort. The problem is you have to keep track of the revision tour. Trust me this is supposed to be your last tour on quicksort sort. I will be using C++ to code/design my algorithm.</p><h5 id="quicksort-is-also-called-sorting-by-randomization">Quicksort is also called sorting by randomization</h5><p>Quicksort divides the list of numbers into low and high piles respectively. Suppose you choose any <code>p</code> from the list of numbers. It will be divided as the numbers greater than p and other pile where numbers are less than pile p. This method is called <code>partitioning.</code></p><p>Basically everything is done if you solve this partitioning problem.</p><p>Toooo eaassyy?? Yup, its easy and cooooll :)</p><pre><code> quicksort(item_type s[],int low, int high){ int p; /*Partitioning position index*/ if (high-1 &gt; 0){ p = partition(s,low,high); quicksort(s,low,p-1); quicksort(s,p+1,high); } } </code></pre><p>We can partition the array in one linear scan for a particular pivot element by maintaining three section of the array: less than pivot(to the left of the firsthigh), greater than or equal to the pivot (between firsthigh and i), and unexplored(to right of i), as implemented below:</p><pre><code> int partition (item type s[], int low, int high){ int i; int p; // Pivot element index int firsthigh; //divider position for the index. p = high; firsthigh = 1; for (int i = low; i &lt; high; i++){ if (s[i] &lt; s[p]){ swap(&amp;s[i],&amp;s[firsthigh]); firsthigh++; } } swap(&amp;s[p],&amp;s[firsthigh]); return firsthigh; } </code></pre></article><div class="back"> <a href="/">Back</a></div></main></body></html>
127.84
2,146
0.682416
2616228c8c2d79026737544bb86b5ca5a5f5f929
1,196
java
Java
src/slogo/view/canvas/CanvasHolder.java
blucifer22/slow-go
ab32f2462b95faa8d3bf379fd5b4d37b78078754
[ "MIT" ]
null
null
null
src/slogo/view/canvas/CanvasHolder.java
blucifer22/slow-go
ab32f2462b95faa8d3bf379fd5b4d37b78078754
[ "MIT" ]
null
null
null
src/slogo/view/canvas/CanvasHolder.java
blucifer22/slow-go
ab32f2462b95faa8d3bf379fd5b4d37b78078754
[ "MIT" ]
null
null
null
package slogo.view.canvas; import java.util.function.Consumer; import javafx.geometry.Insets; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.CornerRadii; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; import slogo.view.SelectorTarget; /** * Holds the turtle canvas in the main part of the application window. * * @author David Li */ public class CanvasHolder extends StackPane implements SelectorTarget<Color> { private final TurtleCanvas myTurtleCanvas; /** * Main Constructor */ public CanvasHolder() { this.setId("CanvasHolder"); myTurtleCanvas = new TurtleCanvas(); this.getChildren().addAll(myTurtleCanvas); } /** * Changes background color of the turtle canvas when a new background color is selected */ @Override public Consumer<Color> updateAction() { return color -> myTurtleCanvas .setBackground(new Background(new BackgroundFill(color, CornerRadii.EMPTY, Insets.EMPTY))); } public TurtleCanvas getTurtleCanvas() { return myTurtleCanvas; } public TurtleView getTurtleView() { return myTurtleCanvas.getTurtleView(); } }
24.408163
99
0.742475
d31849ebe5f145e47b26f3aeecda74d55da467fc
16,929
kt
Kotlin
workspace/src/main/kotlin/club/itsp/elang/agmob/workspace/App.kt
Linsho/AgMob
8c2285e0c4cb461ca13038ad74dca400147e8812
[ "MIT" ]
1
2020-09-14T10:45:57.000Z
2020-09-14T10:45:57.000Z
workspace/src/main/kotlin/club/itsp/elang/agmob/workspace/App.kt
Linsho/AgMob
8c2285e0c4cb461ca13038ad74dca400147e8812
[ "MIT" ]
9
2020-09-06T14:57:37.000Z
2022-03-25T18:45:32.000Z
workspace/src/main/kotlin/club/itsp/elang/agmob/workspace/App.kt
LiC0ng/AgMob
19b38ba1ce68b959a573cd80781dd59ca0b2b722
[ "MIT" ]
1
2019-11-08T05:01:11.000Z
2019-11-08T05:01:11.000Z
package club.itsp.elang.agmob.workspace import io.ktor.application.call import io.ktor.application.install import io.ktor.application.log import io.ktor.http.ContentType import io.ktor.http.HttpStatusCode import io.ktor.http.cio.websocket.* import io.ktor.request.receiveText import io.ktor.response.respondText import io.ktor.routing.get import io.ktor.routing.post import io.ktor.routing.put import io.ktor.routing.routing import io.ktor.server.engine.embeddedServer import io.ktor.server.netty.Netty import io.ktor.websocket.WebSocketServerSession import io.ktor.websocket.WebSockets import io.ktor.websocket.webSocket import kotlinx.serialization.Serializable import kotlinx.serialization.Transient import kotlinx.serialization.json.Json import org.slf4j.LoggerFactory import java.util.* import kotlin.collections.HashMap @Serializable class SessionConfiguration( // The length of a 'mob session' in seconds var interval: Int, // The unix time stamp in seconds (JavaScript: Date.now() / 1000) var begin: Long, // The mode of a 'mob session' var mode: String = "Free Mode", // The state of a mob 'session' var state: String = "No Connection" ) @Serializable class Session(var config: SessionConfiguration) { val id = UUID.randomUUID().toString() // The history of chat var history: String = "" @Transient var driver: DriverConnection? = null private set @Transient val navigators = HashMap<Int, NavigatorConnection>() @Transient val log = LoggerFactory.getLogger(this.javaClass)!! @Synchronized fun addNavigator(conn: NavigatorConnection) { navigators[conn.id] = conn } @Synchronized suspend fun setDriver(conn: DriverConnection?) { disconnectDriver(driver) log.debug("[$id] connecting driver: $conn") driver = conn // Notify already-connected navigators that they can now attempt WebRTC connection log.debug("[$id] notifying navigators connection of driver: $conn") navigators.values.forEach { nav -> if (!nav.dead) nav.notifyDriverReady() } pruneDeadNavigators() } // Yucks @Synchronized suspend fun disconnectDriver(current: DriverConnection?) { log.debug("[$id] disconnecting driver: $current") if (driver != current || current == null) return log.debug("[$id] disconnecting WebSocket with driver: $current") current.disconnect() driver = null log.debug("[$id] notifying navigators disconnection of driver: $current") navigators.values.forEach { nav -> if (!nav.dead) nav.notifyDriverQuit() } } @Synchronized private fun pruneDeadNavigators() { ArrayList(navigators.values).forEach { if (it.dead) navigators.remove(it.id) } } } abstract class BaseConnection(val session: Session, protected val wsSession: WebSocketServerSession) { val id = idBase++ var dead = false private set protected fun markAsDead() { dead = true } protected suspend fun sendMessage(m: WebSocketMessage) { if (dead) session.log.info("[BUG] sendMessage called on a dead connection: ${Exception().stackTrace}") val s = m.toJson() try { wsSession.send(s) } catch (e: Exception) { session.log.debug("[${session.id}] dead connection detected during sendMessage: $this") markAsDead() } } suspend fun disconnect() { wsSession.close() } companion object { private var idBase = 0 } } class DriverConnection(session: Session, wsSession: WebSocketServerSession) : BaseConnection(session, wsSession) { suspend fun requestSdpOffer(navConn: NavigatorConnection, message: WebSocketMessage) { sendMessage(WebSocketMessage("request_sdp", message.payload, navConn.id)) } suspend fun receiveNavigatorSdp(navConn: NavigatorConnection, message: WebSocketMessage, remoteId: Int) { sendMessage(WebSocketMessage("navigator_sdp", message.payload, navConn.id, remoteId)) } suspend fun answerNavigatorSdp(navConn: NavigatorConnection, message: WebSocketMessage, remoteId: Int) { sendMessage(WebSocketMessage("navigator_answer", message.payload, navConn.id, remoteId)) } suspend fun navigatorIce(navConn: NavigatorConnection, message: WebSocketMessage, remoteId: Int) { sendMessage(WebSocketMessage("navigator_ice", message.payload, navConn.id, remoteId)) } suspend fun receiveSdpAnswer(navConn: NavigatorConnection, message: WebSocketMessage) { sendMessage(WebSocketMessage("sdp", message.payload, navConn.id)) } suspend fun receiveIceCandidate(navConn: NavigatorConnection, message: WebSocketMessage) { sendMessage(WebSocketMessage("ice_candidate", message.payload, navConn.id)) } suspend fun sendChatMessage(navConn: NavigatorConnection, message: WebSocketMessage) { sendMessage(WebSocketMessage("chat", message.payload, navConn.id)) } suspend fun driverChatMessage(message: WebSocketMessage) { sendMessage(WebSocketMessage("chat", message.payload)) } } class NavigatorConnection(session: Session, wsSession: WebSocketServerSession) : BaseConnection(session, wsSession) { suspend fun requestSdpOffer(message: WebSocketMessage, navigator_id: Int, remoteId: Int) { sendMessage(WebSocketMessage("navigator_request_sdp", message.payload, navigator_id, remoteId)) } suspend fun receiveNavigatorSdp(message: WebSocketMessage, navigator_id: Int, remoteId: Int) { sendMessage(WebSocketMessage("navigator_sdp", message.payload, navigator_id, remoteId)) } suspend fun answerNavigatorSdp(message: WebSocketMessage, navigator_id: Int, remoteId: Int) { sendMessage(WebSocketMessage("navigator_answer", message.payload, navigator_id, remoteId)) } suspend fun navigatorIce(message: WebSocketMessage, navigator_id: Int, remoteId: Int) { sendMessage(WebSocketMessage("navigator_ice", message.payload, navigator_id, remoteId)) } suspend fun receiveSdpOffer(message: WebSocketMessage, navigator_id: Int) { sendMessage(WebSocketMessage("sdp", message.payload, navigator_id)) } suspend fun receiveIceCandidate(message: WebSocketMessage, navigator_id: Int) { sendMessage(WebSocketMessage("ice_candidate", message.payload, navigator_id)) } suspend fun notifyDriverReady() { sendMessage(WebSocketMessage("driver_ready", "")) } suspend fun notifyDriverQuit() { sendMessage(WebSocketMessage("driver_quit", "")) } } // FIXME: navigator_id smells bad @Serializable data class WebSocketMessage(val kind: String, val payload: String, val navigator_id: Int = -1, val remoteId: Int = -1) { fun toJson(): String = Json.stringify(serializer(), this) companion object { fun parseJson(data: String) = Json.parse(serializer(), data) } } fun main(args: Array<String>) { val sessions = HashMap<String, Session>() embeddedServer(Netty, 8080) { install(WebSockets) routing { post("/api/session") { val configText = call.receiveText() // FIXME: Once driver supports it, this 'if' must be removed val sess = Session(if (configText.isNotBlank()) Json.parse(SessionConfiguration.serializer(), configText) else SessionConfiguration(10 * 60, System.currentTimeMillis() / 1000L)) sessions[sess.id] = sess call.respondText(Json.stringify(Session.serializer(), sess), ContentType.Application.Json) } put("/api/session/{id}") { val sess = sessions[call.parameters["id"]] if (sess == null) { call.respondText("FIXME: invalid sess id", status = HttpStatusCode.BadRequest) return@put } val newConfig = Json.parse(SessionConfiguration.serializer(), call.receiveText()) sess.config = newConfig call.respondText(Json.stringify(Session.serializer(), sess), ContentType.Application.Json) } get("/api/session/{id}") { val sess = sessions[call.parameters["id"]] if (sess == null) { call.respondText("FIXME: invalid sess id", status = HttpStatusCode.BadRequest) return@get } call.respondText(Json.stringify(Session.serializer(), sess), ContentType.Application.Json) } webSocket("/api/session/{id}/navigator") { val sess = sessions[call.parameters["id"]] if (sess == null) { call.respondText("FIXME: invalid sess id", status = HttpStatusCode.BadRequest) return@webSocket } val conn = NavigatorConnection(sess, this) log.debug("[${sess.id}] connecting navigator: $conn") sess.addNavigator(conn) for (frame in incoming) { if (frame !is Frame.Text) { close(CloseReason(CloseReason.Codes.CANNOT_ACCEPT, "FIXME: invalid frame")) continue } val msg = WebSocketMessage.parseJson(frame.readText()) when (msg.kind) { "request_sdp" -> { val driver = sess.driver if (driver == null) log.debug("[${sess.id}] ignoring request_sdp from nav-${conn.id}") driver?.requestSdpOffer(conn, msg) } "navigator_sdp" -> { val driver = sess.driver val remoteId = msg.remoteId; if (driver == null) log.debug("[${sess.id}] ignoring sdp from nav-${conn.id}") driver?.receiveNavigatorSdp(conn, msg, remoteId) } "navigator_answer" -> { val driver = sess.driver val remoteId = msg.remoteId; if (driver == null) log.debug("[${sess.id}] ignoring sdp from nav-${conn.id}") driver?.answerNavigatorSdp(conn, msg, remoteId) } "navigator_ice" -> { val driver = sess.driver val remoteId = msg.remoteId; if (driver == null) log.debug("[${sess.id}] ignoring sdp from nav-${conn.id}") driver?.navigatorIce(conn, msg, remoteId) } "sdp" -> { val driver = sess.driver if (driver == null) log.debug("[${sess.id}] ignoring sdp from nav-${conn.id}") driver?.receiveSdpAnswer(conn, msg) } "ice_candidate" -> { val driver = sess.driver if (driver == null) log.debug("[${sess.id}] ignoring ice_candidate from nav-${conn.id}") driver?.receiveIceCandidate(conn, msg) } "chat" -> { val driver = sess.driver if (driver == null) log.debug("[${sess.id}] ignoring chat from nav-${conn.id}") driver?.sendChatMessage(conn, msg) } else -> { log.info("[${sess.id}] invalid websocket message ${msg.kind} from nav-${conn.id}") } } } } webSocket("/api/session/{id}/driver") { val sess = sessions[call.parameters["id"]] if (sess == null) { call.respondText("FIXME: invalid sess id", status = HttpStatusCode.BadRequest) return@webSocket } val conn = DriverConnection(sess, this) log.debug("[${sess.id}] connecting driver: $conn") sess.setDriver(conn) try { for (frame in incoming) { if (frame !is Frame.Text) { close(CloseReason(CloseReason.Codes.CANNOT_ACCEPT, "FIXME: invalid frame")) continue } val msg = WebSocketMessage.parseJson(frame.readText()) when (msg.kind) { "navigator_request_sdp" -> { val navConn = sess.navigators[msg.navigator_id] if (navConn == null) log.debug("[${sess.id}] ignoring request sdp to nav-${msg.navigator_id}") navConn?.requestSdpOffer(msg, msg.navigator_id, msg.remoteId) } "navigator_sdp" -> { val navConn = sess.navigators[msg.navigator_id] if (navConn == null) log.debug("[${sess.id}] ignoring request sdp to nav-${msg.navigator_id}") navConn?.receiveNavigatorSdp(msg, msg.navigator_id, msg.remoteId) } "navigator_answer" -> { val navConn = sess.navigators[msg.navigator_id] if (navConn == null) log.debug("[${sess.id}] ignoring request sdp to nav-${msg.navigator_id}") navConn?.answerNavigatorSdp(msg, msg.navigator_id, msg.remoteId) } "navigator_ice" -> { val navConn = sess.navigators[msg.navigator_id] if (navConn == null) log.debug("[${sess.id}] ignoring request sdp to nav-${msg.navigator_id}") navConn?.navigatorIce(msg, msg.navigator_id, msg.remoteId) } "sdp" -> { val navConn = sess.navigators[msg.navigator_id] if (navConn == null) log.debug("[${sess.id}] ignoring sdp to nav-${msg.navigator_id}") log.debug("${msg.navigator_id}") log.debug(msg.payload) navConn?.receiveSdpOffer(msg, msg.navigator_id) } "ice_candidate" -> { val navConn = sess.navigators[msg.navigator_id] if (navConn == null) log.debug("[${sess.id}] ignoring ice_candidate to nav-${msg.navigator_id}") log.debug("${msg.navigator_id}") log.debug(msg.payload) navConn?.receiveIceCandidate(msg, msg.navigator_id) } "quit" -> { log.info("driver: quitting") close() return@webSocket } "driver_quit" -> { sess.config.state = "No Connection" } "chat_history" -> { sess.history += msg.payload } "chat" -> { val driver = sess.driver driver?.driverChatMessage(msg) } else -> { log.info("invalid websocket message from driver: " + msg.kind) } } } } finally { sess.disconnectDriver(conn) } } } }.start(wait = true) }
42.535176
120
0.527615
a2d1762ee59d4ac5106098428764a717900ee316
1,442
swift
Swift
DJExtensionDemo/DJExtensionDemo/DJExtension/DJConstants.swift
iwufan/DJExtension
05272b6191fce7c059c2417ec18e10fac3d4cc1c
[ "MIT" ]
3
2018-08-06T07:53:55.000Z
2020-09-13T19:52:35.000Z
DJExtensionDemo/DJExtensionDemo/DJExtension/DJConstants.swift
iwufan/DJExtension
05272b6191fce7c059c2417ec18e10fac3d4cc1c
[ "MIT" ]
null
null
null
DJExtensionDemo/DJExtensionDemo/DJExtension/DJConstants.swift
iwufan/DJExtension
05272b6191fce7c059c2417ec18e10fac3d4cc1c
[ "MIT" ]
null
null
null
// // Constants.swift // DJExtension // // Created by David Jia on 15/8/2017. // Copyright © 2017 David Jia. All rights reserved. // import UIKit // common values public let djScreenWidth = UIScreen.main.bounds.width public let djScreenHeight = UIScreen.main.bounds.height // colors public let djCoverColor = UIColor.black.withAlphaComponent(0.5) // cover color public let djWhite = UIColor.white public let djBlack = UIColor.black public let djDarkGray = UIColor.darkGray public let djLightGray = UIColor.lightGray public let djGray = UIColor.gray public let djRed = UIColor.red public let djGreen = UIColor.green public let djBlue = UIColor.blue public let djCyan = UIColor.cyan public let djYellow = UIColor.yellow public let djMagenta = UIColor.magenta public let djOrange = UIColor.orange public let djPurple = UIColor.purple public let djBrown = UIColor.brown public let djClear = UIColor.clear // info public let djCFBundleVersion = "CFBundleShortVersionString" // app version // key public let djRangeLocation = "rangeLocation" // used in creating AttributeString, DON'T modify it public let djRangeLength = "rangeLength" // used in creating AttributeString, DON'T modify it
36.974359
119
0.643551
e75ab7927efc4328f80acc7512104f429a4b52b9
3,424
js
JavaScript
src/brink/main.js
gigafied/brink.js
a53fce00c923cab37356816ccd16694a51821855
[ "MIT", "Unlicense" ]
null
null
null
src/brink/main.js
gigafied/brink.js
a53fce00c923cab37356816ccd16694a51821855
[ "MIT", "Unlicense" ]
null
null
null
src/brink/main.js
gigafied/brink.js
a53fce00c923cab37356816ccd16694a51821855
[ "MIT", "Unlicense" ]
null
null
null
'use strict'; var $b, _global, CONFIG, IS_NODE, EMPTY_FN; /*jshint ignore : start */ IS_NODE = typeof module !== 'undefined' && module.exports; /*jshint ignore : end */ EMPTY_FN = function () {}; _global = IS_NODE ? global : window; CONFIG = _global.Brink || _global.$b || {}; $b = _global.$b = _global.Brink = function () { var args; args = Array.prototype.slice.call(arguments, 0); if (args.length) { if (args.length === 1 && typeof args[0] === 'string') { if ($b.require) { return $b.require.apply(_global, args); } } if ($b.define) { if (!Array.isArray(args[0]) && !Array.isArray(args[1])) { args.splice(args.length - 1, 0, []); } return $b.define.apply(_global, args); } } return $b; }; $b.F = EMPTY_FN; /* These are empty functions for production builds, only the dev version actually implements these, but we don't want code that uses them to Error. */ $b.assert = $b.error = EMPTY_FN; $b.configure = function (o) { var p; for (p in o) { CONFIG[p] = o[p]; } $b.require.config(CONFIG); return $b; }; $b.init = function (deps, cb) { $b.require( /* jscs : disable requireCommaBeforeLineBreak */ /*{{modules}}*/ [ 'brink/config', 'brink/dev/assert', 'brink/dev/error', 'brink/dev/warn', 'brink/utils/alias', 'brink/utils/bindTo', 'brink/utils/clone', 'brink/utils/computed', 'brink/utils/configure', 'brink/utils/defineProperty', 'brink/utils/extend', 'brink/utils/expandProps', 'brink/utils/flatten', 'brink/utils/intersect', 'brink/utils/params', 'brink/utils/Q', 'brink/utils/xhr', 'brink/utils/ready', 'brink/utils/isBrinkInstance', 'brink/utils/isFunction', 'brink/utils/isObject', 'brink/utils/merge', 'brink/utils/set', 'brink/utils/trim', 'brink/utils/unbound', 'brink/core/Object', 'brink/core/Class', 'brink/core/Array', 'brink/core/Dictionary', 'brink/core/ObjectProxy', 'brink/core/InstanceManager', 'brink/data/Adapter', 'brink/data/RESTAdapter', 'brink/data/attr', 'brink/data/belongsTo', 'brink/data/hasMany', 'brink/data/Model', 'brink/data/Schema', 'brink/data/Store', 'brink/data/Collection', 'brink/node/build' ] /*{{/modules}}*/ , function () { /* jscs : enable */ /********* ALIASES *********/ $b.merge($b.config, CONFIG); if ($b.isFunction(deps)) { cb = deps; cb($b); } else { deps = deps || []; if (deps.length) { $b.require(deps, cb); } else { if (cb) { cb(); } } } } ); }; if (IS_NODE) { module.exports = $b; }
20.878049
69
0.451519
24be93f271c8e2b4347cdb0bc07871a1e4802389
636
asm
Assembly
ch07/32 bit/Multiply.asm
William0Friend/my_masm
e8073266c03c01424ad84b9ed9cf13e9da1eabb1
[ "Apache-2.0" ]
null
null
null
ch07/32 bit/Multiply.asm
William0Friend/my_masm
e8073266c03c01424ad84b9ed9cf13e9da1eabb1
[ "Apache-2.0" ]
null
null
null
ch07/32 bit/Multiply.asm
William0Friend/my_masm
e8073266c03c01424ad84b9ed9cf13e9da1eabb1
[ "Apache-2.0" ]
null
null
null
; Multiplication Examples (Multiply.asm) ; This program shows examples of both signed and unsigned multiplication. INCLUDE Irvine32.inc .code main PROC mov ax,255 mov bx,255 imul bx ;Example 1 mov al,5h mov bl,10h mul bl ; CF = 0 ;Example 2 .data val1 WORD 2000h val2 WORD 0100h .code mov ax,val1 mul val2 ; CF = 1 ;Example 3: mov eax,12345h mov ebx,1000h mul ebx ; CF = 1 ; IMUL Examples: ; Example 4: .data val3 SDWORD ? .code mov eax,+4823424 mov ebx,-423 imul ebx ; EDX=FFFFFFFFh, EAX=86635D80h mov val3,eax exit main ENDP END main
14.133333
74
0.625786
7aba976f8e04dd8ffbd9c1f112f2b697445f910f
1,009
rs
Rust
src/pricingengines/traits.rs
surfertas/quantlib
5b2634b1cacae23e7201a786b479d429f186437f
[ "MIT" ]
68
2020-04-12T15:48:25.000Z
2022-03-08T17:14:52.000Z
src/pricingengines/traits.rs
rafalpiotrowski/quantlib
5b2634b1cacae23e7201a786b479d429f186437f
[ "MIT" ]
4
2021-02-27T13:26:05.000Z
2021-04-15T13:56:44.000Z
src/pricingengines/traits.rs
rafalpiotrowski/quantlib
5b2634b1cacae23e7201a786b479d429f186437f
[ "MIT" ]
16
2020-06-19T07:35:21.000Z
2022-01-17T13:25:41.000Z
use crate::definitions::Money; use crate::time::Date; use std::collections::HashMap; pub trait PricingEngine { type R: Results; type A: Arguments; fn get_results(&self) -> Self::R; fn get_arguments(&self) -> Self::A; fn reset(&self); fn update(&self); fn calculate(&self); } pub trait Results { fn reset(&mut self); fn get(&self) -> &BaseResults; } /// Results. /// ============================ /// /// /// BaseResults is a base class for pricing engine results. pub struct BaseResults { pub value: Money, pub error_estimate: Money, pub valuation_date: Date, pub additional_results: HashMap<String, Money>, } impl Results for BaseResults { fn reset(&mut self) { self.valuation_date = Date::default(); self.value = Money::default(); self.error_estimate = Money::default(); self.additional_results.clear(); } fn get(&self) -> &BaseResults { self } } pub trait Arguments { fn validate(&self); }
21.468085
59
0.607532
40c89078b0fd4bcca4fe39acf06dbdc315d11f2b
67
py
Python
ptsr/config/__init__.py
prateek-77/rcan-it
587904556d8127bca83690deaaa26e34e051a576
[ "MIT" ]
57
2022-01-28T04:44:42.000Z
2022-03-31T13:26:35.000Z
ptsr/config/__init__.py
chisyliu/rcan-it
eb1794777ffef4eadd8a6a06f4419380a0b17435
[ "MIT" ]
6
2022-02-08T11:17:19.000Z
2022-03-27T07:40:18.000Z
ptsr/config/__init__.py
chisyliu/rcan-it
eb1794777ffef4eadd8a6a06f4419380a0b17435
[ "MIT" ]
10
2022-01-28T07:31:12.000Z
2022-03-15T01:35:03.000Z
from .defaults import get_cfg_defaults from .utils import load_cfg
33.5
39
0.850746
47d0c3e469af82a26b7b003836d29c5289e1f43e
98
sql
SQL
apex/page/54/region/Data Load Wizard Progress/sub_region/Data Load Results/page_item/P54_ERROR_COUNT/P54_ERROR_COUNT[sourceQuery].sql
vincentmorneau/insum-insider-demo
f359a5fe205a6598a226c0e90f56cb1f93b2d9b0
[ "CC0-1.0" ]
2
2020-04-30T11:20:35.000Z
2020-05-03T22:22:02.000Z
apex/page/54/region/Data Load Wizard Progress/sub_region/Data Load Results/page_item/P54_ERROR_COUNT/P54_ERROR_COUNT[sourceQuery].sql
vincentmorneau/insum-insider-demo
f359a5fe205a6598a226c0e90f56cb1f93b2d9b0
[ "CC0-1.0" ]
8
2020-04-29T18:23:56.000Z
2020-08-24T18:39:32.000Z
apex/page/54/region/Data Load Wizard Progress/sub_region/Data Load Results/page_item/P54_ERROR_COUNT/P54_ERROR_COUNT[sourceQuery].sql
vincentmorneau/insum-insider-demo
f359a5fe205a6598a226c0e90f56cb1f93b2d9b0
[ "CC0-1.0" ]
null
null
null
select count(*) c from apex_collections where collection_name = 'LOAD_CONTENT' and c047 = 'FAILED'
98
98
0.785714
16d69b036fac464e51def8c876d1b4c662c6195b
1,148
ts
TypeScript
client/styles/boxshadows.ts
JungKyuHyun/guest-book
7186a1e40568436af9edfe887f004c4cc5137800
[ "MIT" ]
3
2021-08-04T17:59:30.000Z
2021-08-05T06:37:05.000Z
client/styles/boxshadows.ts
JungKyuHyun/guest-book
7186a1e40568436af9edfe887f004c4cc5137800
[ "MIT" ]
1
2021-08-08T06:29:51.000Z
2021-08-08T11:44:10.000Z
client/styles/boxshadows.ts
JungKyuHyun/guest-book
7186a1e40568436af9edfe887f004c4cc5137800
[ "MIT" ]
1
2021-08-08T06:26:25.000Z
2021-08-08T06:26:25.000Z
export const boxShadows = { dp0: 'none', dp1: '0 1px 1px 0 rgba(0,0,0,0.14),0 2px 1px -1px rgba(0,0,0,0.12),0 1px 3px 0 rgba(0,0,0,0.20)', dp2: '0 2px 2px 0 rgba(0,0,0,0.14),0 3px 1px -2px rgba(0,0,0,0.12),0 1px 5px 0 rgba(0,0,0,0.20)', dp3: '0 3px 4px 0 rgba(0,0,0,0.14),0 3px 3px -2px rgba(0,0,0,0.12),0 1px 8px 0 rgba(0,0,0,0.20)', dp4: '0 4px 5px 0 rgba(0,0,0,0.14),0 1px 10px 0 rgba(0,0,0,0.12),0 2px 4px -1px rgba(0,0,0,0.20)', dp6: '0 6px 10px 0 rgba(0,0,0,0.14),0 1px 18px 0 rgba(0,0,0,0.12),0 3px 5px -1px rgba(0,0,0,0.20)', dp8: '0 8px 10px 1px rgba(0,0,0,0.14),0 3px 14px 2px rgba(0,0,0,0.12),0 5px 5px -3px rgba(0,0,0,0.20)', dp9: '0 9px 12px 1px rgba(0,0,0,0.14),0 3px 16px 2px rgba(0,0,0,0.12),0 5px 6px -3px rgba(0,0,0,0.20)', dp12: '0 12px 17px 2px rgba(0,0,0,0.14),0 5px 22px 4px rgba(0,0,0,0.12),0 7px 8px -4px rgba(0,0,0,0.20)', dp16: '0 16px 24px 2px rgba(0,0,0,0.14),0 6px 30px 5px rgba(0,0,0,0.12),0 8px 10px -5px rgba(0,0,0,0.20)', dp24: '0 24px 38px 3px rgba(0,0,0,0.14),0 9px 46px 8px rgba(0,0,0,0.12),0 11px 15px -7px rgba(0,0,0,0.20)', } as const; export type BoxShadows = keyof typeof boxShadows;
71.75
109
0.616725
4b0348078988be29e3d28124d7fc4ce29f52bdcc
63
kt
Kotlin
app/src/main/java/io/de4l/app/ui/event/TokenInfoClickedEvent.kt
DE4L-Project/de4l-sensor-android-app
11040a53ba7760b987eade68b46d048d5f83569f
[ "MIT" ]
null
null
null
app/src/main/java/io/de4l/app/ui/event/TokenInfoClickedEvent.kt
DE4L-Project/de4l-sensor-android-app
11040a53ba7760b987eade68b46d048d5f83569f
[ "MIT" ]
null
null
null
app/src/main/java/io/de4l/app/ui/event/TokenInfoClickedEvent.kt
DE4L-Project/de4l-sensor-android-app
11040a53ba7760b987eade68b46d048d5f83569f
[ "MIT" ]
1
2022-02-17T11:06:30.000Z
2022-02-17T11:06:30.000Z
package io.de4l.app.ui.event class TokenInfoClickedEvent { }
10.5
29
0.777778
abfbb0d952e0074613db6afaeac2223914044f6d
624
rb
Ruby
lib/cinebase/title_sanitizer.rb
andycroll/cinebase
5011c487c28ef1d0bad2216fdad696de5cfa9c7c
[ "MIT" ]
2
2016-08-12T06:35:09.000Z
2017-02-10T22:11:39.000Z
lib/cinebase/title_sanitizer.rb
andycroll/cinebase
5011c487c28ef1d0bad2216fdad696de5cfa9c7c
[ "MIT" ]
null
null
null
lib/cinebase/title_sanitizer.rb
andycroll/cinebase
5011c487c28ef1d0bad2216fdad696de5cfa9c7c
[ "MIT" ]
null
null
null
module Cinebase # Sabitize titles base class TitleSanitizer = Struct.new(:title) do def sanitized @sanitized ||= begin sanitized = title remove.each do |pattern| sanitized.gsub! pattern, '' end replace.each do |pattern, prefix| sanitized.gsub!(pattern) { |_| prefix + $1 } end sanitized.squeeze(' ').strip end end private def remove fail NotImplementedError, "This #{self.class} cannot respond to: " end def replace fail NotImplementedError, "This #{self.class} cannot respond to: " end end end
22.285714
72
0.597756
7d5bb2713fb9d148204a6d822b729aea91bdc648
61,093
html
HTML
_site/assets/notes/summary_of_git_usage.html
weiSupreme/weiSupreme.github.io
59d419f2d8207c7da0a427330b21546f4f0d85d0
[ "CC-BY-4.0" ]
3
2018-09-15T05:47:35.000Z
2019-04-08T07:00:02.000Z
_site/assets/notes/summary_of_git_usage.html
weiSupreme/weiSupreme.github.io
59d419f2d8207c7da0a427330b21546f4f0d85d0
[ "CC-BY-4.0" ]
null
null
null
_site/assets/notes/summary_of_git_usage.html
weiSupreme/weiSupreme.github.io
59d419f2d8207c7da0a427330b21546f4f0d85d0
[ "CC-BY-4.0" ]
null
null
null
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Git&nbsp;命令总结_枝叶飞扬_新浪博客</title> <meta name="keywords" content="Git&nbsp;命令总结_枝叶飞扬_新浪博客,枝叶飞扬,git,branch,checkout,merge,commit,it" /> <meta name="description" content="Git&nbsp;命令总结_枝叶飞扬_新浪博客,枝叶飞扬," /> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" /> <meta http-equiv="mobile-agent" content="format=html5; url=http://blog.sina.cn/dpool/blog/s/blog_605f5b4f010194fg.html?vt=4"> <meta http-equiv="mobile-agent" content="format=wml; url=http://blog.sina.cn/dpool/blog/ArtRead.php?nid=605f5b4f010194fg&vt=1"> <!–[if lte IE 6]> <script type="text/javascript"> try{ document.execCommand("BackgroundImageCache", false, true); }catch(e){} </script> <![endif]–> <script type="text/javascript"> window.staticTime=new Date().getTime(); </script> <link rel="pingback" href="http://upload.move.blog.sina.com.cn/blog_rebuild/blog/xmlrpc.php" /> <link rel="EditURI" type="application/rsd+xml" title="RSD" href="http://upload.move.blog.sina.com.cn/blog_rebuild/blog/xmlrpc.php?rsd" /> <link href="http://blog.sina.com.cn/blog_rebuild/blog/wlwmanifest.xml" type="application/wlwmanifest+xml" rel="wlwmanifest" /> <link rel="alternate" type="application/rss+xml" href="http://blog.sina.com.cn/rss/1616862031.xml" title="RSS" /> <link href="http://simg.sinajs.cn/blog7style/css/conf/blog/article.css" type="text/css" rel="stylesheet" /><link href="http://simg.sinajs.cn/blog7style/css/common/common.css" type="text/css" rel="stylesheet" /><link href="http://simg.sinajs.cn/blog7style/css/blog/blog.css" type="text/css" rel="stylesheet" /><link href="http://simg.sinajs.cn/blog7style/css/module/common/blog.css" type="text/css" rel="stylesheet" /><style id="tplstyle" type="text/css">@charset "utf-8";@import url("http://simg.sinajs.cn/blog7newtpl/css/4/4_1/t.css"); </style> <style id="positionstyle" type="text/css"> .sinabloghead .blogtoparea{ left:120px;top:41%;} .sinabloghead .blognav{ left:120px;top:63%;} </style> <style id="bgtyle" type="text/css"> </style> <style id="headtyle" type="text/css"> </style> <style id="navtyle" type="text/css"> </style> <script type="text/javascript" src="http://d1.sina.com.cn/litong/zhitou/sspnew.js"></script></head> <body> <!--$sinatopbar--> <div style="z-index:512;" class="nsinatopbar"> <div style="position:absolute;left:0;top:0;" id="trayFlashConnetion"></div> <div class="ntopbar_main"> <a id="login_bar_logo_link_350" href="http://blog.sina.com.cn" target="_blank"><img class="ntopbar_logo" src="http://simg.sinajs.cn/blog7style/images/common/topbar/topbar_logo.gif" width="100" alt="新浪博客"></a> <div class="ntopbar_floatL"> <div class="ntopbar_search" id="traySearchBar"></div> <div class="ntopbar_ad" id="loginBarActivity" style="display:none;"></div> </div> <div class="ntopbar_loading"><img src="http://simg.sinajs.cn/blog7style/images/common/loading.gif">加载中…</div> </div> </div> <!--$end sinatopbar--> <div class="sinabloga" id="sinabloga"> <div id="sinablogb" class="sinablogb"> <div id="sinablogHead" class="sinabloghead"> <div style="display: none;" id="headflash" class="headflash"></div> <div id="headarea" class="headarea"> <div id="blogTitle" class="blogtoparea"> <h1 id="blogname" class="blogtitle"><a href="http://blog.sina.com.cn/12leaves"><span id="blognamespan">加载中...</span></a></h1> <div id="bloglink" class="bloglink"><a href="http://blog.sina.com.cn/12leaves">http://blog.sina.com.cn/12leaves</a> <a onclick="return false;" class="CP_a_fuc" href="#" id="SubscribeNewRss">[<cite>订阅</cite>]</a><a class="CP_a_fuc" href="javascript:void(scope.pa_add.add('1616862031'));">[<cite>手机订阅</cite>]</a></div> </div> <div class="blognav" id="blognav"> <div id="blognavBg" class="blognavBg"></div> <div class="blognavInfo"> <span><a href="http://blog.sina.com.cn/12leaves">首页</a></span> <span><a class="on" href="http://blog.sina.com.cn/s/articlelist_1616862031_0_1.html">博文目录</a></span> <span><a href="http://photo.blog.sina.com.cn/12leaves">图片</a></span> <span class="last"><a href="http://blog.sina.com.cn/s/profile_1616862031.html">关于我</a></span></div> </div> <div class="autoskin" id="auto_skin"> </div> <div class="adsarea"> <a href="#"><div id="template_clone_pic" class="pic"></div></a> <div id="template_clone_link" class="link wdc_HInf"></div> <div id="template_clone_other" class="other"></div> </div> </div> </div> <!--主题内容开始 --> <div class="sinablogbody" id="sinablogbody"> <!--第一列start--> <div id="column_1" class="SG_colW21 SG_colFirst"><div class="SG_conn" id="module_901"> <div class="SG_connHead"> <span class="title" comp_title="个人资料">个人资料</span> <span class="edit"> </span> </div> <div class="SG_connBody"> <div class="info"> <div class="info_img" id="comp_901_head"><img src="http://simg.sinajs.cn/blog7style/images/common/sg_trans.gif" real_src ="http://portrait8.sinaimg.cn/1616862031/blog/180" id="comp_901_head_image" width="180" height="180" alt="枝叶飞扬" title="枝叶飞扬" /></div> <div class="info_txt"> <div class="info_nm"> <img id="comp_901_online_icon" style="display:none;" class="SG_icon SG_icon1" src="http://simg.sinajs.cn/blog7style/images/common/sg_trans.gif" width="15" height="15" align="absmiddle" /> <span class="SG_txtb"><strong id="ownernick">枝叶飞扬 </strong></span> <div class="clearit"></div> </div> <div class="info_btn1"> <a target="_blank" href="http://weibo.com/u/1616862031?source=blog" class="SG_aBtn SG_aBtn_ico"><cite><img class="SG_icon SG_icon51" src="http://simg.sinajs.cn/blog7style/images/common/sg_trans.gif" width="15" height="15" align="absmiddle" />微博</cite></a> <div class="clearit"></div> </div> <div class="SG_j_linedot"></div> <div class="info_locate" id = "info_locate_id"> <div class="SG_j_linedot"></div> <div class="info_btn2"> <p> <a href="javascript:void(0);" class="SG_aBtn " id="comp901_btn_invite"><cite >加好友</cite></a> <a href="javascript:void(0);" class="SG_aBtn" id="comp901_btn_sendpaper"><cite >发纸条</cite></a> </p> <p> <a href="http://blog.sina.com.cn/s/profile_1616862031.html#write" class="SG_aBtn" id="comp901_btn_msninfo"><cite>写留言</cite></a> <a href="#" onclick="return false;" class="SG_aBtn" id="comp901_btn_follow"><cite onclick="Module.SeeState.add()">加关注</cite></a> </p> <div class="clearit"></div> </div> <div class="SG_j_linedot"></div> </div> <div class="info_list"> <ul class="info_list1"> <li><span class="SG_txtc">博客等级:</span><span id="comp_901_grade"><img src="http://simg.sinajs.cn/blog7style/images/common/sg_trans.gif" real_src="http://simg.sinajs.cn/blog7style/images/common/number/2.gif" /><img src="http://simg.sinajs.cn/blog7style/images/common/sg_trans.gif" real_src="http://simg.sinajs.cn/blog7style/images/common/number/0.gif" /></span></li> <li><span class="SG_txtc">博客积分:</span><span id="comp_901_score"><strong>0</strong></span></li> </ul> <ul class="info_list2"> <li><span class="SG_txtc">博客访问:</span><span id="comp_901_pv"><strong>1,012,571</strong></span></li> <li><span class="SG_txtc">关注人气:</span><span id="comp_901_attention"><strong>188</strong></span></li> <li><span class="SG_txtc">获赠金笔:</span><strong id="comp_901_d_goldpen">0支</strong></li> <li><span class="SG_txtc">赠出金笔:</span><strong id="comp_901_r_goldpen">0支</strong></li> <li class="lisp" id="comp_901_badge"><span class="SG_txtc">荣誉徽章:</span></li> </ul> </div> <div class="clearit"></div> </div> <div class="clearit"></div> </div> </div> <div class="SG_connFoot"></div> </div> <div id="module_903" class="SG_conn "> <div class="SG_connHead"> <span comp_title="相关博文" class="title">相关博文</span> <span class="edit"> </span> </div> <div class="SG_connBody"> <div class="atcTitList relaList"> <ul class=""> <li class="SG_j_linedot1" style="display:none;"> <p id="atcTitLi_SLOT_41" class="atcTitCell_tit SG_dot" style="display:none"> </p> </li> <li class="SG_j_linedot1" style="display:none;"> <p id="atcTitLi_SLOT_42" class="atcTitCell_tit SG_dot" style="display:none"> </p> </li> </ul> <div class="atcTit_more"><span class="SG_more"><a href="http://blog.sina.com.cn/" target="_blank">更多&gt;&gt;</a></span></div></div> </div> <div class="SG_connFoot"></div> </div> <div class="SG_conn " id="module_904"> <div class="SG_connHead"> <span class="title">推荐博文</span> </div> <div class="SG_connBody "> <div class="atcTitList relaList"> <ul class=""> <li class="SG_j_linedot1"><p class="atcTitCell_tit SG_dot"><a suda-uatrack="key=blog_tjblog&value=h_tjblog" title="站在高处看见了别样的景观" target="_blank" href="http://blog.sina.com.cn/s/blog_4ae252b40102yxgi.html?tj=2?tj=2">站在高处看见了别样的景观</a></p> <p class="atcTitCell_nm"><a suda-uatrack="key=blog_tjblog&value=h_tjblog" target="_blank" href="http://blog.sina.com.cn/u/1256346292" class="SG_linkb"></a></p> </li><li class="SG_j_linedot1"><p class="atcTitCell_tit SG_dot"><a suda-uatrack="key=blog_tjblog&value=h_tjblog" title="网红【奶酪包】" target="_blank" href="http://blog.sina.com.cn/s/blog_500017680102w79w.html?tj=2?tj=2">网红【奶酪包】</a></p> <p class="atcTitCell_nm"><a suda-uatrack="key=blog_tjblog&value=h_tjblog" target="_blank" href="http://blog.sina.com.cn/u/1342183272" class="SG_linkb"></a></p> </li><li class="SG_j_linedot1"><p class="atcTitCell_tit SG_dot"><a suda-uatrack="key=blog_tjblog&value=h_tjblog" title="#斯里兰卡旅行#印度洋日出" target="_blank" href="http://blog.sina.com.cn/s/blog_5868baa90102whk7.html?tj=2?tj=2">#斯里兰卡旅行#印度洋日出</a></p> <p class="atcTitCell_nm"><a suda-uatrack="key=blog_tjblog&value=h_tjblog" target="_blank" href="http://blog.sina.com.cn/u/1483258537" class="SG_linkb"></a></p> </li><li class="SG_j_linedot1"><p class="atcTitCell_tit SG_dot"><a suda-uatrack="key=blog_tjblog&value=h_tjblog" title="吊打百度固然痛快,然后呢?" target="_blank" href="http://blog.sina.com.cn/s/blog_56c35a550102wnnc.html?tj=2?tj=2">吊打百度固然痛快,然后呢?</a></p> <p class="atcTitCell_nm"><a suda-uatrack="key=blog_tjblog&value=h_tjblog" target="_blank" href="http://blog.sina.com.cn/u/1455643221" class="SG_linkb"></a></p> </li><li class="SG_j_linedot1"><p class="atcTitCell_tit SG_dot"><a suda-uatrack="key=blog_tjblog&value=h_tjblog" title="台湾科技挣扎,人祸大于天灾?" target="_blank" href="http://blog.sina.com.cn/s/blog_4a46c3960102wifo.html?tj=2?tj=2">台湾科技挣扎,人祸大于天灾?</a></p> <p class="atcTitCell_nm"><a suda-uatrack="key=blog_tjblog&value=h_tjblog" target="_blank" href="http://blog.sina.com.cn/u/1246151574" class="SG_linkb"></a></p> </li><li class="SG_j_linedot1"><p class="atcTitCell_tit SG_dot"><a suda-uatrack="key=blog_tjblog&value=h_tjblog" title="新浪微博业绩超预期,是什么驱动" target="_blank" href="http://blog.sina.com.cn/s/blog_4af36ea50102wfge.html?tj=2?tj=2">新浪微博业绩超预期,是什么驱动</a></p> <p class="atcTitCell_nm"><a suda-uatrack="key=blog_tjblog&value=h_tjblog" target="_blank" href="http://blog.sina.com.cn/u/1257467557" class="SG_linkb"></a></p> </li><li class="SG_j_linedot1"><p class="atcTitCell_tit SG_dot"><a suda-uatrack="key=blog_tjblog&value=h_tjblog" title="收入份额=市场份额,虎嗅想干什" target="_blank" href="http://blog.sina.com.cn/s/blog_5ff50e8f0102w4tq.html?tj=2?tj=2">收入份额=市场份额,虎嗅想干什</a></p> <p class="atcTitCell_nm"><a suda-uatrack="key=blog_tjblog&value=h_tjblog" target="_blank" href="http://blog.sina.com.cn/u/1609895567" class="SG_linkb"></a></p> </li><li class="SG_j_linedot1"><p class="atcTitCell_tit SG_dot"><a suda-uatrack="key=blog_tjblog&value=h_tjblog" title="烧钱下的分享经济分享的是投资人" target="_blank" href="http://blog.sina.com.cn/s/blog_4a46c3960102woqx.html?tj=2?tj=2">烧钱下的分享经济分享的是投资人</a></p> <p class="atcTitCell_nm"><a suda-uatrack="key=blog_tjblog&value=h_tjblog" target="_blank" href="http://blog.sina.com.cn/u/1246151574" class="SG_linkb"></a></p> </li><li class="SG_j_linedot1"><p class="atcTitCell_tit SG_dot"><a suda-uatrack="key=blog_tjblog&value=h_tjblog" title="传奇的谢幕,谈岩田聪和他的任天" target="_blank" href="http://blog.sina.com.cn/s/blog_b4474abf0102vqy3.html?tj=2?tj=2">传奇的谢幕,谈岩田聪和他的任天</a></p> <p class="atcTitCell_nm"><a suda-uatrack="key=blog_tjblog&value=h_tjblog" target="_blank" href="http://blog.sina.com.cn/u/3024571071" class="SG_linkb"></a></p> </li><li class="SG_j_linedot1"><p class="atcTitCell_tit SG_dot"><a suda-uatrack="key=blog_tjblog&value=h_tjblog" title="家常主食轻松做之——培根香葱花" target="_blank" href="http://blog.sina.com.cn/s/blog_500017680102vrck.html?tj=2?tj=2">家常主食轻松做之——培根香葱花</a></p> <p class="atcTitCell_nm"><a suda-uatrack="key=blog_tjblog&value=h_tjblog" target="_blank" href="http://blog.sina.com.cn/u/1342183272" class="SG_linkb"></a></p> </li> </ul> <div id="atcPicList"> </div> <div class="atcTit_more"><span class="SG_more"><a target="_blank" href="http://blog.sina.com.cn/">查看更多</a>&gt;&gt;</span></div></div></div> <div class="SG_connFoot"></div> </div> <div class="SG_conn" id="module_47"><div class="SG_connHead"> <span class="title" comp_title="谁看过这篇博文">谁看过这篇博文</span> <span class="edit"></span> </div> <div class="SG_connBody"> <div class="wdtLoading"><img src="http://simg.sinajs.cn/blog7style/images/common/loading.gif" />加载中…</div> </div> <div class="SG_connFoot"></div> </div></div> <!--第一列end--> <!--第二列start--> <div id="column_2" class="SG_colW73"> <div id="module_920" class="SG_conn"> <div class="SG_connHead"> <span comp_title="正文" class="title">正文</span> <span class="edit"><span id="articleFontManage" class="fontSize">字体大小:<a href="javascript:;" onclick="changeFontSize(2);return false;">大</a> <strong>中</strong> <a href="javascript:;" onclick="changeFontSize(0);return false;">小</a></span></span> </div> <div class="SG_connBody"> <!--博文正文 begin --> <div id="articlebody" class="artical" favMD5='{"605f5b4f010194fg":"45467bf92e1089aa482bde7771e8a91b"}'> <div class="articalTitle"> <h2 id="t_605f5b4f010194fg" class="titName SG_txta">Git&nbsp;命令总结</h2> <span class="time SG_txtc">(2013-07-21 13:37:22)</span><div class="turnBoxzz"><a href="javascript:;" class="SG_aBtn SG_aBtn_ico SG_turn" action-type="reblog" action-data="{srcBlog:1, blogId:'605f5b4f010194fg'}"><cite><img class="SG_icon SG_icon111" src="http://simg.sinajs.cn/blog7style/images/common/sg_trans.gif" width="15" height="15" align="absmiddle">转载<em class="arrow">▼</em></cite></a></div> </div> <div class="articalTag" id="sina_keyword_ad_area"> <table> <tr> <td class="blog_tag"> <script> var $tag='git,branch,checkout,merge,commit,it'; var $tag_code='339006796dd7c46e64d9468caff1edf5'; var $r_quote_bligid='605f5b4f010194fg'; var $worldcup='0'; var $worldcupball='0'; </script> <span class="SG_txtb">标签:</span> <h3><a href="http://search.sina.com.cn/?c=blog&q=git&by=tag" target="_blank">git</a></h3> <h3><a href="http://search.sina.com.cn/?c=blog&q=branch&by=tag" target="_blank">branch</a></h3> <h3><a href="http://search.sina.com.cn/?c=blog&q=checkout&by=tag" target="_blank">checkout</a></h3> <h3><a href="http://search.sina.com.cn/?c=blog&q=merge&by=tag" target="_blank">merge</a></h3> <h3><a href="http://search.sina.com.cn/?c=blog&q=commit&by=tag" target="_blank">commit</a></h3> <h3><a href="http://search.sina.com.cn/?c=blog&q=it&by=tag" target="_blank">it</a></h3> </td> <td class="blog_class"> <span class="SG_txtb">分类:</span> <a target="_blank" href="http://blog.sina.com.cn/s/articlelist_1616862031_8_1.html">linux</a> </td> </tr> </table> </div> <!-- 正文开始 --> <div id="sina_keyword_ad_area2" class="articalContent "> <p STYLE="margin: 10px 0px 0px; padding: 0px; color: rgb(34, 34, 34); font-family: 'open sans', Helveticaneue-Light, 'Helvetica neue Light', 'Helvetica neue', Helvetica, Arial, sans-serif; line-height: 28px; text-align: justify; background-color: rgb(255, 255, 255);"> 這篇主要是給自己做個記錄,因為 Git 指令實在太多了…</P> <ol STYLE="margin: 10px 0px 0px 20px; padding: 0px; color: rgb(34, 34, 34); font-family: 'open sans', Helveticaneue-Light, 'Helvetica neue Light', 'Helvetica neue', Helvetica, Arial, sans-serif; line-height: 28px; text-align: justify; background-color: rgb(255, 255, 255);"> <li STYLE="margin: 0px; padding: 0px;"><a HREF="http://blog.gogojimmy.net/2012/01/17/how-to-use-git-1-git-basic/"> Git 教學(1):Git的基本使用</A></LI> <li STYLE="margin: 0px; padding: 0px;"><a HREF="http://blog.gogojimmy.net/2012/01/21/how-to-use-git-2-basic-usage-and-worflow/"> Git 教學(2):Git Branch 的操作與基本工作流程</A></LI> <li STYLE="margin: 0px; padding: 0px;"> <p STYLE="margin: 10px 0px 0px; padding: 0px;"><a HREF="http://blog.gogojimmy.net/2012/02/29/git-scenario/"> Git 情境劇:告訴你使用 Git 時什麼情況該下什麼指令</A></P> </LI> <li STYLE="margin: 0px; padding: 0px;"> <p STYLE="margin: 10px 0px 0px; padding: 0px;">如何安裝 Git</P> <ul STYLE="margin: 0px 0px 0px 20px; padding: 0px;"> <li STYLE="margin: 0px; padding: 0px;"> <p STYLE="margin: 10px 0px 0px; padding: 0px;">Mac : 安裝&nbsp;<wbr><a HREF="http://mxcl.github.com/homebrew/">Homebrew</A></P> <pre STYLE="margin-top: 10px; margin-bottom: 0px; padding: 5px 15px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; line-height: 1.5; overflow-x: auto; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px;"> <code STYLE="margin: 0px; padding: 0px; background-image: none; border: none; font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 0px; border-top-right-radius: 0px; border-bottom-right-radius: 0px; border-bottom-left-radius: 0px; background-position: initial initial; background-repeat: initial initial;"> brew install git </CODE> </PRE></LI> <li STYLE="margin: 0px; padding: 0px;">Linux(Debian) :&nbsp;<wbr><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;">apt-get install git-core</CODE></LI> <li STYLE="margin: 0px; padding: 0px;">Linux(Fedora) :&nbsp;<wbr><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;">yum install git-core</CODE></LI> <li STYLE="margin: 0px; padding: 0px;">Windows : 下載安裝&nbsp;<wbr><a HREF="http://code.google.com/p/msysgit">msysGit</A></LI> </UL> </LI> <li STYLE="margin: 0px; padding: 0px;"> <p STYLE="margin: 10px 0px 0px; padding: 0px;">如何設定 Git</P> <ul STYLE="margin: 0px 0px 0px 20px; padding: 0px;"> <li STYLE="margin: 0px; padding: 0px;">Mac :&nbsp;<wbr><a HREF="http://help.github.com/mac-set-up-git/">Set Up Git on Mac</A></LI> <li STYLE="margin: 0px; padding: 0px;">Linux :&nbsp;<wbr><a HREF="http://help.github.com/linux-set-up-git/">Set Up Git on Linux</A></LI> <li STYLE="margin: 0px; padding: 0px;">Windows :&nbsp;<wbr><a HREF="http://help.github.com/win-set-up-git/">Set up Git on Windows</A></LI> </UL> </LI> <li STYLE="margin: 0px; padding: 0px;"> <p STYLE="margin: 10px 0px 0px; padding: 0px;">如何開始一個 Git Respository</P> <ul STYLE="margin: 0px 0px 0px 20px; padding: 0px;"> <li STYLE="margin: 0px; padding: 0px;"> 在專案底下使用&nbsp;<wbr><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;">git init</CODE>&nbsp;<wbr>開始一個新的 Git repo.</LI> <li STYLE="margin: 0px; padding: 0px;"> 使用&nbsp;<wbr><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;">git clone</CODE>&nbsp;<wbr>複製一個專案</LI> </UL> </LI> <li STYLE="margin: 0px; padding: 0px;"> <p STYLE="margin: 10px 0px 0px; padding: 0px;">如何將檔案加入 Stage</P> <ul STYLE="margin: 0px 0px 0px 20px; padding: 0px;"> <li STYLE="margin: 0px; padding: 0px;"> 使用&nbsp;<wbr><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;">git add</CODE>&nbsp;<wbr>將想要的檔案加入 Stage.</LI> <li STYLE="margin: 0px; padding: 0px;"><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;"> git add .</CODE>&nbsp;<wbr>會將所有編修過的檔案加入 Stage (新增但還沒 Commit 過的檔案並不會加入)</LI> </UL> </LI> <li STYLE="margin: 0px; padding: 0px;"> <p STYLE="margin: 10px 0px 0px; padding: 0px;">如何將檔案從 Stage 中移除(取消add)</P> <ul STYLE="margin: 0px 0px 0px 20px; padding: 0px;"> <li STYLE="margin: 0px; padding: 0px;"><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;"> git reset HEAD 檔案名稱</CODE></LI> </UL> </LI> <li STYLE="margin: 0px; padding: 0px;"> <p STYLE="margin: 10px 0px 0px; padding: 0px;">如何將檔案提交(commit)</P> <ul STYLE="margin: 0px 0px 0px 20px; padding: 0px;"> <li STYLE="margin: 0px; padding: 0px;"> 使用&nbsp;<wbr><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;">git commit</CODE>會將 Stage 狀態的檔案做 Commit 動作</LI> <li STYLE="margin: 0px; padding: 0px;"><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;"> git commit -m "commit訊息"</CODE>&nbsp;<wbr>可以略過編輯器直接輸入 commit 訊息完成提交。</LI> <li STYLE="margin: 0px; padding: 0px;"><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;"> git commit -am "commit訊息"</CODE>&nbsp;<wbr>等同於先<code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;">git add .</CODE>後略過編輯器提交 commit。</LI> </UL> </LI> <li STYLE="margin: 0px; padding: 0px;"> <p STYLE="margin: 10px 0px 0px; padding: 0px;">如何修改/取消上一次的 commit</P> <ul STYLE="margin: 0px 0px 0px 20px; padding: 0px;"> <li STYLE="margin: 0px; padding: 0px;"><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;"> git commit --amend</CODE>&nbsp;<wbr>修改上一次的 commit 訊息。</LI> <li STYLE="margin: 0px; padding: 0px;"><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;"> git commit --amend 檔案1 檔案2...</CODE>&nbsp;<wbr>將檔案1、檔案2加入上一次的 commit。</LI> <li STYLE="margin: 0px; padding: 0px;"><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;"> git reset HEAD^ --soft</CODE>&nbsp;<wbr>取消剛剛的 commit,但保留修改過的檔案。</LI> <li STYLE="margin: 0px; padding: 0px;"><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;"> git reset HEAD^ --hard</CODE>&nbsp;<wbr>取消剛剛的 commit,回到再上一次 commit的 乾淨狀態。</LI> </UL> </LI> <li STYLE="margin: 0px; padding: 0px;"> <p STYLE="margin: 10px 0px 0px; padding: 0px;">分支基本操作(branch)</P> <ul STYLE="margin: 0px 0px 0px 20px; padding: 0px;"> <li STYLE="margin: 0px; padding: 0px;"><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;"> git branch</CODE>&nbsp;<wbr>列出所有本地端的 branch。</LI> <li STYLE="margin: 0px; padding: 0px;"><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;"> git branch -r</CODE>&nbsp;<wbr>列出所有遠端的 branch。</LI> <li STYLE="margin: 0px; padding: 0px;"><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;"> git branch -a</CODE>&nbsp;<wbr>列出所有本地及遠端的 branch。</LI> <li STYLE="margin: 0px; padding: 0px;"><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;"> git branch "branch名稱"</CODE>&nbsp;<wbr>建立一個新的 branch。</LI> <li STYLE="margin: 0px; padding: 0px;"><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;"> git checkout -b "branch名稱"</CODE>&nbsp;<wbr>建立一個新的 branch 並切換到該 branch。</LI> <li STYLE="margin: 0px; padding: 0px;"><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;"> git branch branch名稱 起始點</CODE>&nbsp;<wbr>以起始點作為基準建立一個新的 branch,起始點可以是一個 tag,branch 或是 commit。</LI> <li STYLE="margin: 0px; padding: 0px;"><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;"> git branch --track branch名稱 遠端branch</CODE>&nbsp;<wbr>建立一個 tracking 遠端 branch 的 branch,這樣以後 push/pull都會直接對應到該遠端的branch。</LI> <li STYLE="margin: 0px; padding: 0px;"><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;"> git branch --set-upstream branch 遠端branch</CODE>&nbsp;<wbr>將一個已存在的 branch 設定成 tracking 遠端的branch。</LI> <li STYLE="margin: 0px; padding: 0px;"><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;"> git branch -d "branch 名稱"</CODE>&nbsp;<wbr>刪除 branch。</LI> <li STYLE="margin: 0px; padding: 0px;"><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;"> git -r -d 遠端branch</CODE>&nbsp;<wbr>刪除一個 tracking 的遠端 branch,例如<code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;">git branch -r -d wycats/master</CODE></LI> <li STYLE="margin: 0px; padding: 0px;"><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;"> git push repository名稱 :遠端branch</CODE>&nbsp;<wbr>刪除一個 repository 的 branch,通常用在刪除遠端的 branch,例如<code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;">git push origin :old_branch_to_be_deleted</CODE>。</LI> <li STYLE="margin: 0px; padding: 0px;"><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;"> git checkout branch名稱</CODE>&nbsp;<wbr>切換到另一個 branch(所有修改過程會被保留)。</LI> </UL> </LI> <li STYLE="margin: 0px; padding: 0px;"> <p STYLE="margin: 10px 0px 0px; padding: 0px;">遠端操作(remote)</P> <ul STYLE="margin: 0px 0px 0px 20px; padding: 0px;"> <li STYLE="margin: 0px; padding: 0px;"><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;"> git remote add remote名稱 remote網址</CODE>&nbsp;<wbr>加入一個 remote repository,例如&nbsp;<wbr><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;">git remote add github git://github.com/gogojimmy/test.git</CODE></LI> <li STYLE="margin: 0px; padding: 0px;"><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;"> git push remote名稱 :branch名稱</CODE>&nbsp;<wbr>刪除遠端 branch,例如&nbsp;<wbr><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;">git push origin :somebranch</CODE>。</LI> <li STYLE="margin: 0px; padding: 0px;"><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;"> git pull remote名稱 branch名稱</CODE>&nbsp;<wbr>下載一個遠端的 branch 並合併(注意是下載遠端的 branch 合併到目前本地端所在的 branch)。</LI> <li STYLE="margin: 0px; padding: 0px;"><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;"> git push</CODE>&nbsp;<wbr>類似於 pull 操作,將本地端的 branch 上傳到遠端。</LI> </UL> </LI> <li STYLE="margin: 0px; padding: 0px;"> <p STYLE="margin: 10px 0px 0px; padding: 0px;">合併操作(merge)</P> <ul STYLE="margin: 0px 0px 0px 20px; padding: 0px;"> <li STYLE="margin: 0px; padding: 0px;"><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;"> git merge branch名稱</CODE>&nbsp;<wbr>合併指定的 branch 到目前的 branch。</LI> <li STYLE="margin: 0px; padding: 0px;"><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;"> git merge branch名稱 --no-commit</CODE>&nbsp;<wbr>合併指定的 branch 到目前的 branch 但是不會產生合併的 commit。</LI> <li STYLE="margin: 0px; padding: 0px;"><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;"> git cherry-pick SHA</CODE>&nbsp;<wbr>將某一個 commit 的內容合併到目前 branch,指定 commit 是使用該 commit 的 SHA 值,例如<code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;">git cherry-pick 7300a6130d9447e18a931e89<wbr>8b64eefedea19544</CODE>。</LI> </UL> </LI> <li STYLE="margin: 0px; padding: 0px;"> <p STYLE="margin: 10px 0px 0px; padding: 0px;">暫存操作(stash)</P> <ul STYLE="margin: 0px 0px 0px 20px; padding: 0px;"> <li STYLE="margin: 0px; padding: 0px;"><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;"> git stash</CODE>&nbsp;<wbr>將目前所做的修改都暫存起來。</LI> <li STYLE="margin: 0px; padding: 0px;"><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;"> git stash apply</CODE>&nbsp;<wbr>取出最新一次的暫存。</LI> <li STYLE="margin: 0px; padding: 0px;"><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;"> git stash pop</CODE>&nbsp;<wbr>取出最新一次的暫存並將他從暫存清單中移除。</LI> <li STYLE="margin: 0px; padding: 0px;"><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;"> git stash list</CODE>&nbsp;<wbr>顯示出所有的暫存清單。</LI> <li STYLE="margin: 0px; padding: 0px;"><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;"> git stash clear</CODE>&nbsp;<wbr>清除所有暫存。</LI> </UL> </LI> <li STYLE="margin: 0px; padding: 0px;"> <p STYLE="margin: 10px 0px 0px; padding: 0px;">常見問題:</P> </LI> <li STYLE="list-style: none"> <ul STYLE="margin: 0px 0px 0px 20px; padding: 0px;"> <li STYLE="margin: 0px; padding: 0px;">我的 code 改爛了我想全部重來,我要如何快速回到乾淨的目錄? <ul STYLE="margin: 0px 0px 0px 20px; padding: 0px;"> <li STYLE="margin: 0px; padding: 0px;"><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;"> git reset --hard</CODE>&nbsp;<wbr>這指令會清除所有與最近一次 commit 不同的修改。</LI> </UL> </LI> <li STYLE="margin: 0px; padding: 0px;">merge 過程中發生 confict 我想放棄 merge,要如何取消 merge? <ul STYLE="margin: 0px 0px 0px 20px; padding: 0px;"> <li STYLE="margin: 0px; padding: 0px;"> 一樣使用&nbsp;<wbr><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;">git reset --hard</CODE>&nbsp;<wbr>可以取消這次的 merge。</LI> </UL> </LI> <li STYLE="margin: 0px; padding: 0px;">如何取消這次的 merge 回到 merge 前的狀態? <ul STYLE="margin: 0px 0px 0px 20px; padding: 0px;"> <li STYLE="margin: 0px; padding: 0px;"><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;"> git reset --hard ORIG_HEAD</CODE>&nbsp;<wbr>這指令會取消最近一次成功的 merge 以及所有你在這次 merge 後所做的修改。</LI> </UL> </LI> <li STYLE="margin: 0px; padding: 0px;">如何回復單獨檔案到原本 commit 的狀態?</LI> <li STYLE="list-style: none"> <ul STYLE="margin: 0px 0px 0px 20px; padding: 0px;"> <li STYLE="margin: 0px; padding: 0px;"><code STYLE="margin: 0px 3px; padding: 1px 3px; background-color: rgb(221, 221, 221); border: 1px solid rgb(204, 204, 204); font-family: Menlo, Monaco, 'Andale Mono', 'lucida console', 'Courier new', monospace; font-size: 0.9em; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; background-position: initial initial; background-repeat: initial initial;"> git checkout 檔案名稱</CODE>&nbsp;<wbr>這指令會將已經被修改過的檔案回復到最近一次 commit 的樣子。</LI> </UL> </LI> </UL> </LI> </OL> <div STYLE="text-align: justify;"><font COLOR="#222222">from:&nbsp;<wbr></FONT><a HREF="http://blog.gogojimmy.net/2012/02/29/git-scenario/">http://blog.gogojimmy.net/2012/02/29/git-scenario/</A></DIV> </div> <!-- 正文结束 --> <div id='share' class="shareUp"> <div class="share SG_txtb"> 分享: <div class="bshare-custom" style="display:inline;margin-left:5px;"><a title="分享到新浪微博" class="bshare-sinaminiblog" href="javascript:void(0);"></a><a title="分享到微信" class="bshare-weixin" href="javascript:void(0);"></a><a title="分享到QQ空间" class="bshare-qzone" href="javascript:void(0);"></a><a title="分享到豆瓣" class="bshare-douban" href="javascript:void(0);"></a><a title="更多平台" class="bshare-more bshare-more-icon more-style-addthis"></a> </div> </div> <div class="up"> <div title="喜欢后让更多人看到" id="dbox_605f5b4f010194fg" class="upBox upBox_click" style="cursor: pointer;"> <p ti_title="Git&nbsp;命令总结" id="dbox2_605f5b4f010194fg" class="count" ></p> <p class="link"><img width="15" height="15" align="absmiddle" src="http://simg.sinajs.cn/blog7style/images/common/sg_trans.gif" class="SG_icon SG_icon34">喜欢</p> </div> <!-- <div class="upBox upBox_add"> <p class="count">0</p> <p class="link"><img width="20" height="16" align="absmiddle" title="推荐" src="http://simg.sinajs.cn/blog7style/images/common/sg_trans.gif" class="SG_icon SG_icon214">赠金笔</p> </div> --> <div class="upBox upBox_add"> <p class="count" id="goldPan-num">0</p> <p class="link" id="goldPan-give"><img class="SG_icon SG_icon214" src="http://simg.sinajs.cn/blog7style/images/common/sg_trans.gif" width="20" height="16" title="赠金笔" align="absmiddle">赠金笔</p> </div> </div> <div class="clearit"></div> </div> <div class="articalInfo"> <!-- 分享到微博 {$t_blog} --> <div class="IL"> 阅读<span id="r_605f5b4f010194fg" class="SG_txtb"></span><em class="SG_txtb">┊</em> <a href="#commonComment">评论</a> <span id="c_605f5b4f010194fg" class="SG_txtb"></span><em class="SG_txtb">┊</em> <a href="javascript:;" onclick="$articleManage('605f5b4f010194fg',5);return false;">收藏</a><span id="f_605f5b4f010194fg" class="SG_txtb"></span> <em class="SG_txtb">┊</em><a href="#" id="quote_set_sign" onclick="return false ;">转载</a><a href="#" id="z_605f5b4f010194fg" onclick="return false ;" class="zznum"></a> <span id="fn_Git&nbsp;命令总结" class="SG_txtb"></span><em class="SG_txtb">┊</em> <a onclick="return false;" href="javascript:;" ><cite id="d1_digg_605f5b4f010194fg">喜欢</cite></a><a id="d1_digg_down_605f5b4f010194fg" href="javascript:;" ><b>▼</b></a> <em class="SG_txtb">┊</em><a href="http://blog.sina.com.cn/main_v5/ria/print.html?blog_id=blog_605f5b4f010194fg" target="_blank">打印</a><em class="SG_txtb">┊</em><a id="q_605f5b4f010194fg" onclick="report('605f5b4f010194fg');return false;" href="#">举报</a> </div> <div class="IR"> <table> <tr> <th class="SG_txtb" scope="row">已投稿到:</th> <td> <div class="IR_list"> <span><img class="SG_icon SG_icon36" src="http://simg.sinajs.cn/blog7style/images/common/sg_trans.gif" width="15" height="15" title="排行榜" align="absmiddle" /> <a href="http://blog.sina.com.cn/lm/114/113/day.html" class="SG_linkb" target="_blank">排行榜</a></span> </div> </td> </tr> </table> </div> </div> <div class="clearit"></div> <div class="blogzz_zzlist borderc" id="blog_quote" style="display:none">加载中,请稍候......</div> <div class="articalfrontback SG_j_linedot1 clearfix" id="new_nextprev_605f5b4f010194fg"> <div><span class="SG_txtb">前一篇:</span><a href="http://blog.sina.com.cn/s/blog_605f5b4f010194fc.html">对话&nbsp;UNIX:&nbsp;使用&nbsp;Screen&nbsp;创建并管理多个&nbsp;shell</a></div> <div><span class="SG_txtb">后一篇:</span><a href="http://blog.sina.com.cn/s/blog_605f5b4f010195w6.html">Hadoop&nbsp;Definitive&nbsp;Guide&nbsp;Compile&nbsp;and&nbsp;Running&nbsp;Pipes&nbsp;Program</a></div> </div> <div class="clearit"></div> <div id="loginFollow"></div> <div class="allComm"> <div class="allCommTit" > <div class="SG_floatL"> <strong>评论</strong> <span id="commAd_1" style="display:none;"> <span style="margin-left:15px; width:220px; display:inline-block;"><a target="_blank" href="http://blog.sina.com.cn/lm/8/2009/0325/105340.html">重要提示:警惕虚假中奖信息</a></span> </span> </div> <div class="SG_floatR"><a class="CP_a_fuc" href="#post">[<cite>发评论</cite>]</a></div> </div> <ul id="article_comment_list" class="SG_cmp_revert"><!-- 循环始 --><li>评论加载中,请稍候...</li><!-- 循环终 --></ul> <div class="clearit"></div> <div class="myCommPages SG_j_linedot1"> <div class="SG_page" id="commentPaging" style="display:none;"> <ul class="SG_pages"> </ul> </div> <div class="clearit"></div> </div> <a name="post"></a> <div class="writeComm"> <div class="allCommTit"> <div class="SG_floatL"> <strong>发评论</strong> <span></span> </div> <div class="SG_floatR"></div> </div> <div class="wrCommTit"> <div class="SG_floatL" id="commentNick" style="display:none;"></div> </div> <div class="formTextarea"> <div style="float:left;" id="commonComment"> <iframe id="postCommentIframe" frameborder="0" style="border:1px solid #C7C7C7; height:158px;width:448px;maring-top:1px;background-color:white;" src="http://blog.sina.com.cn/main_v5/ria/blank2.html"></iframe> <textarea id="commentArea" tabindex="1" style="display:none;"></textarea> </div> <div id="mobileComment" style="float:left;display:none;"> <textarea id="mbCommentTa" style="width:438px;height:150px;border:1px solid #C7C7C7;line-height:18px;padding:5px;"></textarea> </div> <div class="faceblk" id="faceWrap"> <div id="smilesSortShow" class="faceline1"> </div> <ul id="smilesRecommended" class="faceline01"></ul> </div> <div class="clearit"></div> </div> <div class="formLogin"> <div class="SG_floatL"> <p id="commentlogin" style="display:none;"><span>登录名:</span><input type="text" style="width: 115px;" id="login_name" tabindex="2"/> <span>密码:</span><input type="password" style="width: 115px;" id="login_pass" tabindex="3"/> <a href="http://login.sina.com.cn/getpass.html" target="_blank">找回密码</a> <a href="http://login.sina.com.cn/signup/signup.php?entry=blog&src=blogicp&srcuid=1616862031" target="_blank">注册</a> <input type="checkbox" id="login_remember"/><label for="login_remember" style="display:inline-block;" title="建议在网吧/公用电脑上取消该选项">记住登录状态</label></p><p id="commentloginM" style="display:none;"><span>昵&nbsp;&nbsp;&nbsp;称:</span><input type="text" style="width: 115px;" id="comment_anonyous" value="新浪网友"/ tabindex="2" disabled></p><p id="quote_comment_p"><input type="checkbox" id="bb"> <label for="bb"><img height="18" align="absmiddle" width="18" title="" src="http://simg.sinajs.cn/blog7style/images/common/sg_trans.gif" class="SG_icon SG_icon110">分享到微博 <img height="15" align="absmiddle" width="15" title="新" src="http://simg.sinajs.cn/blog7style/images/common/sg_trans.gif" class="SG_icon SG_icon11"></label>&nbsp;&nbsp;&nbsp;<input type="checkbox" id="cbCommentQuote" /><label for="cbCommentQuote">评论并转载此博文</label><img class="SG_icon SG_icon11" src="http://simg.sinajs.cn/blog7style/images/common/sg_trans.gif" width="15" height="15" title="新" align="absmiddle" /></p> <p id="geetest-box" ></p> </div> <span style="display: none; color: rgb(153, 153, 153); margin-left: 10px;" id="login_remember_caution"></span> <div class="SG_floatR" id="anonymity_cont"><input type="checkbox" id="anonymity"/><label for="anonymity">匿名评论</label></div> </div> <div class="formBtn"> <a href="javascript:;" onclick="return false;" class="SG_aBtn" tabindex="5"><cite id="postcommentid">发评论</cite></a> <p class="SG_txtc">以上网友发言只代表其个人观点,不代表新浪网的观点或立场。</p> </div> </div> </div> <div class="clearit"></div> <div class="articalfrontback articalfrontback2 clearfix"> <div class="SG_floatL"><span class="SG_txtb">&lt;&nbsp;前一篇</span><a href="http://blog.sina.com.cn/s/blog_605f5b4f010194fc.html">对话&nbsp;UNIX:&nbsp;使用&nbsp;Screen&nbsp;创建并管理多个&nbsp;shell</a></div> <div class="SG_floatR"><span class="SG_txtb">后一篇&nbsp;&gt;</span><a href="http://blog.sina.com.cn/s/blog_605f5b4f010195w6.html">Hadoop&nbsp;Definitive&nbsp;Guide&nbsp;Compile&nbsp;and&nbsp;Running&nbsp;Pipes&nbsp;Program</a></div> </div> <div class="clearit"></div> </div> <!--博文正文 end --> <script type="text/javascript"> var voteid=""; </script> </div> <div class="SG_connFoot"></div> </div> </div> <!--第二列start--> <!--第三列start--> <div id="column_3" class="SG_colWnone"><div style="width:0px;height:0.1px;margin:0px;">&nbsp;&nbsp;</div></div> <!--第三列end--> </div> <!--主题内容结束 --> <div id="diggerFla" style="position:absolute;left:0px;top:0px;width:0px"></div> <div class="sinablogfooter" id="sinablogfooter" style="position:relative;"> <p class="SG_linka"><a href="http://help.sina.com.cn/index.php?s=askquestion&a=view" target="_blank">新浪BLOG意见反馈留言板</a> <a href="javascript:;" onclick="window.open ('http://control.blog.sina.com.cn/admin/advice/impeach.php?url=http%3A//blog.sina.com.cn/s/blog_4cf7b4ec0100eudp.html%3Ftj%3D1', '','height=495, width=510, top=0, left=0, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=n o, status=no');">不良信息反馈</a> 电话:4006900000 提示音后按1键(按当地市话标准计费) 欢迎批评指正</p> <p class="SG_linka"><a href="http://corp.sina.com.cn/chn/" target="_blank">新浪简介</a> | <a href="http://corp.sina.com.cn/eng/" target="_blank">About Sina</a> | <a href="http://emarketing.sina.com.cn/" target="_blank">广告服务</a> | <a href="http://www.sina.com.cn/contactus.html" target="_blank">联系我们</a> | <a href="http://corp.sina.com.cn/chn/sina_job.html" target="_blank">招聘信息</a> | <a href="http://www.sina.com.cn/intro/lawfirm.shtml" target="_blank">网站律师</a> | <a href="http://english.sina.com" target="_blank">SINA English</a> | <a href="http://members.sina.com.cn/apply/" target="_blank">会员注册</a> | <a href="http://help.sina.com.cn/" target="_blank">产品答疑</a> </p> <p class="copyright SG_linka"> Copyright &copy; 1996 - 2016 SINA Corporation, All Rights Reserved</p> <p class="SG_linka"> 新浪公司 <a href="http://www.sina.com.cn/intro/copyright.shtml" target="_blank">版权所有</a></p> <a href="http://www.bj.cyberpolice.cn/index.jsp" target="_blank" class="gab_link"></a> </div> </div> </div> <div id="swfbox"></div> <script id="PVCOUNTER_FORIE" type="text/javascript"></script> </body> <script type="text/javascript"> var scope = { $newTray : 1, $setDomain : true, $uid : "1616862031", $PRODUCT_NAME : "blog7", //blog7photo,blog7icp $pageid : "article", $key : "11219f5b13fde78a21191728a164c830", $uhost : "12leaves", $ownerWTtype :"", $private: {"cms":0,"hidecms":0,"blogsize":0,"ad":0,"sms":0,"adver":0,"tj":0,"p4p":0,"spamcms":0,"pageset":0,"invitationset":0,"top":0,"active":"4","medal7":3,"t_sina":"1616862031","oauth_token":1,"oauth_token_secret":1,"uname":"","p_push_t":0,"p_get_t":0,"articleclass":"117"}, $summary: " 這篇主要是給自己做個記錄,因為 Git 指令實在太多了… Git 教學(1):Git的基本使用 Git 教學(2):Git Branch 的操作與基本工... (来自 @头条博客)", $is_photo_vip:0, $nClass:0, $articleid:"605f5b4f010194fg", $sort_id:113, $cate_id:193, $isCommentAllow:0, $album_pic:"", $pn_x_rank:0, $x_quote_c:"2", $flag2008:"", component_lists:{"2":{"size":730,"list":[920]},"1":{"size":210,"list":[901,903,904,47]}}, formatInfo:1, UserPic:[{"pid":"","repeat":"repeat-x","align-h":"center","align-v":"top","apply":"0"},{"pid":"","repeat":"repeat-x","align-h":"center","align-v":"top","apply":"0"},{"pid":"","repeat":"repeat-x","align-h":"center","align-v":"top","apply":"0"}], UserBabyPic:{"photoX":0,"photoY":0,"photoURL":null,"angle":0,"zoom":0,"maskX":0,"maskY":0,"maskURL":null,"frameURL":null}, UserColor:1, backgroundcolor:"#f6f6f6", tpl:"4_1", reclist:0 }; var $encrypt_code = "3f9381854888f6389050727839db44c0"; </script> <script type="text/javascript" src="http://sjs.sinajs.cn/blog7common/js/boot.js"></script> <script type="text/javascript">__load_js();</script> <script type="text/javascript">__render_page();</script> <script type="text/javascript" charset="utf-8" src="http://static.bshare.cn/b/buttonLite.js#style=-1&amp;uuid=b436f96b-ce3c-469f-93ca-9c0c406fcf10&amp;pophcol=2&amp;lang=zh"></script><script type="text/javascript" charset="utf-8" src="http://static.bshare.cn/b/bshareC0.js"></script> <script type="text/javascript" charset="utf-8"> bShare.addEntry({pic: "", title:"分享自枝叶飞扬 《Git 命令总结》", summary:" 這篇主要是給自己做個記錄,因為 Git 指令實在太多了… Git 教學(1):Git的基本使用 Git 教學(2):Git Branch 的操作與基本工... (来自 @头条博客)"}); </script> <script type="text/javascript" src="http://sjs.sinajs.cn/xblogtheme/js/blog680-min.js"></script> <script type="text/javascript"> var slotArr = ['atcTitLi_SLOT_41', 'atcTitLi_SLOT_42','loginBarActivity']; //广告位id var sourceArr = ['SLOT_41','SLOT_42','SLOT_43,SLOT_47,SLOT_48']; //广告资源id SinaBlog680.staticBox(slotArr, sourceArr); </script> </html>
87.275714
1,395
0.687313
393140ff60d5efff67d0345134b81ece3cff3d86
10,820
html
HTML
public/faster/lua-yarv.html
4creators/BenchmarksGame
89d83531dbfcdbbbafd2ad06f2fd9eb54a39b193
[ "BSD-3-Clause" ]
null
null
null
public/faster/lua-yarv.html
4creators/BenchmarksGame
89d83531dbfcdbbbafd2ad06f2fd9eb54a39b193
[ "BSD-3-Clause" ]
null
null
null
public/faster/lua-yarv.html
4creators/BenchmarksGame
89d83531dbfcdbbbafd2ad06f2fd9eb54a39b193
[ "BSD-3-Clause" ]
null
null
null
<!DOCTYPE html> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta name="robots" content="all" /> <meta name="description" content="Lua Ruby - Which programs are faster?" /> <title>Lua&nbsp;vs&nbsp;Ruby - Which programs are faster? | Computer Language Benchmarks Game </title> <style><!-- a{color:black;text-decoration:none}article,footer{padding:0 0 2.9em}article,div,footer,header{margin:auto;width:92%}body{font:100% Droid Sans, Ubuntu, Verdana, sans-serif;margin:0;-webkit-text-size-adjust:100%}h3, h1, h2, nav li a{font-family:Ubuntu Mono,Consolas,Menlo,monospace}div,footer,header{max-width:31em}h3{font-size:1.4em;font-weight:bold;margin:0;padding: .4em}h3, h3 a{color:white;background-color:#dd4814}h3 small{font-size:0.64em}h1,h2{margin:1.5em 0 0}h1{font-size:1.4em;font-weight:normal}h2{font-size:1.2em}li{display:inline-block}nav li{list-style-type:none}nav li a{display:block;font-size:1.2em;margin: .5em .5em 0;padding: .5em .5em .3em}nav ul{clear:left;margin:-0.3em 0 1.5em;padding-left:0;text-align:center}p{color:#333;line-height:1.4;margin: .3em 0 0}p a,span{border-bottom: .1em solid #333;padding-bottom: .1em}.best{font-weight:bold}.message{font-size: .8em}table{color:#333;margin:1.3em auto 0;text-align:right}tbody::after{content:"-";display:block;line-height:2.6em;visibility:hidden}tbody:last-child{text-align:left}td{border-bottom: .15em dotted #eee;padding: .7em 0 0 1em}td a, th a{display:block}td:first-child,th:first-child{text-align:left;padding-left:0}td:nth-child(6),th:nth-child(6){display:table-cell}th{font-weight:normal;padding: .7em 0 0 1em}@media only screen{th:nth-child(3),td:nth-child(3),th:nth-child(4),td:nth-child(4),th:nth-child(5),td:nth-child(5),th:nth-child(6),td:nth-child(6){display:none}h2::after{content:" (too narrow: mem, gz, cpu, cpu-load columns are hidden)";font-weight:normal;font-size: .9em}}@media only screen and (min-width: 28em){th:nth-child(3),td:nth-child(3),th:nth-child(4),td:nth-child(4),th:nth-child(5),td:nth-child(5){display:table-cell}h2::after{content:" (cpu-load column is hidden)"}}@media only screen and (min-width: 41em){th:nth-child(6),td:nth-child(6){display:table-cell}h2::after{display:none}}@media only screen and (min-width: 60em){article,footer,header{font-size:1.25em}} --></style> <link rel="shortcut icon" href="./favicon.ico"> <header> <h3><a href="https://benchmarksgame-team.pages.debian.net/benchmarksgame/">The&nbsp;<small>Computer&nbsp;Language</small><br>Benchmarks&nbsp;Game</a></h3> </header> <article> <div> <h1>Lua versus Ruby fastest programs</h1> <aside> <nav> <ul> <li><a href="../faster/lua-node.html"><span>vs JavaScript</span></a> <li><a href="../faster/lua.html"><span>vs Java</span></a> <li><a href="../faster/lua-python3.html"><span>vs Python</span></a> <li class="best">vs Ruby </ul> </nav> </aside> </div> <section> <div> <h2>by faster benchmark performance</h2> </div> <table> <tbody> <tr> <th colspan="3"><a href="../performance/mandelbrot.html"><span>mandelbrot</span></a> <th colspan="3"> <tr> <th>source <th>secs <th>mem <th>gz <th>cpu <th>cpu load <tr> <td><a href="../program/mandelbrot-lua-6.html"><span>Lua</span></a> <td class="best">250.10 <td>22,652 <td>623 <td>779.68 <td class="message">100%&nbsp;72%&nbsp;74%&nbsp;67% <tr> <td><a href="../program/mandelbrot-yarv-2.html"><span>Ruby</span></a> <td>482.93 <td>144,684 <td>954 <td>1,926.62 <td class="message">100%&nbsp;100%&nbsp;100%&nbsp;100% <tbody> <tr> <th colspan="3"><a href="../performance/fasta.html"><span>fasta</span></a> <th colspan="3"> <tr> <th>source <th>secs <th>mem <th>gz <th>cpu <th>cpu load <tr> <td><a href="../program/fasta-lua-2.html"><span>Lua</span></a> <td class="best">50.08 <td>2,920 <td>1061 <td>50.06 <td class="message">0%&nbsp;7%&nbsp;94%&nbsp;0% <tr> <td><a href="../program/fasta-yarv-6.html"><span>Ruby</span></a> <td>55.67 <td>104,364 <td>1069 <td>96.83 <td class="message">53%&nbsp;24%&nbsp;78%&nbsp;22% <tbody> <tr> <th colspan="3"><a href="../performance/nbody.html"><span>n-body</span></a> <th colspan="3"> <tr> <th>source <th>secs <th>mem <th>gz <th>cpu <th>cpu load <tr> <td><a href="../program/nbody-lua-4.html"><span>Lua</span></a> <td>404.83 <td>1,404 <td>1305 <td>404.76 <td class="message">0%&nbsp;98%&nbsp;3%&nbsp;0% <tr> <td><a href="../program/nbody-yarv-2.html"><span>Ruby</span></a> <td>357.61 <td>12,284 <td>1137 <td>401.68 <td class="message">8%&nbsp;95%&nbsp;5%&nbsp;5% <tbody> <tr> <th colspan="3"><a href="../performance/spectralnorm.html"><span>spectral-norm</span></a> <th colspan="3"> <tr> <th>source <th>secs <th>mem <th>gz <th>cpu <th>cpu load <tr> <td><a href="../program/spectralnorm-lua-1.html"><span>Lua</span></a> <td>193.27 <td>2,848 <td>329 <td>193.24 <td class="message">0%&nbsp;0%&nbsp;0%&nbsp;100% <tr> <td><a href="../program/spectralnorm-yarv-5.html"><span>Ruby</span></a> <td>132.22 <td>54,944 <td>862 <td>494.13 <td class="message">94%&nbsp;95%&nbsp;93%&nbsp;92% <tbody> <tr> <th colspan="3"><a href="../performance/knucleotide.html"><span>k-nucleotide</span></a> <th colspan="3"> <tr> <th>source <th>secs <th>mem <th>gz <th>cpu <th>cpu load <tr> <td><a href="../program/knucleotide-lua-2.html"><span>Lua</span></a> <td>184.25 <td>513,992 <td>613 <td>183.19 <td class="message">81%&nbsp;1%&nbsp;1%&nbsp;20% <tr> <td><a href="../program/knucleotide-yarv-7.html"><span>Ruby</span></a> <td>104.85 <td>383,724 <td>880 <td>386.32 <td class="message">96%&nbsp;88%&nbsp;99%&nbsp;86% <tbody> <tr> <th colspan="3"><a href="../performance/fannkuchredux.html"><span>fannkuch-redux</span></a> <th colspan="3"> <tr> <th>source <th>secs <th>mem <th>gz <th>cpu <th>cpu load <tr> <td><a href="../program/fannkuchredux-lua-1.html"><span>Lua</span></a> <td>1,383.93 <td>1,460 <td>462 <td>1,383.69 <td class="message">0%&nbsp;100%&nbsp;1%&nbsp;0% <tr> <td><a href="../program/fannkuchredux-yarv-2.html"><span>Ruby</span></a> <td>581.68 <td>36,872 <td>1454 <td>2,272.55 <td class="message">99%&nbsp;94%&nbsp;99%&nbsp;99% <tbody> <tr> <th colspan="3"><a href="../performance/revcomp.html"><span>reverse-complement</span></a> <th colspan="3"> <tr> <th>source <th>secs <th>mem <th>gz <th>cpu <th>cpu load <tr> <td><a href="../program/revcomp-lua-2.html"><span>Lua</span></a> <td>75.98 <td>2,943,804 <td>553 <td>75.07 <td class="message">53%&nbsp;4%&nbsp;2%&nbsp;58% <tr> <td><a href="../program/revcomp-yarv-2.html"><span>Ruby</span></a> <td>31.12 <td>500,868 <td>264 <td>62.94 <td class="message">47%&nbsp;60%&nbsp;40%&nbsp;57% <tbody> <tr> <th colspan="3"><a href="../performance/binarytrees.html"><span>binary-trees</span></a> <th colspan="3"> <tr> <th>source <th>secs <th>mem <th>gz <th>cpu <th>cpu load <tr> <td><a href="../program/binarytrees-lua-2.html"><span>Lua</span></a> <td>468.12 <td>2,312,236 <td>412 <td>467.62 <td class="message">59%&nbsp;1%&nbsp;1%&nbsp;42% <tr> <td><a href="../program/binarytrees-yarv-5.html"><span>Ruby</span></a> <td>52.83 <td>433,920 <td>1107 <td>177.53 <td class="message">79%&nbsp;94%&nbsp;87%&nbsp;78% <tbody> <tr> <th colspan="3"><a href="../performance/regexredux.html"><span>regex-redux</span></a> <th colspan="3"> <tr> <th>source <th>secs <th>mem <th>gz <th>cpu <th>cpu load <tr> <td><a href="../program/regexredux-lua-2.html"><span>Lua</span></a> <td>&nbsp; <td class="message">Bad&nbsp;Output <td colspan="3"> <tr> <td><a href="../program/regexredux-yarv-3.html"><span>Ruby</span></a> <td>0.57 <td>12,596 <td>751 <td>0.94 <td class="message">63%&nbsp;26%&nbsp;49%&nbsp;68% <tbody> <tr> <th colspan="3"><a href="../performance/pidigits.html"><span>pidigits</span></a> <th colspan="3"> <tr> <th>source <th>secs <th>mem <th>gz <th>cpu <th>cpu load <tr> <td><a href="../program/pidigits-lua-5.html"><span>Lua</span></a> <td>&nbsp; <td class="message">Failed <td colspan="3"> <tr> <td><a href="../program/pidigits-yarv-1.html"><span>Ruby</span></a> <td>1.31 <td>53,240 <td>518 <td>2.63 <td class="message">64%&nbsp;33%&nbsp;5%&nbsp;100% <tbody> <tr> <td>Lua <td colspan="5" class="message"><p>Lua 5.3.4 Copyright (C) 1994-2017 Lua.org, PUC-Rio <tr> <td>Ruby <td colspan="5" class="message"><p>ruby 2.6.0preview2 (2018-05-31 trunk 63539) [x86_64-linux] </table> <nav> <ul> <p><a href="../measurements/lua.html">all other Lua programs & measurements</a> </ul> </nav> </section> </article> <footer> <nav> <ul> <li><a href="../why-measure-toy-benchmark-programs.html"><span>Why toy programs?</span></a> <li><a href="../how-programs-are-measured.html"><span>How programs are measured</span></a> <li><a href="../dont-jump-to-conclusions.html"><span>The Ultimate Benchmark</span></a> </ul> </nav> <aside> <p>We want easy answers, but easy answers are often incomplete or wrong. You and I know, there's more we need to understand. </aside> </footer>
34.903226
1,965
0.545749
e28e566f11a5d4a374d8ced7f3d32c73de994765
341
swift
Swift
Sources/fusionauth-swift-client/domain/io/fusionauth/domain/api/IPAccessControlListRequest.swift
f0rever-johnson/fusionauth-swift-client
0a810db9a995ec8962657c1033a6f89dc0a92bfe
[ "Apache-2.0" ]
null
null
null
Sources/fusionauth-swift-client/domain/io/fusionauth/domain/api/IPAccessControlListRequest.swift
f0rever-johnson/fusionauth-swift-client
0a810db9a995ec8962657c1033a6f89dc0a92bfe
[ "Apache-2.0" ]
null
null
null
Sources/fusionauth-swift-client/domain/io/fusionauth/domain/api/IPAccessControlListRequest.swift
f0rever-johnson/fusionauth-swift-client
0a810db9a995ec8962657c1033a6f89dc0a92bfe
[ "Apache-2.0" ]
1
2021-04-04T10:04:19.000Z
2021-04-04T10:04:19.000Z
// // File.swift // // // Created by Everaldlee Johnson on 8/20/21. // import Foundation public struct IPAccessControlListRequest:Codable{ public var ipAccessControlList:IPAccessControlList? public init(ipAccessControlList: IPAccessControlList? = nil) { self.ipAccessControlList = ipAccessControlList } }
18.944444
66
0.71261
1c87ba9ec0c8ac8c4f0c5f5b50edba6af36dbf66
1,718
sql
SQL
schema.sql
jkelly101/employee-tracker
cd61fd6276460c200f63891b5828e5d41a1438db
[ "MIT" ]
null
null
null
schema.sql
jkelly101/employee-tracker
cd61fd6276460c200f63891b5828e5d41a1438db
[ "MIT" ]
null
null
null
schema.sql
jkelly101/employee-tracker
cd61fd6276460c200f63891b5828e5d41a1438db
[ "MIT" ]
1
2021-03-15T14:48:17.000Z
2021-03-15T14:48:17.000Z
DROP DATABASE IF EXISTS employee_db; CREATE DATABASE employee_db; USE employee_db; CREATE TABLE departments( id INTEGER auto_increment NOT NULL, department VARCHAR(30) NOT NULL, PRIMARY KEY(id) ); CREATE TABLE roles( id INTEGER auto_increment NOT NULL, title VARCHAR(30) NOT NULL, salary DECIMAL(8, 2) NOT NULL, departments_id INTEGER, FOREIGN KEY (departments_id) REFERENCES departments(id), PRIMARY KEY(id) ); CREATE TABLE employees( id INTEGER auto_increment NOT NULL, first_name VARCHAR(30) NOT NULL, last_name VARCHAR(30) NOT NULL, roles_id INTEGER, manager_id INTEGER, FOREIGN KEY (roles_id) REFERENCES roles(id), PRIMARY KEY(id) ); INSERT INTO departments (department) VALUES ("Sales"); INSERT INTO departments (department) VALUES ("Engineering"); INSERT INTO departments (department) VALUES ("Finance"); INSERT INTO roles (title, salary, departments_id) VALUES ("Sales Lead", 100000, 1); INSERT INTO roles (title, salary, departments_id) VALUES ("Lead Engineer", 150000, 2); INSERT INTO roles (title, salary, departments_id) VALUES ("Accountant", 125000, 3); INSERT INTO employees (first_name, last_name, roles_id, manager_id) VALUES ("Jen", "Kelly", 1, 1); INSERT INTO employees (first_name, last_name, roles_id, manager_id) VALUES ("Tom", "Cruz", 2, 2); INSERT INTO employees (first_name, last_name, roles_id, manager_id) VALUES ("Matt", "Smith", 3, 3); USE employee_db; SELECT employees.id, employees.first_name, employees.last_name, roles.title, departments.department, roles.salary, employees.manager_id FROM employees LEFT JOIN roles ON employees.roles_id = roles.id LEFT JOIN departments ON roles.departments_id = departments.id -- LEFT JOIN employees ON employees.manager_id = employees.id;
34.36
199
0.77532
c7f8cb65405bfb60febc17a6a933b0cd29c7079b
13,799
java
Java
pankti-extract/src/test/java/se/kth/castor/pankti/extract/processors/CandidateTaggerTest.java
castor-software/pankti
1b93443e3013b947937ec5304769c85c0a77816a
[ "MIT" ]
8
2020-08-10T17:44:52.000Z
2021-04-06T11:58:28.000Z
pankti-extract/src/test/java/se/kth/castor/pankti/extract/processors/CandidateTaggerTest.java
castor-software/pankti
1b93443e3013b947937ec5304769c85c0a77816a
[ "MIT" ]
40
2020-03-20T10:51:16.000Z
2022-01-21T09:45:51.000Z
pankti-extract/src/test/java/se/kth/castor/pankti/extract/processors/CandidateTaggerTest.java
castor-software/pankti
1b93443e3013b947937ec5304769c85c0a77816a
[ "MIT" ]
2
2020-04-24T13:09:33.000Z
2021-09-27T07:00:19.000Z
package se.kth.castor.pankti.extract.processors; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import se.kth.castor.pankti.extract.launchers.PanktiLauncher; import se.kth.castor.pankti.extract.runners.PanktiMain; import spoon.MavenLauncher; import spoon.reflect.CtModel; import spoon.reflect.code.*; import spoon.reflect.declaration.CtMethod; import spoon.reflect.visitor.filter.TypeFilter; import java.net.URISyntaxException; import java.nio.file.Path; import static org.junit.jupiter.api.Assertions.*; public class CandidateTaggerTest { static PanktiMain panktiMain; static PanktiLauncher panktiLauncher; static MavenLauncher mavenLauncher; static CtModel testModel; static MethodProcessor methodProcessor; static CandidateTagger candidateTagger; @BeforeAll public static void setUpLauncherAndModel() throws URISyntaxException { methodProcessor = new MethodProcessor(true); panktiMain = new PanktiMain(Path.of("src/test/resources/jitsi-videobridge"), false); panktiLauncher = new PanktiLauncher(); mavenLauncher = panktiLauncher.getMavenLauncher(panktiMain.getProjectPath().toString(), panktiMain.getProjectPath().getFileName().toString()); testModel = panktiLauncher.buildSpoonModel(mavenLauncher); testModel.processWith(methodProcessor); panktiLauncher.addMetaDataToCandidateMethods(methodProcessor.getCandidateMethods()); candidateTagger = new CandidateTagger(); testModel.processWith(candidateTagger); } // Test the number of extracted methods that return a value @Test public void testNumberOfMethodsRetuningAValue() { assertEquals(214, candidateTagger.methodsReturningAValue.size(), "214 extracted methods in test resource should return a value"); } // Test that some extracted methods are void @Test public void testSomeExtractedMethodsDoNotReturnAValue() { assertEquals(methodProcessor.candidateMethods.size() - candidateTagger.methodsReturningAValue.size(), candidateTagger.methodsNotReturningAValue.size(), "Some extracted methods in test resource are void"); } // Test that an extracted method found to return a value actually does so @Test public void testMethodRetuningAValue() { CtMethod<?> methodReturningAValue = candidateTagger.methodsReturningAValue.get(0); assertTrue((methodReturningAValue.getElements(new TypeFilter<>(CtReturn.class)).size() > 0 && !methodReturningAValue.getType().getSimpleName().equals("void") && (methodReturningAValue.getType().isPrimitive() || !methodReturningAValue.getType().isPrimitive())), "Method should have a return statement, and return a primitive or an object, " + "and its return type cannot be void"); } // Test that an extracted method returning a value is tagged as such @Test public void testTagOfMethodRetuningAValue() { CtMethod<?> methodReturningAValue = candidateTagger.methodsReturningAValue.get(0); assertTrue((candidateTagger.allMethodTags.get(methodReturningAValue).get("returns")), "returns tag should be true for method"); } // Test that some extracted methods are void @Test public void testNumberOfMethodsNotReturningAValue() { assertFalse(candidateTagger.methodsNotReturningAValue.isEmpty(), "some extracted methods in test resource are void"); } // Test the number of extracted methods returning a primitive @Test public void testNumberOfMethodsReturningPrimitives() { assertEquals(65, candidateTagger.methodsReturningAPrimitive.size(), "65 extracted methods in test resource return a primitive value"); } // Test that an extracted method found to return a primitive actually does so @Test public void testMethodRetuningAPrimitive() { CtMethod<?> methodReturningAPrimitive = candidateTagger.methodsReturningAPrimitive.get(0); assertTrue((methodReturningAPrimitive.getElements(new TypeFilter<>(CtReturn.class)).size() > 0 && !methodReturningAPrimitive.getType().getSimpleName().equals("void") && methodReturningAPrimitive.getType().isPrimitive()), "Method should have a return statement, and return a primitive, " + "and its return type cannot be void"); } // Test that an extracted method returning a primitive is tagged as such @Test public void testTagOfMethodRetuningAPrimitive() { CtMethod<?> methodReturningAPrimitive = candidateTagger.methodsReturningAPrimitive.get(0); assertTrue((candidateTagger.allMethodTags.get(methodReturningAPrimitive).get("returns_primitives")), "returns_primitives tag should be true for method"); } // Test the number of extracted methods not returning a primitive @Test public void testNumberOfMethodsNotReturningPrimitives() { assertEquals(149, candidateTagger.methodsReturningAValue.size() - candidateTagger.methodsReturningAPrimitive.size(), "149 extracted methods in test resource return an object"); } // Test that an extracted method found to not return a primitive actually does not @Test public void testMethodRetuningNotAPrimitive() { for (CtMethod<?> methodReturningAValue : candidateTagger.methodsReturningAValue) { if (!candidateTagger.methodsReturningAPrimitive.contains(methodReturningAValue)) { assertTrue((methodReturningAValue.getElements(new TypeFilter<>(CtReturn.class)).size() > 0 && !methodReturningAValue.getType().getSimpleName().equals("void") && !methodReturningAValue.getType().isPrimitive()), "Method should have a return statement, and return an object, " + "and its return type cannot be void"); break; } } } // Test that an extracted method not returning a primitive is tagged as such @Test public void testTagOfMethodNotRetuningAPrimitive() { for (CtMethod<?> methodReturningAValue : candidateTagger.methodsReturningAValue) { if (!candidateTagger.methodsReturningAPrimitive.contains(methodReturningAValue)) { assertFalse(candidateTagger.allMethodTags.get(methodReturningAValue).get("returns_primitives"), "returns_primitives tag should be false for method"); break; } } } // Test the number of extracted methods with if conditions @Test public void testNumberOfMethodsWithIfConditions() { assertEquals(160, candidateTagger.methodsWithIfConditions.size(), "160 extracted methods in test resource have an if condition"); } // Test that an extracted method found to have if condition(s) actually does so @Test public void testMethodsWithIfCondition() { CtMethod<?> methodWithIfCondition = candidateTagger.methodsWithIfConditions.get(0); assertTrue(methodWithIfCondition.getElements(new TypeFilter<>(CtIf.class)).size() > 0, "Method should have an if condition"); } // Test that an extracted method having if condition(s) is tagged as such @Test public void testTagOfMethodWithIfCondition() { CtMethod<?> methodWithIfCondition = candidateTagger.methodsWithIfConditions.get(0); assertTrue(candidateTagger.allMethodTags.get(methodWithIfCondition).get("ifs"), "ifs tag should be true for method"); } // Test the number of extracted methods with conditional operators @Test public void testNumberOfMethodsWithConditionals() { assertEquals(10, candidateTagger.methodsWithConditionalOperators.size(), "10 extracted methods in test resource use a conditional operator"); } // Test that an extracted method found to have conditional operator(s) actually does so @Test public void testMethodWithConditionals() { CtMethod<?> methodWithIfCondition = candidateTagger.methodsWithConditionalOperators.get(0); assertTrue(methodWithIfCondition.getElements(new TypeFilter<>(CtConditional.class)).size() > 0, "Method should have a conditional operator"); } // Test that an extracted method with conditional operator(s) is tagged as such @Test public void testTagOfMethodWithConditionals() { CtMethod<?> methodWithConditional = candidateTagger.methodsWithConditionalOperators.get(0); assertTrue(candidateTagger.allMethodTags.get(methodWithConditional).get("conditionals"), "conditionals tag should be true for method"); } // Test the number of extracted methods with loops @Test public void testNumberOfMethodsWithLoops() { assertEquals(28, candidateTagger.methodsWithLoops.size(), "28 extracted method in test resource have a loop"); } // Test the number of extracted methods with switch statements @Test public void testNumberOfMethodsWithSwitchStatements() { assertEquals(5, candidateTagger.methodsWithSwitchStatements.size(), "5 extracted methods in test resource have switch statements"); } // Test that an extracted method found to have switch statement(s) actually does so @Test public void testMethodWithSwitchStatements() { CtMethod<?> methodWithSwitchStatements = candidateTagger.methodsWithSwitchStatements.get(0); assertTrue(methodWithSwitchStatements.getElements(new TypeFilter<>(CtSwitch.class)).size() > 0, "Method should have a conditional operator"); } // Test that an extracted method with switch statement(s) is tagged as such @Test public void testTagOfMethodWithSwitchStatements() { CtMethod<?> methodWithSwitchStatements = candidateTagger.methodsWithSwitchStatements.get(0); assertTrue(candidateTagger.allMethodTags.get(methodWithSwitchStatements).get("switches"), "switches tag should be true for method"); } // Test the number of extracted methods with parameters @Test public void testNumberOfMethodsWithParameters() { assertEquals(229, candidateTagger.methodsWithParameters.size(), "229 extracted methods in test resource have parameters"); } // Test that an extracted method found to have parameters actually does so @Test public void testMethodWithParameters() { CtMethod<?> methodWithParameters = candidateTagger.methodsWithParameters.get(0); assertTrue(methodWithParameters.getParameters().size() > 0, "Method should have a conditional operator"); } // Test that an extracted method with parameters is tagged as such @Test public void testTagOfMethodWithParameters() { CtMethod<?> methodWithParameters = candidateTagger.methodsWithParameters.get(0); assertTrue(candidateTagger.allMethodTags.get(methodWithParameters).get("parameters"), "parameters tag should be true for method"); } // Test the number of extracted methods with multiple statements @Test public void testNumberOfMethodsWithMultipleStatements() { assertEquals(191, candidateTagger.methodsWithMultipleStatements.size(), "191 extracted methods in test resource have multiple statements"); } // Test that an extracted method found to have multiple statements actually does so @Test public void testMethodWithMultipleStatements() { CtMethod<?> methodWithMultipleStatements = candidateTagger.methodsWithMultipleStatements.get(0); assertTrue(methodWithMultipleStatements.getBody().getStatements().size() > 0, "Method should have multiple statements"); } // Test that an extracted method with multiple statements is tagged as such @Test public void testTagOfMethodWithMultipleStatements() { CtMethod<?> methodWithMultipleStatements = candidateTagger.methodsWithMultipleStatements.get(0); assertTrue(candidateTagger.allMethodTags.get(methodWithMultipleStatements).get("multiple_statements"), "multiple_statements tag should be true for method"); } // Test the number of methods with local variables @Test public void testNumberOfMethodsWithLocalVariables() { assertEquals(161, candidateTagger.methodsWithLocalVariables.size(), "161 extracted methods in test resource define local variables"); } // Test that an extracted method found to have local variables actually does so @Test public void testMethodWithLocalVariables() { CtMethod<?> methodWithLocalVariables = candidateTagger.methodsWithLocalVariables.get(0); assertTrue(methodWithLocalVariables.getElements(new TypeFilter<>(CtLocalVariable.class)).size() > 0, "Method should have local variables"); } // Test that an extracted method defining local variables is tagged as such @Test public void testTagOfMethodWithLocalVariables() { CtMethod<?> methodWithLocalVariables = candidateTagger.methodsWithLocalVariables.get(0); assertTrue(candidateTagger.allMethodTags.get(methodWithLocalVariables).get("local_variables"), "local_variables tag should be true for method"); } }
46.618243
123
0.696572
915f342e04eb8b0ae20aa7b963e8c6180ade0d7d
12,341
html
HTML
static/sample.html
rickysahu/mpngen
da8b2f46fa293e6f12b41a3e2413ceb238d83bb6
[ "MIT" ]
5
2017-06-06T15:08:01.000Z
2020-08-21T03:41:00.000Z
static/sample.html
rickysahu/mpngen
da8b2f46fa293e6f12b41a3e2413ceb238d83bb6
[ "MIT" ]
null
null
null
static/sample.html
rickysahu/mpngen
da8b2f46fa293e6f12b41a3e2413ceb238d83bb6
[ "MIT" ]
null
null
null
<style> body { margin: 10px; font-family: system-ui, Roboto, Helvetica, sans-serif; line-height: 1.5rem; } h2 { color: #3dace3; font-weight: 400; background-color: #ebebeb; padding: 1.5rem; margin-bottom: 0px; } a { color: #3dace3; } /* Table styles */ table { width: 100%; border-collapse: collapse; } th, td { padding: 1.5rem; vertical-align: top; border: 1px solid #eee } th { background-color: #f7f7f7; } th:last-child, td:last-child { width: 40%; } /* Tooltip container */ .tooltip { position: relative; display: inline-block; border-bottom: 3px solid #ccc; } /* Tooltip text */ .tooltip .tooltiptext { visibility: hidden; width: 200px; font-weight: 400; font-size: 12px; line-height: 15px; background-color: #555; color: #fff; text-align: left; padding: 5px 7px; border-radius: 3px; /* Position the tooltip text */ position: absolute; z-index: 1; bottom: 125%; left: 50%; margin-left: -60px; /* Fade in tooltip */ opacity: 0; transition: opacity 1s; } /* Tooltip arrow */ .tooltip .tooltiptext::after { content: ""; position: absolute; top: 100%; left: 50%; margin-left: -5px; border-width: 5px; border-style: solid; border-color: #555 transparent transparent transparent; } /* Show the tooltip text when you mouse over the tooltip container */ .tooltip:hover .tooltiptext { visibility: visible; opacity: 1; } .half { display: inline-block; width:49%; } @media only screen and (max-width: 600px) { .half { display: inline-block; width: 100%; } } </style> <h1 id="1uphealthincmodelprivacynotice">1upHealth, Inc. Model Privacy Notice</h1> <p><strong>Note:</strong> Developers of consumer health technology or apps (“health technology developers”) that collect digital health data about individuals would use this template to disclose to consumers the developer’s privacy and security policies. <strong>"We"</strong> refers to the health technology developer or technology product and <strong>"you/your"</strong> refers to the user/consumer of the health technology. </div> </p> <p><br></br></p> <h2 id="1uphealthincisahipaacoveredentity">1upHealth, Inc. is a HIPAA Covered Entity</h2> <div style="display:inline-block">Some of the health data we collect as part of this 1upHealth Patient App also are protected by HIPAA. Read our <a href='https://1uphealth.care/hipaa-policy' target='_blank'>HIPAA Notice of Privacy Practices</a> (https://1uphealth.care/hipaa-policy) for more information.</div> <p><br></br> </p> <h2 id="usehowweuseyourdatainternally">Use: How we use your data internally</h2> <h3> We collect and use your <div class="tooltip"> identifiable data <div class="tooltiptext"> Identifiable data means: data, such as your name, phone number, email, address, health services, information on your physical or mental health conditions, or your social security number, that can be used on its own or with other information to identify you. </div> </div>: </h3> <ul><li>To provide the <span class="tooltip"> primary service <div class="tooltiptext"> Primary service means: 1upHealth stores patient data from multiple systems </div> </span> of the app or technology</li></ul> <ul> <li>To conduct scientific research </li> </ul> <ul><li>To develop and improve new and current products and services (e.g., <span class="tooltip"> analytics <div class="tooltiptext"> Analytics means: the process of examining data to draw conclusions from that information. </div> </span> )</li></ul> <p><br></br> </p> <h2 id="sharehowweshareyourdataexternallywithothercompaniesorentities">Share: How we share your data externally with other companies or entities</h2> <h3> We share your <div class="tooltip"> identifiable data <div class="tooltiptext"> Identifiable data means: data, such as your name, phone number, email, address, health services, information on your physical or mental health conditions, or your social security number, that can be used on its own or with other information to identify you. </div> </div>: </h3> <ul><li>To provide the <span class="tooltip"> primary service <div class="tooltiptext"> Primary service means: 1upHealth stores patient data from multiple systems </div> </span> of the app or technology</li></ul> <ul> <li><p>To conduct scientific research </p></li> <li><p>For company operations (e.g. quality control or fraud detection) </p></li> </ul> <p><br></br> </p> <h3 id="weshareyourdataafterremovingidentifiersnotethatremainingdatamaynotbeanonymous">We share your data AFTER removing identifiers (note that remaining data may not be anonymous):</h3> <ul> <li>We DO NOT share your data after removing identifiers<br /> <br></br> </li> </ul> <h2 id="sellwhowesellyourdatato">Sell: Who we sell your data to</h2> <table> <tr> <th><strong>Sold Data<strong></th> <th style='width:40%;'><strong>Do we sell?<strong></th> </tr> <tr> <td> <strong> We sell your <span class="tooltip"> identifiable data <div class="tooltiptext"> Identifiable data means: data, such as your name, phone number, email, address, health services, information on your physical or mental health conditions, or your social security number, that can be used on its own or with other information to identify you. </div> </span> to <span class="tooltip"> data brokers <div class="tooltiptext"> Data broker means: companies that collect personal information about consumers from a variety of public and non-public sources and resell the information to other companies </div> </span> , marketing, advertising networks, or analytics firms. </strong> </td> <td> No </td> </tr> <tr> <td><strong>We sell your data AFTER removing identifiers (note that remaining data may not be anonymous) to <span class="tooltip"> data brokers <div class="tooltiptext"> Data broker means: companies that collect personal information about consumers from a variety of public and non-public sources and resell the information to other companies </div> </span> , marketing, advertising networks, or analytics firms.</strong></td> <td> No </td> </tr> </table> <p><br></br></p> <h2 id="storehowwestoreyourdata">Store: How we store your data</h2> <table> <tr> <th><strong>Stored Data<strong></th> <th><strong>Is it stored?<strong></th> </tr> <tr> <td><strong>Are your data stored on the device? </strong></td> <td>Yes </td> </tr> <tr> <td><strong>Are your data stored outside the device at our company or through a third party?</strong></td> <td>Yes </td> </tr> </table> <p><br /> <br></br></p> <h2 id="encryptionhowweencryptyourdata">Encryption: How we encrypt your data</h2> <table> <tr> <th><strong>Encrypted Data<strong></th> <th><strong>Is it encrypted?<strong></th> </tr> <tr> <td><strong>Does the app or technology use <div class="tooltip"> encryption <div class="tooltiptext"> Encryption means: a method of converting an original message of regular text into encoded text in such a way that only authorized parties can read it. </div> </div> to encrypt your data in the device or app? </strong></td> <td>Yes, by default </td> </tr> <tr> <td><strong>Does the app or technology use <div class="tooltip"> encryption <div class="tooltiptext"> Encryption means: a method of converting an original message of regular text into encoded text in such a way that only authorized parties can read it. </div> </div> to encrypt your data when stored on our company servers or with an outside <div class="tooltip"> cloud computing <div class="tooltiptext"> Cloud computing means: a kind of Internet-based computing that provides shared processing resources and data to computers and other devices on demand. </div> </div> services provider?</strong></td> <td>Yes, by default </td> </tr> <tr> <td><strong>Does the app or technology use <div class="tooltip"> encryption <div class="tooltiptext"> Encryption means: a method of converting an original message of regular text into encoded text in such a way that only authorized parties can read it. </div> </div> to encrypt your data while it is transmitted?</strong></td> <td>Yes, by default </td> </tr> </table> <p> <br></br> </p> <h2 id="privacyhowthistechnologyaccessesotherdata">Privacy: How this technology accesses other data</h2> <table style='vertical-align: top'> <tr> <th><strong>Other Data<strong></th> <th style='width:40%;'><strong>Is it accessed?<strong></th> </tr> <tr> <td><strong>Will this technology or app request access to other device data or applications, such as your phone’s camera, photos, or contacts? </strong></td> <td> <div> Yes, only with your permission. It connects to... <li>Photo</li> <li>Location</li> <li>Health monitoring devices</li> To check settings, visit our <a target='_blank' href='https://1uphealth.care/device-permissions'>help page</a> </div> </td> </tr> <tr> <td><strong>Does this technology or app allow you to share the collected data with your social media accounts, like Facebook?</strong></td> <td>Yes, only with your permission. To check settings, visit our <a target='_blank' href='https://1uphealth.care/social-permissions'>help page</a> </td> </tr> </table> <p><br></br></p> <h2 id="useroptionswhatyoucandowiththedatathatwecollect">User Options: What you can do with the data that we collect</h2> <table> <tr> <td><strong>Can you access, edit, share, or delete the data we have about you?</strong></td> <td>Yes, you can ... <br> <li>access your data</li> <li>edit your data</li> <li>share your data</li> <li>delete your data</li> Select data on the manage data page and choose an action. </td> </tr> </table> <p> <br></br></p> <h2> <div class="tooltip"> Deactivation <div class="tooltiptext"> Deactivation means: an individual takes action or a company ceases operation or deactivates an individual’s account due to inactivity. </div> </div>: What happens to your data when your account is deactivated </h2> <table> <tr> <td><strong>When your account is deactivated/terminated by you or the company, your data are... </strong></td> <td> Permanently retained and used </td> </tr> </table> <p><br></br></p> <h2 id="policychangeshowwewillnotifyyouifourprivacypolicychanges">Policy Changes: How we will notify you if our privacy policy changes</h2> <p>You will be notified via email</p> <div>Find out more in the <a href='https://1uphealth.care/policy#changes' target='_blank'>Changes section of our Privacy Policy</a> (https://1uphealth.care/policy#changes)<br></div> <p><br></br></p> <h2> <div class="tooltip"> Breach <div class="tooltiptext"> Breach means: an unauthorized disclosure. </div> </div>: How we will notify you and protect your data in case of an improper disclosure </h2> <p>1upHealth, Inc. complies with all applicable laws regarding breaches.<br /> You will be notified via email</p> <div>Find out more in the <a href='https://1uphealth.care/policy#breach' target='_blank'>Breach section of our Privacy Policy</a> (https://1uphealth.care/policy#breach)<br></div> <p><br></br></p> <h2 id="contactus">Contact Us</h2> <h3 id="1uphealthinc">1upHealth, Inc.</h3> <div><a href='https://1uphealth.care/privacy-policy' target='_blank'>Privacy Policy</a> (https://1uphealth.care/privacy-policy)<br></div> <div><a href='http://1uphealth.care/contact' target='_blank'>Contact Page</a> (http://1uphealth.care/contact)<br></div> <p><a href="mailto:hello@1uphealth.care">hello@1uphealth.care</a><br /> <a href="tel:123-321-3124">123-321-3124</a> </p> <p>1upHealth, Inc.<br /> 123 Easy St. Boston MA<br /> United States of America </p>
35.875
310
0.671096
0bad2da3e1dacf427841f734f0e1eaaf1149a295
432
swift
Swift
Geometris/Core/UDRVResponse.swift
geometris/geometrisIOS
81f341dae5695c8d28209402eb66abd3c19a748f
[ "MIT" ]
null
null
null
Geometris/Core/UDRVResponse.swift
geometris/geometrisIOS
81f341dae5695c8d28209402eb66abd3c19a748f
[ "MIT" ]
null
null
null
Geometris/Core/UDRVResponse.swift
geometris/geometrisIOS
81f341dae5695c8d28209402eb66abd3c19a748f
[ "MIT" ]
1
2021-08-20T08:13:53.000Z
2021-08-20T08:13:53.000Z
// // UDRVResponse.swift // Geometris // // Created by Bipin Kadel on 3/22/18. // Copyright © 2018 geometris. All rights reserved. // import Foundation public class UDRVResponse: BaseResponse { /// ReqType public internal(set) var address:String? init(requestId reqId: ReqType, address add: String?, withError error:Error?){ address = add super.init(requestId: reqId, withError: error) } }
22.736842
81
0.668981
c2555ecef729d5bbd11b9aa0cba8369b484200d9
1,204
lua
Lua
src/apis/proc.lua
Brenden2008/sPhone
c50a5dfbfa460123ae60ee33c20bb83ed6a37932
[ "MIT" ]
1
2016-10-14T13:10:40.000Z
2016-10-14T13:10:40.000Z
src/apis/proc.lua
Brenden2008/sPhone
c50a5dfbfa460123ae60ee33c20bb83ed6a37932
[ "MIT" ]
null
null
null
src/apis/proc.lua
Brenden2008/sPhone
c50a5dfbfa460123ae60ee33c20bb83ed6a37932
[ "MIT" ]
null
null
null
-- "multitasking" local _proc = {} local _killProc = {} function signal(pid, sig) local p = _proc[pid] if p then if not p.filter or p.filter == "signal" then local ok, rtn = coroutine.resume(p.co, "signal", tostring(sig)) if ok then p.filter = rtn end end return true end return false end function kill(pid) _killProc[pid] = true end function launch(fn, name) _proc[#_proc + 1] = { name = name or "lua", co = coroutine.create(setfenv(fn, getfenv())), } return true end function getInfo() local t = {} for pid, v in pairs(_proc) do t[pid] = v.name end return t end function run() os.queueEvent("multitask") while _proc[1] ~= nil do local ev = {os.pullEventRaw()} for pid, v in pairs(_proc) do if not v.filter or ev[1] == "terminate" or v.filter == ev[1] then local ok, rtn = coroutine.resume(v.co, unpack(ev)) if ok then v.filter = rtn end end if coroutine.status(v.co) == "dead" then _killProc[pid] = true end end for pid in pairs(_killProc) do _proc[pid] = nil end if next(_killProc) then _killProc = {} end end end
20.758621
71
0.58887
7d922a09d1772692622fd3dc4607c53aba34aa21
23,700
html
HTML
plugins/testmanagement/scripts/testmanagement/src/execution/execution-detail.tpl.html
yasir2000/brown-bear
03ebf384d27013b60f1469a230b3523322e192c9
[ "MIT" ]
6
2022-03-06T15:48:13.000Z
2022-03-07T16:27:29.000Z
plugins/testmanagement/scripts/testmanagement/src/execution/execution-detail.tpl.html
yasir2000/brown-bear
03ebf384d27013b60f1469a230b3523322e192c9
[ "MIT" ]
null
null
null
plugins/testmanagement/scripts/testmanagement/src/execution/execution-detail.tpl.html
yasir2000/brown-bear
03ebf384d27013b60f1469a230b3523322e192c9
[ "MIT" ]
null
null
null
<div class="tlp-alert-danger" ng-if="execution.error">{{ execution.error }}</div> <div class="tuleap-modal-loading" ng-if="artifact_links_graph_modal_loading.is_loading || edit_artifact_modal_loading.loading"></div> <div class="linked-issue-alert tlp-alert-success" ng-if="linkedIssueAlertVisible"> <span class="linked-issue-alert-text"> {{ "Bug" | translate }} <a ng-href="/plugins/tracker/?aid={{ linkedIssueId }}">#{{ linkedIssueId }}</a> {{ "has been successfully linked to this test." | translate }} </span> <button type="button" class="linked-issue-alert-close tlp-button-success tlp-button-outline tlp-button-mini" ng-click="closeLinkedIssueAlert()" > <i class="fa fa-times-circle" aria-hidden="true"></i> </button> </div> <section id="test" class="tlp-pane current-test" ng-class="{ 'passed': execution.status === 'passed', 'failed': execution.status === 'failed', 'blocked': execution.status === 'blocked', 'notrun': execution.status === 'notrun', 'comment-expanded': isCommentAreaExpanded }" data-test="current-test" > <div class="tlp-pane-container" role="tabpanel" id="{{ execution.definition.id }}-tabpanel" aria-labelledby="{{ execution.definition.id }}-tab" > <section class="current-test-header-container"> <div class="loader" ng-if="! execution.id"></div> <div class="current-test-header"> <h1 class="current-test-header-title" data-test="current-test-header-title"> <i ng-if="execution.is_automated" class="fa current-test-title-icon-auto" ng-class="{ 'fa-tlp-robot notrun': execution.status === 'notrun', 'fa-tlp-robot blocked': execution.status === 'blocked', 'fa-tlp-robot-happy passed': execution.status === 'passed', 'fa-tlp-robot-unhappy failed': execution.status === 'failed' }"></i> {{ execution.definition.summary }} </h1> <div class="current-test-header-actions"> <div class="tlp-dropdown" ng-if="linkMenuIsVisible"> <button class="current-test-header-action tlp-button-secondary" type="button" id="dropdown-link-bug" title="{{ 'Open bug options dropdown' | translate }}" open-tlp-dropdown > <i class="fa fa-fw fa-tlp-new-bug" aria-hidden="true"></i> </button> <div class="tlp-dropdown-menu tlp-dropdown-menu-right tlp-dropdown-menu-on-icon" role="menu"> <button class="tlp-dropdown-menu-item" type="button" role="menuitem" ng-if="canCreateIssue" ng-click="showLinkToNewBugModal()" data-shortcut-new-bug > <i class="tlp-dropdown-menu-item-icon fa fa-fw fa-plus" aria-hidden="true"></i> <span translate>Create a new bug</span> </button> <button class="tlp-dropdown-menu-item" type="button" role="menuitem" ng-if="canLinkIssue" ng-click="showLinkToExistingBugModal()" data-shortcut-link-bug > <i class="tlp-dropdown-menu-item-icon fa fa-fw fa-link" aria-hidden="true"></i> <span translate>Link to an existing bug</span> </button> </div> </div> <button class="current-test-header-action tlp-button-secondary" type="button" ng-if="! linkMenuIsVisible && canCreateIssue" ng-click="showLinkToNewBugModal()" title="{{ 'Create a new bug' | translate }}" data-shortcut-new-bug > <i class="fa fa-fw fa-tlp-new-bug" aria-hidden="true"></i> </button> <a href="/plugins/tracker/?aid={{ execution.definition.id }}" class="current-test-header-action tlp-button-secondary" data-test="current-test-edit" ng-click="showEditArtifactModal($event, execution.definition)" title="{{ 'Edit this test' | translate }}" data-shortcut-edit-test > <i class="fas fa-fw fa-pencil-alt" aria-hidden="true"></i> </a> <button class="current-test-header-action tlp-button-secondary" type="button" ng-click="showArtifactLinksGraphModal(execution)" title="{{ 'Show dependencies graph for this test' | translate }}" data-shortcut-dependency-graph > <i class="fa fa-tlp-dependencies-graph" aria-hidden="true"></i> </button> </div> </div> <section ng-if="execution.definition.all_requirements.length + execution.linked_bugs.length > 2 && execution.is_automated === false" class="current-test-requirement-or-bug" > <div class="tlp-dropdown"> <button ng-if="execution.definition.all_requirements.length > 0" ng-class="{ 'tlp-badge-success': execution.status === 'passed', 'tlp-badge-danger': execution.status === 'failed', 'tlp-badge-info': execution.status === 'blocked', 'tlp-badge-secondary': execution.status === 'notrun' }" type="button" open-tlp-dropdown > <span translate translate-n="execution.definition.all_requirements.length" translate-plural="{{ $count }} requirements covered">1 requirement covered</span> </button> <div class="tlp-dropdown-menu"> <a class="tlp-dropdown-menu-item" role="menuitem" href="/plugins/tracker/?aid={{ requirement.id }}" ng-repeat="requirement in execution.definition.all_requirements track by requirement.id" > <span ng-class="['cross-ref-badge', 'cross-ref-badge-' + requirement.tracker.color_name, 'linked-issues-dropdown-content-badge']"> {{ requirement.xref }} </span> {{ requirement.title }} </a> </div> </div> <div class="tlp-dropdown"> <button ng-if="execution.linked_bugs.length > 0" ng-class="{ 'tlp-badge-success': execution.status === 'passed', 'tlp-badge-danger': execution.status === 'failed', 'tlp-badge-info': execution.status === 'blocked', 'tlp-badge-secondary': execution.status === 'notrun' }" type="button" open-tlp-dropdown > <span translate translate-n="execution.linked_bugs.length" translate-plural="{{ $count }} bugs linked">1 bug linked</span> </button> <div class="tlp-dropdown-menu"> <a class="tlp-dropdown-menu-item" role="menuitem" href="/plugins/tracker/?aid={{ bug.id }}" ng-repeat="bug in execution.linked_bugs track by bug.id" > <span ng-class="['cross-ref-badge', 'cross-ref-badge-' + bug.tracker.color_name, 'linked-issues-dropdown-content-badge']"> {{ bug.xref }} </span> {{ bug.title }} </a> </div> </div> </section> <section ng-if="execution.definition.all_requirements.length > 0 && execution.definition.all_requirements.length + execution.linked_bugs.length <= 2 && execution.is_automated === false" class="current-test-requirement-or-bug" ng-repeat="requirement in execution.definition.all_requirements track by requirement.id" data-test="current-test-requirement" > <i class="fas fa-fw fa-long-arrow-alt-right current-test-requirement-or-bug-icon" aria-hidden="true"></i> <a href="/plugins/tracker/?aid={{ requirement.id }}"> <span ng-class="['current-test-requirement-or-bug-badge', 'cross-ref-badge', 'cross-ref-badge-' + requirement.tracker.color_name]"> {{ requirement.xref }} </span> <span>{{ requirement.title }}</span> </a> </section> <section ng-if="execution.linked_bugs.length > 0 && execution.definition.all_requirements.length + execution.linked_bugs.length <= 2 && execution.is_automated === false" class="current-test-requirement-or-bug" ng-repeat="bug in execution.linked_bugs track by bug.id" data-test="current-test-bug" > <i class="fas fa-fw fa-bug current-test-requirement-or-bug-icon" aria-hidden="true"></i> <a href="/plugins/tracker/?aid={{ bug.id }}"> <span ng-class="['current-test-requirement-or-bug-badge', 'cross-ref-badge', 'cross-ref-badge-' + bug.tracker.color_name]"> {{ bug.xref }} </span> <span>{{ bug.title }}</span> </a> </section> <section ng-if="execution.previous_result.has_been_run_at_least_once" class="current-test-latest-result" > <i class="fa fa-check-circle current-test-status" ng-if="execution.status === 'passed'"></i> <i class="fa fa-times-circle current-test-status" ng-if="execution.status === 'failed'"></i> <i class="fa fa-exclamation-circle current-test-status" ng-if="execution.status === 'blocked'"></i> <div class="current-test-header-who"> <span ng-if="execution.previous_result.submitted_on"> {{ execution.previous_result.submitted_on | amCalendar }} </span> <span ng-if="execution.previous_result.submitted_by.real_name"> <span translate>by</span> {{ execution.previous_result.submitted_by.real_name }} </span> </div> </section> </section> <section ng-if="! execution.definition.steps.length && execution.is_automated === false" class="current-test-content tlp-pane-section"> <section ng-class="{'empty-state-pane': execution.definition.description.length === 0}"> <execution-detail-just-updated></execution-detail-just-updated> <p class="empty-state-text" ng-if="execution.definition.description.length === 0" translate > This test has no description. Please edit it. </p> <div ng-bind-html="execution.definition.description"></div> </section> </section> <execution-with-steps class="current-test-content" ng-if="execution.definition.steps.length && execution.is_automated === false" execution="execution" campaign="campaign" tabindex="-1" ></execution-with-steps> <section class="tlp-pane-section current-test-footer-section current-test-footer-section-comment current-test-footer-top" ng-class="{'current-test-footer-section-readonly-comment-container': ! displayTestCommentEditor }" ng-if="shouldCommentSectionBeDisplayed() && execution.is_automated === false && ! execution.userCanReloadTestBecauseDefinitionIsUpdated" data-test="comment-footer-section" execution-attachments-drop-zone execution-attachments-drop-zone-allow-dnd="displayTestCommentEditor && execution.upload_url !== null" > <div class="tlp-alert-warning current-test-message-warning" ng-if="onlyStatusHasBeenChanged" data-test="warning-status-changed" > <span translate>Only the test status has changed, not the comment. Maybe you should have a look at it.</span> <div class="current-test-message-warning-actions"> <button type="button" class="tlp-button-warning tlp-button-small" ng-click="userIsAcceptingThatOnlyStatusHasBeenChanged()" > <i class="fas fa-check tlp-button-icon" aria-hidden="true"></i> <span translate>Ok, got it</span> </button> </div> </div> <div class="tlp-alert-warning current-test-message-warning" ng-if="displayTestCommentWarningOveriding"> {{ getWarningTestCommentHasBeenUpdatedMessage(execution) }} <div class="current-test-message-warning-actions"> <button type="button" class="tlp-button-warning tlp-button-small" ng-click="onLoadNewComment(execution)"> <span translate>Load the new comment</span> </button> <button type="button" class="tlp-button-warning tlp-button-small" ng-click="onContinueToEditComment()"> <span translate>Continue to edit your comment</span> </button> </div> </div> <div class="current-comment-header-section"> <label class="tlp-label" for="execution_{{execution.id}}" translate>Comment</label> <button type="button" class="current-comment-header-toggler tlp-button-secondary tlp-button-outline" data-test="expand-details-button" ng-click="toggleCommentArea()" title="{{ getToggleTitle() }}" > <i class="fas tlp-button-icon" ng-class="{'fa-compress-alt': isCommentAreaExpanded, 'fa-expand-alt': !isCommentAreaExpanded}" aria-hidden="true" ></i> </button> </div> <div class="current-test-results-container"> <div ng-show="displayTestCommentEditor && campaign.is_open" class="current-test-comment" id="execution_{{execution.id}}" data-test="current-test-comment" data-shortcut-current-test-comment > </div> <div ng-if="! displayTestCommentEditor" class="current-test-comment-displayer" data-test="current-test-comment-preview" ng-bind-html="execution.previous_result.result" > </div> <execution-attachments execution="execution" is-in-comment-mode="displayTestCommentEditor" ></execution-attachments> </div> </section> <section ng-if="execution.userCanReloadTestBecauseDefinitionIsUpdated" class="tlp-pane-section current-test-footer-section current-test-footer-bottom" > <div class="tlp-alert-warning current-test-message-warning"> <span translate>The test has been changed by someone else. You should reload the test before executing it.</span> <div class="current-test-message-warning-actions"> <button type="button" class="tlp-button-warning tlp-button-small current-test-should-be-reloaded-button" ng-click="onReloadTestBecauseDefinitionIsUpdated(execution)"> <i class="fas fa-fw fa-sync tlp-button-icon"></i> <span translate>Reload the test</span> </button> </div> </div> </section> <section ng-if="execution.is_automated === false && campaign.is_open && ! execution.userCanReloadTestBecauseDefinitionIsUpdated" class="tlp-pane-section current-test-footer-section current-test-footer-section-buttons-container current-test-footer-bottom" execution-attachments-drop-zone execution-attachments-drop-zone-allow-dnd="displayTestCommentEditor && execution.upload_url !== null" > <div class="current-test-edit-comment-buttons" ng-if="! displayTestCommentWarningOveriding"> <button type="button" ng-if="! displayTestCommentEditor" class="tlp-button-secondary tlp-button-small tlp-button-outline" data-test="edit-comment-button" ng-click="showTestCommentEditor(execution)" data-shortcut-edit-comment-button > {{ 'Edit comment' | translate }} </button> <button type="button" ng-show="shouldCancelEditionCommentBeDisplayed(execution)" class="tlp-button-secondary tlp-button-small tlp-button-outline" data-test="cancel-edit-comment-button" ng-click="onCancelEditionComment(execution)" ng-disabled="execution.saving || areFilesUploading(execution)" > {{ 'Cancel edition' | translate }} </button> <button type="button" ng-if="displayTestCommentEditor" class="tlp-button-secondary tlp-button-small tlp-button-outline" data-test="save-comment-button" ng-click="updateComment($event, execution)" ng-disabled="execution.saving || areFilesUploading(execution)" > {{ 'Save comment' | translate }} </button> </div> <div class="current-test-results"> <button id="test-result-passed" type="button" data-test="mark-test-as-passed" class="current-test-result tlp-button-large tlp-button-success" title="{{ 'Passed' | translate }}" ng-click="pass($event, execution)" data-shortcut-passed ng-disabled="execution.saving || areFilesUploading(execution)"> <i class="fas fa-fw fa-check"></i> </button> <button id="test-result-failed" type="button" data-test="mark-test-as-failed" class="current-test-result tlp-button-large tlp-button-danger" title="{{ 'Failed' | translate }}" ng-click="fail($event, execution)" ng-disabled="execution.saving || areFilesUploading(execution)"> <i class="fas fa-fw fa-times"></i> </button> <button id="test-result-blocked" type="button" data-test="mark-test-as-blocked" class="current-test-result tlp-button-large tlp-button-info" title="{{ 'Blocked' | translate }}" ng-click="block($event, execution)" data-shortcut-blocked ng-disabled="execution.saving || areFilesUploading(execution)"> <i class="fas fa-fw fa-exclamation"></i> </button> <button id="test-result-notrun" type="button" data-test="mark-test-as-notrun" class="current-test-result tlp-button-large tlp-button-secondary" title="{{ 'Not run' | translate }}" ng-click="notrun($event, execution)" data-shortcut-not-run ng-disabled="execution.saving || areFilesUploading(execution)"> <i class="fas fa-fw fa-question"></i> </button> </div> <execution-attachments-drop-zone-message></execution-attachments-drop-zone-message> </section> <section ng-if="execution.is_automated === false && ! campaign.is_open" class="tlp-pane-section current-test-footer-section current-test-footer-bottom current-test-footer-section-closed-campaign"> <span translate>The campaign is closed.</span> <span translate>You cannot execute the tests anymore.</span> </section> <div ng-if="execution.is_automated === true" class="current-test-empty-pane"> <div class="empty-state-page current-test-automated-message"> <robot-svg-displayer class="empty-state-icon "test-status="execution.status"></robot-svg-displayer> <h1 class="empty-state-title">{{ "This is an automated test" | translate }}</h1> <span ng-if="execution.status === 'notrun'" class="empty-state-text"> {{ "Please come back later to see the result." | translate }} </span> <span ng-if="execution.status === 'passed'" class="empty-state-text"> {{ "Its status is passed." | translate }} </span> <span ng-if="execution.status === 'failed'" class="empty-state-text"> {{ "Its status is failed." | translate }} </span> <span ng-if="execution.status === 'blocked'" class="empty-state-text"> {{ "Its status is blocked." | translate }} </span> </div> </div> </div> </section>
54.861111
204
0.500422
7b24d2e9b95a0dea221ef6f523e24cbf39fb098f
104
rb
Ruby
app/controllers/admin/base_controller.rb
NYCMOTI/open-bid
518335e8f3622e318af287426b1d3b083b7569b4
[ "CC0-1.0" ]
74
2015-10-23T10:53:29.000Z
2021-11-14T22:01:52.000Z
app/controllers/admin/base_controller.rb
NYCMOTI/open-bid
518335e8f3622e318af287426b1d3b083b7569b4
[ "CC0-1.0" ]
1,196
2015-10-21T13:59:49.000Z
2019-02-11T17:33:26.000Z
app/controllers/admin/base_controller.rb
NYCMOTI/open-bid
518335e8f3622e318af287426b1d3b083b7569b4
[ "CC0-1.0" ]
41
2015-11-16T19:19:54.000Z
2021-02-14T11:25:44.000Z
class Admin::BaseController < ApplicationController layout 'admin' before_action :require_admin end
20.8
51
0.817308
b1135fc669630a9cc0ec97971fc899017ea9de3e
552
css
CSS
src/styles/Header.css
lorddesert/robotum-game
45e1ef2d66c29a13898f730c6a7a713c7461ebeb
[ "MIT" ]
1
2020-05-19T20:21:07.000Z
2020-05-19T20:21:07.000Z
src/styles/Header.css
lorddesert/robotum-game
45e1ef2d66c29a13898f730c6a7a713c7461ebeb
[ "MIT" ]
5
2021-03-10T04:45:51.000Z
2022-02-26T22:31:55.000Z
src/styles/Header.css
lorddesert/robotum-game
45e1ef2d66c29a13898f730c6a7a713c7461ebeb
[ "MIT" ]
null
null
null
.Header { height: 100px; background: #FFFF; color: #272727; box-shadow: 0 0 5px black; } .Header-container { display: flex; height: 100%; gap: 10px; background-color: #efefef; } .Header-item { margin: auto; justify-content: center; } h1 { margin: 0 auto; text-align: center; margin: 0 auto; font-size: 2em; font-family: 'Roboto Mono', Arial, Helvetica, sans-serif; letter-spacing: .2em; text-shadow: #272727 0 0 4px; font-size: 4rem; transition: all ease-out 200ms; } h1:hover { text-shadow: #040404 0 0 7px; }
17.806452
59
0.650362
b680b4d7996c733273be19da3c22855e82dac68f
3,035
rb
Ruby
2019/day4/solution.rb
jibarra/advent-of-code
9be56354f59c8279e13a4b89348e32fdfffd4677
[ "MIT" ]
null
null
null
2019/day4/solution.rb
jibarra/advent-of-code
9be56354f59c8279e13a4b89348e32fdfffd4677
[ "MIT" ]
null
null
null
2019/day4/solution.rb
jibarra/advent-of-code
9be56354f59c8279e13a4b89348e32fdfffd4677
[ "MIT" ]
null
null
null
# TODO: not the best method name def digits_never_decrease(number) i = 0 digits = number.digits.reverse digits.all? do |digit| i += 1 if i >= digits.size true else digit <= digits[i] end end end def has_adjacent_same_digit(number) i = 0 digits = number.digits digits.any? do |digit| i += 1 if i >= digits.size false else digit == digits[i] end end end def has_repeating_digits_of_just_2_count(number) digits = number.digits i = 1 previous_digit = digits.first run_count = 0 while(i < digits.size) if previous_digit == digits[i] run_count += 1 else return true if run_count == 1 run_count = 0 end previous_digit = digits[i] i += 1 end if run_count == 1 true else false end end def has_no_repeating_group_odd_count(number) digits = number.digits repeated_digit_group_counts = [] current_repeated_digit = nil current_repeated_digit_count = 2 digits.each_with_index do |digit, i| next if (i + 1) >= digits.size if digit == digits[i + 1] if current_repeated_digit == digit current_repeated_digit_count += 1 else repeated_digit_group_counts << current_repeated_digit_count current_repeated_digit = digit current_repeated_digit_count = 2 end end end if current_repeated_digit repeated_digit_group_counts << current_repeated_digit_count end repeated_digit_group_counts.all? { |num| num.even? } end def test_methods puts 'test digits_never_decrease' puts digits_never_decrease(123456) == true puts digits_never_decrease(111111) == true puts digits_never_decrease(123454) == false puts digits_never_decrease(132) == false puts 'test has_adjacent_same_digit' puts has_adjacent_same_digit(123456) == false puts has_adjacent_same_digit(111111) == true puts has_adjacent_same_digit(112345) == true puts has_adjacent_same_digit(123445) == true puts has_adjacent_same_digit(123455) == true puts 'has_repeating_digits_of_just_2_count' puts has_repeating_digits_of_just_2_count(123456) == false puts has_repeating_digits_of_just_2_count(112233) == true puts has_repeating_digits_of_just_2_count(123444) == false puts has_repeating_digits_of_just_2_count(111111) == false puts has_repeating_digits_of_just_2_count(111122) == true puts has_repeating_digits_of_just_2_count(123455) == true puts has_repeating_digits_of_just_2_count(123555) == false puts has_repeating_digits_of_just_2_count(1135555) == true puts has_repeating_digits_of_just_2_count(5555311) == true end test_methods input_range = (307237..769058) # Part 1 possible_passwords = input_range.select do |number| digits_never_decrease(number) && has_adjacent_same_digit(number) end puts possible_passwords.size possible_passwords = input_range.select do |number| digits_never_decrease(number) && has_repeating_digits_of_just_2_count(number) end # 349 is too low, 491 is too low puts possible_passwords.size
24.877049
79
0.737397
a4c01aecd47aa61501093cc8cbbd3c8f6a2a8d3d
1,508
kt
Kotlin
list_repos/app/src/main/java/com/sheraz/listrepos/internal/Extensions.kt
sheraz-nadeem/ListGitHubRepos
2b6583bb1b5895daabb17bd7c2bd6cdd4dbb8d1b
[ "Apache-2.0" ]
5
2020-02-03T09:44:41.000Z
2021-06-25T19:08:08.000Z
list_repos/app/src/main/java/com/sheraz/listrepos/internal/Extensions.kt
sheraz-nadeem/ListGitHubRepos
2b6583bb1b5895daabb17bd7c2bd6cdd4dbb8d1b
[ "Apache-2.0" ]
null
null
null
list_repos/app/src/main/java/com/sheraz/listrepos/internal/Extensions.kt
sheraz-nadeem/ListGitHubRepos
2b6583bb1b5895daabb17bd7c2bd6cdd4dbb8d1b
[ "Apache-2.0" ]
3
2019-03-11T23:02:03.000Z
2021-09-15T09:56:15.000Z
package com.sheraz.listrepos.internal import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.DialogFragment import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProviders import com.sheraz.listrepos.utils.Logger import java.io.IOException /** * AppCompatActivity Extension functions */ inline fun <reified T : Fragment> AppCompatActivity.findFragmentByTag(tag: String) : T? = supportFragmentManager.findFragmentByTag(tag) as? T inline fun <reified T : Fragment> AppCompatActivity.findFragmentByTagWithAutoDismiss(tag: String) : T? { val fragment = supportFragmentManager.findFragmentByTag(tag) as? T when (fragment) { is DialogFragment -> fragment.dismiss() } return fragment } inline fun <reified V : ViewModel> AppCompatActivity.bindViewModel(viewModelFactory: ViewModelProvider.Factory) = lazy { ViewModelProviders.of(this, viewModelFactory).get(V::class.java) } /** * Network Utility Extension functions */ suspend fun safeApiCall(networkBlock: suspend () -> Unit, failureBlock: (Exception) -> Unit, errorMessage: String) { return try { networkBlock() } catch (e: Exception) { // An exception was thrown when calling the API so we're converting this to an IOException // Logger.e("safeApiCall", "safeApiCall(): Exception occurred, Error => " + e.message) failureBlock(IOException(errorMessage, e)) } }
36.780488
187
0.755968
4d01f88d52de74990373ff4224a5660a7662fbf6
363
kt
Kotlin
mobile-ui/src/main/java/com/playone/mobile/ui/injection/module/NavigatorModule.kt
lekaha/playone-android
15ca77cbe9189554723b9b5cd4302946fd4675a8
[ "MIT" ]
1
2018-08-11T08:44:30.000Z
2018-08-11T08:44:30.000Z
mobile-ui/src/main/java/com/playone/mobile/ui/injection/module/NavigatorModule.kt
lekaha/playone-android
15ca77cbe9189554723b9b5cd4302946fd4675a8
[ "MIT" ]
56
2018-02-13T14:18:17.000Z
2018-07-10T13:56:24.000Z
mobile-ui/src/main/java/com/playone/mobile/ui/injection/module/NavigatorModule.kt
lekaha/playone-android
15ca77cbe9189554723b9b5cd4302946fd4675a8
[ "MIT" ]
null
null
null
package com.playone.mobile.ui.injection.module import android.content.Context import com.playone.mobile.ui.Navigator import com.playone.mobile.ui.injection.qualifier.ApplicationContext import dagger.Module import dagger.Provides @Module class NavigatorModule { @Provides fun provideNavigator(@ApplicationContext context: Context) = Navigator(context) }
25.928571
83
0.823691
0ccc2e5ca0664e29a1337110f68367598882b29e
3,936
py
Python
azure-iot-device/azure/iot/device/iothub/models/message.py
elhorton/azure-iot-sdk-python
484b804a64c245bd92930c13b970ff86f868b5fe
[ "MIT" ]
1
2019-02-06T06:52:44.000Z
2019-02-06T06:52:44.000Z
azure-iot-device/azure/iot/device/iothub/models/message.py
elhorton/azure-iot-sdk-python
484b804a64c245bd92930c13b970ff86f868b5fe
[ "MIT" ]
null
null
null
azure-iot-device/azure/iot/device/iothub/models/message.py
elhorton/azure-iot-sdk-python
484b804a64c245bd92930c13b970ff86f868b5fe
[ "MIT" ]
1
2019-12-17T17:50:43.000Z
2019-12-17T17:50:43.000Z
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- """This module contains a class representing messages that are sent or received. """ from azure.iot.device import constant # TODO: Revise this class. Does all of this REALLY need to be here? class Message(object): """Represents a message to or from IoTHub :ivar data: The data that constitutes the payload :ivar custom_properties: Dictionary of custom message properties :ivar lock_token: Used by receiver to abandon, reject or complete the message :ivar message id: A user-settable identifier for the message used for request-reply patterns. Format: A case-sensitive string (up to 128 characters long) of ASCII 7-bit alphanumeric characters + {'-', ':', '.', '+', '%', '_', '#', '*', '?', '!', '(', ')', ',', '=', '@', ';', '$', '''} :ivar sequence_number: A number (unique per device-queue) assigned by IoT Hub to each message :ivar to: A destination specified for Cloud-to-Device (C2D) messages :ivar expiry_time_utc: Date and time of message expiration in UTC format :ivar enqueued_time: Date and time a C2D message was received by IoT Hub :ivar correlation_id: A property in a response message that typically contains the message_id of the request, in request-reply patterns :ivar user_id: An ID to specify the origin of messages :ivar ack: A feedback message generator. This property is used in C2D messages to request IoT Hub to generate feedback messages as a result of the consumption of the message by the device :ivar content_encoding: Content encoding of the message data. Can be 'utf-8', 'utf-16' or 'utf-32' :ivar content_type: Content type property used to route messages with the message-body. Can be 'application/json' :ivar output_name: Name of the output that the is being sent to. """ def __init__( self, data, message_id=None, content_encoding="utf-8", content_type="application/json", output_name=None, ): """ Initializer for Message :param data: The data that constitutes the payload :param str message_id: A user-settable identifier for the message used for request-reply patterns. Format: A case-sensitive string (up to 128 characters long) of ASCII 7-bit alphanumeric characters + {'-', ':', '.', '+', '%', '_', '#', '*', '?', '!', '(', ')', ',', '=', '@', ';', '$', '''} :param str content_encoding: Content encoding of the message data. Default is 'utf-8'. Other values can be utf-16' or 'utf-32' :param str content_type: Content type property used to routes with the message body. Default value is 'application/json' :param str output_name: Name of the output that the is being sent to. """ self.data = data self.custom_properties = {} self.lock_token = None self.message_id = message_id self.sequence_number = None self.to = None self.expiry_time_utc = None self.enqueued_time = None self.correlation_id = None self.user_id = None self.ack = None self.content_encoding = content_encoding self.content_type = content_type self.output_name = output_name self._iothub_interface_id = None @property def iothub_interface_id(self): return self._iothub_interface_id def set_as_security_message(self): """ Set the message as a security message. This is a provisional API. Functionality not yet guaranteed. """ self._iothub_interface_id = constant.SECURITY_MESSAGE_INTERFACE_ID def __str__(self): return str(self.data)
50.461538
298
0.649644
81919675581fbfc6d9196c6ac599332d89683d31
11,541
rs
Rust
examples/vendored/complicated_cargo_library/cargo/vendor/libc-0.2.53/src/cloudabi/mod.rs
tommilligan/cargo-raze
b20c29f8f6a0902a7aadf5424dd830cd045ac92d
[ "Apache-2.0" ]
77
2019-06-17T07:05:07.000Z
2022-03-07T03:26:27.000Z
examples/vendored/complicated_cargo_library/cargo/vendor/libc-0.2.53/src/cloudabi/mod.rs
tommilligan/cargo-raze
b20c29f8f6a0902a7aadf5424dd830cd045ac92d
[ "Apache-2.0" ]
22
2019-07-18T02:32:10.000Z
2022-03-24T03:39:11.000Z
examples/vendored/complicated_cargo_library/cargo/vendor/libc-0.2.53/src/cloudabi/mod.rs
tommilligan/cargo-raze
b20c29f8f6a0902a7aadf5424dd830cd045ac92d
[ "Apache-2.0" ]
49
2019-06-18T03:31:56.000Z
2022-03-13T05:23:10.000Z
pub type int8_t = i8; pub type int16_t = i16; pub type int32_t = i32; pub type int64_t = i64; pub type uint8_t = u8; pub type uint16_t = u16; pub type uint32_t = u32; pub type uint64_t = u64; pub type c_schar = i8; pub type c_uchar = u8; pub type c_short = i16; pub type c_ushort = u16; pub type c_int = i32; pub type c_uint = u32; pub type c_float = f32; pub type c_double = f64; pub type c_longlong = i64; pub type c_ulonglong = u64; pub type intmax_t = i64; pub type uintmax_t = u64; pub type size_t = usize; pub type ptrdiff_t = isize; pub type intptr_t = isize; pub type uintptr_t = usize; pub type ssize_t = isize; pub type in_addr_t = u32; pub type in_port_t = u16; pub type pthread_key_t = usize; pub type pthread_t = usize; pub type sa_family_t = u8; pub type socklen_t = usize; pub type time_t = i64; s! { pub struct addrinfo { pub ai_flags: ::c_int, pub ai_family: ::c_int, pub ai_socktype: ::c_int, pub ai_protocol: ::c_int, pub ai_addrlen: ::socklen_t, pub ai_addr: *mut ::sockaddr, pub ai_canonname: *mut ::c_char, pub ai_next: *mut addrinfo, } pub struct in_addr { pub s_addr: in_addr_t, } pub struct in6_addr { pub s6_addr: [u8; 16], } pub struct pthread_attr_t { __detachstate: ::c_int, __stacksize: usize, } pub struct sockaddr { pub sa_family: sa_family_t, pub sa_data: [::c_char; 0], } pub struct sockaddr_in { pub sin_family: ::sa_family_t, pub sin_port: ::in_port_t, pub sin_addr: ::in_addr, } pub struct sockaddr_in6 { pub sin6_family: sa_family_t, pub sin6_port: ::in_port_t, pub sin6_flowinfo: u32, pub sin6_addr: ::in6_addr, pub sin6_scope_id: u32, } pub struct sockaddr_storage { pub ss_family: ::sa_family_t, __ss_data: [u8; 32], } } pub const INT_MIN: c_int = -2147483648; pub const INT_MAX: c_int = 2147483647; pub const _SC_NPROCESSORS_ONLN: ::c_int = 52; pub const _SC_PAGESIZE: ::c_int = 54; pub const AF_INET: ::c_int = 1; pub const AF_INET6: ::c_int = 2; pub const EACCES: ::c_int = 2; pub const EADDRINUSE: ::c_int = 3; pub const EADDRNOTAVAIL: ::c_int = 4; pub const EAGAIN: ::c_int = 6; pub const ECONNABORTED: ::c_int = 13; pub const ECONNREFUSED: ::c_int = 14; pub const ECONNRESET: ::c_int = 15; pub const EEXIST: ::c_int = 20; pub const EINTR: ::c_int = 27; pub const EINVAL: ::c_int = 28; pub const ENOENT: ::c_int = 44; pub const ENOTCONN: ::c_int = 53; pub const EPERM: ::c_int = 63; pub const EPIPE: ::c_int = 64; pub const ETIMEDOUT: ::c_int = 73; pub const EWOULDBLOCK: ::c_int = EAGAIN; pub const EAI_SYSTEM: ::c_int = 9; pub const EXIT_FAILURE: ::c_int = 1; pub const EXIT_SUCCESS: ::c_int = 0; pub const PTHREAD_STACK_MIN: ::size_t = 1024; pub const SOCK_DGRAM: ::c_int = 128; pub const SOCK_STREAM: ::c_int = 130; #[cfg_attr(feature = "extra_traits", derive(Debug))] pub enum FILE {} impl ::Copy for FILE {} impl ::Clone for FILE { fn clone(&self) -> FILE { *self } } #[cfg_attr(feature = "extra_traits", derive(Debug))] pub enum fpos_t {} // TODO: fill this out with a struct impl ::Copy for fpos_t {} impl ::Clone for fpos_t { fn clone(&self) -> fpos_t { *self } } extern { pub fn isalnum(c: c_int) -> c_int; pub fn isalpha(c: c_int) -> c_int; pub fn iscntrl(c: c_int) -> c_int; pub fn isdigit(c: c_int) -> c_int; pub fn isgraph(c: c_int) -> c_int; pub fn islower(c: c_int) -> c_int; pub fn isprint(c: c_int) -> c_int; pub fn ispunct(c: c_int) -> c_int; pub fn isspace(c: c_int) -> c_int; pub fn isupper(c: c_int) -> c_int; pub fn isxdigit(c: c_int) -> c_int; pub fn tolower(c: c_int) -> c_int; pub fn toupper(c: c_int) -> c_int; pub fn fopen(filename: *const c_char, mode: *const c_char) -> *mut FILE; pub fn freopen(filename: *const c_char, mode: *const c_char, file: *mut FILE) -> *mut FILE; pub fn fflush(file: *mut FILE) -> c_int; pub fn fclose(file: *mut FILE) -> c_int; pub fn remove(filename: *const c_char) -> c_int; pub fn rename(oldname: *const c_char, newname: *const c_char) -> c_int; pub fn tmpfile() -> *mut FILE; pub fn setvbuf(stream: *mut FILE, buffer: *mut c_char, mode: c_int, size: size_t) -> c_int; pub fn setbuf(stream: *mut FILE, buf: *mut c_char); pub fn getchar() -> c_int; pub fn putchar(c: c_int) -> c_int; pub fn fgetc(stream: *mut FILE) -> c_int; pub fn fgets(buf: *mut c_char, n: c_int, stream: *mut FILE) -> *mut c_char; pub fn fputc(c: c_int, stream: *mut FILE) -> c_int; pub fn fputs(s: *const c_char, stream: *mut FILE) -> c_int; pub fn puts(s: *const c_char) -> c_int; pub fn ungetc(c: c_int, stream: *mut FILE) -> c_int; pub fn fread(ptr: *mut c_void, size: size_t, nobj: size_t, stream: *mut FILE) -> size_t; pub fn fwrite(ptr: *const c_void, size: size_t, nobj: size_t, stream: *mut FILE) -> size_t; pub fn fseek(stream: *mut FILE, offset: c_long, whence: c_int) -> c_int; pub fn ftell(stream: *mut FILE) -> c_long; pub fn rewind(stream: *mut FILE); pub fn fgetpos(stream: *mut FILE, ptr: *mut fpos_t) -> c_int; pub fn fsetpos(stream: *mut FILE, ptr: *const fpos_t) -> c_int; pub fn feof(stream: *mut FILE) -> c_int; pub fn ferror(stream: *mut FILE) -> c_int; pub fn perror(s: *const c_char); pub fn atoi(s: *const c_char) -> c_int; pub fn strtod(s: *const c_char, endp: *mut *mut c_char) -> c_double; pub fn strtol(s: *const c_char, endp: *mut *mut c_char, base: c_int) -> c_long; pub fn strtoul(s: *const c_char, endp: *mut *mut c_char, base: c_int) -> c_ulong; pub fn calloc(nobj: size_t, size: size_t) -> *mut c_void; pub fn malloc(size: size_t) -> *mut c_void; pub fn realloc(p: *mut c_void, size: size_t) -> *mut c_void; pub fn free(p: *mut c_void); pub fn abort() -> !; pub fn exit(status: c_int) -> !; pub fn _exit(status: c_int) -> !; pub fn atexit(cb: extern fn()) -> c_int; pub fn system(s: *const c_char) -> c_int; pub fn getenv(s: *const c_char) -> *mut c_char; pub fn getline (lineptr: *mut *mut c_char, n: *mut size_t, stream: *mut FILE) -> ssize_t; pub fn strcpy(dst: *mut c_char, src: *const c_char) -> *mut c_char; pub fn strncpy(dst: *mut c_char, src: *const c_char, n: size_t) -> *mut c_char; pub fn strcat(s: *mut c_char, ct: *const c_char) -> *mut c_char; pub fn strncat(s: *mut c_char, ct: *const c_char, n: size_t) -> *mut c_char; pub fn strcmp(cs: *const c_char, ct: *const c_char) -> c_int; pub fn strncmp(cs: *const c_char, ct: *const c_char, n: size_t) -> c_int; pub fn strcoll(cs: *const c_char, ct: *const c_char) -> c_int; pub fn strchr(cs: *const c_char, c: c_int) -> *mut c_char; pub fn strrchr(cs: *const c_char, c: c_int) -> *mut c_char; pub fn strspn(cs: *const c_char, ct: *const c_char) -> size_t; pub fn strcspn(cs: *const c_char, ct: *const c_char) -> size_t; pub fn strdup(cs: *const c_char) -> *mut c_char; pub fn strpbrk(cs: *const c_char, ct: *const c_char) -> *mut c_char; pub fn strstr(cs: *const c_char, ct: *const c_char) -> *mut c_char; pub fn strcasecmp(s1: *const c_char, s2: *const c_char) -> c_int; pub fn strncasecmp(s1: *const c_char, s2: *const c_char, n: size_t) -> c_int; pub fn strlen(cs: *const c_char) -> size_t; pub fn strnlen(cs: *const c_char, maxlen: size_t) -> size_t; pub fn strerror(n: c_int) -> *mut c_char; pub fn strtok(s: *mut c_char, t: *const c_char) -> *mut c_char; pub fn strxfrm(s: *mut c_char, ct: *const c_char, n: size_t) -> size_t; pub fn wcslen(buf: *const wchar_t) -> size_t; pub fn wcstombs(dest: *mut c_char, src: *const wchar_t, n: size_t) -> ::size_t; pub fn memchr(cx: *const c_void, c: c_int, n: size_t) -> *mut c_void; pub fn memcmp(cx: *const c_void, ct: *const c_void, n: size_t) -> c_int; pub fn memcpy(dest: *mut c_void, src: *const c_void, n: size_t) -> *mut c_void; pub fn memmove(dest: *mut c_void, src: *const c_void, n: size_t) -> *mut c_void; pub fn memset(dest: *mut c_void, c: c_int, n: size_t) -> *mut c_void; pub fn abs(i: c_int) -> c_int; pub fn atof(s: *const c_char) -> c_double; pub fn labs(i: c_long) -> c_long; pub fn rand() -> c_int; pub fn srand(seed: c_uint); pub fn arc4random_buf(buf: *const ::c_void, len: ::size_t); pub fn freeaddrinfo(res: *mut addrinfo); pub fn gai_strerror(errcode: ::c_int) -> *const ::c_char; pub fn getaddrinfo( node: *const c_char, service: *const c_char, hints: *const addrinfo, res: *mut *mut addrinfo, ) -> ::c_int; pub fn getsockopt( sockfd: ::c_int, level: ::c_int, optname: ::c_int, optval: *mut ::c_void, optlen: *mut ::socklen_t, ) -> ::c_int; pub fn posix_memalign( memptr: *mut *mut ::c_void, align: ::size_t, size: ::size_t, ) -> ::c_int; pub fn pthread_attr_destroy(attr: *mut ::pthread_attr_t) -> ::c_int; pub fn pthread_attr_init(attr: *mut ::pthread_attr_t) -> ::c_int; pub fn pthread_attr_setstacksize( attr: *mut ::pthread_attr_t, stack_size: ::size_t, ) -> ::c_int; pub fn pthread_create( native: *mut ::pthread_t, attr: *const ::pthread_attr_t, f: extern fn(*mut ::c_void) -> *mut ::c_void, value: *mut ::c_void, ) -> ::c_int; pub fn pthread_detach(thread: ::pthread_t) -> ::c_int; pub fn pthread_getspecific(key: pthread_key_t) -> *mut ::c_void; pub fn pthread_join( native: ::pthread_t, value: *mut *mut ::c_void, ) -> ::c_int; pub fn pthread_key_create( key: *mut pthread_key_t, dtor: ::Option<unsafe extern fn(*mut ::c_void)>, ) -> ::c_int; pub fn pthread_key_delete(key: pthread_key_t) -> ::c_int; pub fn pthread_setspecific( key: pthread_key_t, value: *const ::c_void, ) -> ::c_int; pub fn send( socket: ::c_int, buf: *const ::c_void, len: ::size_t, flags: ::c_int, ) -> ::ssize_t; pub fn sysconf(name: ::c_int) -> ::c_long; } cfg_if! { if #[cfg(target_arch = "aarch64")] { mod aarch64; pub use self::aarch64::*; } else if #[cfg(any(target_arch = "arm"))] { mod arm; pub use self::arm::*; } else if #[cfg(any(target_arch = "x86"))] { mod x86; pub use self::x86::*; } else if #[cfg(any(target_arch = "x86_64"))] { mod x86_64; pub use self::x86_64::*; } else { // Unknown target_arch } } cfg_if! { if #[cfg(libc_core_cvoid)] { pub use ::ffi::c_void; } else { // Use repr(u8) as LLVM expects `void*` to be the same as `i8*` to help // enable more optimization opportunities around it recognizing things // like malloc/free. #[repr(u8)] #[allow(missing_copy_implementations)] #[allow(missing_debug_implementations)] pub enum c_void { // Two dummy variants so the #[repr] attribute can be used. #[doc(hidden)] __variant1, #[doc(hidden)] __variant2, } } }
34.450746
80
0.600468
e9b1a7d21b0e98b4584662d8408ebca8b9d55868
753
go
Go
internal/identity/identity.go
ayakovlenko/zit
5330640806fa01c0c1b08dd80e42594195c0b95a
[ "MIT" ]
15
2020-04-13T22:35:14.000Z
2022-01-21T22:45:56.000Z
internal/identity/identity.go
ayakovlenko/zit
5330640806fa01c0c1b08dd80e42594195c0b95a
[ "MIT" ]
13
2020-04-10T13:53:11.000Z
2021-06-30T23:21:40.000Z
internal/identity/identity.go
ayakovlenko/zit
5330640806fa01c0c1b08dd80e42594195c0b95a
[ "MIT" ]
1
2020-04-11T13:10:18.000Z
2020-04-11T13:10:18.000Z
package identity import ( "zit/internal/config" "zit/internal/git" ) func findBestMatch(conf config.HostV2, repo git.RepoInfo) (user *config.User) { if conf.Default != nil { user = &config.User{ Name: conf.Default.Name, Email: conf.Default.Email, } } if conf.Overrides != nil { for _, override := range conf.Overrides { if override.Repo != "" { if override.Owner == repo.Owner && override.Repo == repo.Name { user = &config.User{ Name: override.User.Name, Email: override.User.Email, } break } else { continue } } if override.Owner == repo.Owner { user = &config.User{ Name: override.User.Name, Email: override.User.Email, } break } } } return }
17.928571
79
0.602922
2915748c1cadf8aea2ef964a5084baf9dd90101e
2,016
py
Python
custom_components/gazpar/util.py
Vebryn/home-assistant-gazpar
2d9998b7ba2d5bf089b045488b59f23f8f4b4d8d
[ "MIT" ]
4
2022-01-21T23:35:09.000Z
2022-02-17T13:31:24.000Z
custom_components/gazpar/util.py
Vebryn/home-assistant-gazpar
2d9998b7ba2d5bf089b045488b59f23f8f4b4d8d
[ "MIT" ]
3
2022-01-26T08:34:18.000Z
2022-01-27T12:44:39.000Z
custom_components/gazpar/util.py
Vebryn/home-assistant-gazpar
2d9998b7ba2d5bf089b045488b59f23f8f4b4d8d
[ "MIT" ]
1
2022-01-25T21:47:38.000Z
2022-01-25T21:47:38.000Z
from pygazpar.enum import PropertyName from pygazpar.enum import Frequency from homeassistant.const import CONF_USERNAME, ATTR_ATTRIBUTION, ATTR_UNIT_OF_MEASUREMENT, ATTR_FRIENDLY_NAME, ATTR_ICON, ENERGY_KILO_WATT_HOUR # -------------------------------------------------------------------------------------------- class Util: __HA_ATTRIBUTION = "Data provided by GrDF" __LAST_INDEX = -1 __BEFORE_LAST_INDEX = -2 # ---------------------------------- @staticmethod def toState(pygazparData: list) -> str: if len(pygazparData) > 0: return pygazparData[Util.__LAST_INDEX].get(PropertyName.ENERGY.value) else: return None # ---------------------------------- @staticmethod def toAttributes(username: str, frequency: Frequency, pygazparData: list) -> dict: friendlyNameByFrequency = { Frequency.HOURLY: "Gazpar hourly energy", Frequency.DAILY: "Gazpar daily energy", Frequency.WEEKLY: "Gazpar weekly energy", Frequency.MONTHLY: "Gazpar monthly energy" } res = { ATTR_ATTRIBUTION: Util.__HA_ATTRIBUTION, CONF_USERNAME: username, ATTR_UNIT_OF_MEASUREMENT: ENERGY_KILO_WATT_HOUR, ATTR_FRIENDLY_NAME: friendlyNameByFrequency[frequency], ATTR_ICON: "mdi:fire" } if frequency == Frequency.WEEKLY or frequency == Frequency.MONTHLY: # Cases WEEKLY and MONTHLY. if len(pygazparData) > 1: res["previous"] = pygazparData[Util.__BEFORE_LAST_INDEX] if len(pygazparData) > 0: res["current"] = pygazparData[Util.__LAST_INDEX] elif frequency == Frequency.DAILY and len(pygazparData) > 0: # Cases DAILY. for propertyName in PropertyName: value = pygazparData[Util.__LAST_INDEX].get(propertyName.value) if value is not None: res[propertyName.value] = value return res
38.037736
143
0.58879
40b69de7c43fb5091d2c9782be25e478c8d9e267
4,076
html
HTML
docs/io.paymenthighway.sdk/-backend-adapter/index.html
PaymentHighway/paymenthighway-android-sdk
dfa236724490a58e5e234e7b2ece3003099c879e
[ "MIT" ]
null
null
null
docs/io.paymenthighway.sdk/-backend-adapter/index.html
PaymentHighway/paymenthighway-android-sdk
dfa236724490a58e5e234e7b2ece3003099c879e
[ "MIT" ]
null
null
null
docs/io.paymenthighway.sdk/-backend-adapter/index.html
PaymentHighway/paymenthighway-android-sdk
dfa236724490a58e5e234e7b2ece3003099c879e
[ "MIT" ]
null
null
null
<HTML> <HEAD> <meta charset="UTF-8"> <title>BackendAdapter - </title> <link rel="stylesheet" href="../../style.css"> </HEAD> <BODY> <a href="../index.html">io.paymenthighway.sdk</a>&nbsp;/&nbsp;<a href="./index.html">BackendAdapter</a><br/> <br/> <h1>BackendAdapter</h1> <code><span class="keyword">interface </span><span class="identifier">BackendAdapter</span><span class="symbol">&lt;</span><span class="identifier">V</span><span class="symbol">&gt;</span></code> <p>Backend Adapter</p> <p>This interface defines what customer has to implement (in own backend) in order to use Payment Highway API</p> <h3>Parameters</h3> <p><a name="T"></a> <code>T</code> - the type of the return data for addCardCompleted</p> <h3>Functions</h3> <table> <tbody> <tr> <td> <p><a href="add-card-completed.html">addCardCompleted</a></p> </td> <td> <code><span class="keyword">abstract</span> <span class="keyword">fun </span><span class="identifier">addCardCompleted</span><span class="symbol">(</span><span class="identifier" id="io.paymenthighway.sdk.BackendAdapter$addCardCompleted(io.paymenthighway.sdk.model.TransactionId, kotlin.Function1((io.paymenthighway.sdk.util.Result((io.paymenthighway.sdk.BackendAdapter.V, java.lang.Exception)), kotlin.Unit)))/transactionId">transactionId</span><span class="symbol">:</span>&nbsp;<a href="../../io.paymenthighway.sdk.model/-transaction-id/index.html"><span class="identifier">TransactionId</span></a><span class="symbol">, </span><span class="identifier" id="io.paymenthighway.sdk.BackendAdapter$addCardCompleted(io.paymenthighway.sdk.model.TransactionId, kotlin.Function1((io.paymenthighway.sdk.util.Result((io.paymenthighway.sdk.BackendAdapter.V, java.lang.Exception)), kotlin.Unit)))/completion">completion</span><span class="symbol">:</span>&nbsp;<span class="symbol">(</span><a href="../../io.paymenthighway.sdk.util/-result/index.html"><span class="identifier">Result</span></a><span class="symbol">&lt;</span><a href="index.html#V"><span class="identifier">V</span></a><span class="symbol">,</span>&nbsp;<a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-exception/index.html"><span class="identifier">Exception</span></a><span class="symbol">&gt;</span><span class="symbol">)</span>&nbsp;<span class="symbol">-&gt;</span>&nbsp;<a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-unit/index.html"><span class="identifier">Unit</span></a><span class="symbol">)</span><span class="symbol">: </span><a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-unit/index.html"><span class="identifier">Unit</span></a></code> <p>Add card completed</p> </td> </tr> <tr> <td> <p><a href="get-transaction-id.html">getTransactionId</a></p> </td> <td> <code><span class="keyword">abstract</span> <span class="keyword">fun </span><span class="identifier">getTransactionId</span><span class="symbol">(</span><span class="identifier" id="io.paymenthighway.sdk.BackendAdapter$getTransactionId(kotlin.Function1((io.paymenthighway.sdk.util.Result((io.paymenthighway.sdk.model.TransactionId, java.lang.Exception)), kotlin.Unit)))/completion">completion</span><span class="symbol">:</span>&nbsp;<span class="symbol">(</span><a href="../../io.paymenthighway.sdk.util/-result/index.html"><span class="identifier">Result</span></a><span class="symbol">&lt;</span><a href="../../io.paymenthighway.sdk.model/-transaction-id/index.html"><span class="identifier">TransactionId</span></a><span class="symbol">,</span>&nbsp;<a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-exception/index.html"><span class="identifier">Exception</span></a><span class="symbol">&gt;</span><span class="symbol">)</span>&nbsp;<span class="symbol">-&gt;</span>&nbsp;<a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-unit/index.html"><span class="identifier">Unit</span></a><span class="symbol">)</span><span class="symbol">: </span><a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-unit/index.html"><span class="identifier">Unit</span></a></code> <p>Get the transaction id</p> </td> </tr> </tbody> </table> </BODY> </HTML>
97.047619
1,751
0.72105
1604d014514ec6bf27e915eeccd18a56088f71a7
1,965
c
C
NHL95DBEditor/src/file_utils.c
peruukki/NHL95DBEditor
d85f4cd73380577217d886a2ec871a223f359e2f
[ "MIT" ]
null
null
null
NHL95DBEditor/src/file_utils.c
peruukki/NHL95DBEditor
d85f4cd73380577217d886a2ec871a223f359e2f
[ "MIT" ]
null
null
null
NHL95DBEditor/src/file_utils.c
peruukki/NHL95DBEditor
d85f4cd73380577217d886a2ec871a223f359e2f
[ "MIT" ]
null
null
null
#include <errno.h> #include "file_utils.h" #include "output.h" static size_t read_db_data(db_data_t *data, const char *file_name) { FILE *fp; if ((fp = fopen(file_name, "rb")) == NULL) { INFO("Failed to open file '%s' for reading", file_name); return 0; } data->length = fread(data->data, 1, sizeof(data->data), fp); fclose(fp); return data->length; } bool_t read_db_file(db_data_t *data, const char *file_name) { size_t bytes_read = read_db_data(data, file_name); if (bytes_read) DEBUG("Read %lu bytes from file %s\n", bytes_read, file_name); return bytes_read != 0; } static size_t write_db_data(db_data_t *data, const char *file_name) { size_t bytes_written; FILE *fp; if ((fp = fopen(file_name, "wb")) == NULL) { INFO("Failed to open file '%s' for writing", file_name); return 0; } bytes_written = fwrite(data->data, 1, data->length, fp); fclose(fp); return bytes_written; } bool_t write_db_file(db_data_t *data, const char *file_name) { size_t bytes_written = write_db_data(data, file_name); if (bytes_written) DEBUG("Wrote %u bytes to file %s\n", bytes_written, file_name); return bytes_written != 0; } bool_t file_exists(const char *file_name) { FILE *fp; if ((fp = fopen(file_name, "rb")) == NULL) return (errno != ENOENT); fclose(fp); return TRUE; } bool_t copy_file(const char *src_name, const char *dst_name) { db_data_t data; if (read_db_data(&data, src_name) == 0) goto error; if (write_db_data(&data, dst_name) == 0) goto error; INFO("copied file %s to %s\n", src_name, dst_name); return TRUE; error: INFO("failed to copy file %s to %s\n", src_name, dst_name); return FALSE; } bool_t delete_file(const char *file_name) { INFO("Deleting file %s\n", file_name); if (remove(file_name) != 0) { INFO("Failed to delete file %s: error %d\n", file_name, errno); return FALSE; } return TRUE; }
20.05102
69
0.652417
d2e07f0d243d4540e6af4de96d499d2f6cdd0965
1,680
php
PHP
resources/views/partials/navbar.blade.php
dhaferbakri/klnaMaswuwl
0f39a249d39bcffcd2e631e68e1482f61945c3a9
[ "MIT" ]
1
2020-05-05T01:34:34.000Z
2020-05-05T01:34:34.000Z
resources/views/partials/navbar.blade.php
dhaferbakri/klnaMaswuwl
0f39a249d39bcffcd2e631e68e1482f61945c3a9
[ "MIT" ]
3
2021-02-02T18:03:36.000Z
2022-02-27T03:46:41.000Z
resources/views/partials/navbar.blade.php
dhaferbakri/klnaMaswuwl
0f39a249d39bcffcd2e631e68e1482f61945c3a9
[ "MIT" ]
null
null
null
<div class="inner"> <h3 class="masthead-brand"><a href="/">klnaMaswuwl - كلنا مسؤول</a></h3> <nav class="nav nav-masthead justify-content-center"> <a class="nav-link active" href="/">الرئيسية</a> <a class="nav-link" href="/about">عنا</a> <a class="nav-link" href="/permissions/create">طلب تصريح</a> <!-- Authentication Links --> @guest <a class="nav-link" href="{{ route('login') }}"> <i class="fas fa-user fa-1x"></i> الدخول</a> @else <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre> {{ Auth::user()->name }} <span class="caret"></span> </a> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="{{ url('/permissions') }}">لوحة التحكم</a> <a class="dropdown-item" href="{{ route('logout') }}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();"> {{ __('Logout') }} </a> <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;"> @csrf </form> </div> @endguest </nav> </div> </header>
54.193548
175
0.43869
3e8d0aac7e7ee8f5fc1f578b62ec2f6d52772ff9
2,019
kt
Kotlin
app/src/main/java/io/henrikhorbovyi/moviesapp/navigation/MainGraph.kt
henrikhorbovyi/movies-app
e5a03e6f2140379f565fc725f39b082dab8802af
[ "MIT" ]
null
null
null
app/src/main/java/io/henrikhorbovyi/moviesapp/navigation/MainGraph.kt
henrikhorbovyi/movies-app
e5a03e6f2140379f565fc725f39b082dab8802af
[ "MIT" ]
null
null
null
app/src/main/java/io/henrikhorbovyi/moviesapp/navigation/MainGraph.kt
henrikhorbovyi/movies-app
e5a03e6f2140379f565fc725f39b082dab8802af
[ "MIT" ]
null
null
null
package io.henrikhorbovyi.moviesapp.navigation import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.compose.foundation.layout.padding import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.navigation.NavGraphBuilder import androidx.navigation.NavType import androidx.navigation.compose.composable import androidx.navigation.navArgument import androidx.navigation.navigation import io.henrikhorbovyi.moviesapp.R import io.henrikhorbovyi.moviesapp.ui.screen.movies.details.Details import io.henrikhorbovyi.moviesapp.ui.screen.movies.favorites.Favorites import io.henrikhorbovyi.moviesapp.ui.screen.movies.feed.Movies import io.henrikhorbovyi.moviesapp.viewmodel.MoviesViewModel import kotlin.properties.Delegates enum class MainGraph( @StringRes val title: Int, @DrawableRes val icon: Int, val route: String ) { Feed(R.string.feed, R.drawable.ic_movies, "main/feed"), Favorites(R.string.favorites, R.drawable.ic_favorite, "main/favorites"), } fun NavGraphBuilder.mainGraph( moviesViewModel: MoviesViewModel, onMovieSelected: (id: String?) -> Unit = {} ) { navigation(startDestination = MainGraph.Feed.route, route = "main") { composable(MainGraph.Feed.route) { Movies( moviesViewModel = moviesViewModel, onMovieSelected = onMovieSelected, modifier = Modifier.padding(bottom = 32.dp), ) } composable(MainGraph.Favorites.route) { Favorites( /*moviesViewModel = moviesViewModel,*/ onMovieSelected = onMovieSelected, modifier = Modifier.padding(bottom = 80.dp) ) } } composable( route = "details/{movieId}", arguments = listOf(navArgument("movieId") { type = NavType.StringType }) ) { backStackEntry -> val movieId = backStackEntry.arguments?.getString("movieId") Details(movieId = movieId) } }
35.421053
80
0.706786
75db59825111cb9a76dcb2e5ab838a13da2660b9
871
php
PHP
application/libraries/Layout.php
gavinhouse/blog
37cd058121c69f132a66a15a93a76a1fad1b67ec
[ "MIT" ]
null
null
null
application/libraries/Layout.php
gavinhouse/blog
37cd058121c69f132a66a15a93a76a1fad1b67ec
[ "MIT" ]
null
null
null
application/libraries/Layout.php
gavinhouse/blog
37cd058121c69f132a66a15a93a76a1fad1b67ec
[ "MIT" ]
null
null
null
<?php /** * The Layout class is used in order to load pages and pass data to said pages. * * * @property CI_Loader $load */ class Layout{ private $viewVars = []; //initialize a CI instance to use CI_Loader public function __construct() { $this->CI =& get_instance(); } //Sets values in viewVars for use in loaded pages public function set($name,$value){ $this->viewVars[$name] = $value; } //Loads a given page /** * * * * * * @param $pageName * @param $directory */ public function load($pageName, $directory) { $this->CI->load->view($directory .'/display/header', $this->viewVars); $this->CI->load->view($directory . '/' . $pageName , $this->viewVars); $this->CI->load->view($directory .'/display/footer', $this->viewVars); } }
20.738095
79
0.562572
703000ceb160ccd1619aded5c822e738809b91b9
3,461
kt
Kotlin
kronos/src/test/java/com/ironsource/aura/kronos/defaultValue/DefaultProviderTest.kt
hananrh/Kronos
08c71c5c7da6965484377fd9d9d1128e388320ea
[ "MIT" ]
null
null
null
kronos/src/test/java/com/ironsource/aura/kronos/defaultValue/DefaultProviderTest.kt
hananrh/Kronos
08c71c5c7da6965484377fd9d9d1128e388320ea
[ "MIT" ]
1
2021-03-30T12:56:44.000Z
2021-04-26T06:34:14.000Z
kronos/src/test/java/com/ironsource/aura/kronos/defaultValue/DefaultProviderTest.kt
hananrh/Kronos
08c71c5c7da6965484377fd9d9d1128e388320ea
[ "MIT" ]
null
null
null
package com.ironsource.aura.kronos.defaultValue import android.graphics.Color import com.ironsource.aura.kronos.common.Label import com.ironsource.aura.kronos.common.kronosTest import com.ironsource.aura.kronos.common.mapConfig import com.ironsource.aura.kronos.config.FeatureRemoteConfig import com.ironsource.aura.kronos.config.type.* import com.ironsource.aura.kronos.config.type.util.ColorInt import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import java.util.* import kotlin.reflect.KClass import kotlin.test.assertEquals import kotlin.test.assertNotEquals object DefaultProviderTest : Spek(kronosTest { class Config : FeatureRemoteConfig by mapConfig() { val someInt by intConfig { default { 0 } } val someIntWithCache by intConfig { default { Random().nextInt() } } val someIntWithoutCache by intConfig { default(cache = false) { Random().nextInt() } cached = false } val someLong by longConfig { default { 0 } } val someFloat by floatConfig { default { 0f } } val someString by stringConfig { default { "" } } val someStringSet by stringSetConfig { default { setOf("") } } val someNullableString by nullableStringConfig { default { null } } val someBoolean by booleanConfig { default { false } } val someColor by colorConfig { default { ColorInt( Color.WHITE) } } val someTyped by typedConfig<Label> { default { Label("default") } } } val config = Config() describe("Fallback to default provider resolved value when no remote value configured") { it("Should return default - intConfig") { assertEquals(0, config.someInt) } it("Should return default - longConfig") { assertEquals(0, config.someLong) } it("Should return default - floatConfig") { assertEquals(0f, config.someFloat) } it("Should return default - Should return default - stringConfig") { assertEquals("", config.someString) } it("Should return default - stringSetConfig") { assertEquals(setOf(""), config.someStringSet) } it("Should return default - nullableStringConfig") { assertEquals(null, config.someNullableString) } it("Should return default - booleanConfig") { assertEquals(false, config.someBoolean) } it("Should return default - colorConfig") { assertEquals(ColorInt( Color.WHITE), config.someColor) } it("Should return default - typedConfig") { assertEquals(Label("default"), config.someTyped) } } describe("Cache flag should control number of calls to default provider") { it("Config with cache - default provider should only be called once") { assertEquals(config.someIntWithCache, config.someIntWithCache) } it("Config without cache - default provider should be called every time field getter called") { assertNotEquals(config.someIntWithoutCache, config.someIntWithoutCache) } } })
30.359649
103
0.611384
925d9b56abd0680d681fd7c9185478058e19c347
236
kt
Kotlin
src/main/kotlin/no/nav/personbruker/minesaker/api/common/exception/CommunicationException.kt
joakibj/mine-saker-api
51dd522799ecbd53207a55a44c8378ecdb819547
[ "MIT" ]
null
null
null
src/main/kotlin/no/nav/personbruker/minesaker/api/common/exception/CommunicationException.kt
joakibj/mine-saker-api
51dd522799ecbd53207a55a44c8378ecdb819547
[ "MIT" ]
null
null
null
src/main/kotlin/no/nav/personbruker/minesaker/api/common/exception/CommunicationException.kt
joakibj/mine-saker-api
51dd522799ecbd53207a55a44c8378ecdb819547
[ "MIT" ]
1
2022-02-11T12:11:46.000Z
2022-02-11T12:11:46.000Z
package no.nav.personbruker.minesaker.api.common.exception open class CommunicationException(message: String, cause: Throwable?) : AbstractMineSakerException(message, cause) { constructor(message: String) : this(message, null) }
29.5
116
0.788136
56ff69bea8fb59e8cd185a7d8e7bd4e0a0d91b26
274
ts
TypeScript
app/src/apps/SnowmanApp/components/TabBar/TabBarProps.ts
HPI-Information-Systems/snowman
2b518b5f22950c7171c50c5313e0d73162a40644
[ "MIT" ]
20
2021-02-24T13:38:34.000Z
2022-03-31T02:54:56.000Z
app/src/apps/SnowmanApp/components/TabBar/TabBarProps.ts
HPI-Information-Systems/snowman
2b518b5f22950c7171c50c5313e0d73162a40644
[ "MIT" ]
122
2021-02-24T15:41:02.000Z
2022-02-28T11:09:03.000Z
app/src/apps/SnowmanApp/components/TabBar/TabBarProps.ts
HPI-Information-Systems/snowman
2b518b5f22950c7171c50c5313e0d73162a40644
[ "MIT" ]
3
2021-02-25T17:15:58.000Z
2021-03-02T08:14:42.000Z
import { ViewIDs } from 'types/ViewIDs'; export interface TabBarDispatchProps { openSubApp(viewID: ViewIDs): void; } export interface TabBarStateProps { activeSubApp: ViewIDs; showTabBar: boolean; } export type TabBarProps = TabBarDispatchProps & TabBarStateProps;
21.076923
65
0.777372
5c5ee8ac63956b28d835ee0e7cd7aa92ff7378a7
207
h
C
Demo/CheckViewController.h
zhang28602/ZZYQRCode
7a16b4557f9cc8fd704f80acb31ec6d372b0c19d
[ "MIT" ]
494
2017-05-20T22:21:10.000Z
2019-10-25T12:16:56.000Z
Demo/CheckViewController.h
threeWolf/ZZYQRCode
7a16b4557f9cc8fd704f80acb31ec6d372b0c19d
[ "MIT" ]
4
2017-08-13T11:02:54.000Z
2018-05-21T03:50:13.000Z
Demo/CheckViewController.h
threeWolf/ZZYQRCode
7a16b4557f9cc8fd704f80acb31ec6d372b0c19d
[ "MIT" ]
27
2017-05-20T22:46:28.000Z
2019-06-24T18:07:30.000Z
// // CheckViewController.h // Demo // // Created by 张泽宇 on 2017/5/20. // Copyright © 2017年 zzy. All rights reserved. // #import <UIKit/UIKit.h> @interface CheckViewController : UIViewController @end
14.785714
49
0.690821
d27990ce5265d0431365428e8cc9d2c03178e854
12,435
php
PHP
application/api/controller/dormitory2020/Api.php
Li-Jiadong/yiban-app
19d13bc6b271a8fb0b6c2445407aa773dc8d0327
[ "Apache-2.0" ]
null
null
null
application/api/controller/dormitory2020/Api.php
Li-Jiadong/yiban-app
19d13bc6b271a8fb0b6c2445407aa773dc8d0327
[ "Apache-2.0" ]
null
null
null
application/api/controller/dormitory2020/Api.php
Li-Jiadong/yiban-app
19d13bc6b271a8fb0b6c2445407aa773dc8d0327
[ "Apache-2.0" ]
1
2018-03-26T16:30:01.000Z
2018-03-26T16:30:01.000Z
<?php namespace app\api\controller\dormitory2020; use app\common\library\Token; use think\exception\HttpResponseException; use think\exception\ValidateException; use think\Loader; use think\Request; use think\Response; use app\api\model\dormitory2020\User as userModel; use app\api\model\dormitory2020\Wxuser as wxUserModel; use think\Config; use think\Db; /** * 订阅号API控制器基类 */ class Api { /** * @var Request Request 实例 */ protected $request; /** * @var bool 验证失败是否抛出异常 */ protected $failException = false; /** * @var bool 是否批量验证 */ protected $batchValidate = false; /** * 无需绑定门户的方法 * @var array */ protected $noNeedBindPortal = []; /** * 默认响应输出类型,支持json/xml * @var string */ protected $responseType = 'json'; /** * 用户信息 * @var array */ protected $_user = NULL; /** * 用户绑定状态信息 * @var array */ protected $_bindStatus = NULL; /** * 用户token * @var string */ protected $_token = ''; protected $requestUri = ''; //默认配置 protected $config = []; protected $options = []; /** * 构造方法 * @access public * @param Request $request Request 对象 */ public function __construct(Request $request = null) { $this->request = is_null($request) ? Request::instance() : $request; // 控制器初始化 $this->_initialize(); } /** * 初始化操作 * @access protected */ protected function _initialize() { if($_SERVER['REQUEST_METHOD'] == 'OPTIONS'){ header('Access-Control-Allow-Origin:*'); header('Access-Control-Allow-Methods:POST,GET,OPTIONS'); header('Access-Control-Allow-Headers: Authorization'); header('Access-Control-Allow-Credentials: true'); header('Access-Control-Max-Age: 600'); exit; } header('Access-Control-Allow-Origin:*'); // header('Access-Control-Max-Age: 600'); $modulename = $this->request->module(); $controllername = strtolower($this->request->controller()); $actionname = strtolower($this->request->action()); $token = $this->request->header('Authorization'); $path = str_replace('.', '/', $controllername) . '/' . $actionname; // 设置当前请求的URI $this->setRequestUri($path); //判断方法是否需要绑定门户 if (!$this->match($this->noNeedBindPortal)) { //初始化 $ret = $this->init($token); if (!$ret) { $this->error('Token Expired', null, 0,null,["statuscode" => "403"]); } if (!$this->isBindPortal()) { $this->error('Please bind Portal Account first', null, 0,null,["statuscode" => "403"]); } } else { // 如果有传递token才验证是否登录状态 if ($token) { $this->init($token); } } } /** * 判断用户是否绑定信息门户 * @return boolean */ public function isBindPortal() { if ($this->_bindStatus["is_bind"]) { return true; } return false; } /** * 获取当前Token * @return string */ public function getToken() { return $this->_token; } /** * 获取当前请求的URI * @return string */ public function getRequestUri() { return $this->requestUri; } /** * 设置当前请求的URI * @param string $uri */ public function setRequestUri($uri) { $this->requestUri = $uri; } /** * 检测当前控制器和方法是否匹配传递的数组 * * @param array $arr 需要验证权限的数组 * @return boolean */ public function match($arr = []) { $request = Request::instance(); $arr = is_array($arr) ? $arr : explode(',', $arr); if (!$arr) { return FALSE; } $arr = array_map('strtolower', $arr); // 是否存在 if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) { return TRUE; } // 没找到匹配 return FALSE; } /** * 根据Token初始化 * * @param string $token Token * @return boolean */ public function init($token) { $userModel = new userModel(); $data = Token::get($token); /**data * ["token"] =string(36) "b24d3f6a-e433-4144-9e00-8680cbad7bfb" * ["user_id"] = int(1) * ["createtime"] = int(1562827900) * ["expiretime"] = int(1565419900) * ["expires_in"] = int(2591068) * */ if (!$data) { return FALSE; } $user_id = $data['user_id']; if (!empty($user_id)) { $is_bind = false; $is_bind_mobile = false; $userInfo = $userModel->where("id",$user_id)->find(); if (empty($userInfo)) { $this->error('Please Bind Portal Correct Account first', null, 0,null,["statuscode" => "403"]); } // 验证用户是否绑定微信 if (!$this->checkWechatAuth($userInfo["unionid"])) { $this->error(__('Please finish WeChat authorization first'), null, 0,null,["statuscode" => "401"]); } $is_bind_mobile = $this->checkMobileBind($userInfo["unionid"]); $openid = Db::name("wx_unionid_user")->where("unionid",$userInfo["unionid"])->field("open_id")->find(); $userInfo["openid"] = $openid["open_id"]; $userInfo["XQ"] = $userInfo["type"] == 0 ? "north" : "south"; $userInfo["step"] = $this->getStep($userInfo); $this->_user = $userInfo; $this->_token = $token; $this->_bindStatus = [ "is_bind" => true, "is_bind_mobile" => $is_bind_mobile, ]; return TRUE; } else { $this->error(__('Please bind Portal Account first'), null, 0,null,["statuscode" => "403"]); } } /** * 获取学生当前步骤 * @param array userinfo * @return array */ public function getStep($param) { $XQ = $param["XQ"]; $temp = []; $timeList = Config::get("dormitoryStep.$XQ"); foreach ($timeList as $key => $value) { $start_time = strtotime($value["start"]); $end_time = strtotime($value["end"]); $now_time = strtotime('now'); if ($now_time <= $end_time && $now_time >= $start_time) { $YXDM = $param["YXDM"]; if ($value["step"] == "NST") { $temp = [ "step" => $value["step"], "msg" => $value["msg"], "start_time" => Config::get("dormitory.$YXDM"), ]; } elseif ($value["step"] == "FML") { $YXDM = $param["YXDM"]; $start_college_time = Config::get("dormitory.$YXDM"); $start_college_time_back = strtotime($start_college_time); if ($now_time < $start_college_time_back) { $temp = [ "step" => "NST", "msg" => "未开始", "start_time" => $start_college_time, ]; } else { $temp = [ "step" => $value["step"], "msg" => $value["msg"], ]; } } else { $temp = [ "step" => $value["step"], "msg" => $value["msg"], ]; } break; } } return $temp; } /** * 操作成功返回的数据 * @param string $msg 提示信息 * @param mixed $data 要返回的数据 * @param int $code 错误码,默认为 1 * @param string $type 输出类型 * @param array $header 发送的 Header 信息 */ protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = []) { $this->result($msg, $data, $code, $type, $header); } /** * 操作失败返回的数据 * @param string $msg 提示信息 * @param mixed $data 要返回的数据 * @param int $code 错误码,默认为0 * @param string $type 输出类型 * @param array $header 发送的 Header 信息 */ protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = []) { $this->result($msg, $data, $code, $type, $header); } /** * 返回封装后的 API 数据到客户端 * @access protected * @param mixed $msg 提示信息 * @param mixed $data 要返回的数据 * @param int $code 错误码,默认为0 * @param string $type 输出类型,支持json/xml/jsonp * @param array $header 发送的 Header 信息 * @return void * @throws HttpResponseException */ protected function result($msg, $data = null, $code = 0, $type = null, array $header = []) { $result = [ 'code' => $code, 'msg' => $msg, 'time' => Request::instance()->server('REQUEST_TIME'), 'data' => $data, ]; // 如果未设置类型则自动判断 $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType); if (isset($header['statuscode'])) { $code = $header['statuscode']; unset($header['statuscode']); } else { //未设置状态码,根据code值判断 $code = $code >= 1000 || $code < 200 ? 200 : $code; } $response = Response::create($result, $type, $code)->header($header); throw new HttpResponseException($response); } /** * 设置验证失败后是否抛出异常 * @access protected * @param bool $fail 是否抛出异常 * @return $this */ protected function validateFailException($fail = true) { $this->failException = $fail; return $this; } /** * 验证数据 * @access protected * @param array $data 数据 * @param string|array $validate 验证器名或者验证规则数组 * @param array $message 提示信息 * @param bool $batch 是否批量验证 * @param mixed $callback 回调方法(闭包) * @return array|string|true * @throws ValidateException */ protected function validate($data, $validate, $message = [], $batch = false, $callback = null) { if (is_array($validate)) { $v = Loader::validate(); $v->rule($validate); } else { // 支持场景 if (strpos($validate, '.')) { list($validate, $scene) = explode('.', $validate); } $v = Loader::validate($validate); !empty($scene) && $v->scene($scene); } // 批量验证 if ($batch || $this->batchValidate) $v->batch(true); // 设置错误信息 if (is_array($message)) $v->message($message); // 使用回调验证 if ($callback && is_callable($callback)) { call_user_func_array($callback, [$v, &$data]); } if (!$v->check($data)) { if ($this->failException) { throw new ValidateException($v->getError()); } return $v->getError(); } return true; } /** * 验证用户是否微信授权 * @access public * @param string $unionid 用户unionid * @return bool */ public function checkWechatAuth($unionid) { if (empty($unionid) ){ return false; } $wxUserModel = new wxUserModel; $userCount = $wxUserModel->where("unionid",$unionid) -> field("id") -> count(); if($userCount == 1) { return true; } return false; } /** * 验证用户是否绑定手机 * @access public * @param string $unionid 用户unionid * @return bool */ public function checkMobileBind($unionid) { if (empty($unionid) ){ return false; } $wxUserModel = new wxUserModel; $user_mobile = $wxUserModel->where("unionid",$unionid) -> field("mobile") -> find(); if(!empty($user_mobile["mobile"])) { return true; } return false; } }
26.513859
117
0.473181
f1a2be3eaeca593130eadc6f1752f813e8561a69
103
rb
Ruby
ruby/grains/grains.rb
gchan/exercism-code-samples
c10ceb007fafa72eca969aae846922932db8ecb4
[ "MIT" ]
13
2015-04-30T09:24:58.000Z
2021-02-04T15:25:47.000Z
ruby/grains/grains.rb
gchan/exercism-code-samples
c10ceb007fafa72eca969aae846922932db8ecb4
[ "MIT" ]
null
null
null
ruby/grains/grains.rb
gchan/exercism-code-samples
c10ceb007fafa72eca969aae846922932db8ecb4
[ "MIT" ]
4
2017-03-28T11:05:05.000Z
2018-10-18T21:01:22.000Z
class Grains def square(squares) 1 << squares - 1 end def total (1 << 64) - 1 end end
10.3
21
0.553398
2f770471f68331231e5ecb391df124e5bc6810ae
2,055
sql
SQL
L10_insertInto.sql
jkatsioloudes/SQLTutorial
07d346dab4e1cf20f6886884ec6fb3c374762fc5
[ "MIT" ]
null
null
null
L10_insertInto.sql
jkatsioloudes/SQLTutorial
07d346dab4e1cf20f6886884ec6fb3c374762fc5
[ "MIT" ]
null
null
null
L10_insertInto.sql
jkatsioloudes/SQLTutorial
07d346dab4e1cf20f6886884ec6fb3c374762fc5
[ "MIT" ]
null
null
null
# LESSON 10 (A). # Please DO try the following queries yourselves but most importantly try different variations and always ask yourself: "Why am I getting this back?". # The INSERT INTO statement. # It is used to insert new records in a table and is possible to write it in two ways. # The first way specifies both the column names and the values to be inserted: INSERT INTO Categories(CategoryName, Description) VALUES ('Sports', 'Athletic Equipment') # We can also write into just one of the columns, for example in CategoryName, and this will have as a result for the value in the field Description to be a null. INSERT INTO Categories(CategoryName) VALUES ('Home') # The second way is to just specify the table name. I tried passing 2 params as above omitting the ID but an error was returned therefore I passed the next availble ID too but this should be avoided. INSERT INTO Categories VALUES ('11', 'Home Furniture', 'Home Equipment') # LESSON 10 (B). # Let's now talk about null values. A field with a NULL value is a field which has no value, not 0, just nothing inside. This happens when we insert or update a record and we don't include a value in an optional field. # Q: How do I test for NULL values? # A: Not possible with comparison operators (i.e =, <, or <>). We need to make use of IS NULL and IS NOT NULL operators. The query that follows will return the second record insertion we had today. SELECT CategoryName, Description FROM Categories WHERE Description IS NULL # This returns the categories which have no NULL Description and have ID < than 4. SELECT CategoryID, CategoryName, Description FROM Categories WHERE Description IS NOT NULL AND CategoryID < 4 ORDER BY CategoryID # NOTE: IS NULL can be used for fields that have no values inside at all, so not only for NULLs. Therefore a good example is a customer record where there is the home phone and mobile phone number and not all of them have both phones. Therefore the one will be empty and checking for IS NULL in home phone or mobile phone will be useful.
60.441176
339
0.768856
db0c7893aea34ad8f0f75a9f528e045b22b32da9
402
kt
Kotlin
android/core/src/main/java/app/visly/shard/ShardContext.kt
0xflotus/shard-mobile
b6928831f5f8112284078ab284d19b1e4d35aa71
[ "MIT" ]
null
null
null
android/core/src/main/java/app/visly/shard/ShardContext.kt
0xflotus/shard-mobile
b6928831f5f8112284078ab284d19b1e4d35aa71
[ "MIT" ]
null
null
null
android/core/src/main/java/app/visly/shard/ShardContext.kt
0xflotus/shard-mobile
b6928831f5f8112284078ab284d19b1e4d35aa71
[ "MIT" ]
1
2020-07-10T12:25:42.000Z
2020-07-10T12:25:42.000Z
package app.visly.shard import android.content.Context import android.content.ContextWrapper internal interface ActionDelegate { fun on(action: String, value: JsonValue?) } class ShardContext(ctx: Context) : ContextWrapper(ctx) { internal var actionDelegate: ActionDelegate? = null fun dispatch(action: String, value: JsonValue?) { this.actionDelegate?.on(action, value) } }
25.125
56
0.741294