identifier
stringlengths
42
383
collection
stringclasses
1 value
open_type
stringclasses
1 value
license
stringlengths
0
1.81k
date
float64
1.99k
2.02k
title
stringlengths
0
100
creator
stringlengths
1
39
language
stringclasses
157 values
language_type
stringclasses
2 values
word_count
int64
1
20k
token_count
int64
4
1.32M
text
stringlengths
5
1.53M
__index_level_0__
int64
0
57.5k
https://github.com/mage-game/metagame-xm-server/blob/master/src/gameworld/gameworld/other/fb/rolepersonbossfb.hpp
Github Open Source
Open Source
MIT
2,022
metagame-xm-server
mage-game
C++
Code
59
245
#ifndef __ROLE_FB_PERSONBOSS__ #define __ROLE_FB_PERSONBOSS__ #include "obj/character/attribute.hpp" #include "servercommon/fbdef.hpp" class Role; class RolePersonBossFB { public: RolePersonBossFB(); ~RolePersonBossFB(); void SetRole(Role *role) { m_role = role; } void Init(Role *role, const PersonBossParam &param); void GetInitParam(PersonBossParam *param); void OnDayChange(unsigned int old_dayid, unsigned int now_dayid); void OnRoleLogin(); int GetTodayEnterByLayer(int layer); void AddTodayEnterTimesByLayer(int layer); void ReqPersonBossInfo(); private: void SendPersonBossInfo(); Role *m_role; PersonBossParam m_param; }; #endif
2,817
https://github.com/wangxingyu-group/newstandard-front/blob/master/mock/newReVisit/taskGetRevisitData.js
Github Open Source
Open Source
MIT
2,020
newstandard-front
wangxingyu-group
JavaScript
Code
137
373
import Mock from 'mockjs' const List = [] const count = 20 for (let i = 0; i < count; i++) { List.push(Mock.mock({ task: '@ctitle(2, 5)', group: '@integer(1,20)', expression: '@ctitle(5, 10)', address: '@ctitle(10, 15)', 'status|1': ['effective', 'noneffective'], remarks: '@ctitle(3, 6)', datetime: '@datetime' })) } export default [ { url: '/taskGetRevisitData/create', type: 'post', response: _ => { return { code: 20000, data: 'success' } } }, { url: '/taskGetRevisitData/update', type: 'post', response: _ => { return { code: 20000, data: 'success' } } }, { url: '/taskGetRevisitData/list', type: 'get', response: config => { const { page = 1, limit = 10 } = config.query const pageList = List.filter((item, index) => index < limit * page && index >= limit * (page - 1)) return { code: 20000, data: { total: List.length, items: pageList } } } } ]
33,074
https://github.com/MaggiWuerze/xddcwebloader/blob/master/src/main/java/de/maggiwuerze/xdccloader/persistency/ChannelRepository.java
Github Open Source
Open Source
Apache-2.0
2,021
xddcwebloader
MaggiWuerze
Java
Code
21
114
package de.maggiwuerze.xdccloader.persistency; import de.maggiwuerze.xdccloader.model.entity.Channel; import java.util.List; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.stereotype.Repository; @Repository public interface ChannelRepository extends PagingAndSortingRepository<Channel, Long> { List<Channel> findAll(); }
15,971
https://github.com/AlisProject/frontend-application/blob/master/app/components/pages/CoinRanking.vue
Github Open Source
Open Source
MIT
2,023
frontend-application
AlisProject
Vue
Code
147
534
<template> <div class="coin-ranking-container"> <app-header /> <default-header-nav /> <coin-ranking /> <app-footer /> </div> </template> <script> import AppHeader from '../organisms/AppHeader' import DefaultHeaderNav from '../molecules/DefaultHeaderNav' import CoinRanking from '../organisms/CoinRanking' import AppFooter from '../organisms/AppFooter' export default { components: { AppHeader, DefaultHeaderNav, CoinRanking, AppFooter } } </script> <style lang="scss" scoped> .coin-ranking-container { display: grid; /* prettier-ignore */ grid-template-areas: "app-header app-header app-header " "nav nav nav " "... ranking ... " "app-footer app-footer app-footer "; grid-template-columns: minmax(0, 1fr) 1080px minmax(0, 1fr); grid-template-rows: 100px auto auto 75px; min-height: 100vh; } @media screen and (max-width: 1296px) { .coin-ranking-container { grid-template-columns: minmax(0, 1fr) 710px minmax(0, 1fr); } } @media screen and (max-width: 920px) { .coin-ranking-container { grid-template-columns: minmax(0, 1fr) 340px minmax(0, 1fr); } } @media screen and (max-width: 550px) { .coin-ranking-container { grid-template-columns: minmax(0, 1fr) 340px minmax(0, 1fr); } } @media screen and (max-width: 370px) { .coin-ranking-container { grid-template-columns: 10px minmax(0, 1fr) 10px; } } </style>
18,503
https://github.com/pawank/PlayRestAPIWithTests/blob/master/app/controllers/CRUD.scala
Github Open Source
Open Source
MIT
null
PlayRestAPIWithTests
pawank
Scala
Code
830
2,270
package controllers import models.{AppBaseModel, PK} import org.joda.time.{LocalDateTime,DateTime} import play.api.libs.json._ import models.common._ import play.api.mvc.{AnyContent, Result, Controller, Action} import tables.{AppDbContract} import javax.inject._ /** * CRUD and other related actions for `Controller` with desired output type e.g. JsValue, Html etc * @tparam OT */ trait CRUDActions[OT,PK] extends Controller{ import utils.json.JsonReadsWrites.commonlyUsedJsonFormats /** * POST: Create / save an incoming object as Json * @return JSON of input */ def create: Action[OT] /** * GET: Get the object represented by incoming 'id' * @param id * @return JSON of object */ def get(id: PK): Action[AnyContent] /** * PUT: Update (partially / fully) incoming object (as Json) with the object available with 'id' in the data storage system * @param id * @return Updated JSON of object */ def update(id: PK): Action[OT] /** * DELETE: Delete an object represented by incoming 'id' * @param id * @return Status of delete action */ def delete(id: PK): Action[AnyContent] /** * GET: Find records and filter based on pageIndex and limit as input query parameters * @return JSON array of objects */ def getAll: Action[AnyContent] /** * POST: Filter results based on parameters from incoming request as JSON * @return JSON array of objects */ def search:Action[OT] /** * Default Json success message * @param message * @return */ def Js200(message:String = "Success") = Json.toJson(AppMessage(code = 200, message = message)) /** * Default bad request Json message * @param message * @return */ def Js400(message:String = "BadRequest") = Json.toJson(AppMessage(code = 400, message = message)) /** * Default Json error message * @param message * @return */ def Js500(message:String = "Error") = Json.toJson(AppMessage(code = 500, message = message)) /** * Default Json error message * @param message * @return */ def JsX(code:Int, message:String) = Json.toJson(AppMessage(code = code, message = message)) } /** Points to consider while returning http status codes for RESTful requests: DELETE 200 (if your want send some additional data in the Response) or 204 (recommended). 202 Operation deleted has not been committed yet. If there's nothing to delete, use 204 or 404 (DELETE operation is idempotent, delete an already deleted item is operation sucessful, so you can return 204, but it's true that idempotent doesn't implies necessarily the response) Other errors: 400 Bad Request (Malformed syntax or a bad query is strange but possible). 401 Unauthorized 403 Forbidden: Authentication failure or invalid Application ID. 405 Not Allowed. Sure. 409 Resource Conflict can be possible in complex systems. 501, 502 in case of errors. PUT If you're updating an element of a collection 200/204 with the same reasons as DELETE above. 202 if the operation has not been commited yet. The referenced element doesn't exists: PUT can be 201 (if you created the element because that is your behaviour) 404 If you don't want to create elements via PUT. 400 Bad Request (Malformed syntax or a bad query more common than in case of DELETE). 401 Unauthorized 403 Forbidden: Authentication failure or invalid Application ID. 405 Not Allowed. Sure. 409 Resource Conflict can be possible in complex systems, as in DELETE. And 501, 502 in case of errors. */ abstract class CrudController[E <: AppBaseModel] @Inject() (dbContract:AppDbContract[E]) extends CRUDActions[JsValue,PK] { import scala.concurrent.ExecutionContext.Implicits.global import utils.json.JsonReadsWrites._ implicit def reader: Reads[E] implicit def writer: Writes[E] implicit def readerForList: Reads[List[E]] implicit def writerForList: Writes[List[E]] /* implicit val reader: Reads[E] = implicitly[Reads[E]] implicit val writer: Writes[E] = implicitly[Writes[E]] implicit val readerForList: Reads[List[E]] = implicitly[Reads[List[E]]] implicit val writerForList: Writes[List[E]] = implicitly[Writes[List[E]]] */ def create = Action.async(parse.json) { implicit request => scala.concurrent.Future { println(s"create:${request.body}") Json.fromJson[E](request.body)(reader).map { entity => val persistedEntity: E = { println("Creating entity: " + entity) dbContract.insertRecord(entity).get } Created(Json.toJson(persistedEntity)(writer)) }.recoverTotal { e => BadRequest(JsError.toJson(e)) } } } def bulkCreate = Action.async(parse.json) { implicit request => scala.concurrent.Future { println(s"bulkCreate:${request.body}") Json.fromJson[List[E]](request.body)(readerForList).map { entities => println(entities) val persistedEntityList:List[E] = entities.map(entity => { println("Creating entity: " + entity) dbContract.insertRecord(entity).get }) println("Bulk create done") Created(Json.toJson(persistedEntityList)(writerForList)) }.recoverTotal { e => BadRequest(JsError.toJson(e)) } } } def findById(id:PK):Option[E] = dbContract.getRecord(id) def deleteById(id:PK):Int = if (dbContract.deleteRecordById(id)) 1 else 0 def getAbstract(id:PK)(f: Any => Result) = Action.async(parse.json) { implicit request => scala.concurrent.Future { val obj:Option[E] = this.findById(id) f(obj) } } def get(id:PK) = Action.async { implicit request => scala.concurrent.Future { val obj:Option[E] = this.findById(id) if (obj.isDefined) { Ok(Json.toJson(obj.get)(writer)) } else { NotFound(JsX(NOT_FOUND,"Object for the given ID not found")) } } } def getAll = Action.async { implicit request => scala.concurrent.Future { val skip = request.queryString.get("skip").flatMap(_.headOption.map(_.toInt)).getOrElse(0) val pageSize = request.queryString.get("pageSize").flatMap(_.headOption.map(_.toInt)).getOrElse(0) println(dbContract != null) val records:List[E] = dbContract.finalAllRecords() println(records) Ok(Json.toJson(records)(writerForList)) } } def search = Action.async(parse.json) { implicit request => scala.concurrent.Future { val records:List[E] = dbContract.finalAllRecords() Ok(Json.toJson(records)(writerForList)) } } def delete(id:PK) = Action.async { implicit request => scala.concurrent.Future { val deletedId = this.deleteById(id) if (deletedId >= 0) { Ok(Json.obj("id" -> deletedId)) } else { NotFound(JsX(NOT_FOUND,"Object for the given ID not found")) } } } def update(id:PK) = Action.async(parse.json) { implicit request => scala.concurrent.Future { println(s"update:${request.body}") this.findById(id) match { case Some(existingEntity) => Json.fromJson[E](request.body)(reader).map { entity => Ok(Json.toJson(entity)(writer)) }.recoverTotal { e => BadRequest(JsError.toJson(e)) } case _ => NotFound(JsX(NOT_FOUND,"Object for the given ID not found")) } } } }
28,961
https://github.com/Sea2Data/NMDEchosounder/blob/master/runLSSSreport/getNMDinfo.py
Github Open Source
Open Source
MIT
null
NMDEchosounder
Sea2Data
Python
Code
81
448
class getNMDinfo: def __init__(self): ''' Constructor for this class. ''' # import urllib.request import xmltodict import urllib3 import pandas as pd import numpy as np self.server = "http://tomcat7.imr.no:8080/apis/nmdapi/reference/v2/dataset/cruiseseries?version=2.0" http = urllib3.PoolManager() f = http.request('GET',self.server) data = xmltodict.parse(f.data) df = pd.DataFrame([]) for i in range(0,len(data['list']['row'])): name = data['list']['row'][i]['name'] cruise_id = [] for ii in range(0,len(data['list']['row'][i]['samples']['sample'])): for iii in range(0,len(data['list']['row'][i]['samples']['sample'][ii]['cruises']['cruise'])): try: cruise_id=np.hstack((cruise_id,data['list']['row'][i]['samples']['sample'][ii]['cruises']['cruise'][iii]['cruisenr'])) except KeyError: cruise_id=np.hstack((cruise_id,data['list']['row'][i]['samples']['sample'][ii]['cruises']['cruise']['cruisenr'])) cruise_id = (np.unique(cruise_id)) d = {'name':name,'cruiseid':list(cruise_id)} df = df.append(pd.DataFrame(d)) self.df = df #Return function def __int__(self): return int(self.df)
19,553
https://github.com/mephan/regrasp/blob/master/node_modules/express-stormpath/node_modules/stormpath/node_modules/memcached/node_modules/hashring/benchmarks/benchmark.js
Github Open Source
Open Source
MIT, Apache-2.0
2,016
regrasp
mephan
JavaScript
Code
247
729
/** * Benchmark dependencies */ var Benchmark = require('benchmark') , microtime = require('microtime'); /** * Different hashring drivers */ var hashring = require('hashring') , hash_ring = require('hash_ring') , nodes = {'192.168.0.102:11212': 1, '192.168.0.103:11212': 1, '192.168.0.104:11212': 1}; /** * prebuild hashrings */ var ring1 = new hashring(nodes) , ring2 = new hash_ring(nodes); /** * Benchmark the constructing and generating of a hashring */ var constructing = new Benchmark.Suite; constructing .add('hashring', function(){ var r = new hashring(nodes); }) .add('hash_ring', function(){ var r = new hash_ring(nodes); }) .on('cycle', function(bench){ console.log("Executing benchmark: " + bench); }) .on('complete', function(){ console.log(this.filter('fastest').pluck('name') + ' has the fastest constructor'); // run the next benchmark if it exists var next = benchmarks.shift(); if (next && next.run) next.run(); }); var random = new Benchmark.Suite; random .add('hashring', function(){ ring1.getNode('key' + Math.random()) }) .add('hash_ring', function(){ ring2.getNode('key' + Math.random()) }) .on('cycle', function(bench){ console.log("Executing benchmark: " + bench); }) .on('complete', function(){ console.log(this.filter('fastest').pluck('name') + ' has the fastest random key getNode'); // run the next benchmark if it exists var next = benchmarks.shift(); if (next && next.run) next.run(); }); var same = new Benchmark.Suite; same .add('hashring', function(){ ring1.getNode('key') }) .add('hash_ring', function(){ ring2.getNode('key') }) .on('cycle', function(bench){ console.log("Executing benchmark: " + bench); }) .on('complete', function(){ console.log(this.filter('fastest').pluck('name') + ' has the fastest same key getNode'); // run the next benchmark if it exists var next = benchmarks.shift(); if (next && next.run) next.run(); }); /** * Add all benchmarks that that need to be run. */ var benchmarks = [constructing,random,same]; // run benchmarks if (benchmarks.length) benchmarks.shift().run();
26,384
https://github.com/eduardbadillo-igrid/deep-readdir-extended/blob/master/test/index.js
Github Open Source
Open Source
MIT
null
deep-readdir-extended
eduardbadillo-igrid
JavaScript
Code
323
1,145
/// <reference path='../typescript-definitions/mocha.d.ts' /> /// <reference path='../typescript-definitions/node.d.ts' /> /* jshint mocha:true */ 'use strict'; var rdr = require('../index'); var assert = require('assert'); var _a = [rdr.deepReaddir, rdr.deepReaddirSync], deepReaddir = _a[0], deepReaddirSync = _a[1]; describe('deep-readdir', function () { it('should return an array', function () { assert(Array.isArray(deepReaddirSync('test/mocks/onlyfiles/'))); assert(Array.isArray(deepReaddirSync('test/mocks/empty/'))); }); it('should throw an error if first argument is not a directory', function () { assert.throws(deepReaddirSync); assert.throws(function () { deepReaddirSync('foo'); }); }); it('should return a list of files in directory', function () { assert.equal(deepReaddirSync('test/mocks/onlyfiles/').length, 5); assert.equal(deepReaddirSync('test/mocks/onlyfiles').length, 5); assert.equal(deepReaddirSync('test/mocks/subs').length, 6); }); it('should call a callback (if provided) with results', function (done) { var promises = 4; deepReaddir('test/mocks/onlyfiles/', function (result) { promises--; assert.equal(result.length, 5); if (promises === 0) { done(); } }); deepReaddir('test/mocks/onlyfiles', function (result) { promises--; assert.equal(result.length, 5); if (promises === 0) { done(); } }); deepReaddir('test/mocks/subs', function (result) { promises--; assert.equal(result.length, 6); if (promises === 0) { done(); } }); deepReaddir('test/mocks/empty', function (result) { promises--; assert(Array.isArray(result)); if (promises === 0) { done(); } }); }); it('should accept an optional options object', function (done) { deepReaddir('test/mocks/onlyfiles/', function (result) { assert(Array.isArray(result)); done(); }, {}); }); it('should allow filtering by extension', function (done) { var promises = 3; deepReaddir('test/mocks/extensions/', function (result) { promises--; assert(Array.isArray(result)); assert.equal(result.length, 2); if (promises === 0) { done(); } }, { extension: 'html' }); deepReaddir('test/mocks/extensions/', function (result) { promises--; assert(Array.isArray(result)); assert.equal(result.length, 3); if (promises === 0) { done(); } }, { extension: '.txt' }); deepReaddir('test/mocks/extensions/', function (result) { promises--; assert(Array.isArray(result)); assert.equal(result.length, 6); if (promises === 0) { done(); } }, { extension: '' }); }); it('should allow filtering hidden files', function (done) { var promises = 3; deepReaddir('test/mocks/hidden/', function (result) { promises--; assert(Array.isArray(result)); assert.equal(result.length, 4); if (promises === 0) { done(); } }, { hidden: true }); deepReaddir('test/mocks/hidden/', function (result) { promises--; assert(Array.isArray(result)); assert.equal(result.length, 1); if (promises === 0) { done(); } }, { hidden: false }); deepReaddir('test/mocks/hidden/', function (result) { promises--; assert(Array.isArray(result)); assert.equal(result.length, 1); if (promises === 0) { done(); } }, {}); }); });
653
https://github.com/Tjoppen/mxflib/blob/master/mxfwrap/parseoptions.h
Github Open Source
Open Source
Zlib
2,020
mxflib
Tjoppen
C
Code
222
395
/*! \file parsoptions.h * \brief Declarations for MXFWrap commandline options * * \version $Id: parseoptions.h,v 1.1 2011/01/10 10:42:27 matt-beard Exp $ * */ /* * Copyright (c) 2010, Metaglue Corporation * * This software is provided 'as-is', without any express or implied warranty. * In no event will the authors be held liable for any damages arising from * the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must * not claim that you wrote the original software. If you use this * software in a product, an acknowledgment in the product * documentation would be appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must * not be misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source * distribution. */ #ifndef _parseoptions_h_ #define _parseoptions_h_ #include "libprocesswrap/process.h" //! Parse the command line options /*! \return -1 if an error or none supplied, 1 if pause before exit (-z), 0 otherwise */ int ParseOptions(int &argc, char **argv, ProcessOptions *pOpt); #endif // _parseoptions_h_
49,062
https://github.com/YangHao666666/hawq/blob/master/src/backend/catalog/caql/caller.py
Github Open Source
Open Source
Artistic-1.0-Perl, ISC, bzip2-1.0.5, TCL, Apache-2.0, BSD-3-Clause-No-Nuclear-License-2014, MIT, PostgreSQL, BSD-3-Clause
2,018
hawq
YangHao666666
Python
Code
496
1,172
#!/usr/bin/env python # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. #----------------------------------------------------------------------------- # # caller.py # # Collect CaQL caller places and emit to stdout. The output is used to # know the CaQL code coverage, which you can see in caqltrack regression test. # The basic flow is to build `.i` files from `.c` and grep `caql1` lines # which don't look like definition, then tokenize the line to fields. #----------------------------------------------------------------------------- import os import subprocess import sys def lex_line(line): """Tokenize the caql1 line.""" # state constants INITIAL = 0 # initial state; before cql1 IN_PAR = 1 # inside parenthesis; eg cql1(xxxx) IN_STR = 2 # inside string literal i = 0 l = len(line) currbuf = [] buffers = [] state = INITIAL while i < l: if state == INITIAL: # don't need to bother by white spaces, given the cql() definition if line.startswith('cql1(', i): i += 5 level = 0 state = IN_PAR continue i += 1 elif state == IN_PAR: c = line[i] if c == '"': i += 1 state = IN_STR continue elif c == ' ': pass elif c == ',': buffers.append(''.join(currbuf)) currbuf = [] elif c == '(': level += 1 currbuf.append(c) elif c == ')': if level == 0: break level -= 1 currbuf.append(c) else: currbuf.append(c) i += 1 elif state == IN_STR: c = line[i] if c == '"': i += 1 state = IN_PAR continue else: currbuf.append(c) i += 1 else: raise Exception() return buffers def main(): # cdb-pg directory rootdir = os.path.join(os.path.dirname(__file__), '../../../..') # caql.files know which `.c` files should be processed. input_file = os.path.join(rootdir, 'src/backend/catalog/caql/caql.files') for line in open(input_file): line = line.strip() abspath = os.path.join(rootdir, 'src/backend/catalog/caql', line) dirname = os.path.dirname(abspath) dirname_fromtop = os.path.relpath(abspath, rootdir) filename = os.path.basename(abspath) filename_i = os.path.splitext(filename)[0] + '.i' # run C preprocessor ret = subprocess.call(['make', '-C', dirname, filename_i], stdout=subprocess.PIPE) if ret != 0: sys.stderr.write('make failed for ' + filename_i) continue for line_i in open(os.path.join(dirname, filename_i)): # avoid definitions and find lines with 'cql1' if ('#define' not in line_i and not line_i.startswith('cq_list') and 'cql1' in line_i): # tokenize words = lex_line(line_i) # we drop the trailing parts as we don't need tup = words[0:3] tup.append(dirname_fromtop) sys.stdout.write('\t'.join(tup) + "\n") # clean up `.i` files os.unlink(os.path.join(dirname, filename_i)) if __name__ == '__main__': main()
4,022
https://github.com/suvadeepchaudhuri/ember-string-fns/blob/master/addon/helpers/string-to-kebab-case.js
Github Open Source
Open Source
MIT
2,020
ember-string-fns
suvadeepchaudhuri
JavaScript
Code
48
132
import { helper } from '@ember/component/helper'; /** * kebab-case a string. * * @public * @function stringToKebabCase * @param {string} value The string to kebab-case. * @returns {string} The kebab-cased string. */ export function stringToKebabCase([value = '']) { return value .toLowerCase() .split(' ') .join('-'); } export default helper(stringToKebabCase);
5,132
https://github.com/K-Wu/libcxx.doc/blob/master/test/std/language.support/support.limits/limits/numeric.limits.members/quiet_NaN.pass.cpp
Github Open Source
Open Source
Apache-2.0
null
libcxx.doc
K-Wu
C++
Code
143
680
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // test numeric_limits // quiet_NaN() #include <limits.hxx> #include <cmath.hxx> #include <type_traits.hxx> #include <cassert.hxx> #include "test_macros.h" template <class T> void test_imp(std::true_type) { assert(std::isnan(std::numeric_limits<T>::quiet_NaN())); assert(std::isnan(std::numeric_limits<const T>::quiet_NaN())); assert(std::isnan(std::numeric_limits<volatile T>::quiet_NaN())); assert(std::isnan(std::numeric_limits<const volatile T>::quiet_NaN())); } template <class T> void test_imp(std::false_type) { assert(std::numeric_limits<T>::quiet_NaN() == T()); assert(std::numeric_limits<const T>::quiet_NaN() == T()); assert(std::numeric_limits<volatile T>::quiet_NaN() == T()); assert(std::numeric_limits<const volatile T>::quiet_NaN() == T()); } template <class T> inline void test() { test_imp<T>(std::is_floating_point<T>()); } int main(int, char**) { test<bool>(); test<char>(); test<signed char>(); test<unsigned char>(); test<wchar_t>(); #if TEST_STD_VER > 17 && defined(__cpp_char8_t) test<char8_t>(); #endif #ifndef _LIBCPP_HAS_NO_UNICODE_CHARS test<char16_t>(); test<char32_t>(); #endif // _LIBCPP_HAS_NO_UNICODE_CHARS test<short>(); test<unsigned short>(); test<int>(); test<unsigned int>(); test<long>(); test<unsigned long>(); test<long long>(); test<unsigned long long>(); #ifndef _LIBCPP_HAS_NO_INT128 test<__int128_t>(); test<__uint128_t>(); #endif test<float>(); test<double>(); test<long double>(); return 0; }
35,291
https://github.com/jiangbingyang/amazon-advertising-api-csharp/blob/master/source/Amazon.Advertising.API/Models/RequestReportParameter.cs
Github Open Source
Open Source
BSD-3-Clause
2,020
amazon-advertising-api-csharp
jiangbingyang
C#
Code
180
352
using Newtonsoft.Json; namespace Amazon.Advertising.API.Models { public class RequestReportParameter { /// <summary> /// The type of campaign for which performance data should be /// generated.Must be sponsoredProducts /// </summary> [JsonProperty("campaignType")] public string CampaignType { get; set; } /// <summary> /// Optional. Dimension on which to segment the report. If specified, must be query. /// </summary> [JsonProperty("segment")] public string Segment { get; set; } /// <summary> /// The date for which to retrieve the performance report in YYYYMMDD /// format.The time zone is specified by the profile used to request the /// report.If this date is today, then the performance report may contain /// partial information.Reports are not available for data older than 60 /// days.For details on data latency, see the Service Guarantees in the /// Developer Notes. /// </summary> [JsonProperty("reportDate")] public string ReportDate { get; set; } /// <summary> /// A comma-separated list of the metrics to be included in the report. See /// Report Metrics in the Developer Notes for a complete list of supported /// metrics. /// </summary> [JsonProperty("metrics")] public string Metrics { get; set; } } }
39,223
https://github.com/n-syuichi/LAaaS-docker/blob/master/caliper/app/Translator/DiscussionViewed.php
Github Open Source
Open Source
MIT
2,022
LAaaS-docker
n-syuichi
PHP
Code
82
316
<?php namespace App\Translator; use App\Models\Moodle\{Event, User, Forum}; final class DiscussionViewed extends Translator { private $partOf; public function __construct(Event $event) { $this->actor = $this->getUser($event->userid); $this->object = $this->getModule($event->objecttable, $event->objectid); $this->partOf = $this->getModule('forum', $this->object->forum); $this->course = $this->getCourse($this->object->course); $this->courseCategory = $this->getCourseCategory($this->course->category ?? 'null'); $this->eventTime = $event->timecreated->timestamp; } public function getActor(): User { return $this->actor; } public function getObject() { return $this->object; } public function getPartOf(): Forum { return $this->partOf; } public function getIsPartOfCourse() { return $this->course; } public function getCategory(): string { return $this->courseCategory; } }
14,288
https://github.com/iantal/AndroidPermissions/blob/master/apks/playstore_apps/com_idamob_tinkoff_android/source/com/google/zxing/e/j.java
Github Open Source
Open Source
Apache-2.0
2,019
AndroidPermissions
iantal
Java
Code
159
462
package com.google.zxing.e; import com.google.zxing.NotFoundException; public final class j extends x { private final int[] a = new int[4]; public j() {} protected final int a(com.google.zxing.common.a paramA, int[] paramArrayOfInt, StringBuilder paramStringBuilder) throws NotFoundException { int[] arrayOfInt = this.a; arrayOfInt[0] = 0; arrayOfInt[1] = 0; arrayOfInt[2] = 0; arrayOfInt[3] = 0; int m = paramA.b; int i = paramArrayOfInt[1]; int j = 0; int n; int k; while ((j < 4) && (i < m)) { paramStringBuilder.append((char)(a(paramA, arrayOfInt, i, d) + 48)); n = arrayOfInt.length; k = 0; while (k < n) { i += arrayOfInt[k]; k += 1; } j += 1; } i = a(paramA, i, true, c)[1]; j = 0; while ((j < 4) && (i < m)) { paramStringBuilder.append((char)(a(paramA, arrayOfInt, i, d) + 48)); n = arrayOfInt.length; k = 0; while (k < n) { i += arrayOfInt[k]; k += 1; } j += 1; } return i; } final com.google.zxing.a b() { return com.google.zxing.a.g; } }
5,331
https://github.com/heraclitusj/mgek_imgbed/blob/master/app/api/__init__.py
Github Open Source
Open Source
Apache-2.0
2,020
mgek_imgbed
heraclitusj
Python
Code
51
139
# @Author: Landers1037 # @Github: github.com/landers1037 # @File: __init__.py.py # @Date: 2020-05-12 from flask import Blueprint from flask_cors import CORS api = Blueprint('img_api', __name__) CORS(api) from . import image_upload from . import image_info from . import image_list from . import image_delete from . import image_format #add jwt from app.middleware import jwt_middleware
38,140
https://github.com/coderbydesign/kudo-o-matic/blob/master/app/dashboards/user_dashboard.rb
Github Open Source
Open Source
LicenseRef-scancode-unknown-license-reference, MIT
2,018
kudo-o-matic
coderbydesign
Ruby
Code
233
756
require 'administrate/base_dashboard' class UserDashboard < Administrate::BaseDashboard # ATTRIBUTE_TYPES # a hash that describes the type of each of the model's fields. # # Each different type represents an Administrate::Field object, # which determines how the attribute is displayed # on pages throughout the dashboard. ATTRIBUTE_TYPES = { id: Field::Number, name: Field::String, email: Field::String, avatar_url: Field::String, slack_name: Field::String, admin: Field::Boolean, transaction_received_mail: Field::Boolean, goal_reached_mail: Field::Boolean, summary_mail: Field::Boolean, api_token: Field::String, deactivated_at: Field::DateTime, created_at: Field::DateTime, updated_at: Field::DateTime, sent_transactions: Field::HasMany.with_options(class_name: 'Transaction'), received_transactions: Field::HasMany.with_options(class_name: 'Transaction'), votes: Field::HasMany, fcm_tokens: Field::HasMany } # COLLECTION_ATTRIBUTES # an array of attributes that will be displayed on the model's index page. # # By default, it's limited to four items to reduce clutter on index pages. # Feel free to add, remove, or rearrange items. COLLECTION_ATTRIBUTES = [ :id, :name, :email, :slack_name, :admin, :sent_transactions, :received_transactions, :deactivated_at ] # SHOW_PAGE_ATTRIBUTES # an array of attributes that will be displayed on the model's show page. SHOW_PAGE_ATTRIBUTES = [ :id, :name, :email, :avatar_url, :slack_name, :admin, :transaction_received_mail, :goal_reached_mail, :summary_mail, :api_token, :created_at, :updated_at, :deactivated_at, :sent_transactions, :received_transactions, :votes, :fcm_tokens ] # FORM_ATTRIBUTES # an array of attributes that will be displayed # on the model's form (`new` and `edit`) pages. FORM_ATTRIBUTES = [ :name, :email, :slack_name, :avatar_url, :admin, :transaction_received_mail, :goal_reached_mail, :summary_mail, :api_token ] # Overwrite this method to customize how users are displayed # across all pages of the admin dashboard. def display_resource(user) user.restricted? ? 'Hidden' : user.name end end
40,996
https://github.com/abelidze/planer-server/blob/master/app/src/test/java/com/skillmasters/server/common/requestbuilder/permission/GrantRequestBuilder.java
Github Open Source
Open Source
MIT
2,019
planer-server
abelidze
Java
Code
49
210
package com.skillmasters.server.common.requestbuilder.permission; import com.skillmasters.server.common.requestbuilder.AppRequestBuilder; import com.skillmasters.server.http.request.PermissionRequest; public class GrantRequestBuilder extends AppRequestBuilder<GrantRequestBuilder> { public GrantRequestBuilder userId(String userId) { return set("user_id", userId); } public GrantRequestBuilder entityId(Long entityId) { return set("entity_id", entityId); } public GrantRequestBuilder entityType(PermissionRequest.EntityType entityType) { return set("entity_type", entityType); } public GrantRequestBuilder action(PermissionRequest.ActionType action) { return set("action", action); } }
5,128
https://github.com/SSoelvsten/coom/blob/master/test/adiar/bdd/test_evaluate.cpp
Github Open Source
Open Source
MIT
2,022
coom
SSoelvsten
C++
Code
809
2,617
go_bandit([]() { describe("BDD: Evaluate", [&]() { // == CREATE BDD FOR UNIT TESTS == // START /* 1 ---- x0 / \ | 2 ---- x1 |/ \ 3 4 ---- x2 / \ / \ F T T 5 ---- x3 / \ F T */ ptr_t sink_T = create_sink_ptr(true); ptr_t sink_F = create_sink_ptr(false); node_file bdd; node_t n5 = create_node(3,0, sink_F, sink_T); node_t n4 = create_node(2,1, sink_T, n5.uid); node_t n3 = create_node(2,0, sink_F, sink_T); node_t n2 = create_node(1,0, n3.uid, n4.uid); node_t n1 = create_node(0,0, n3.uid, n2.uid); { // Garbage collect writer to free write-lock node_writer nw(bdd); nw << n5 << n4 << n3 << n2 << n1; } // END // == CREATE BDD FOR UNIT TESTS == it("should return F on test BDD with assignment (F,F,F,T)", [&bdd]() { assignment_file assignment; { // Garbage collect writer to free write-lock assignment_writer aw(assignment); aw << create_assignment(0, false) << create_assignment(1, false) << create_assignment(2, false) << create_assignment(3, true); } AssertThat(bdd_eval(bdd, assignment), Is().False()); }); it("should return F on test BDD with assignment (F,_,F,T)", [&bdd]() { assignment_file assignment; { // Garbage collect writer to free write-lock assignment_writer aw(assignment); aw << create_assignment(0, false) << create_assignment(2, false) << create_assignment(3, true); } AssertThat(bdd_eval(bdd, assignment), Is().False()); }); it("should return T on test BDD with assignment (F,T,T,T)", [&bdd]() { assignment_file assignment; { // Garbage collect writer to free write-lock assignment_writer aw(assignment); aw << create_assignment(0, false) << create_assignment(1, true) << create_assignment(2, true) << create_assignment(3, true); } AssertThat(bdd_eval(bdd, assignment), Is().True()); }); it("should return F on test BDD with assignment (T,F,F,T)", [&bdd]() { assignment_file assignment; { // Garbage collect writer to free write-lock assignment_writer aw(assignment); aw << create_assignment(0, true) << create_assignment(1, false) << create_assignment(2, false) << create_assignment(3, true); } AssertThat(bdd_eval(bdd, assignment), Is().False()); }); it("should return T on test BDD with assignment (T,F,T,F)", [&bdd]() { assignment_file assignment; { // Garbage collect writer to free write-lock assignment_writer aw(assignment); aw << create_assignment(0, true) << create_assignment(1, false) << create_assignment(2, true) << create_assignment(3, false); } AssertThat(bdd_eval(bdd, assignment), Is().True()); }); it("should return T on test BDD with assignment (T,T,F,T)", [&bdd]() { assignment_file assignment; { // Garbage collect writer to free write-lock assignment_writer aw(assignment); aw << create_assignment(0, true) << create_assignment(1, true) << create_assignment(2, false) << create_assignment(3, true); } AssertThat(bdd_eval(bdd, assignment), Is().True()); }); it("should return T on test BDD with assignment (T,T,T,F)", [&bdd]() { assignment_file assignment; { // Garbage collect writer to free write-lock assignment_writer aw(assignment); aw << create_assignment(0, true) << create_assignment(1, true) << create_assignment(2, true) << create_assignment(3, false); } AssertThat(bdd_eval(bdd, assignment), Is().False()); }); it("should return T on test BDD with assignment (T,T,T,T)", [&bdd]() { assignment_file assignment; { // Garbage collect writer to free write-lock assignment_writer aw(assignment); aw << create_assignment(0, true) << create_assignment(1, true) << create_assignment(2, true) << create_assignment(3, true); } AssertThat(bdd_eval(bdd, assignment), Is().True()); }); // == CREATE 'SKIPPING' BDD == // START /* 1 ---- x0 / \ / \ ---- x1 | | 2 3 ---- x2 / \ / \ F T T | ---- x3 | 4 ---- x4 / \ F T */ node_file skip_bdd; node_t skip_n4 = create_node(4,0, sink_F, sink_T); node_t skip_n3 = create_node(2,1, sink_T, skip_n4.uid); node_t skip_n2 = create_node(2,0, sink_F, sink_T); node_t skip_n1 = create_node(0,0, skip_n2.uid, skip_n3.uid); { // Garbage collect writer to free write-lock node_writer skip_nw(skip_bdd); skip_nw << skip_n4 << skip_n3 << skip_n2 << skip_n1; } // END // == CREATE 'SKIPPING' BDD == it("should be able to evaluate BDD that skips level [1]", [&skip_bdd]() { assignment_file assignment; { // Garbage collect writer to free write-lock assignment_writer aw(assignment); aw << create_assignment(0, false) << create_assignment(1, true) << create_assignment(2, false) << create_assignment(3, true) << create_assignment(4, true); } AssertThat(bdd_eval(skip_bdd, assignment), Is().False()); }); it("should be able to evaluate BDD that skips level [2]", [&skip_bdd]() { assignment_file assignment; { // Garbage collect writer to free write-lock assignment_writer aw(assignment); aw << create_assignment(0, true) << create_assignment(1, false) << create_assignment(2, true) << create_assignment(3, true) << create_assignment(4, false); } AssertThat(bdd_eval(skip_bdd, assignment), Is().False()); }); it("should return T on BDD with non-zero root with assignment (F,T)", [&]() { /* ---- x0 1 ---- x1 / \ F T */ node_file non_zero_bdd; { // Garbage collect writer to free write-lock node_writer nw(non_zero_bdd); nw << create_node(1,0, sink_F, sink_T); } assignment_file assignment; { // Garbage collect writer to free write-lock assignment_writer aw(assignment); aw << create_assignment(0, false) << create_assignment(1, true); } AssertThat(bdd_eval(non_zero_bdd, assignment), Is().True()); }); it("should return F on F sink-only BDD", [&]() { node_file bdd2; { // Garbage collect writer to free write-lock node_writer nw2(bdd2); nw2 << create_sink(false); } assignment_file assignment; { // Garbage collect writer to free write-lock assignment_writer aw(assignment); aw << create_assignment(0, true) << create_assignment(1, false) << create_assignment(2, false) << create_assignment(3, true); } AssertThat(bdd_eval(bdd2, assignment), Is().False()); }); it("should return T on T sink-only BDD", [&]() { node_file bdd2; { // Garbage collect writer to free write-lock node_writer nw2(bdd2); nw2 << create_sink(true); } assignment_file assignment; { // Garbage collect writer to free write-lock assignment_writer aw(assignment); aw << create_assignment(0, true) << create_assignment(1, true) << create_assignment(2, false) << create_assignment(3, true); } AssertThat(bdd_eval(bdd2, assignment), Is().True()); }); }); });
25,271
https://github.com/willryan/MethodToDelegate.Ninject/blob/master/MethodToDelegate.Ninject.Test/ReturnDelegate/DelegateExample.cs
Github Open Source
Open Source
MIT
null
MethodToDelegate.Ninject
willryan
C#
Code
123
305
using System; namespace MethodToDelegate.Ninject.Test.ReturnDelegate { public delegate string PythagDisplay(double x, double y); public static class DelegateExample { public delegate double Add(double x, double y); public delegate double Mult(double x, double y); public delegate double Sqrt(double x); public delegate double Pythag(double x, double y); public delegate string DoubleToString(double x); public static Add Addr() => (double a, double b) => a + b; public static Mult Multr() => (double a, double b) => a*b; public static Sqrt Sqrtr() => Math.Sqrt; public static Pythag Pythagr(Add add, Mult mult, Sqrt sqrt) => (double x, double y) => sqrt(add(mult(x, x), mult(y, y))); public static DoubleToString DoubleToStringr() => (double x) => x.ToString(); public static PythagDisplay PythagD(Pythag pyt, DoubleToString itos) => (double x, double y) => itos(pyt(x, y)); } }
39,113
https://github.com/bbhsu2/druginformation/blob/master/pages/consumer.js
Github Open Source
Open Source
MIT
null
druginformation
bbhsu2
JavaScript
Code
358
1,748
//TODO: abstract this out function focusSearchQuery(){ $("#searchQuery").focus(); } setTimeout(function() { focusSearchQuery(); }, 500); document.addEventListener('DOMContentLoaded', function () { var label = $("div > label"); var flag = false; //TODO: fix this so it's based on checkbox state. label[0].addEventListener('click', function(e){ if(flag) { $(this).html("Check All"); $(".checkboxOption").each(function(){ this.checked = false; }); flag = false; } else{ $(this).html("Unselect All"); $(".checkboxOption").each(function(){ this.checked = true; }); flag = true; } }); //TODO: change this $(":button")[0].addEventListener('click', searchClick); $(".content").keyup(function(e) { if(e.keyCode == 13) { $(":button")[0].click(); } }); $(".form-control").on("click", checkInside); $("#searchQuery").attr('onclick','').unbind('click'); //remove click handler for box }) function checkInside(e) { var box = $(".checkboxOption",$(this).parent()); if(box.prop('checked') == true){ box.prop('checked', false); } else{ box.prop('checked', true); } var allBoxes = $(":checkbox"); var hasUnchecked = true; var box = $(".btn-group > .btn-primary"); for(var i = 0; i < allBoxes.length; i++){ if(!allBoxes[i].checked){ hasUnchecked = true; box.html("Check All"); } else { hasUnchecked = false; box.html("Unselect All"); } } focusSearchQuery(); } function checkAll(e){ $(".checkboxOption").each(function(){ this.checked = true; }); focusSearchQuery(); } //Begin page specific functions function getWikipediaLink(query){ return "http://en.wikipedia.org/wiki/Special:Search?search=" + query + "&go=Go"; } function getMedlinePlusLink(query){ return "http://vsearch.nlm.nih.gov/vivisimo/cgi-bin/query-meta?v%3Aproject=medlineplus&query=" + query + "&x=-1153&y=-113"; } function getGoogleLink(query){ return "https://www.google.com/#q=" + query; } function getMayoClinicLink(query){ return "http://www.mayoclinic.org/search/search-results?q=" + query; } function getWebMDLink(query){ return "http://www.webmd.com/search/search_results/default.aspx?query=" + query; } function getFDALink(query){ return "http://google2.fda.gov/search?q=+" + query + "&client=FDAgov&site=FDAgov&lr=&" + "proxystylesheet=FDAgov" + "&requiredfields=-archive%3AYes&output=xml_no_dtd&getfields=*"; } function getMHRALink(query){ return "http://www.mhra.gov.uk/SearchHelp/GoogleSearch/index.htm?q=" + query; } function getTGALink(query){ return "http://agencysearch.australia.gov.au/s/search.html?query=" + query + "&collection=agencies&profile=tga"; //Therapeutic goods Administration //http://agencysearch.australia.gov.au/s/search.html?query=certolizumab+pegol&collection=agencies&profile=tga } function getISMPLink(query){ return "http://www.ismp.org/searchresults.asp?q=" + query; //institute for safe medication practices //http://www.ismp.org/searchresults.asp?q=epinephrine } function getHealthCanadaLink(query){ return "http://www.healthycanadians.gc.ca/recall-alert-rappel-avis/search-recherche/result-resultat/en?search_text_1="+ query; } function setClickTimeout(func){ setTimeout(func, 125); } function searchClick(e){ var query = document.getElementById("searchQuery").value; var boxes = $(":checkbox"); for(var i = 0; i < boxes.length; i++){ var string = ""; if(boxes[i].checked){ switch(i){ case 0: setClickTimeout(function(){ chrome.tabs.create({url: getFDALink(query)}); }); break; case 1: setClickTimeout(function(){ chrome.tabs.create({url : getGoogleLink(query)}); }); break; case 2: setClickTimeout(function(){ chrome.tabs.create({url : getHealthCanadaLink(query)}); }); break; case 3: setClickTimeout(function(){ chrome.tabs.create({url : getISMPLink(query)}); }); break; case 4: setClickTimeout(function(){ chrome.tabs.create({url: getMayoClinicLink(query)}); }); break; case 5: setClickTimeout(function(){ chrome.tabs.create({ url: getMedlinePlusLink(query)}); }); break; case 6: setClickTimeout(function(){ chrome.tabs.create({ url: getMHRALink(query)}); }); break; case 7: setClickTimeout(function(){ chrome.tabs.create({ url: getTGALink(query)}); }); break; case 8: setClickTimeout(function(){ chrome.tabs.create({ url: getWebMDLink(query)}); }); break; case 9: setClickTimeout(function(){ chrome.tabs.create({url: getWikipediaLink(query)}); }); break; } } } }
21,959
https://github.com/2006-jun15-net/mohamed-code/blob/master/1-chsarp/Serialization/Serialization/Program.cs
Github Open Source
Open Source
MIT
null
mohamed-code
2006-jun15-net
C#
Code
200
624
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; namespace Serialization { class Program { static async void Main(string[] args) { List<playerStats> data; string filePath = "../../../data.json"; try { string initialJson = File.ReadAllText(filePath); data = JsonConvert.DeserializeObject<List<playerStats>>(initialJson); } catch (FileNotFoundException) { data = GetInitialData(); } string json = ConvertToJson(data); WriteStringToFileAsync(filePath, json); } public async static void WriteStringToFileAsync(string filePath, string json) { FileStream fileStream = null; try { //File.WriteAllText(filePath, json); fileStream = new FileStream(filePath, FileMode.Create); } catch (IOException ex) { Console.WriteLine($"error writing file: {ex.Message}"); } finally { fileStream?.Dispose(); } } public static string ConvertToJson(List<playerStats> data) { return JsonConvert.SerializeObject(data, Formatting.Indented); } private static List<playerStats> GetInitialData() { return new List<playerStats> { new playerStats() { Name = "Lebron James", FreeThrowPercentage = 65, PointsPerGame = 25, ArcLocations = new Dictionary<int, double> { [-150] = 30, [-120] = 30, [-90] = 30 } }, new playerStats() { Name = "Lebron James", FreeThrowPercentage = 65, PointsPerGame = 25, ArcLocations = new Dictionary<int, double> { [-150] = 30, [-120] = 30, [-90] = 30 } }, new playerStats() { Name = "Lebron James", FreeThrowPercentage = 65, PointsPerGame = 25, ArcLocations = new Dictionary<int, double> { [-150] = 30, [-120] = 30, [-90] = 30 } }, }; } } }
45,513
https://github.com/magiclen/TakeGhostCard/blob/master/src/org/magiclen/takeghostcard/StringClass.java
Github Open Source
Open Source
Apache-2.0
2,016
TakeGhostCard
magiclen
Java
Code
904
5,233
/* * * Copyright 2015 magiclen.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.magiclen.takeghostcard; /** * 字串常數集。 * * @author Magic Len */ public class StringClass { /** * 儲存玩家名稱(此類別唯一的變數)。 */ public static String userName = "玩家"; //變數 /** * 提示輸入使用者名稱。 */ public static final String SHOW_TYPE_USER_NAME = "請先輸入您的大名:"; /** * 提示輸入的使用者名稱有誤。 */ public static final String SHOW_TYPE_USER_NAME_ERROR = "未輸入大名,請重新輸入:"; /** * 歡迎玩猜數字遊戲的訊息。 */ public static final String SHOW_WELCOME = "\n\t歡迎來玩Java抽鬼詐牌遊戲\n\n"; /** * 歡迎使用者的訊息。 */ public static final String SHOW_USER_WELCOME = "%s 您好!\n"; //printf /** * 主選單的頂端。 */ public static final String SHOW_MENU_TOP = "\n********************主選單********************\n"; /** * 主選單項目的顯示格式。 */ public static final String SHOW_MENU_TYPE = "\t%d.%s\n"; //printf /** * 主選單中的項目。 */ public static final String SHOW_MENU_ITEMS[] = {"人機大戰", "電腦示範", "玩法說明", "離開選單"}; /** * 主選單的底端。 */ public static final String SHOW_MENU_END = "*********************************************\n"; /** * 提示輸入主選單的項目值。 */ public static final String SHOW_TYPE_MENU_ITEM = "請輸入您要的功能[1-" + SHOW_MENU_ITEMS.length + "]:"; /** * 提示輸入的主選單項目值有誤。 */ public static final String SHOW_TYPE_ITEM_ERROR = "輸入有誤,請重新輸入[%d-%d]:"; //printf /** * 是否關閉程式的訊息。 */ public static final String SHOW_EXIT_MENU = "離開選單等於關閉程式,您確定嗎?[Y/N]:"; /** * 取消關閉程式的訊息。 */ public static final String SHOW_WELCOME_BACK = "歡迎回來!"; /** * 關閉程式的訊息。 */ public static final String SHOW_EXIT = "掰掰 %s ,歡迎下次再來挑戰!\n"; //printf /** * Y或N輸入錯誤的訊息。 */ public static final String SHOW_EXIT_ERROR = "輸入有誤,請重新輸入[Y/N]:"; /** * Enter鍵訊息。 */ public static final String SHOW_TYPE_ENTER = "(按下Enter繼續...) "; /** * 提示輸入玩家數量。 */ public static final String SHOW_TYPE_PLAYERS_NUMBER = "請輸入進行抽鬼牌遊戲的玩家數量[3-9]:"; /** * 提示輸入玩家數量的值有誤。 */ public static final String SHOW_TYPE_PLAYERS_NUMBER_ERROR = "數量輸入有誤,請重新輸入[3-9]:"; /** * 電腦名稱。 */ public static final String[] COMPUTER_NAMES = {"「狂獅」鐵戰", "「血手」杜殺", "「不男不女」屠嬌嬌", "「笑裡藏刀」哈哈兒", "「不吃人頭」李大嘴", "「惡賭鬼」軒轅三光", "「迷死人不賠命」蕭咪咪", "「半人半鬼」陰九幽", "「損人不利己」白開心", "「寧死不吃虧、拚命佔便宜」歐陽丁當", "「程式作者」幻嵐", "「詛咒纏身」祿語海", "「霹靂第一」襲滅天來", "「機器貓」小叮噹", "「網球王子」越前龍馬", "「海賊王」哥爾羅傑", "「海賊王的男人」魯夫", "「史上最強弟子」兼一", "「通靈王」麻倉葉", "「遊戲王」武藤遊戲", "「烘焙王」東河馬", "「東邪」黃藥師", "「西毒」歐陽鋒", "「南僧」一燈大師", "「北丐」洪七公", "「中神通」王重陽", "「西狂」楊過", "「北俠」郭靖", "「中頑童」周伯通", "「花果山水濂洞」孫悟空", "「名偵探」柯南"}; /** * 開局訊息。 */ public static final String START_GAME = "\n本局玩家有:"; public static final String START_GAME_Player = "。共%d人。\n\n"; //printf /** * 玩家名稱:說話語句。 */ public static final String SHOW_TALK_NAME_SENTENCE = "%s:%s\n"; /** * 發牌。 */ public static final String[] COMPUTER_DEAL_CARD = {"看你們都沒有人想發牌,那就由我來發吧!", "我來發牌好了。", "我要發牌,怕你們作弊。", "我發牌,絕對公正。", "我就辛苦點,幫你們發牌吧。", "你們這些懶惰鬼,都不想動牌就是了。我來發牌,不要有異議!", "我發牌很快,我來發吧!", "給我1秒,我就能發完牌。", "只要ㄅㄧㄤˋ ㄅㄧㄤˋ聲,我很快地就能把牌發完。", "發牌的事情就交給我吧。", "我這個人最喜歡發牌了,嘻嘻...", "啊是沒人想發牌喔?我來發好了。", "這疊俗稱「荷蘭牌」的撲克牌,就由我來發吧!", "我要發牌。"}; public static final String SHOW_COMPUTER_DEALING_CARD = "(發牌中...)\n"; public static final String[] COMPUTER_DEAL_CARD_FINISH = {"牌發完了,我先來抽吧!", "牌發完了,很快吧~我先抽牌。", "應該沒有發錯,那就先從我開始抽牌。", "終於發完了,手好痠,讓我先抽一張牌吧。", "牌發完啦!", "我發牌還真的挺快的。"}; /** * 剛丟完牌。 */ public static final String[] PILE_EMPTY = {"我沒牌啦!", "沒牌了。", "沒牌了,跳過我吧。", "我沒牌了。", "我結束了。", "沒牌啦!", "幸好這次輸家不是我。", "好家在,牌都沒了。", "看來幸運女神站在我這邊。"}; /** * 抽牌。 */ public static final String[] GET_A_CARD = {"嗯...就抽這張牌!", "我要抽這張牌。", "我要抽你這張。", "就抽你這張!", "你這張牌就交給我吧。", "給抽嗎?"}; /** * 被抽牌。 */ public static final String[] GETTED_A_CARD = {"拿去。", "Here you are.", "拿去吧。", "儘管抽。", "送你啦!", "隨便你抽。", "快點抽走吧。", "快抽吧。", "快點抽。", "快抽啦!", "抽吧。", "真愛抽。", "送你的。", "拿去哺啦。"}; /** * 拒絕被抽(心機)。 */ public static final String[] TAKE_RESIST = {"你確定要抽這張?", "嘿嘿...你確定要抽這張嗎?", "嘻嘻,你摸到的這張不錯。", "嘿嘿,這張好啊!", "建議你換抽別張牌。", "我好心提醒你,最好別抽這張牌。", "你確定要抽這張牌嗎?", "Are you sure?", "呵呵,快點拿走它吧。", "快抽快抽!哈哈哈,不要後悔就好了。", "你確定要抽這張,不會後悔?別說我沒提醒你。", "兄弟,我對你最好了,聽我的,別抽這張。"}; /** * 答應換牌。 */ public static final String[] AGREE_CHANGE = {"感覺有點奇怪,我換一張好了。", "那我換一張牌。", "那我換牌好了。", "我知道你在打什麼主意,騙不了我也嚇不了我。我要換抽別張,以免中你計。", "不用你說,我早就想換抽別張牌了。", "我要換抽別張。"}; /** * 不答應換牌。 */ public static final String[] DISAGREE_CHANGE = {"我就是要這張。", "我確定要抽這張,別想動搖我。", "啦啦啦,不想聽你說話。", "當我白癡嗎?", "我知道你在打什麼主意,騙不了我也嚇不了我。我要抽這張就是這張。", "我相信我的第六感。", "我的直覺最準。", "我相信我的直覺。", "我相信我的第六感。"}; /** * 抽到鬼牌。 */ public static final String[] PICK_GHOST_CARD = {"可惡!", "運氣真差!", "該死。", "居然抽到鬼...呼,差點說溜嘴。", "鬼牌!"}; /** * 鬼牌被抽走。 */ public static final String[] BE_PICK_GHOST_CARD = {"哈哈!", "呵呵!", "恭喜你抽到好牌。", "嘻嘻。", "嘿嘿...", "哇哈哈!"}; /** * 要求洗牌。 */ public static final String[] ASK_RANDOM = {"等一下!先讓我洗個牌。", "我想先洗牌。", "不行!讓我先洗牌。", "別急,讓我洗個牌。"}; /** * 洗牌重抽。 */ public static final String[] PICK_ASK_RANDOM = {"洗什麼牌,真賊。那我抽這張。", "不管你怎麼洗牌,結果都是一樣的。我要抽這張。", "你洗牌!真卑鄙。我要抽這張牌。", "好個洗牌招,讓我不知道抽哪張了。算了,隨便抽一個。"}; /** * 強迫送給對方鬼牌。 */ public static final String[] FORCE_GHOSTCARD = {"這張給你比較快!", "這張直接給你,不用說謝謝了。", "鬼牌直接送你啦!不用還我。", "你要這張嗎?好,給你。", "你好像很想要這張?", "我知道你很需要這張牌。"}; /** * 抽牌訊息。 */ public static final String SHOW_PLAYING_PLAYER = "\n(%s 抽 %s)\n"; //printf /** * 回合訊息。 */ public static final String SHOW_GAME_STAGE = "\n\n------第%d回合------\n"; //printf /** * 牌局結束。 */ public static final String SHOW_GAME_OVER = "\n\n-------------------\n\n經過%d個回合的大戰之後,輸家是......\n"; //printf public static final String SHOW_GAME_OVER_CONTINUE = "%s!!\n\n"; //printf /** * 輸家遺言。 */ public static final String[] LOSER_TALK = {"啊啊啊!輸了!。", "我居然...輸了。", "真難以置信。", "果然玩不過這些心機重的人。", "只是運氣不好。", "運氣不好罷了。"}; /** * 遊戲結束訊息。 */ public static final String SHOW_GAME_EXIT = "\n遊戲已結束,要繼續嗎?[Y/N]:"; /** * 電腦玩家的掰掰語句。 */ public static final String[] COMPUTER_BYE = {"掰掰!", "88", "86", "下次再來。", "886", "881", "再見啦!", "再會啦!", "有緣再見。"}; /** * 抽對象的哪張牌。 */ public static final String TARGET_CARD = "%s 共有%d張牌,您要抽第幾張?[1-%d]:"; //printf /** * User抽牌被駁回。 */ public static final String WANTCHANGE = "對方這樣說,其中必有詐,您要換抽別張牌嗎?[Y/N]:"; /** * User抽牌被洗牌。 */ public static final String RANDOMCHANGE = "對方居然洗了牌。您要抽第幾張?[1-%d]:"; //printf /** * 顯示抽到的牌。 */ public static final String SHOW_GET_WHAT_CARD = "您抽到%s。\n"; //printf /** * 顯示玩家擁有的牌。 */ public static final String SHOW_USER_PILE = "\n您有%d張牌,分別是:%s\n\n"; //printf /** * 顯示對方即將要抽到的牌。 */ public static final String SHOW_COMPUTER_GET = "他想抽您的%s。"; //printf /** * 只剩一張牌,無法耍詐。 */ public static final String USER_ONLY_LEAST_ONE = "您只剩一張牌,無法耍詐。\n"; /** * 詢問耍詐。 */ public static final String USER_TREAK = "要耍詐嗎?[Y/N]:"; /** * 耍詐選單。 */ public static final String USER_TREAK_MENU = "----------------\n1.勸說對方換張牌抽(剩餘%d次)\n2.強制洗牌讓對方重抽(剩餘%d次)\n3.直接送對方一張鬼牌(剩餘%d次)\n----------------\n您想用哪種詐術?[1-3]:"; //printf /** * 耍詐次數用完。 */ public static final String USER_TREAK_OVER = "耍詐次數已用盡,無法再做什麼小動作。\n"; /** * 耍詐次數用完、牌也只剩一張。 */ public static final String USER_TREAK_OVER_ONLY = "\n"; /** * 耍詐次數用完、牌也只剩一張。 */ public static final String SHOW_COMPUTER_GETTED = "他抽了您的%s。\n"; //printf /** * 耍詐次數用完提示。 */ public static final String SHOW_TREAK_LEAK = "此詐術次數已用盡,您已被盯上,只能乖乖給別人抽。\n"; /** * 顯示移除掉的牌。 */ public static final String SHOW_CARD_REMOVED = "\n%s 丟出:%s。\n"; //printf /** * 沒有鬼牌。 */ public static final String SHOW_NO_GHOST_CARD = "您沒有鬼牌。"; }
16,056
https://github.com/IbexOmega/CrazyCanvas/blob/master/LambdaEngine/Include/Networking/API/UDP/INetworkDiscoveryClient.h
Github Open Source
Open Source
MIT
2,021
CrazyCanvas
IbexOmega
C
Code
36
152
#pragma once #include "LambdaEngine.h" #include "Networking/API/BinaryDecoder.h" #include "Networking/API/IPEndPoint.h" #include "Time/API/Timestamp.h" namespace LambdaEngine { class LAMBDA_API INetworkDiscoveryClient { public: DECL_INTERFACE(INetworkDiscoveryClient); virtual void OnServerFound(BinaryDecoder& decoder, const IPEndPoint& endPoint, uint64 serverUID, Timestamp ping, bool isLAN) = 0; }; }
19,762
https://github.com/GaoYYYang/image-optimize-loader/blob/master/test/fixtures/index.js
Github Open Source
Open Source
MIT
2,022
image-optimize-loader
GaoYYYang
JavaScript
Code
16
61
import minijpg from './images/jpg/mini.jpg'; import png1 from './images/png/1.png'; import png2 from './images/png/2.png'; import png3 from './images/png/3.png';
25,852
https://github.com/Marvinmw/dg/blob/master/tools/CMakeFiles/llvm-rd-dump.dir/depend.make
Github Open Source
Open Source
MIT
2,020
dg
Marvinmw
Makefile
Code
104
1,896
# CMAKE generated file: DO NOT EDIT! # Generated by "Unix Makefiles" Generator, CMake Version 3.15 tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: tools/TimeMeasure.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: tools/llvm-rd-dump.cpp tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/ADT/Bitvector.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/ADT/Queue.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/analysis/AnalysisOptions.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/analysis/BFS.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/analysis/CallGraph.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/analysis/NodesWalk.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/analysis/Offset.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/analysis/PointsTo/MemoryObject.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/analysis/PointsTo/PSNode.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/analysis/PointsTo/Pointer.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/analysis/PointsTo/PointerAnalysis.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/analysis/PointsTo/PointerAnalysisFI.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/analysis/PointsTo/PointerAnalysisFS.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/analysis/PointsTo/PointerAnalysisFSInv.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/analysis/PointsTo/PointerAnalysisOptions.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/analysis/PointsTo/PointerGraph.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/analysis/PointsTo/PointerGraphOptimizations.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/analysis/PointsTo/PointsToMapping.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/analysis/PointsTo/PointsToSet.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/analysis/PointsTo/PointsToSets/AlignedPointerIdPointsToSet.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/analysis/PointsTo/PointsToSets/AlignedSmallOffsetsPointsToSet.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/analysis/PointsTo/PointsToSets/OffsetsSetPointsToSet.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/analysis/PointsTo/PointsToSets/PointerIdPointsToSet.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/analysis/PointsTo/PointsToSets/SeparateOffsetsPointsToSet.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/analysis/PointsTo/PointsToSets/SimplePointsToSet.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/analysis/PointsTo/PointsToSets/SmallOffsetsPointsToSet.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/analysis/ReachingDefinitions/DefinitionsMap.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/analysis/ReachingDefinitions/DisjunctiveIntervalMap.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/analysis/ReachingDefinitions/RDMap.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/analysis/ReachingDefinitions/RDNode.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/analysis/ReachingDefinitions/ReachingDefinitions.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/analysis/ReachingDefinitions/ReachingDefinitionsAnalysisOptions.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/analysis/SCC.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/analysis/SubgraphNode.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/llvm/analysis/LLVMAnalysisOptions.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/llvm/analysis/PointsTo/LLVMPointerAnalysisOptions.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/llvm/analysis/PointsTo/LLVMPointsToSet.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/llvm/analysis/PointsTo/PointerAnalysis.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/llvm/analysis/PointsTo/PointerGraph.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/llvm/analysis/ReachingDefinitions/LLVMReachingDefinitionsAnalysisOptions.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/llvm/analysis/ReachingDefinitions/ReachingDefinitions.h tools/CMakeFiles/llvm-rd-dump.dir/llvm-rd-dump.cpp.o: include/dg/util/debug.h
7,186
https://github.com/signalwire/snippets-cluecon-2020-game-theory/blob/master/relay/nodejs/App.js
Github Open Source
Open Source
MIT
null
snippets-cluecon-2020-game-theory
signalwire
JavaScript
Code
164
410
const { RelayConsumer } = require('@signalwire/node'); const consumer = new RelayConsumer({ project: '', token: '', contexts: ['FIRESTARTER'], ready: async ({ client }) => { // Consumer is successfully connected with Relay. // You can make calls or send messages here.. }, onIncomingCall: async (call) => { const { successful } = await call.answer() if (!successful) { return } console.log("Call answered."); // Generate a random number var winning_number = Math.floor(Math.random() * 9) + 1; console.log("Winning number is: " + winning_number); const collect = { type: 'digits', digits_max: 1, initial_timeout: 10, text: 'Please, guess a number between one and nine.' }; var result = await call.promptTTS(collect); console.log(result); if(result.successful){ var guess = result.result; //await call.playTTS({ text: 'You entered ' + guess }) if(guess == winning_number){ await call.playTTS({ text: "Winner! Winner! Chicken Dinner! You guessed correctly." }); }else{ await call.playTTS({ text: "You do not pass go! You have guessed incorrectly." }); } } await call.playTTS({ text: "Thank you for playing, Good Bye!." }); await call.hangup(); } }); consumer.run();
18,455
https://github.com/TriOxygen/oxygen-i18n/blob/master/src/index.ts
Github Open Source
Open Source
MIT
2,023
oxygen-i18n
TriOxygen
TypeScript
Code
85
233
import createTranslator, { Options } from './createTranslator'; export { addMessages } from './createTranslator'; const cache: Record<string, Record<string, ReturnType<typeof createTranslator>>> = {}; const defaultOptions: Options = { fallback: false, locale: 'en-US', currency: 'EUR', format: {} }; export default (options: Options = defaultOptions) => { const _options = { ...defaultOptions, ...options, format: { ...defaultOptions.format, ...(options.format || {}) } }; const { locale, currency } = _options; if (!cache[locale]) { cache[locale] = {}; } if (!cache[locale][currency]) { const translator = createTranslator(_options); cache[locale][currency] = translator; } return cache[locale][currency]; };
8,428
https://github.com/victory-jooyon/otlplus/blob/master/locust/locustfile.py
Github Open Source
Open Source
MIT
null
otlplus
victory-jooyon
Python
Code
741
3,630
from locust import HttpUser, task, between import json class OTL_Locust(HttpUser): wait_time = between(3, 5) code = "c857eb3a9234ccab38eb" state = "8d973242f7cca7d3e253" user_id = "1" course_id = "865" professor_id = "796" csrf_token = None lecture_id = 987440 def on_start(self): self.get_main() self.session_login_callback() # session APIs @task def session(self): return self.session_login() @task def session_login(self): url = "/session/login" \ # + "next=" + "/" data = {"sso_state": self.state} response = self.client.get(url, data=data, name='session_login') # print('Response status code:', response.status_code) # print('Response content:', response.content) @task def session_login_callback(self): url = "/session/login/callback?" \ + "state= " + self.state + "&" \ + "code= " + self.code data = {"sso_state": self.state} response = self.client.get( url, data=data, name='session_login_callback') @task def session_logout(self): url = "/session/logout?" \ # + "next=" + "/" response = self.client.get(url, name='session_logout') # @task # def session_unregister(self): # code = "c857eb3a9234ccab38eb" # state = "8d973242f7cca7d3e253" # url = "/session/unregister" # response = self.client.post(url, name='session_unregister') @task def session_language(self): url = "/session/language" response = self.client.get(url, name='session_language') @task def session_setting_get(self): url = "/session/settings" response = self.client.get(url, name='session_setting_get') @task def session_setting_post(self): url = "/session/settings/" data = { 'language': "ko", 'fav_department': [132, 331, 4423] } response = self.client.post(url, data=data, headers={"X-CSRFToken": self.csrf_token}, cookies={"csrftoken": self.csrf_token}, name='session_setting_post' ) # timetable APIs @task def get_table(self): response = self.client.get('/timetable', name='get_table') @task def table_update_lecture_delete(self): table_id = self.table_create() body = { 'table_id': table_id, 'lecture_id': 1377884, 'delete': u'true', } response = self.client.post('/timetable/api/table_update/', data=body, headers={"X-CSRFToken": self.csrf_token}, cookies={"csrftoken": self.csrf_token}, name='table_update') @task def table_update(self): table_id = self.table_create() body = { 'table_id': table_id, 'lecture_id': 1377884, 'delete': u'false', } response = self.client.post('/timetable/api/table_update/', data=body, headers={"X-CSRFToken": self.csrf_token}, cookies={"csrftoken": self.csrf_token}, name='table_update') @task def table_create(self): body = { 'year': 2018, 'semester': 1, 'lectures': [1, 2], } response = self.client.post('/timetable/api/table_create/', data=body, headers={"X-CSRFToken": self.csrf_token}, cookies={"csrftoken": self.csrf_token}, name='table_create') return response.json()["id"] @task def table_delete(self): table_id = self.table_create() body = { 'table_id': table_id, 'year': 2018, 'semester': 1, } response = self.client.post('/timetable/api/table_delete/', data=body, headers={"X-CSRFToken": self.csrf_token}, cookies={"csrftoken": self.csrf_token}, name='table_delete') @task def table_copy(self): table_id = self.table_create() body = { 'table_id': table_id, 'year': 2018, 'semester': 1, } response = self.client.post('/timetable/api/table_copy/', data=body, headers={"X-CSRFToken": self.csrf_token}, cookies={"csrftoken": self.csrf_token}, name='table_copy') @task def table_load(self): body = { 'year': 2018, 'semester': 1, } response = self.client.post('/timetable/api/table_load/', data=body, headers={"X-CSRFToken": self.csrf_token}, cookies={"csrftoken": self.csrf_token}, name='table_load') @task def table_autocomplete(self): body = { 'year': 2018, 'semester': 1, 'keyword': '논리', } response = self.client.post('/timetable/api/autocomplete/', data=body, headers={"X-CSRFToken": self.csrf_token}, cookies={"csrftoken": self.csrf_token}, name='table_autocomplete') @task def table_search(self): body = json.dumps({ "year": 2018, "semester": 1, "keyword": "논리", }) response = self.client.post('/timetable/api/search/', data=body, headers={"X-CSRFToken": self.csrf_token}, cookies={"csrftoken": self.csrf_token}, name='table_search') @task def comment_load(self): body = { 'lecture_id': self.lecture_id, } response = self.client.post('/timetable/api/comment_load/', data=body, headers={"X-CSRFToken": self.csrf_token}, cookies={"csrftoken": self.csrf_token}, name='comment_load' ) @task def major_load(self): body = { 'year': 2018, 'semester': 1, } response = self.client.post('/timetable/api/list_load_major/', data=body, headers={"X-CSRFToken": self.csrf_token}, cookies={"csrftoken": self.csrf_token}, name='major_load' ) @task def humanity_load(self): body = { 'year': 2018, 'semester': 1, } response = self.client.post('/timetable/api/list_load_humanity/', data=body, headers={"X-CSRFToken": self.csrf_token}, cookies={"csrftoken": self.csrf_token}, name='humanity_load' ) @task def wishlist_load(self): body = { 'year': 2018, 'semester': 1, } response = self.client.post('/timetable/api/wishlist_load/', data=body, headers={"X-CSRFToken": self.csrf_token}, cookies={"csrftoken": self.csrf_token}, name='wishlist_load' ) @task def wishlist_update(self): # can fail due to call before load body = { 'lecture_id': self.lecture_id, 'delete': u'false', } response = self.client.post('/timetable/api/wishlist_update/', data=body, headers={"X-CSRFToken": self.csrf_token}, cookies={"csrftoken": self.csrf_token}, name='wishlist_update' ) @task def wishlist_update_lecture_delete(self): # can fail due to call before update body = { 'lecture_id': self.lecture_id, 'delete': u'true', } response = self.client.post('/timetable/api/wishlist_update/', data=body, headers={"X-CSRFToken": self.csrf_token}, cookies={"csrftoken": self.csrf_token}, name='wishlist_update_lecture_delete' ) @task def share_image(self): table_id = self.table_create() params = { 'table_id': table_id, } response = self.client.get('/timetable/api/share_image', params=params, name='share_image') @task def share_calander(self): table_id = self.table_create() params = { 'table_id': table_id, 'year': 2018, 'semester': 1, } response = self.client.get('/timetable/api/share_calendar', params=params, name='share_calander') @task def google_auth_return(self): params = { 'state': 'some-valid-token', } response = self.client.get('/timetable/google_auth_return', params=params, name='google_auth_return') # review APIs @task def get_main(self): response= self.client.get("/main", name='get_main') self.csrf_token = response.cookies['csrftoken'] # print("TOKEN : ", self.csrf_token) @task def get_review(self): self.client.get("/review/", name='get_review') @task def refresh_review(self): self.client.get("/review/refresh/", name='refresh_review') @task def insert_review(self): self.client.get("/review/refresh/", name='insert_review') @task def get_credits(self): self.client.get("/credits", name='get_credits') @task def get_licenses(self): self.client.get("/licenses", name='get_licenses') @task def get_last_comment_json(self): params = { "filter": ["F"], } self.client.get(f"/review/json/{self.course_id}", params=params, name='get_last_comment_json') @task def get_comment(self): self.client.get(f"/review/result/comment/{self.course_id}", name='get_comment') @task def get_professor_review(self): self.client.get(f"/review/result/professor/{self.professor_id}/{self.course_id}", name='get_professor_review') @task def get_professor_review_json(self): self.client.get(f"/review/result/professor/{self.professor_id}/json/{self.course_id}/1/", name='get_professor_review_json') @task def get_course_review(self): self.client.get(f"/review/result/course/{self.course_id}/1/", name='get_course_review') @task def get_course_review_json(self): self.client.get(f"/review/result/course/{self.course_id}/1/json/1", name='get_course_review_json') @task def get_result(self): params = { "q": "논리적", # 키워드 "sort": "name", # "sort": "total", # "sort": "grade", # "sort": "load", # "sort": "speech", # "semester": 1, # "department": "", # "type": "", # "grade": "", } self.client.get("/review/result/", params=params, name='get_result') @task def get_result_json(self): params = { "q": "논리적", # 키워드 "sort": "name", # "sort": "total", # "sort": "grade", # "sort": "load", # "sort": "speech", # "semester": 1, # "department": "", # "type": "", # "grade": "", } self.client.get("/review/result/json/1/", params=params, name='get_result_json')
44,923
https://github.com/URIS-2021-2022/tim-5---fanray-tim-5-fanray/blob/master/test/Fan.Blog.Tests/Services/PageServiceTest.cs
Github Open Source
Open Source
Apache-2.0
2,021
tim-5---fanray-tim-5-fanray
URIS-2021-2022
C#
Code
659
1,984
using Fan.Blog.Data; using Fan.Blog.Enums; using Fan.Blog.Helpers; using Fan.Blog.Models; using Fan.Blog.Services; using Fan.Blog.Tests.Helpers; using Fan.Exceptions; using Fan.Settings; using Markdig; using MediatR; using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Moq; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using Xunit; namespace Fan.Blog.Tests.Services { public class PageServiceTest { private readonly PageService pageService; private readonly Mock<IPostRepository> postRepoMock = new Mock<IPostRepository>(); public PageServiceTest() { // cache, logger, mapper, mediatr var serviceProvider = new ServiceCollection().AddMemoryCache().AddLogging().BuildServiceProvider(); var cache = new MemoryDistributedCache(serviceProvider.GetService<IOptions<MemoryDistributedCacheOptions>>()); var logger = serviceProvider.GetService<ILoggerFactory>().CreateLogger<PageService>(); var mapper = BlogUtil.Mapper; var mediatorMock = new Mock<IMediator>(); // settings var settingSvcMock = new Mock<ISettingService>(); settingSvcMock.Setup(svc => svc.GetSettingsAsync<CoreSettings>()).Returns(Task.FromResult(new CoreSettings())); settingSvcMock.Setup(svc => svc.GetSettingsAsync<BlogSettings>()).Returns(Task.FromResult(new BlogSettings())); // service pageService = new PageService(settingSvcMock.Object, postRepoMock.Object, cache, logger, mapper, mediatorMock.Object); } [Fact] public async void CreateAsync_Page() { // Arrange // since the final step of CreateAsync is to call repo.GetAsync, // make it return a post postRepoMock.Setup(repo => repo.GetAsync(It.IsAny<int>(), EPostType.Page)) .Returns(Task.FromResult(new Post { Type = EPostType.Page, CreatedOn = DateTimeOffset.Now })); // Act // user creates a new page var pageCreated = await pageService.CreateAsync(new Page { UserId = Actor.ADMIN_ID, Title = "Test Page", Body = "<h1>Test Page</h1>\n", // html comes directly from editor BodyMark = "# Test Page", CreatedOn = DateTimeOffset.Now, Status = EPostStatus.Published, }); // Assert // repo.CreateAsync is called once with the following conditions postRepoMock.Verify(repo => repo.CreateAsync( It.Is<Post>(p => p.Slug == "test-page" && p.Excerpt == null)), Times.Once); // the date displays human friend string var coreSettings = new CoreSettings(); Assert.Equal("now", pageCreated.CreatedOn.ToDisplayString(coreSettings.TimeZoneId)); } [Fact] public async void Page_ValidateTitleAsync_draft_can_have_empty_title() { // When you have a draft with empty title var page = new Page { Title = "", Status = EPostStatus.Draft }; // Then its validation will not fail await page.ValidateTitleAsync(); } /// <summary> /// Slugs may get url encoded which may exceed max length, if that happens the slug is trimmed. /// </summary> [Fact] public void Page_with_Chinese_title_produces_UrlEncoded_slug_which_may_get_trimmed() { // Given a page title of 30 Chinese chars, which will translate into a slug over 250 // chars due to url encoding var pageTitle = string.Join("", Enumerable.Repeat<char>('验', 30)); var page = new Page { Title = pageTitle, }; // When the title is processed, I expect the slug to be 250 char as follows // '验' -> "%E9%AA%8C" 9 chars, 27 * 9 + 7 = 250 var expectedSlug = WebUtility.UrlEncode(string.Join("", Enumerable.Repeat<char>('验', 27))) + "%E9%AA%"; Assert.Equal(250, expectedSlug.Length); // Then the slug comes out to be 250 long Assert.Equal(expectedSlug, PageService.SlugifyPageTitle(page.Title)); } /// <summary> /// Page slug is calculated based on its title, on rare occassions a title could result in /// a conflict with an existing slug. /// </summary> [Fact] public async void Page_title_resulting_duplicate_slug_throws_FanException() { // Given a post slug with max length of 250 chars var slug = WebUtility.UrlEncode(string.Join("", Enumerable.Repeat<char>('验', 27))) + "%E9%AA%"; IList<Post> list = new List<Post> { new Post { Slug = slug, Type = EPostType.Page, Id = 1 }, }; postRepoMock.Setup(repo => repo.GetListAsync(It.IsAny<PostListQuery>())).Returns(Task.FromResult((list, 1))); // When create/update a page title that conflits the existing slug // Then you get FanException var givenTitle = string.Join("", Enumerable.Repeat<char>('验', 30)); var page = new Page { Title = givenTitle }; var slug2 = PageService.SlugifyPageTitle(page.Title); await Assert.ThrowsAsync<FanException>(() => pageService.EnsurePageSlugAsync(slug2, page)); } /// <summary> /// Unlike a blog post, user cannot specify a page slug because a parent page's navigation depends on /// its children's titles to calc their slugs. /// </summary> [Fact] public void Page_navigation_is_tranformed_to_HTML_based_on_child_page_titles() { var parentSlug = "docs"; var navMd = "- [[Getting Started]] \n- [[Deploy to Azure]]"; var actual = PageService.NavMdToHtml(navMd, parentSlug).Replace("\n", ""); var expected = @"<ul><li><a href=""/docs/getting-started"" title=""Getting Started"">Getting Started</a></li><li><a href=""/docs/deploy-to-azure"" title=""Deploy to Azure"">Deploy to Azure</a></li></ul>"; Assert.Equal(expected, actual); } /// <summary> /// Test convert source code md to html by Markdig library. /// </summary> /// <remarks> /// Currently this is not used as html is gotten directly from the editor preview. /// TODO try https://github.com/pauldotknopf/Pek.Markdig.HighlightJs /// </remarks> [Fact] public void SourceCode_markdown_is_tranformed_to_pre_code_html_by_Markdig() { var md = @"```cs var i = 5; ```"; var actual = Markdown.ToHtml(md).Replace("\n", ""); var expected = @"<pre><code class=""language-cs"">var i = 5;</code></pre>"; Assert.Equal(expected, actual); } } }
33,180
https://github.com/soumyadipdas37/finescoop.github.io/blob/master/cache/0fd03ccd14629dea10d8b80ffad78ef8aad874cb.php
Github Open Source
Open Source
MIT
null
finescoop.github.io
soumyadipdas37
PHP
Code
432
781
<?php $__env->startSection('content'); ?><p>The Queen was crippled by obsessive compulsive disorder as a child and used to line up her pencils in perfectly straight lines to feel 'safe,' a new book has claimed.</p> <p>A new book titled The Governess, released last month, has made the extraordinary claim about Britain's longest reigning monarch, 94.</p> <p>The book, listed as 'historical and biographical fiction,' on Amazon and Google Books, tells the story of Marion Crawford, who was Her Majesty's teacher when she was a young princess.</p> <p>The Governess claims a young Princess Elizabeth, pictured in 1940, showed signs of obsessive compulsive disorder, straightening up pencils and plates in order to feel 'safe'  </p> <p>An extract of the book shared by The Sun, reveals how Queen Elizabeth II would straighten up pencils and plates compulsively as a child. </p> <p>Wendy Holden's book reads: 'Marion, whose training encompassed child psychology, now realised she was looking at obsessive compulsion.'</p> <p>Challenged on why she aligned the items, Crawford wrote that the young Elizabeth replied: 'Because it makes me feel safe' </p> <p>The book claims Marion never received an answer from Queen Elizabeth II, as her mother walked in at that very moment</p> <p>'"Safe?" echoed Marion. "Safe from what?"'</p> <p>The book claims Marion never received an answer from the monarch-in-waiting, as the Queen's mother walked in at that very moment. </p> <p>Obsessive compulsive disorder, usually known as OCD, is a common mental health condition which makes people obsess over thoughts and develop behaviour they struggle to control.</p> <p>It can cause people to suffer with unpleasant, intrusive thoughts and they will often act on behaviours as a means of controlling the thoughts.</p> <p>The Governess by Wendy Holden was released last month.  </p> <p>Obsessive compulsive disorder, usually known as OCD, is a common mental health condition which makes people obsess over thoughts and develop behaviour they struggle to control.</p> <p>It can affect anyone at any age but normally develops during young adulthood.</p> <p>It can cause people to have repetitive unwanted or unpleasant thoughts.</p> <p>People may also develop compulsive behaviour – a physical action or something mental – which they do over and over to try to relieve the obsessive thoughts.</p> <p>The condition can be controlled and treatment usually involves psychological therapy or medication.  </p> <p>It is not known why OCD occurs but risk factors include a family history of the condition, certain differences in brain chemicals, or big life events like childbirth or bereavement. </p> <p>People who are naturally tidy, methodical or anxious are also more likely to develop it.</p> <p>Source: NHS </p> <?php $__env->stopSection(); ?> <?php echo $__env->make('_layouts.post', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
21,452
https://github.com/TanakaYasen/SyscallMon/blob/master/SyscallMonUI/symloaddialog.cpp
Github Open Source
Open Source
MIT
2,022
SyscallMon
TanakaYasen
C++
Code
309
2,134
#include "symloaddialog.h" #include "ui_symloaddialog.h" #include "EventMgr.h" #include "DriverWrapper.h" #include "ps.h" #include "nt.h" #include "util.h" SymLoadDialog::SymLoadDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SymLoadDialog) { ui->setupUi(this); setWindowFlags(Qt::Dialog | Qt::WindowCloseButtonHint); setAttribute(Qt::WA_DeleteOnClose); m_LoadState = LoadState::Idle; if(!IsVmxAvailable()) ui->checkBox_vmx->setEnabled(false); ui->checkBox_ps->setCheckState(Qt::CheckState::Checked); connect(m_ModuleMgr, &CModuleMgr::LoadAllImageCompleteNotify, this, &SymLoadDialog::OnLoadAllImageCompleteNotify); connect(m_ModuleMgr, &CModuleMgr::LoadingImageNotify, this, &SymLoadDialog::OnLoadingImageNotify, Qt::QueuedConnection); } SymLoadDialog::~SymLoadDialog() { delete ui; } //void SymLoadDialog::closeEvent(QCloseEvent *e) //{ /*if(m_LoadState != LoadState::Loaded) { e->ignore(); return; }*/ //SetProcessWorkingSetSize(GetCurrentProcess(), -1, -1); //} void SymLoadDialog::EnumSystemModuleProc(ULONG64 ImageBase, ULONG ImageSize, LPCWSTR szImagePath, int LoadOrderIndex) { UNREFERENCED_PARAMETER(ImageBase); UNREFERENCED_PARAMETER(ImageSize); if(LoadOrderIndex == 0) { std::wstring path; NormalizeFilePath(szImagePath, path); m_ModuleMgr->m_Path_ntoskrnl = path; m_ModuleMgr->LoadImageFromFile(path, ui->checkBox_ntoskrnl->isChecked(), true); return; } if(!wcsicmp(szImagePath, L"\\SystemRoot\\System32\\win32k.sys")) { std::wstring path; NormalizeFilePath(szImagePath, path); m_ModuleMgr->m_Path_win32k = path; m_ModuleMgr->LoadImageFromFile(path, ui->checkBox_win32k->isChecked(), true); return; } if(!wcsicmp(szImagePath, L"\\SystemRoot\\System32\\win32kFull.sys")) { std::wstring path; NormalizeFilePath(szImagePath, path); m_ModuleMgr->m_Path_win32kFull = path; m_ModuleMgr->LoadImageFromFile(path, ui->checkBox_win32kFull->isChecked(), true); return; } if(!wcsicmp(szImagePath, L"\\SystemRoot\\System32\\drivers\\fltmgr.sys")) { std::wstring path; NormalizeFilePath(szImagePath, path); m_ModuleMgr->m_Path_fltmgr = path; m_ModuleMgr->LoadImageFromFile(path, ui->checkBox_fltmgr->isChecked(), true); return; } } void SymLoadDialog::on_pushButton_load_clicked() { m_LoadState = LoadState::LoadingSymbol; ui->checkBox_ntoskrnl->setEnabled(false); ui->checkBox_win32k->setEnabled(false); ui->checkBox_win32kFull->setEnabled(false); ui->checkBox_ntdll->setEnabled(false); ui->checkBox_kernel32->setEnabled(false); ui->checkBox_kernelBase->setEnabled(false); ui->checkBox_user32->setEnabled(false); ui->checkBox_fltmgr->setEnabled(false); ui->pushButton_load->setEnabled(false); //drivers... EnumSystemModules(boost::bind(&SymLoadDialog::EnumSystemModuleProc, this, _1, _2, _3, _4)); std::wstring path; NormalizeFilePath(L"\\SystemRoot\\System32\\ntdll.dll", path); m_ModuleMgr->LoadImageFromFile(path, ui->checkBox_ntdll->isChecked(), false); NormalizeFilePath(L"\\SystemRoot\\System32\\kernel32.dll", path); m_ModuleMgr->LoadImageFromFile(path, ui->checkBox_kernel32->isChecked(), false); NormalizeFilePath(L"\\SystemRoot\\System32\\kernelBase.dll", path); m_ModuleMgr->LoadImageFromFile(path, ui->checkBox_kernelBase->isChecked(), false); NormalizeFilePath(L"\\SystemRoot\\System32\\user32.dll", path); m_ModuleMgr->LoadImageFromFile(path, ui->checkBox_user32->isChecked(), false); if(IsAMD64()) { NormalizeFilePath(L"\\SystemRoot\\SysWOW64\\ntdll.dll", path); m_ModuleMgr->LoadImageFromFile(path, ui->checkBox_ntdll->isChecked(), false); NormalizeFilePath(L"\\SystemRoot\\SysWOW64\\kernel32.dll", path); m_ModuleMgr->LoadImageFromFile(path, ui->checkBox_kernel32->isChecked(), false); NormalizeFilePath(L"\\SystemRoot\\SysWOW64\\kernelBase.dll", path); m_ModuleMgr->LoadImageFromFile(path, ui->checkBox_kernelBase->isChecked(), false); NormalizeFilePath(L"\\SystemRoot\\SysWOW64\\user32.dll", path); m_ModuleMgr->LoadImageFromFile(path, ui->checkBox_user32->isChecked(), false); } } void SymLoadDialog::OnLoadAllImageCompleteNotify(void) { //Write symbol file... std::wstring symPath; NormalizeFilePath(L"\\SystemRoot\\SyscallMonSymbol.dat", symPath); HANDLE hFile = CreateFile(symPath.c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, 0, NULL); if(hFile != INVALID_HANDLE_VALUE) { symbol_file_data data = {0}; data.txsb = 'TXSB'; data.ver = SYMBOL_FILE_VERSION; data.EnableVmx = ui->checkBox_vmx->isChecked() ? TRUE : FALSE; data.EnablePs = ui->checkBox_ps->isChecked() ? TRUE : FALSE; CUniqueImage *pWin32k = (m_ModuleMgr->m_Image_win32kFull) ? m_ModuleMgr->m_Image_win32kFull : m_ModuleMgr->m_Image_win32k; if(pWin32k) { data.NtUserSetWindowsHookExOffset = pWin32k->FindFunctionOffsetByName(std::string("NtUserSetWindowsHookEx")); data.NtUserSetWindowsHookAWOffset = pWin32k->FindFunctionOffsetByName(std::string("NtUserSetWindowsHookAW")); data.NtUserFindWindowExOffset = pWin32k->FindFunctionOffsetByName(std::string("NtUserFindWindowEx")); data.NtUserInternalGetWindowTextOffset = pWin32k->FindFunctionOffsetByName(std::string("NtUserInternalGetWindowText")); data.NtUserGetClassNameOffset = pWin32k->FindFunctionOffsetByName(std::string("NtUserGetClassName")); } else { OutputDebugStringW(symPath.c_str()); } DWORD dwWrite = 0; WriteFile(hFile, &data, sizeof(data), &dwWrite, NULL); CloseHandle(hFile); } m_LoadState = LoadState::Loaded; accept(); } void SymLoadDialog::OnLoadingImageNotify(std::wstring moduleName) { ui->label_loadingStatus->setText(tr("Loading symbol for %1...").arg(QString::fromStdWString(moduleName))); }
13,620
https://github.com/Don734/testapp/blob/master/resources/scss/includes/modules/others.sass
Github Open Source
Open Source
MIT
null
testapp
Don734
Sass
Code
219
798
.msg-error max-width: 450px width: 100% margin-top: 20px padding: 10px font-weight: bold box-shadow: 0 5px 10px rgba($color: $color-b, $alpha: 0.3) border-radius: 5px background: $color-w text-align: center .modalForm display: none position: fixed top: 50% left: 50% transform: translate(-50%, -50%) max-width: 450px width: 100% padding: 50px 25px margin-top: 55px box-shadow: 0 5px 10px rgba($color: $color-b, $alpha: 0.3) background: $color-w border-radius: 15px z-index: 2 .modalForm__close position: absolute top: 20px right: 20px background: transparent border: none outline: none cursor: pointer .modalForm__col display: flex flex-direction: column .modalForm__control width: 100% height: 35px padding-left: 20px margin: 10px 0 font-family: 'Montserrat', Arial, sans-serif font-size: 14px border: 1px solid rgba($color: $color-1, $alpha: 0.4) border-radius: 3px .modalForm__submit height: 40px margin-top: 30px font-family: 'Montserrat', Arial, sans-serif font-size: 16px color: $color-1 background: transparent border: 1px solid $color-1 border-radius: 3px cursor: pointer outline: none &:hover color: $color-w background: $color-1 span margin-bottom: 10px font-size: 12px color: $color-1 &.active display: block #modalAddGroup .modalForm__col .container margin-top: 30px .accordion__title display: flex justify-content: space-between align-items: center height: 40px padding: 10px color: $color-w background: $color-2 cursor: pointer .icon transition: .3s &.active .icon transform: rotate(180deg) .accordion__item display: none padding: 10px .dt-buttons position: absolute left: 130px .buttons-excel display: flex align-items: center padding: 10px 15px height: 40px font-family: 'Montserrat', Arial, sans-serif font-size: 16px color: $color-1 background: transparent border: 1px solid $color-2 border-radius: 3px cursor: pointer outline: none &:hover color: $color-w background: $color-2
5,652
https://github.com/gabrieldewes/Aulas-ED1/blob/master/src/Aula13/Elemento.java
Github Open Source
Open Source
MIT
null
Aulas-ED1
gabrieldewes
Java
Code
41
130
package Aula13; import java.util.Scanner; /** * Created by ramon on 10/05/16. */ public class Elemento { public String nome; public Elemento proximo; public void ler (){ System.out.println("Digite nome"); Scanner tc = new Scanner(System.in); this.nome=tc.next(); } public void mostrar(){ System.out.println(this.nome); } }
29,732
https://github.com/itzToxicGaming/Open-Cloud/blob/master/settings.gradle
Github Open Source
Open Source
MIT
2,018
Open-Cloud
itzToxicGaming
Gradle
Code
9
33
rootProject.name = "Open-Cloud" include ':Open-Container' include ':Open-Core' include ':Open-Master'
40,461
https://github.com/Chen-yu-Zheng/Semantic-segmentation-Tianchi/blob/master/dataset.py
Github Open Source
Open Source
MIT
null
Semantic-segmentation-Tianchi
Chen-yu-Zheng
Python
Code
274
1,126
from utils.figure import figureImgandMask import torch import cv2 from utils.rle2img import * import torchvision.transforms as T from torch.utils import data as D import configs import albumentations as A import pandas as pd import matplotlib.pyplot as plt class TianChiDataset(D.Dataset): def __init__(self, paths, rles, test_mode=False): self.paths = paths self.rles = rles self.test_mode = test_mode self.len = len(paths) self.transform = A.Compose([ A.Resize(configs.IMAGE_SIZE, configs.IMAGE_SIZE), # A.RandomCrop(configs.IMAGE_SIZE, configs.IMAGE_SIZE), A.HorizontalFlip(p=0.5), A.VerticalFlip(p=0.5), A.RandomRotate90(p=0.5) ]) self.transform_img = T.Compose([ T.ToTensor(), T.Normalize([0.40464398, 0.42690134, 0.39236653], [0.20213476, 0.18353915, 0.17596193]) ]) self.transform_mask = torch.tensor # get data operation def __getitem__(self, index): img = cv2.imread(self.paths[index]) #cv2 导入的是BGR形式 img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) if not self.test_mode: mask = rle_decode(self.rles[index]) augments = self.transform(image=img, mask=mask) # print('after alum') # plt.figure() # plt.subplot(121) # plt.imshow(augments['image']) # plt.subplot(122) # plt.imshow(augments['mask']) # plt.show() img = self.transform_img(augments['image']) mask = self.transform_mask(augments['mask']).float() # print('after transform') # figureImgandMask(img, mask, 1) return img, mask else: return self.transform_img(img), '' def __len__(self): """ Total number of samples in the dataset """ return self.len def get_TianchiDataset(): train_mask = pd.read_csv(configs.ROOT, sep='\t', names=['name', 'mask']) train_mask['name'] = train_mask['name'].apply(lambda x: 'data/train/' + x) train_mask['mask'] = train_mask['mask'].fillna('') dataset = TianChiDataset( train_mask['name'].values, train_mask['mask'].values, False ) return dataset def getStat(train_data): ''' Compute mean and variance for training data :param train_data: 自定义类Dataset(或ImageFolder即可) :return: (mean, std) ''' print('Compute mean and variance for training data.') print(len(train_data)) mean = torch.zeros(3) std = torch.zeros(3) for X, _ in train_data: for d in range(3): mean[d] += X[d, :, :].mean() std[d] += (X[d, :, :].pow(2)).sum() mean.div_(len(train_data)) std -= len(train_data) * configs.IMAGE_SIZE * configs.IMAGE_SIZE * mean.pow(2) std.div_(len(train_data) * configs.IMAGE_SIZE * configs.IMAGE_SIZE - 1) std.pow_(0.5) return list(mean.numpy()), list(std.numpy()) def main(): mean, std = getStat(get_TianchiDataset()) print(mean) print(std) if __name__ == '__main__': main() ''' [0.40464398, 0.42690134, 0.39236653] [0.20213476, 0.18353915, 0.17596193] '''
49,286
https://github.com/ticketmaster/cloud-custodian/blob/master/c7n/ufuncs/logsub.py
Github Open Source
Open Source
Apache-2.0
null
cloud-custodian
ticketmaster
Python
Code
367
1,032
# Copyright 2016 Capital One Services, LLC # # 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. """Ops feedback via log subscription """ from __future__ import absolute_import, division, print_function, unicode_literals import boto3 import base64 from datetime import datetime import json import textwrap import zlib config = logs = sns = None def init(): global sns, logs, config if sns is None: sns = boto3.client('sns') if logs is None: logs = boto3.client('logs') with open('config.json') as fh: config = json.load(fh) def message_event(evt): dt = datetime.fromtimestamp(evt['timestamp'] / 1000.0) return "%s: %s" % ( dt.ctime(), "\n".join(textwrap.wrap(evt['message'], 80))) def process_log_event(event, context): """Format log events and relay via sns/email""" init() serialized = event['awslogs'].pop('data') data = json.loads(zlib.decompress( base64.b64decode(serialized), 16 + zlib.MAX_WBITS)) # Fetch additional logs for context (20s window) timestamps = [e['timestamp'] for e in data['logEvents']] start = min(timestamps) - 1000 * 15 end = max(timestamps) + 1000 * 5 events = logs.get_log_events( logGroupName=data['logGroup'], logStreamName=data['logStream'], startTime=start, endTime=end, startFromHead=True)['events'] message = [ "An error was detected", "", "Log Group: %s" % data['logGroup'], "Log Stream: %s" % data['logStream'], "Log Owner: %s" % data['owner'], "", "Log Contents", ""] # We may get things delivered from log sub that are not in log events for evt in data['logEvents']: if evt not in events: events.append(evt) for evt in events: message.append(message_event(evt)) message.append("") params = dict( TopicArn=config['topic'], Subject=config['subject'], Message='\n'.join(message)) sns.publish(**params) def get_function(session_factory, name, role, sns_topic, log_groups, subject="Lambda Error", pattern="Traceback"): """Lambda function provisioning. Self contained within the component, to allow for easier reuse. """ # Lazy import to avoid runtime dependency from c7n.mu import ( LambdaFunction, PythonPackageArchive, CloudWatchLogSubscription) config = dict( name=name, handler='logsub.process_log_event', runtime='python2.7', memory_size=512, timeout=15, role=role, description='Custodian Ops Error Notify', events=[ CloudWatchLogSubscription( session_factory, log_groups, pattern)]) archive = PythonPackageArchive() archive.add_py_file(__file__) archive.add_contents( 'config.json', json.dumps({ 'topic': sns_topic, 'subject': subject })) archive.close() return LambdaFunction(config, archive)
29,654
https://github.com/agrz/karma-openui5/blob/master/karma.conf.js
Github Open Source
Open Source
Apache-2.0
null
karma-openui5
agrz
JavaScript
Code
212
1,007
module.exports = function(config) { config.set({ basePath: '', frameworks: ['openui5','qunit'], files: [{ pattern: 'bower_components/openui5-sap.ui.core/resources/**/*', served: true, included: false, watched: false }, { pattern: 'bower_components/openui5-sap.m/resources/**/*', served: true, included: false, watched: false }, { pattern: 'bower_components/openui5-sap.ui.layout/resources/**/*', served: true, included: false, watched: false }, { pattern: 'bower_components/openui5-themelib_sap_bluecrystal/resources/**/*', served: true, included: false, watched: false }, { pattern: 'WebContent/**/*', served: true, included: false, watched: true }, { pattern: 'WebContent/test/**/*.qunit.js', served: true, included: true, watched: true }], proxies: { "/base/WebContent/resources/": "/base/bower_components/openui5-sap.ui.core/resources/" }, openui5: { path: 'bower_components/openui5-sap.ui.core/resources/sap-ui-core.js', useMockServer: true }, client: { openui5: { config: { theme: 'sap_bluecrystal', libs: 'sap.m', resourceroots: { 'sap.m': '/base/bower_components/openui5-sap.m/resources/sap/m', 'sap.ui.layout': '/base/bower_components/openui5-sap.ui.layout/resources/sap/ui/layout', 'sap.ui': '/base/bower_components/openui5-sap.ui.core/resources/sap/ui', 'test': '/base/WebContent/test', 'sap.ui.demo.bulletinboard': '/base/WebContent', 'sap.ui.demo.bulletinboard.app' : '/base/WebContent/test/testService', 'sap.ui.demo.bulletinboard.test' : '/base/WebContent/test' }, themeroots: { 'sap_bluecrystal': '/base/bower_components/openui5-themelib_sap_bluecrystal/resources' } }, mockserver: { config: { autoRespond: true }, rootUri: '/data/', metadataURL: '/base/WebContent/localService/metadata.xml', mockdataSettings: {'sMockdataBaseUrl':'/base/WebContent/localService/mockdata/','bGenerateMissingMockData' : 'true'} } } }, reporters: ['progress','junit'], junitReporter: { outputDir: '', // results will be saved as $outputDir/$browserName.xml outputFile: undefined, // if included, results will be saved as $outputDir/$browserName/$outputFile suite: 'openui5', // suite will become the package name attribute in xml testsuite element useBrowserName: true // add browser name to report and classes names }, port: 9876, colors: true, logLevel: config.LOG_DEBUG, loggers: [{type:'console'}, { "type": "file", "filename": "karma.log", "maxLogSize": 20480, "backups": 3 } ], autoWatch: true, browsers: ['Chrome'], singleRun: false }); };
27,721
https://github.com/carnophager/node_modules/blob/master/intro_course/write_file.js
Github Open Source
Open Source
MIT
null
node_modules
carnophager
JavaScript
Code
20
69
const fs = require("fs") fs.writeFile('message.txt', 'Hello world', function(error_message) { if ( error_message ) { return console.error(error_message); } console.log("Writing finished!"); });
6,323
https://github.com/dbo1001/UBU-TFG-Medidor-estadistico-metajuego-Magic-The-Gathering/blob/master/src/java/Controlador/RegistroManagedBean.java
Github Open Source
Open Source
MIT
2,020
UBU-TFG-Medidor-estadistico-metajuego-Magic-The-Gathering
dbo1001
Java
Code
161
574
package Controlador; import Modelo.GestorBD; import Modelo.Usuario; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import javax.faces.context.FacesContext; @ManagedBean(name = "registroManagedBean") @RequestScoped public class RegistroManagedBean { private String nombre, clave, clave_repetir, correo, rol_solicitado; private ArrayList<String> roles; private GestorBD gestorBD; public RegistroManagedBean() { gestorBD = new GestorBD(); } public String getNombre() { return nombre; } public String getClave() { return clave; } public String getCorreo() { return correo; } public String getClave_repetir() { return clave_repetir; } public void setClave_repetir(String clave_repetir) { this.clave_repetir = clave_repetir; } public ArrayList<String> getRoles() { return roles; } public String getRol_solicitado() { return rol_solicitado; } public void setNombre(String nombre) { this.nombre = nombre; } public void setClave(String clave) { this.clave = clave; } public void setCorreo(String correo) { this.correo = correo; } public void setRoles(ArrayList<String> roles) { this.roles = roles; } public void setRol_solicitado(String rol_solicitado) { this.rol_solicitado = rol_solicitado; } public void carga_pagina_registro() { try { FacesContext.getCurrentInstance() .getExternalContext() .redirect(""); } catch (IOException e) { e.printStackTrace(); } } }
50,826
https://github.com/Fyrlex/bs/blob/master/src/typings/bot.ts
Github Open Source
Open Source
MIT
null
bs
Fyrlex
TypeScript
Code
68
176
import { ApplicationCommandOption } from 'discord.js'; import { BSClient } from '../lib/structures/BSClient.js'; export interface BSCommand { readonly name: string readonly comingSoon: boolean readonly description: string readonly dev: boolean readonly ephemeral: boolean readonly options: ApplicationCommandOption[] run: (client: BSClient, ...param: unknown[]) => Promise<unknown> } export interface BSEvent { readonly name: string run: (client: BSClient, ...param: unknown[]) => Promise<unknown> } export type BSEventNames = 'debug' | 'guildCreate' | 'interactionCreate' | 'ready';
22,853
https://github.com/Taiterbase/react-native-elements/blob/master/src/overlay/__tests__/Overlay.js
Github Open Source
Open Source
MIT
2,020
react-native-elements
Taiterbase
JavaScript
Code
153
494
import React from 'react'; import { Text } from 'react-native'; import { shallow } from 'enzyme'; import toJson from 'enzyme-to-json'; import { create } from 'react-test-renderer'; import { ThemeProvider } from '../../config'; import ThemedOverlay, { Overlay } from '../Overlay'; describe('Overlay', () => { it('should render without issues', () => { const component = shallow( <Overlay isVisible> <Text>I'm in an Overlay</Text> </Overlay> ); expect(component.length).toBe(1); expect(toJson(component)).toMatchSnapshot(); }); it('should render nothing if not visible', () => { const component = shallow( <Overlay isVisible={false}> <Text>I'm in an Overlay</Text> </Overlay> ); expect(component.getElement()).toBeFalsy(); expect(toJson(component)).toMatchSnapshot(); }); it('should be able to render fullscreen', () => { const component = shallow( <Overlay isVisible={true} fullScreen> <Text>I'm in an Overlay</Text> </Overlay> ); expect(toJson(component)).toMatchSnapshot(); }); it('should apply values from theme', () => { const theme = { Overlay: { windowBackgroundColor: 'green', }, }; const component = create( <ThemeProvider theme={theme}> <ThemedOverlay isVisible={true}> <Text>I'm in an Overlay</Text> </ThemedOverlay> </ThemeProvider> ); expect( component.root.children[0].children[0].children[0].children[0].props.style .backgroundColor ).toBe('green'); expect(component.toJSON()).toMatchSnapshot(); }); });
2,477
https://github.com/jordanwallwork/jello/blob/master/src/Jello/Nodes/TerminalNode.cs
Github Open Source
Open Source
MIT
2,014
jello
jordanwallwork
C#
Code
24
56
namespace Jello.Nodes { public abstract class TerminalNode<T> : Node<T> where T : class { public override INode GetSingleChild() { return null; } } }
28,204
https://github.com/Kreijeck/learning/blob/master/Python/zzz_training_challenge/Python_Challenge/solutions/ch04_strings/solutions/ex07_capitalize.py
Github Open Source
Open Source
MIT
null
learning
Kreijeck
Python
Code
188
681
# Beispielprogramm für das Buch "Python Challenge" # # Copyright 2020 by Michael Inden def capitalize(input): input_chars = list(input) capitalize_next_char = True for i, current_char in enumerate(input_chars): if current_char.isspace(): capitalize_next_char = True elif capitalize_next_char and current_char.isalpha(): input_chars[i] = current_char.upper() capitalize_next_char = False return "".join(input_chars) def capitalize_shorter(input): converted = [word[0].upper() + word[1:] for word in input.split()] return " ".join(converted) def capitalize_special(input): input_chars = list(input) capitalize_next_char = True for i, current_char in enumerate(input_chars): if current_char.isspace(): capitalize_next_char = True elif capitalize_next_char: input_chars[i] = current_char.upper() capitalize_next_char = False return "".join(input_chars) def capitalize_words(words): return [capitalize_word(word) for word in words] def capitalize_words_old(words): capitalized_words = [] for word in words: capitalized_words.append(capitalize_word(word)) return capitalized_words def capitalize_word(word): if not word: return "" return word[0].upper() + word[1:] def capitalize_special_2(words, ignorable_words): capitalized_words = [] for word in words: if word in ignorable_words: capitalized_words.append(word) else: capitalized_words.append(capitalize_word(word)) return capitalized_words def main(): print(capitalize("alles scheint in ordnung")) print(capitalize("Dies ist ein text")) print(capitalize("Dies \t ist ein text")) print(capitalize("what a wonderful day and feature")) print(capitalize_shorter("alles scheint in ordnung")) print(capitalize_shorter("Dies ist ein text")) print(capitalize_shorter("Dies \t ist ein text")) print(capitalize_word("micha el")) print(capitalize_word("")) print("Dies ist ein text".title()) print("what a wonderful day and feature".title()) if __name__ == "__main__": main()
48,111
https://github.com/adiwg/mdTranslator/blob/master/lib/adiwg/mdtranslator/writers/html/sections/html_verticalExtent.rb
Github Open Source
Open Source
Unlicense
2,022
mdTranslator
adiwg
Ruby
Code
121
424
# HTML writer # vertical extent # History: # Stan Smith 2017-04-04 refactored for mdTranslator 2.0 # Stan Smith 2015-04-03 original script require_relative 'html_spatialReference' module ADIWG module Mdtranslator module Writers module Html class Html_VerticalExtent def initialize(html) @html = html end def writeHtml(hExtent) # classes used referenceClass = Html_SpatialReference.new(@html) # vertical extent - description unless hExtent[:description].nil? @html.em('Description: ') @html.section(:class => 'block') do @html.text!(hExtent[:description]) end end # vertical extent - min value unless hExtent[:minValue].nil? @html.em('Minimum Value: ') @html.text!(hExtent[:minValue].to_s) @html.br end # vertical extent - max value unless hExtent[:maxValue].nil? @html.em('Maximum Value: ') @html.text!(hExtent[:maxValue].to_s) @html.br end # vertical extent - CRS ID {spatialReference} unless hExtent[:crsId].empty? @html.em('Reference System: ') @html.section(:class => 'block') do referenceClass.writeHtml(hExtent[:crsId]) end end end # writeHtml end # Html_VerticalExtent end end end end
31,630
https://github.com/GouvernementFR/dsfr/blob/master/src/core/style/color/function/_get-color-from-option.scss
Github Open Source
Open Source
MIT
2,022
dsfr
GouvernementFR
SCSS
Code
99
210
//// /// Core Function : Color get color from set /// @group core //// /// Obtenir une couleur depuis une combinaison /// @access private /// @param {String} $option - option de couleur (voir setting/options) /// @param {String} $space - espace de la couleur (hex, hue, saturation, lightness) /// @return {String} Retourne la couleur correspondante @function _get-color-from-option($option, $space: hex) { @if $space == hex { @return nth($option, 1); } @else if $space == hue { @return nth($option, 2); } @else if $space == saturation { @return nth($option, 3); } @else if $space == lightness { @return nth($option, 4); } }
24,026
https://github.com/Roney-juma/NoteBook-Flask/blob/master/app/models.py
Github Open Source
Open Source
MIT
2,021
NoteBook-Flask
Roney-juma
Python
Code
181
776
from enum import unique from flask_sqlalchemy.model import Model from . import db,login_manager from datetime import datetime from flask_login import UserMixin,current_user from werkzeug.security import generate_password_hash,check_password_hash @login_manager.user_loader def load_user(user_id): return User.query.get(user_id) class User(UserMixin,db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key = True) username = db.Column(db.String(255),unique = True,nullable = False) email = db.Column(db.String(255),unique = True,nullable = False) secure_password = db.Column(db.String(255),nullable = False) bio = db.Column(db.String(255)) profile_pic_path = db.Column(db.String()) notes = db.relationship('Note', backref='user', lazy='dynamic') @property def set_password(self): raise AttributeError('You cannot read the password attribute') @set_password.setter def password(self, password): self.secure_password = generate_password_hash(password) def verify_password(self, password): return check_password_hash(self.secure_password,password) def save_u(self): db.session.add(self) db.session.commit() def delete(self): db.session.delete(self) db.session.commit() def __repr__(self): return f'User {self.username}' class Note(db.Model): __tablename__ = 'notes' id = db.Column(db.Integer, primary_key = True) title = db.Column(db.String(255),nullable = False) content = db.Column(db.Text(), nullable = False) user_id = db.Column(db.Integer, db.ForeignKey('users.id')) time = db.Column(db.DateTime, default = datetime.utcnow) category = db.Column(db.String(255), index = True,nullable = False) def save(self): db.session.add(self) db.session.commit() def delete(self): db.session.delete(self) db.session.commit() def get_note(id): note = Note.query.filter_by(id=id).first() return note def __repr__(self): return f'Note {self.title}' class Subscriber(db.Model): __tablename__='subscribers' id=db.Column(db.Integer,primary_key=True) email = db.Column(db.String(255),unique=True,index=True) def save_subscriber(self): db.session.add(self) db.session.commit() def __repr__(self): return f'Subscriber {self.email}'
19,766
https://github.com/kanish671/goalert/blob/master/auth/authtoken/token_test.go
Github Open Source
Open Source
Apache-2.0
2,022
goalert
kanish671
Go
Code
340
1,375
package authtoken import ( "bytes" "encoding/base64" "encoding/binary" "testing" "time" uuid "github.com/satori/go.uuid" "github.com/stretchr/testify/assert" ) func TestToken_Version0(t *testing.T) { tok := &Token{ ID: uuid.UUID{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, } s, err := tok.Encode(nil) assert.NoError(t, err) // v0 integration keys are just a hex-encoded UUID assert.Equal(t, "01020304-0506-0708-090a-0b0c0d0e0f10", s) parsed, isOld, err := Parse(s, nil) assert.NoError(t, err) assert.False(t, isOld) assert.EqualValues(t, tok, parsed) } func TestToken_Version1(t *testing.T) { t.Run("encoding/decoding", func(t *testing.T) { tok := &Token{ Version: 1, ID: uuid.FromStringOrNil("a592fe16-edb5-45bb-a7d2-d109fae252bc"), Type: TypeSession, } s, err := tok.Encode(func(b []byte) ([]byte, error) { return []byte("sig"), nil }) assert.NoError(t, err) // v1 integration keys are just a hex-encoded UUID dec, err := base64.URLEncoding.DecodeString(s) assert.NoError(t, err) // should be valid base64 var exp bytes.Buffer exp.WriteByte('S') // Session key exp.Write(tok.ID.Bytes()) // ID exp.WriteString("sig") // Signature assert.Equal(t, exp.Bytes(), dec) parsed, isOld, err := Parse(s, func(typ Type, p, sig []byte) (bool, bool) { assert.Equal(t, TypeSession, typ) assert.Equal(t, exp.Bytes()[:exp.Len()-3], p) assert.Equal(t, []byte("sig"), sig) return true, true }) assert.NoError(t, err) assert.True(t, isOld) assert.EqualValues(t, tok, parsed) }) t.Run("existing key", func(t *testing.T) { const exampleKey = "U9obklyVC0wduWIy75nbivABDxwc-rANyqNA4CZQzhkJHuNlUCfJDPpcG6W9bEIPddqPbh-sxMS1Km87jC9yLASp3i1UWtdDu2udCzM=" parsed, isOld, err := Parse(exampleKey, func(Type, []byte, []byte) (bool, bool) { return true, true }) assert.NoError(t, err) assert.True(t, isOld) assert.EqualValues(t, &Token{ Type: TypeSession, Version: 1, ID: uuid.FromStringOrNil("da1b925c-950b-4c1d-b962-32ef99db8af0"), }, parsed) }) } func TestToken_Version2(t *testing.T) { tok := &Token{ Version: 2, Type: TypeCalSub, ID: uuid.UUID{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, CreatedAt: time.Unix(1337, 0), } s, err := tok.Encode(func(b []byte) ([]byte, error) { return []byte("sig"), nil }) assert.NoError(t, err) // v2 integration keys are just a hex-encoded UUID dec, err := b64Encoding.DecodeString(s) assert.NoError(t, err) // should be valid base64 var exp bytes.Buffer exp.WriteByte('V') // Versioned header flag exp.WriteByte(2) // version exp.WriteByte(byte(TypeCalSub)) // type exp.Write(tok.ID.Bytes()) // ID binary.Write(&exp, binary.BigEndian, uint64(tok.CreatedAt.Unix())) // CreatedAt exp.WriteString("sig") // Signature assert.Equal(t, exp.Bytes(), dec) parsed, isOld, err := Parse(s, func(typ Type, p, sig []byte) (bool, bool) { assert.Equal(t, TypeCalSub, typ) assert.Equal(t, exp.Bytes()[:exp.Len()-3], p) assert.Equal(t, sig, []byte("sig")) return true, true }) assert.NoError(t, err) assert.True(t, isOld) assert.EqualValues(t, tok, parsed) }
32,860
https://github.com/kaka-lin/kaka-configs/blob/master/configs/mac/zshrc
Github Open Source
Open Source
MIT
2,023
kaka-configs
kaka-lin
Shell
Code
575
2,109
# If you come from bash you might have to change your $PATH. # export PATH=$HOME/bin:/usr/local/bin:$PATH # gnome-terminal-colors-solarized # ~/.dir_colors/themefile #eval `gdircolors $HOME/.dir_colors/dircolors.256dark` eval `gdircolors $HOME/.dir_colors/dircolors.ansi-dark` if [ -n "$LS_COLORS" ]; then zstyle ':completion:*' list-colors "${(@s.:.)LS_COLORS}" fi # Path to your oh-my-zsh installation. export ZSH=/Users/kakalin/.oh-my-zsh # Set name of the theme to load. Optionally, if you set this to "random" # it'll load a random theme each time that oh-my-zsh is loaded. # See https://github.com/robbyrussell/oh-my-zsh/wiki/Themes ZSH_THEME="powerlevel9k/powerlevel9k" POWERLEVEL9K_MODE='nerdfont-complete' # Uncomment the following line to use case-sensitive completion. # CASE_SENSITIVE="true" # Uncomment the following line to use hyphen-insensitive completion. Case # sensitive completion must be off. _ and - will be interchangeable. # HYPHEN_INSENSITIVE="true" # Uncomment the following line to disable bi-weekly auto-update checks. # DISABLE_AUTO_UPDATE="true" # Uncomment the following line to change how often to auto-update (in days). # export UPDATE_ZSH_DAYS=13 # Uncomment the following line to disable colors in ls. # DISABLE_LS_COLORS="true" # Uncomment the following line to disable auto-setting terminal title. # DISABLE_AUTO_TITLE="true" # Uncomment the following line to enable command auto-correction. # ENABLE_CORRECTION="true" # Uncomment the following line to display red dots whilst waiting for completion. # COMPLETION_WAITING_DOTS="true" # Uncomment the following line if you want to disable marking untracked files # under VCS as dirty. This makes repository status check for large repositories # much, much faster. # DISABLE_UNTRACKED_FILES_DIRTY="true" # Uncomment the following line if you want to change the command execution time # stamp shown in the history command output. # The optional three formats: "mm/dd/yyyy"|"dd.mm.yyyy"|"yyyy-mm-dd" # HIST_STAMPS="mm/dd/yyyy" # Would you like to use another custom folder than $ZSH/custom? # ZSH_CUSTOM=/path/to/new-custom-folder # Which plugins would you like to load? (plugins can be found in ~/.oh-my-zsh/plugins/*) # Custom plugins may be added to ~/.oh-my-zsh/custom/plugins/ # Example format: plugins=(rails git textmate ruby lighthouse) # Add wisely, as too many plugins slow down shell startup. plugins=(git) source $ZSH/oh-my-zsh.sh # User configuration # export MANPATH="/usr/local/man:$MANPATH" # You may need to manually set your language environment # export LANG=en_US.UTF-8 # Preferred editor for local and remote sessions # if [[ -n $SSH_CONNECTION ]]; then # export EDITOR='vim' # else # export EDITOR='mvim' # fi # Compilation flags # export ARCHFLAGS="-arch x86_64" # ssh # export SSH_KEY_PATH="~/.ssh/rsa_id" # Set personal aliases, overriding those provided by oh-my-zsh libs, # plugins, and themes. Aliases can be placed here, though oh-my-zsh # users are encouraged to define aliases within the ZSH_CUSTOM folder. # For a full list of active aliases, run `alias`. # # Example aliases # alias zshconfig="mate ~/.zshrc" # alias ohmyzsh="mate ~/.oh-my-zsh" # ebook-converter export PATH=~/Applications/calibre.app/Contents/MacOS/:$PATH # Qt export PATH="/usr/local/opt/qt/bin:$PATH" # java export JAVA_HOME=$(/usr/libexec/java_home) export PATH=$PATH:$JAVA_HOME/bin export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar # Setting for the new UTF-8 terminal support in Lion export LC_CTYPE=en_US.UTF-8 export LC_ALL=en_US.UTF-8 ######################################################################################### # powerlevel9k: https://github.com/Powerlevel9k/powerlevel9k # Anaconda POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS=(anaconda battery) #POWERLEVEL9K_ANACONDA_RIGHT_DELIMITER='>' #POWERLEVEL9K_ANACONDA_LEFT_DELIMITER='<' POWERLEVEL9K_ANACONDA_BACKGROUND="clear" POWERLEVEL9K_ANACONDA_FOREGROUND="white" #POWERLEVEL9K_PYTHON_ICON='\ue63c' # Git POWERLEVEL9K_VCS_GIT_HOOKS=(vcs-detect-changes git-untracked git-aheadbehind git-remotebranch git-tagname) POWERLEVEL9K_VCS_GIT_ICON='\uf1d3' POWERLEVEL9K_VCS_GIT_GITHUB_ICON='\uf09b' POWERLEVEL9K_VCS_CLEAN_FOREGROUND='black' POWERLEVEL9K_VCS_CLEAN_BACKGROUND='green' POWERLEVEL9K_VCS_UNTRACKED_FOREGROUND='black' POWERLEVEL9K_VCS_UNTRACKED_BACKGROUND='yellow' #POWERLEVEL9K_VCS_MODIFIED_FOREGROUND='white' #POWERLEVEL9K_VCS_MODIFIED_BACKGROUND='black' POWERLEVEL9K_VCS_UNTRACKED_ICON='\u25CF' POWERLEVEL9K_VCS_UNSTAGED_ICON='\u00b1' POWERLEVEL9K_VCS_INCOMING_CHANGES_ICON='\u2193' POWERLEVEL9K_VCS_OUTGOING_CHANGES_ICON='\u2191' POWERLEVEL9K_VCS_COMMIT_ICON="\uf417" # command line 左邊想顯示的內容 #POWERLEVEL9K_LEFT_PROMPT_ELEMENTS=(context dir dir_writable vcs vi_mode) POWERLEVEL9K_LEFT_PROMPT_ELEMENTS=(anaconda user dir vcs) # command line 右邊想顯示的內容 #POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS=(status history ram load time) POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS=(status time) ######################################################################################### #Warning: Homebrew's sbin was not found in your PATH but you have installed #formulae that put executables in /usr/local/sbin. #Consider setting the PATH for example like so: export PATH="/usr/local/sbin:$PATH" # The next line updates PATH for the Google Cloud SDK. if [ -f '/Users/kakalin/opt/google-cloud-sdk/path.zsh.inc' ]; then . '/Users/kakalin/opt/google-cloud-sdk/path.zsh.inc'; fi # The next line enables shell command completion for gcloud. if [ -f '/Users/kakalin/opt/google-cloud-sdk/completion.zsh.inc' ]; then . '/Users/kakalin/opt/google-cloud-sdk/completion.zsh.inc'; fi
4,395
https://github.com/meltedlilacs/doodles/blob/master/build.rb
Github Open Source
Open Source
MIT
null
doodles
meltedlilacs
Ruby
Code
236
1,041
require "date" def dir_parts(dir) parts = dir.split("_") month = Date::MONTHNAMES.select { |m| !m.nil? && m.downcase.include?(parts[2]) }[0] { num: parts[1], month: month, day: parts[3], year: "20#{parts[4]}" } end def pretty_text_dir(dir) parts = dir_parts(dir) "day #{parts[:num]}: #{parts[:month]} #{parts[:day]}, #{parts[:year]}" end def pretty_html_dir(dir) parts = dir_parts(dir) "<a href='#{dir}/index.html' class='list_item'><div class='num'>#{parts[:num]}</div><div class='date'>#{parts[:month]} #{parts[:day]}, #{parts[:year]}</div></a>" end dirs = Dir.glob("*/").sort_by { |dir| dir_parts(dir)[:num].to_i }.reverse.map { |dir| dir.chomp '/' } count = dirs.size File.open("index.html", "w") do |homepage| homepage.write <<-eos <!DOCTYPE html> <html> <head> <meta charset='UTF-8'> <title>daily digital doodles doubtfully dueling depression</title> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <header> <div class='icon'>d6</div><div class='title'>daily digital doodles doubtfully dueling depression</div> </header> <main> eos dirs.each_with_index do |dir, i| File.open("#{dir}/index.html", "w") do |doodlepage| doodlepage.write <<-eos <!DOCTYPE html> <html> <head> <meta charset='UTF-8'> <title>daily digital doodles doubtfully dueling depression</title> <link rel="stylesheet" type="text/css" href="../style.css"> <script src='../processing.min.js'></script> <script src='../script.js'></script> </head> <body> <header> <div class='icon'>d6</div><div class='title'>#{pretty_text_dir(dir)}</div> </header> <main> eos doodlepage.write " <nav>" + (i < count-1 ? "<a href='../#{dirs[i+1]}/index.html' class='prev nav_item'>previous</a>" : "<s class='prev nav_item disabled'>previous</s>") + "<a href='../index.html' class='list nav_item'>list</a><a href='#' class='random nav_item'>random</a>" + (i > 0 ? "<a href='../#{dirs[i-1]}/index.html' class='next nav_item'>next</a>" : "<s class='next nav_item disabled'>next</s>") + "</nav>\n" doodlepage.write <<-eos <canvas data-processing-sources="#{dir}.pde"></canvas> </main> </body> </html> eos end homepage.write <<-eos #{pretty_html_dir(dir)} eos end homepage.write <<-eos </main> </body> </html> eos end File.open("script.js", "w") do |scriptpage| scriptpage.write <<-eos window.onload = function() { document.getElementsByClassName('random')[0].onclick = function() { var pages = new Array(#{dirs.map { |dir| "'../#{dir}/index.html'" }.join(", ")}); window.location = pages[Math.floor(Math.random() * pages.length)]; }; }; eos end
32,911
https://github.com/scokljat/instagram-clone-client/blob/master/src/App.js
Github Open Source
Open Source
MIT
null
instagram-clone-client
scokljat
JavaScript
Code
186
574
import { Route, Routes, useNavigate } from "react-router-dom"; import { useDispatch, useSelector } from "react-redux"; import { ChakraProvider, ColorModeScript, Button, Flex, } from "@chakra-ui/react"; import ThemeSwitcher from "./components/ThemeSwitcher"; import TheNavbar from "./components/TheNavbar"; import Login from "./pages/Login"; import Signup from "./pages/Signup"; import Home from "./pages/Home"; import Profile from "./pages/Profile"; import Error from "./pages/Error"; import EditProfile from "./pages/EditProfile"; import AppAlert from "./components/AppAlert"; import { logout } from "./actions/auth"; import { SET_ALERT } from "./constants/actionTypes"; function App() { const dispatch = useDispatch(); let navigate = useNavigate(); const isLoggedIn = useSelector((state) => state.authReducer.isLoggedIn); const handleLogout = () => { localStorage.removeItem("token"); dispatch(logout); navigate("/"); dispatch({ type: SET_ALERT, payload: "You are successfully logged out" }); }; return ( <ChakraProvider> <header> <Flex justifyContent="space-between"> <ColorModeScript initialColorMode="light" /> <ThemeSwitcher /> {isLoggedIn ? ( <Button onClick={handleLogout} margin={5}> Logout </Button> ) : ( " " )} </Flex> {isLoggedIn ? <TheNavbar /> : " "} <AppAlert /> </header> <main> <Routes> <Route exact path="/" element={<Login />} /> <Route path="/home" element={<Home />} /> <Route path="/signup" element={<Signup />} /> <Route path="/profile" element={<Profile />} /> <Route path="/edit-profile" element={<EditProfile />} /> <Route path="*" element={<Error />} /> </Routes> </main> </ChakraProvider> ); } export default App;
5,149
https://github.com/ZoltanTheHun/AppleII/blob/master/basic/zbudget.bas
Github Open Source
Open Source
BSD-3-Clause
null
AppleII
ZoltanTheHun
Visual Basic
Code
601
1,695
1 TEXT 10 PRINT "STARTING ZBUDGET 0.031" 15 ONERR GOTO 11000 21 BC=50:REM "MAX BOND COUNT" 22 SS=500:REM "MAX STOCK COUNT" 25 DIM AI$(50):REM "ID":REM "ARRAYS FOR BONDS" 26 DIM AC(50):REM "CAPITAL" 27 DIM AR(50):REM "RATE" 28 DIM AM(50):REM "MATURITY" 29 DIM AY(50):REM "YEARS TO MATURITY" 30 DIM AU$(50):REM "CURRENCY" 40 DIM ST$(500):REM "TICKER":REM "ARRAYS FOR STOCKS" 41 DIM SI(500):REM "BUY/SELL INDICATOR" 42 DIM SP(500):REM "PRICE" 43 DIM SQ(500):REM "QUANTITY" 44 DIM SD(500):REM "DATE" 45 DIM SC$(500):REM "CURRENCY" 46 PRINT "SO FAR OK" 50 CB=0:REM "CURRENT NUMBER OF BONDS" 51 CS=0:REM "CURRENT NUMBER OF STOCKS" 90 GOSUB 100 95 GOSUB 11000 100 REM "LOAD DB ROUTINE" 110 PRINT CHR$(4) "OPEN ZBUDGETDB" 120 PRINT CHR$(4) "READ ZBUDGETDB" 125 INPUT CB:REM "READ BOND DATA" 126 FOR I = 1 TO BC 127 INPUT AI$(I):INPUT AC(I):INPUT AR(I):INPUT AM(I):INPUT AY(I):INPUT AU$(I) 128 NEXT I 130 INPUT CS:REM "READ STOCK DATA" 131 FOR I = 1 TO SS 132 INPUT ST$(I):INPUT SI(I):INPUT SP(I):INPUT SQ(I):INPUT SD(I):INPUT SC$(I) 133 NEXT I 140 PRINT CHR$(4) "CLOSE ZBUDGETDB" 150 RETURN 200 REM "WRITE DB ROUTINE" 210 PRINT CHR$(4) "OPEN ZBUDGETDB" 220 PRINT CHR$(4) "WRITE ZBUDGETDB" 225 PRINT CB:REM "WRITE BOND DATA" 226 FOR I = 1 TO BC 227 PRINT AI$(I):PRINT AC(I):PRINT AR(I):PRINT AM(I):PRINT AY(I):PRINT AU$(I) 228 NEXT I 230 PRINT CS:REM "WRITE STOCK DATA" 231 FOR I = 1 TO SS 232 PRINT ST$(I):PRINT SI(I):PRINT SP(I):PRINT SQ(I):PRINT SD(I):PRINT SC$(I) 233 NEXT I 240 PRINT CHR$(4) "CLOSE ZBUDGETDB" 250 RETURN 300 REM "NEW INPUT ROUTINE" 301 HOME:POKE 37,17: CALL -922: CALL -998: POKE 36,0:PRINT "PLEASE ENTER WHICH LINE TO EDIT (1-10)" 303 INPUT "";LN:IF LN < 1 OR LN > 10 THEN PRINT "OUT OF RANGE":GOTO 301 304 GOSUB 700:PRINT "PLEASE ENTER ID(MAX 4 CHARACTER)":INPUT "";AI$(LN) 310 GOSUB 700:PRINT "PLEASE ENTER CAPITAL":INPUT "";AC(LN) 330 GOSUB 700:PRINT "PLEASE ENTER INTEREST":INPUT "";AR(LN) 350 GOSUB 700:PRINT "PLEASE ENTER MATURITY (FORMAT: YYYYMMDD)":INPUT "";AM(LN) 370 GOSUB 700:PRINT "PLEASE ENTER YEARS TO MATURITY":INPUT "";AY(LN) 390 RETURN 400 REM "DISPLAY INSTRUMENTS" 409 POKE 37,1: CALL -922: CALL -998: POKE 36,0:PRINT " !ID !CAPITAL!INTR!MATR !PAID" 410 TC=0:REM "TOTAL CAPITAL" 411 TP=0:REM "TOTAL PAID" 414 FOR I = 1 TO 10 415 POKE 37,I+1: CALL -922: CALL -998: POKE 36,0:PRINT I 416 POKE 37,I+1: CALL -922: CALL -998: POKE 36,2:PRINT "!"AI$(I) 420 POKE 37,I+1: CALL -922: CALL -998: POKE 36,7:PRINT "!"AC(I) 460 POKE 37,I+1: CALL -922: CALL -998: POKE 36,15:PRINT "!"AR(I) 465 POKE 37,I+1: CALL -922: CALL -998: POKE 36,20:PRINT "!"AM(I) 470 POKE 37,I+1: CALL -922: CALL -998: POKE 36,29:PRINT "!"AC(I)+AC(I)*AR(I)*AY(I) 471 TC=TC+AC(I):TP=TP+AC(I)+AC(I)*AR(I)*AY(I) 480 NEXT I 481 PRINT "":PRINT "TOTAL INVESTED: "TC:PRINT "TOTAL PAID : "TP:PRINT "TOTAL EARNED : "TP-TC 580 RETURN 700 REM "DISPLAY BOND DETAILS" 710 HOME:POKE 37,1: CALL -922: CALL -998: POKE 36,0:PRINT "BOND NAME: "AI$(LN) 720 PRINT "CAPITAL : "AC(LN):PRINT "RATE : "AR(LN):PRINT "MATURITY : "AM(LN):PRINT "YEARS : "AY(LN) 790 POKE 37,17: CALL -922: CALL -998: POKE 36,0 800 RETURN 1000 REM "DISPLAY BOND":PRINT "HIT ANY KEY TO RETURN":INPUT AA:RETURN 999 HOME:GOSUB 400:POKE 37,17: CALL -922: CALL -998: POKE 36,0 1020 INPUT "WHICH BOND TO BE DISPLAYED?";LN:GOSUB 710 1030 INPUT "HIT ANY KEY TO RETURN";AA 1500 RETURN 11000 HOME 11002 PRINT "ZBUDGET" 11003 GOSUB 400 11004 POKE 37,17: CALL -922: CALL -998: POKE 36,0 11010 PRINT "PLEASE SELECT FROM OPTIONS BELOW" 11040 PRINT "1) STORE INSTRUMENTS" 11050 PRINT "2) NEW INSTRUMENT" 11060 PRINT "3) SHOW DETAILS" 11080 PRINT "9) EXIT" 11090 INPUT OP 11120 IF OP = 1 THEN GOSUB 200 11130 IF OP = 2 THEN GOSUB 300 11140 IF OP = 3 THEN GOSUB 1000 11150 IF OP = 9 THEN GOSUB 20010 20000 GOTO 11000 20010 HOME 20015 PRINT "ERROR" 20020 END
38,469
https://github.com/Prashanth-Billa/Basic-IT-Ticket-management-CMS/blob/master/project_dbms/js/home.js
Github Open Source
Open Source
Apache-2.0
null
Basic-IT-Ticket-management-CMS
Prashanth-Billa
JavaScript
Code
221
1,223
$(document).ready(function() { //$("body").css("display", "none"); // $("body").fadeIn(200); $('#dattym').mouseover(function(){ $('#overlay').fadeIn('fast'); }); $("#cussearch").click(function () { $(".cus").toggle("medium"); return false; }); $(".op,.fd").css("opacity","0.6"); $(".op,.fd").hover(function () { $(this).stop().animate({ opacity: 1.0 }, "medium"); }, function () { $(this).stop().animate({ opacity: 0.6 }, "medium"); }); $("#opp1").mouseover(function () { $("#oppp1").animate({ opacity: 1.0 }, "medium"); }); $("#opp1").mouseout(function () { $("#oppp1").animate({ opacity: 0.6 }, "medium"); }); // $("#opp2").mouseover(function () { $("#oppp2").animate({ opacity: 1.0 }, "medium"); }); $("#opp2").mouseout(function () { $("#oppp2").animate({ opacity: 0.6 }, "medium"); }); // $("#opp3").mouseover(function () { $("#oppp3").animate({ opacity: 1.0 }, "medium"); }); $("#opp3").mouseout(function () { $("#oppp3").animate({ opacity: 0.6 }, "medium"); }); // $("#opp4").mouseover(function () { $("#oppp4").animate({ opacity: 1.0 }, "medium"); }); $("#opp4").mouseout(function () { $("#oppp4").animate({ opacity: 0.6 }, "medium"); }); $(".op").click(function () { $(".op").fadeOut("slow"); }); $(".op").click(function () { $(".op").fadeIn("slow"); }); $(".contactc").mouseover(function(){ $(this).fadeOut("fast"); $(this).fadeIn("fast"); }); }); function dat() { var d = new Date(); var curr_hour = d.getHours(); var curr_sec = d.getSeconds(); var suf="am"; if(curr_hour>12) { if(curr_hour==13) {curr_hour=1; suf="pm";} if(curr_hour==14) {curr_hour=2; suf="pm";} if(curr_hour==15) {curr_hour=3; suf="pm";} if(curr_hour==16) {curr_hour=4; suf="pm";} if(curr_hour==17) {curr_hour=5; suf="pm";} if(curr_hour==18) {curr_hour=6; suf="pm";} if(curr_hour==19) {curr_hour=7; suf="pm";} if(curr_hour==20) {curr_hour=8; suf="pm";} if(curr_hour==21) {curr_hour=9; suf="pm";} if(curr_hour==22) {curr_hour=10; suf="pm";} if(curr_hour==23) {curr_hour=11; suf="pm";} if(curr_hour==24) {curr_hour=12; suf="pm";} } var curr_min = d.getMinutes(); if(curr_min<10) { curr_min="0"+curr_min; } var week=d.getDay(); var weekd; if(week==0) weekd="Sunday"; if(week==1) weekd="Monday"; if(week==2) weekd="Tuesday"; if(week==3) weekd="Wednesday"; if(week==4) weekd="Thursday"; if(week==5) weekd="Friday"; if(week==6) weekd="Saturday"; document.getElementById('dattym').value=curr_hour+":"+curr_min+":"+curr_sec+" "+suf+" "+weekd; t=setTimeout('dat()',500); } function addbookmark(){ if (document.all) window.external.AddFavorite("http://localhost:8008/project_dbms/index.php","cluster fun home"); }
48,946
https://github.com/xuxiaowei007/balm/blob/master/src/example/java/net/sf/balm/example/web/protocal/PageExample.java
Github Open Source
Open Source
Apache-2.0
2,009
balm
xuxiaowei007
Java
Code
20
100
package net.sf.balm.example.web.protocal; import net.sf.balm.web.annotation.Uri; import org.springframework.context.annotation.Scope; @Uri("/example/protocal/page") @Scope("prototype") public class PageExample { public String execute() { return "page:/example/protocal/pagesuccess.jsp"; } }
17,382
https://github.com/xmlet/RegexApi/blob/master/src/main/java/org/xmlet/regexapi/IfGroupMatchThenExpression.java
Github Open Source
Open Source
MIT
2,019
RegexApi
xmlet
Java
Code
134
490
package org.xmlet.regexapi; import java.util.function.Consumer; public class IfGroupMatchThenExpression<Z extends Element> implements CustomAttributeGroup<IfGroupMatchThenExpression<Z>, Z> { protected final Z parent; protected final ElementVisitor visitor; public IfGroupMatchThenExpression(ElementVisitor visitor) { this.visitor = visitor; this.parent = null; } public IfGroupMatchThenExpression(Z parent) { this.parent = parent; this.visitor = parent.getVisitor(); } protected IfGroupMatchThenExpression(Z parent, ElementVisitor visitor, boolean shouldVisit) { this.parent = parent; this.visitor = visitor; } public Z __() { this.visitor.visitParentIfGroupMatchThenExpression(this); return this.parent; } public final IfGroupMatchThenExpression<Z> dynamic(Consumer<IfGroupMatchThenExpression<Z>> consumer) { this.visitor.visitOpenDynamic(); consumer.accept(this); this.visitor.visitCloseDynamic(); return this; } public final IfGroupMatchThenExpression<Z> of(Consumer<IfGroupMatchThenExpression<Z>> consumer) { consumer.accept(this); return this; } public Z getParent() { return this.parent; } public final ElementVisitor getVisitor() { return this.visitor; } public String getName() { return "ifGroupMatch"; } public final IfGroupMatchThenExpression<Z> self() { return this; } public IfGroupMatchComplete<Z> elseExpression(String elseExpression) { ((ElseExpression)(new ElseExpression(this, this.visitor, true)).text(elseExpression)).__(); return new IfGroupMatchComplete(this.parent, this.visitor, true); } }
3,155
https://github.com/tellurianinteractive/Tellurian.Trains.ModulesRegistryApp/blob/master/SourceCode/Data/ModulesDbContext.cs
Github Open Source
Open Source
MIT
2,022
Tellurian.Trains.ModulesRegistryApp
tellurianinteractive
C#
Code
1,533
8,252
using Microsoft.EntityFrameworkCore; #nullable disable namespace ModulesRegistry.Data { public partial class ModulesDbContext : DbContext { //public ModulesDbContext() { } public ModulesDbContext(DbContextOptions<ModulesDbContext> options) : base(options) { } public virtual DbSet<Cargo> Cargos { get; set; } public virtual DbSet<CargoDirection> CargoDirections { get; set; } public virtual DbSet<CargoReadyTime> CargoReadyTimes { get; set; } public virtual DbSet<CargoRelation> CargoRelations { get; set; } public virtual DbSet<QuantityUnit> CargoUnits { get; set; } public virtual DbSet<Country> Countries { get; set; } public virtual DbSet<Document> Documents { get; set; } public virtual DbSet<ExternalStation> ExternalStations { get; set; } public virtual DbSet<ExternalStationCustomer> ExternalStationCustomers { get; set; } public virtual DbSet<ExternalStationCustomerCargo> ExternalStationCustomerCargos { get; set; } public virtual DbSet<Group> Groups { get; set; } public virtual DbSet<GroupDomain> GroupDomains { get; set; } public virtual DbSet<GroupMember> GroupMembers { get; set; } public virtual DbSet<Layout> Layouts { get; set; } public virtual DbSet<LayoutLine> LayoutLines { get; set; } public virtual DbSet<LayoutModule> LayoutModules { get; set; } public virtual DbSet<LayoutStation> LayoutStations { get; set; } public virtual DbSet<Meeting> Meetings { get; set; } public virtual DbSet<MeetingParticipant> MeetingParticipants { get; set; } public virtual DbSet<Module> Modules { get; set; } public virtual DbSet<ModuleExit> ModuleExits { get; set; } public virtual DbSet<ModuleGableType> ModuleGableTypes { get; set; } public virtual DbSet<ModuleOwnership> ModuleOwnerships { get; set; } public virtual DbSet<ModuleStandard> ModuleStandards { get; set; } public virtual DbSet<NHM> NhmCodes { get; set; } public virtual DbSet<OperatingBasicDay> OperatingBasicDays { get; set; } public virtual DbSet<OperatingDay> OperatingDays { get; set; } public virtual DbSet<Operator> Operators { get; set; } public virtual DbSet<Person> People { get; set; } public virtual DbSet<Property> Properties { get; set; } public virtual DbSet<Region> Regions { get; set; } public virtual DbSet<Scale> Scales { get; set; } public virtual DbSet<Station> Stations { get; set; } public virtual DbSet<StationCustomer> StationCustomers { get; set; } public virtual DbSet<StationCustomerCargo> StationCustomerCargos { get; set; } public virtual DbSet<StationTrack> StationTracks { get; set; } public virtual DbSet<User> Users { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { optionsBuilder.UseSqlServer("Name=ConnectionStrings:TimetablePlanningDatabase", options => options.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery)); } } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.HasAnnotation("Relational:Collation", "Finnish_Swedish_CI_AS"); modelBuilder.Entity<Cargo>(entity => { entity.ToTable("Cargo"); entity.Property(e => e.DefaultClasses).HasMaxLength(10); entity.Property(e => e.NhmCode).HasColumnName("NHMCode"); entity.Property(e => e.EN) .HasMaxLength(50) .HasColumnName("EN"); entity.Property(e => e.DA) .HasMaxLength(50) .HasColumnName("DA"); entity.Property(e => e.DE) .HasMaxLength(50) .HasColumnName("DE"); entity.Property(e => e.NL) .HasMaxLength(50) .HasColumnName("NL"); entity.Property(e => e.NO) .HasMaxLength(50) .HasColumnName("NO"); entity.Property(e => e.PL) .HasMaxLength(50) .HasColumnName("PL"); entity.Property(e => e.SV) .HasMaxLength(50) .HasColumnName("SV"); entity.HasOne<NHM>() .WithMany() .HasForeignKey(e => e.NhmCode); }); modelBuilder.Entity<CargoDirection>(entity => { entity.ToTable("CargoDirection"); entity.Property(e => e.Id).ValueGeneratedNever(); entity.Property(e => e.FullName) .IsRequired() .HasMaxLength(10); entity.Property(e => e.ShortName) .IsRequired() .HasMaxLength(4); }); modelBuilder.Entity<CargoReadyTime>(entity => { entity.ToTable("CargoReadyTime"); entity.Property(e => e.FullName) .IsRequired() .HasMaxLength(20); entity.Property(e => e.ShortName) .IsRequired() .HasMaxLength(10); }); modelBuilder.Entity<CargoRelation>(entity => { entity.ToTable("CargoRelation"); entity.HasOne(d => d.OperatingDay) .WithMany() .HasForeignKey(d => d.OperatingDayId) .HasConstraintName("FK_CargoRelation_OperatingDay"); entity.HasOne(d => d.SupplierStationCustomerCargo) .WithMany() .HasForeignKey(d => d.SupplierStationCustomerCargoId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK_CargoRelation_CargoCustomer_Supplier"); entity.HasOne(d => d.ConsumerStationCustomerCargo) .WithMany() .HasForeignKey(d => d.ConsumerStationCustomerCargoId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK_CargoRelation_CargoCustomer_Consumer"); }); modelBuilder.Entity<QuantityUnit>(entity => { entity.ToTable("CargoUnit"); entity.Property(e => e.Designation) .IsRequired() .HasMaxLength(6); entity.Property(e => e.FullName) .IsRequired() .HasMaxLength(12); }); modelBuilder.Entity<Country>(entity => { entity.ToTable("Country"); entity.Property(e => e.DomainSuffix) .IsRequired() .HasMaxLength(2) .IsFixedLength(true); entity.Property(e => e.EnglishName) .IsRequired() .HasMaxLength(50); entity.Property(e => e.Languages) .HasMaxLength(10) .HasComment("A semicolon separated list of two-letter language codes."); }); modelBuilder.Entity<Document>(entity => { entity.ToTable("Document"); entity.Property(e => e.FileExtension) .IsRequired() .HasMaxLength(5) .IsFixedLength(true); }); modelBuilder.Entity<ExternalStation>(entity => { entity.ToTable("ExternalStation"); entity.Property(e => e.Note).HasMaxLength(20); entity.Property(e => e.FullName) .IsRequired() .HasMaxLength(50); entity.Property(e => e.Signature) .IsRequired() .HasMaxLength(6); entity.HasOne(d => d.Region) .WithMany(p => p.ExternalStations) .HasForeignKey(d => d.RegionId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK_ExternalStation_Region"); }); modelBuilder.Entity<ExternalStationCustomer>(entity => { entity.ToTable("ExternalStationCustomer"); entity.Property(e => e.CustomerName) .IsRequired() .HasMaxLength(50); entity.HasOne(d => d.ExternalStation) .WithMany(p => p.ExternalStationCustomers) .HasForeignKey(d => d.ExternalStationId) .HasConstraintName("FK_ExternalStationCustomer_ExternalStation"); }); modelBuilder.Entity<ExternalStationCustomerCargo>(entity => { entity.ToTable("ExternalStationCustomerCargo"); entity.Property(e => e.SpecialCargoName).HasMaxLength(20); entity.Property(e => e.SpecificWagonClass).HasMaxLength(10); entity.HasOne(e => e.Cargo) .WithMany() .HasForeignKey(d => d.CargoId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK_ExternalStationCustomerCargo_Cargo"); entity.HasOne(d => d.Direction) .WithMany() .HasForeignKey(d => d.DirectionId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK_ExternalStationCustomerCargo_CargoDirection"); entity.HasOne(d => d.ExternalStationCustomer) .WithMany(p => p.ExternalStationCustomerCargos) .HasForeignKey(d => d.ExternalStationCustomerId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK_ExternalStationCustomerCargo_StationCustomer"); entity.HasOne(d => d.OperatingDay) .WithMany() .HasForeignKey(d => d.OperatingDayId) .HasConstraintName("FK_ExternalStationCustomerCargo_OperatingDay"); entity.HasOne(e => e.QuantityUnit) .WithMany() .HasForeignKey(d => d.QuantityUnitId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK_ExternalStationCustomerCargo_QuantityUnit"); }); modelBuilder.Entity<Group>(entity => { entity.ToTable("Group"); entity.Property(e => e.Category) .IsRequired() .HasMaxLength(20); entity.Property(e => e.CityName).HasMaxLength(50); entity.Property(e => e.FullName) .IsRequired() .HasMaxLength(50); entity.Property(e => e.ShortName).HasMaxLength(10); entity.HasOne(d => d.Country) .WithMany(p => p.Groups) .HasForeignKey(d => d.CountryId) .OnDelete(DeleteBehavior.Restrict) .HasConstraintName("FK_Group_Country"); entity.HasOne(d => d.GroupDomain) .WithMany(p => p.Groups) .HasForeignKey(d => d.GroupDomainId) .OnDelete(DeleteBehavior.Restrict) .HasConstraintName("FK_Group_GroupDomain"); }); modelBuilder.Entity<GroupDomain>(entity => entity.ToTable("GroupDomain")); modelBuilder.Entity<GroupMember>(entity => { entity.ToTable("GroupMember"); entity.HasOne(d => d.Group) .WithMany(p => p.GroupMembers) .HasForeignKey(d => d.GroupId) .HasConstraintName("FK_GroupMember_Group"); entity.HasOne(d => d.Person) .WithMany(p => p.GroupMembers) .HasForeignKey(d => d.PersonId) .OnDelete(DeleteBehavior.NoAction) .HasConstraintName("FK_GroupMember_Person"); }); modelBuilder.Entity<Layout>(entity => { entity.Property(e => e.Note) .HasMaxLength(50); entity.ToTable("Layout"); entity.HasOne(d => d.Meeting) .WithMany(p => p.Layouts) .HasForeignKey(d => d.MeetingId) .OnDelete(DeleteBehavior.Cascade) .HasConstraintName("FK_Layout_Meeting"); entity.HasOne(d => d.ResponsibleGroup) .WithMany() .HasForeignKey(d => d.ResponsibleGroupId) .HasConstraintName("FK_Layout_Group"); entity.HasOne(d => d.PrimaryModuleStandard) .WithMany() .HasForeignKey(d => d.PrimaryModuleStandardId) .HasConstraintName("FK_Layout_ModuleStandard"); }); modelBuilder.Entity<LayoutLine>(entity => { entity.ToTable("LayoutLine"); entity.HasOne(e => e.Layout) .WithMany(e => e.LayoutLines) .OnDelete(DeleteBehavior.Cascade) .HasForeignKey(e => e.LayoutId); entity.HasOne(e => e.FromLayoutStation) .WithMany(e => e.StartingLines) .HasForeignKey(e => e.FromLayoutStationId) .HasConstraintName("FK_LayoutLine_FromLayoutStation"); entity.HasOne(e => e.FromStationExit) .WithMany() .HasForeignKey(e => e.FromStationExitId) .HasConstraintName("FK_LayoutLine_FromStationExit"); entity.HasOne(e => e.ToLayoutStation) .WithMany(e => e.EndingLines) .HasForeignKey(e => e.ToLayoutStationId) .HasConstraintName("FK_LayoutLine_ToLayoutStation"); entity.HasOne(e => e.ToStationExit) .WithMany() .HasForeignKey(e => e.ToStationExitId) .HasConstraintName("FK_LayoutLine_ToStationExit"); }); modelBuilder.Entity<LayoutModule>(entity => { entity.Property(e => e.Note) .HasMaxLength(50); entity.ToTable("LayoutModule"); entity.HasOne(e => e.Layout) .WithMany(e => e.LayoutModules) .HasForeignKey(e => e.LayoutId) .OnDelete(DeleteBehavior.Cascade) .HasConstraintName("FK_LayoutModule_Layout"); entity.HasOne(e => e.Module) .WithMany() .HasForeignKey(e => e.ModuleId) .HasConstraintName("FK_LayoutModule_Module"); entity.HasOne(e => e.Participant) .WithMany(e => e.LayoutModules) .HasForeignKey(e => e.ParticipantId) .HasConstraintName("FK_LayoutModule_Participant"); entity.HasOne(e => e.LayoutLine) .WithMany(e => e.Lines) .HasForeignKey(e => e.LayoutLineId) .HasConstraintName("FK_LayoutModule_LayoutLine"); entity.HasOne(e => e.LayoutStation) .WithMany(e => e.LayoutModules) .HasForeignKey(e => e.LayoutStationId) .HasConstraintName("FK_LayoutModule_LayoutStation"); }); modelBuilder.Entity<LayoutStation>(entity => { entity.Property(e => e.OtherName) .HasMaxLength(50); entity.Property(e => e.OtherSignature) .HasMaxLength(5); entity.ToTable("LayoutStation"); entity.HasOne(e => e.Layout) .WithMany(e => e.LayoutStations) .HasForeignKey(e => e.LayoutId) .OnDelete(DeleteBehavior.Cascade) .HasConstraintName("FK_LayoutStation_Layout"); entity.HasMany(e => e.Regions) .WithMany(e => e.LayoutStations); entity.HasOne(e => e.Station) .WithOne() .HasForeignKey<LayoutStation>(e => e.StationId) .HasConstraintName("FK_LayoutStation_Station"); entity.HasOne(e => e.OtherCountry) .WithOne() .HasForeignKey<LayoutStation>(e => e.OtherCountryId) .HasConstraintName("FK_LayoutStation_OtherCountry"); }); modelBuilder.Entity<Meeting>(entity => { entity.ToTable("Meeting"); entity.HasOne(d => d.OrganiserGroup) .WithMany() .HasForeignKey(d => d.OrganiserGroupId) .HasConstraintName("FK_Meeting_Group"); }); modelBuilder.Entity<MeetingParticipant>(entity => { entity.ToTable("MeetingParticipant"); entity.HasOne(d => d.Meeting) .WithMany(d => d.Participants) .HasForeignKey(d => d.MeetingId) .HasConstraintName("FK_MeetingParticipant_Meeting"); entity.HasOne(d => d.Person) .WithMany() .HasForeignKey(d => d.PersonId) .HasConstraintName("FK_MeetingParticipant_Person"); }); modelBuilder.Entity<Module>(entity => { entity.ToTable("Module"); entity.Property(e => e.ConfigurationLabel).HasMaxLength(10); entity.Property(e => e.FullName) .IsRequired() .HasMaxLength(50); entity.Property(e => e.Note).HasMaxLength(255); entity.Property(e => e.NumberOfThroughTracks).HasDefaultValueSql("((1))"); entity.Property(e => e.PackageLabel).HasMaxLength(10); entity.Property(e => e.Theme).HasMaxLength(50); entity.HasOne(d => d.DwgDrawing) .WithMany() .HasForeignKey(d => d.DwgDrawingId) .HasConstraintName("FK_Module_DwgDocument"); entity.HasOne(d => d.SkpDrawing) .WithMany() .HasForeignKey(d => d.SkpDrawingId) .HasConstraintName("FK_Module_SkpDocument"); entity.HasOne(d => d.PdfDocumentation) .WithMany() .HasForeignKey(d => d.PdfDocumentationId) .OnDelete(DeleteBehavior.Cascade) .HasConstraintName("FK_Module_PdfDocument"); entity.HasOne(d => d.Scale) .WithMany(p => p.Modules) .HasForeignKey(d => d.ScaleId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK_Module_Scale"); entity.HasOne(d => d.Station) .WithMany(p => p.Modules) .HasForeignKey(d => d.StationId) .OnDelete(DeleteBehavior.SetNull) .HasConstraintName("FK_Module_Station"); }); modelBuilder.Entity<ModuleExit>(entity => { entity.ToTable("ModuleExit"); entity.Property(e => e.Label) .IsRequired() .HasMaxLength(50); entity.HasOne(d => d.Module) .WithMany(p => p.ModuleExits) .HasForeignKey(d => d.ModuleId) .OnDelete(DeleteBehavior.Cascade) .HasConstraintName("FK_ModuleExit_Module"); entity.HasOne(d => d.GableType) .WithMany() .HasForeignKey(d => d.GableTypeId) .OnDelete(DeleteBehavior.NoAction) .HasConstraintName("FK_ModuleExit_ModuleGableType"); }); modelBuilder.Entity<ModuleGableType>(entity => { entity.ToTable("ModuleGableType"); entity.Property(e => e.Designation) .IsRequired(); entity.HasOne(d => d.Scale) .WithMany() .HasForeignKey(d => d.ScaleId) .OnDelete(DeleteBehavior.Restrict) .HasConstraintName("FK_ModuleGableType_Scale"); entity.HasOne(d => d.PdfDocument) .WithMany() .HasForeignKey(d => d.PdfDocumentId) .OnDelete(DeleteBehavior.Cascade) .HasConstraintName("FK_ModuleGableType_Document"); }); modelBuilder.Entity<ModuleOwnership>(entity => { entity.ToTable("ModuleOwnership"); entity.Property(e => e.GroupId).HasComment("Owning organisation (if null, a Person must own it)"); entity.Property(e => e.OwnedShare) .HasDefaultValueSql("((1))") .HasComment("The ownerships share as 1/this value."); entity.Property(e => e.PersonId).HasComment("Owning person (if null, an Organisation must own it)"); entity.HasOne(d => d.Group) .WithMany(p => p.ModuleOwnerships) .HasForeignKey(d => d.GroupId) .HasConstraintName("FK_ModuleOwnership_Group"); entity.HasOne(d => d.Module) .WithMany(p => p.ModuleOwnerships) .HasForeignKey(d => d.ModuleId) .HasConstraintName("FK_ModuleOwnership_Module"); entity.HasOne(d => d.Person) .WithMany(p => p.ModuleOwnerships) .HasForeignKey(d => d.PersonId) .HasConstraintName("FK_ModuleOwnership_Person"); }); modelBuilder.Entity<ModuleStandard>(entity => { entity.ToTable("ModuleStandard"); entity.Property(e => e.AcceptedNorm).HasMaxLength(255); entity.Property(e => e.Couplings).HasMaxLength(20); entity.Property(e => e.Electricity).HasMaxLength(20); entity.Property(e => e.PreferredTheme).HasMaxLength(20); entity.Property(e => e.ShortName).HasMaxLength(10); entity.Property(e => e.TrackSystem).HasMaxLength(20); entity.Property(e => e.Wheelset).HasMaxLength(50); entity.HasOne(d => d.Scale) .WithMany(p => p.ModuleStandards) .HasForeignKey(d => d.ScaleId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK_ModuleStandard_Scale"); }); modelBuilder.Entity<NHM>(entity => entity.ToTable("NHM")); modelBuilder.Entity<OperatingBasicDay>(entity => { entity.HasKey(e => new { e.OperatingDayId, e.BasicDayId }) .HasName("PK_OperatingDayId_BasicDayId"); entity.ToTable("OperatingBasicDay"); entity.HasOne(d => d.BasicDay) .WithMany(p => p.OperatingBasicDayBasicDays) .HasForeignKey(d => d.BasicDayId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK_OperatingBasicDay_BasicDays"); entity.HasOne(d => d.OperatingDay) .WithMany(p => p.OperatingBasicDayOperatingDays) .HasForeignKey(d => d.OperatingDayId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK_OperatingBasicDay_OperatingDays"); }); modelBuilder.Entity<OperatingDay>(entity => { entity.ToTable("OperatingDay"); entity.Property(e => e.Id).ValueGeneratedNever(); entity.Property(e => e.FullName) .IsRequired() .HasMaxLength(50); entity.Property(e => e.ShortName) .IsRequired() .HasMaxLength(10); }); modelBuilder.Entity<Operator>(entity => { entity.ToTable("Operator"); entity.Property(e => e.FullName) .IsRequired() .HasMaxLength(50); entity.Property(e => e.Signature) .IsRequired() .HasMaxLength(6); }); modelBuilder.Entity<Person>(entity => { entity.ToTable("Person"); entity.Property(e => e.CityName).HasMaxLength(50); entity.Property(e => e.EmailAddresses).HasMaxLength(50); entity.Property(e => e.FirstName) .IsRequired() .HasMaxLength(50); entity.Property(e => e.FremoOwnerSignature).HasMaxLength(10); entity.Property(e => e.LastName) .IsRequired() .HasMaxLength(50); entity.Property(e => e.MiddleName).HasMaxLength(50); entity.HasOne(d => d.Country) .WithMany(p => p.People) .HasForeignKey(d => d.CountryId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK_Person_Country"); entity.HasOne(d => d.User) .WithOne(p => p.Person) .HasForeignKey<Person>(d => d.UserId) .HasConstraintName("FK_Person_User"); }); modelBuilder.Entity<Property>(entity => { entity.ToTable("Property"); entity.HasIndex(e => new { e.Name, e.Value }, "IX_Property_Unique") .IsUnique(); entity.Property(e => e.Name) .IsRequired() .HasMaxLength(50); entity.Property(e => e.Value) .IsRequired() .HasMaxLength(50); }); modelBuilder.Entity<Region>(entity => { entity.ToTable("Region"); entity.Property(e => e.BackColor) .IsRequired() .HasMaxLength(10); entity.Property(e => e.ColourName) .HasMaxLength(10); entity.Property(e => e.EnglishName) .HasMaxLength(50); entity.Property(e => e.ForeColor) .IsRequired() .HasMaxLength(10); entity.Property(e => e.LocalName) .IsRequired() .HasMaxLength(50); entity.HasOne(d => d.Country) .WithMany(p => p.Regions) .HasForeignKey(d => d.CountryId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK_Region_Country"); }); modelBuilder.Entity<Scale>(entity => { entity.ToTable("Scale"); entity.Property(e => e.ShortName) .IsRequired() .HasMaxLength(10); }); modelBuilder.Entity<Station>(entity => { entity.ToTable("Station"); entity.Property(e => e.FullName) .IsRequired() .HasMaxLength(50); entity.Property(e => e.Signature) .IsRequired() .HasMaxLength(5); entity.HasOne(d => d.Region) .WithMany(p => p.Stations) .HasForeignKey(d => d.RegionId) .HasConstraintName("FK_Station_Region"); }); modelBuilder.Entity<StationCustomer>(entity => { entity.ToTable("StationCustomer"); entity.Property(e => e.Comment) .HasMaxLength(50) .IsUnicode(false); entity.Property(e => e.CustomerName) .IsRequired() .HasMaxLength(50) .IsUnicode(false); entity.Property(e => e.TrackOrArea).HasMaxLength(50); entity.Property(e => e.TrackOrAreaColor) .HasMaxLength(10) .IsFixedLength(true); entity.HasOne(d => d.Station) .WithMany(p => p.StationCustomers) .HasForeignKey(d => d.StationId) .HasConstraintName("FK_StationCustomer_Station"); }); _ = modelBuilder.Entity<StationCustomerCargo>(entity => { entity.ToTable("StationCustomerCargo"); entity.Property(e => e.QuantityUnitId).HasDefaultValueSql("((4))"); entity.Property(e => e.SpecialCargoName).HasMaxLength(20); entity.Property(e => e.TrackOrArea).HasMaxLength(10); entity.Property(e => e.TrackOrAreaColor) .HasMaxLength(10) .IsFixedLength(true); entity.Property(e => e.SpecificWagonClass).HasMaxLength(10); entity.HasOne(e => e.Cargo) .WithMany() .HasForeignKey(d => d.CargoId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK_CargoCustomer_Cargo"); entity.HasOne(d => d.Direction) .WithMany() .HasForeignKey(d => d.DirectionId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK_CargoCustomer_CargoDirection"); entity.HasOne(d => d.OperatingDay) .WithMany() .HasForeignKey(d => d.OperatingDayId) .HasConstraintName("FK_CargoCustomer_OperatingDay"); entity.HasOne(d => d.ReadyTime) .WithMany() .HasForeignKey(d => d.ReadyTimeId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK_CargoCustomer_CargoReadyTime"); entity.HasOne(d => d.StationCustomer) .WithMany(p => p.StationCustomerCargos) .HasForeignKey(d => d.StationCustomerId) .HasConstraintName("FK_CargoCustomer_StationCustomer") .OnDelete(DeleteBehavior.Cascade); entity.HasOne(e => e.QuantityUnit) .WithMany() .HasForeignKey(d => d.QuantityUnitId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK_StationCustomerCargo_QuantityUnit"); }); modelBuilder.Entity<StationTrack>(entity => { entity.ToTable("StationTrack"); entity.Property(e => e.Designation) .IsRequired() .HasMaxLength(5); entity.Property(e => e.UsageNote).HasMaxLength(20); entity.HasOne(d => d.Station) .WithMany(p => p.StationTracks) .HasForeignKey(d => d.StationId) .HasConstraintName("FK_StationTrack_Station"); }); modelBuilder.Entity<User>(entity => { entity.ToTable("User"); entity.HasIndex(e => e.EmailAddress, "IX_User_EmailAddress") .IsUnique(); entity.Property(e => e.EmailAddress) .IsRequired() .HasMaxLength(255); entity.Property(e => e.HashedPassword).HasMaxLength(255); entity.Property(e => e.RegistrationTime).HasDefaultValueSql("(getdate())"); }); OnModelCreatingPartial(modelBuilder); } partial void OnModelCreatingPartial(ModelBuilder modelBuilder); } }
29,644
https://github.com/parisk/nbg-python-sdk/blob/master/nbg/auth/signature_test.py
Github Open Source
Open Source
Apache-2.0
null
nbg-python-sdk
parisk
Python
Code
195
776
from unittest import mock import os import pytest from . import signature @pytest.fixture def client(): return signature.SignedClientMixin() def test_nbg_certificate(client): """ Ensure that the signed client always returns the appropriate NBG certificate. """ current_dir = os.path.dirname(__file__) certs_dir = os.path.join(current_dir, "certs") client.production = True with open(os.path.join(certs_dir, "nbg-qseal-production.cer"), "rb") as certificate: assert client.nbg_certificate == certificate.read() client.production = False with open(os.path.join(certs_dir, "nbg-qseal-sandbox.cer"), "rb") as certificate: assert client.nbg_certificate == certificate.read() def test_tpp_certificate(client): """ Ensure that the TPP certificate can be set and read successfully on the client via a public method and property accordingly. """ tpp_certificate = "this-should-be-a-tpp-certificate" client.set_tpp_certificate(tpp_certificate) assert client.tpp_certificate == tpp_certificate def test_tpp_private_key(client): """ Ensure that the TPP private_key can be set and read successfully on the client via a public method and property accordingly. """ tpp_private_key = "secret-key" client.set_tpp_private_key(tpp_private_key) assert client.tpp_private_key == tpp_private_key def test_signature_headers(client): """ Ensure that `SignedClientMixin` generates the appropriate HTTP headers for the provided request body. """ request_body = {} jws_signature = "some_header.some_payload.some_signature" jws_detached_signature = "some_header..some_signature" tpp_private_key = "secret-key" tpp_certificate = "this-is-a-certificate" expected_signature_headers = { "X-Certificate-Check": "true", "TPP-Signature-Certificate": tpp_certificate, "Signature": jws_detached_signature, } client.set_tpp_private_key(tpp_private_key) client.set_tpp_certificate(tpp_certificate) with mock.patch("nbg.auth.signature.SignedClientMixin.signing_enabled", True): with mock.patch("jose.jws.sign", return_value=jws_signature) as sign_mock: signature_headers = client.signature_headers(request_body) sign_mock.assert_called_once_with( request_body, tpp_private_key, algorithm="RS256", ) assert signature_headers == expected_signature_headers
14,279
https://github.com/akorda/Mp3Effects/blob/master/src/Mp3Effects.CLI/Program.cs
Github Open Source
Open Source
MIT
null
Mp3Effects
akorda
C#
Code
95
284
using System; using System.Collections.Generic; using System.Linq; using CommandLine; using Mp3Effects.Options; using Mp3Effects.UI; namespace Mp3Effects { class Program { static int Main(string[] args) { var result = Parser.Default.ParseArguments<CommandLineOptions>(args).MapResult(options => { return Run(options); }, errors => -1); return result; } private static int Run(IEffectsOptions options) { if (options.Semitones == 0) { Console.WriteLine("Changing the pitch by 0 semitones does not alter the original audio. Skipping."); return 0; } try { using (var progressBar = new ProgressBarProgressNotifier()) { var pipeline = new AudioPipeline(progressBar); pipeline.ApplyEffects(options); } return 0; } catch (Exception ex) { Console.WriteLine(ex.Message); return -1; } } } }
47,991
https://github.com/jvmf1/arduino-blink-c/blob/master/blink.c
Github Open Source
Open Source
MIT
2,022
arduino-blink-c
jvmf1
C
Code
49
149
#include <avr/io.h> #include <util/delay.h> #include <stdbool.h> #define DELAY 1000 int main() { // Put B5 in output mode DDRB |= (1 << DDB5); while (true) { // Set B5 HIGH PORTB |= (1 << DDB5); _delay_ms(DELAY); // Set B5 LOW PORTB &= ~ (1 << DDB5); _delay_ms(DELAY); } }
18,522
https://github.com/psyll0n/bash_scripts/blob/master/bash_simple_menu.sh
Github Open Source
Open Source
MIT
null
bash_scripts
psyll0n
Shell
Code
80
182
#!/bin/bash # bash_simple_menu.sh - Demonstrates how a menu can be built with 'while' loop and 'case' definitions. function create_directory() { declare -l directory read -p "Enter a directory name: " directory mkdir "$directory" } while true ; do clear echo "Choose from the menu below: " echo "1: List users." echo "2: Create a directory." echo "3: Quit" read -sn1 case "$REPLY" in 1) who;; 2) create_directory;;\ 3) exit 0;; esac read -n1 -p "Press any key to continue" done
21,863
https://github.com/ChoiChangYong/Game_Programing/blob/master/WinAPI/WinAPI_180202_Mouse/WinAPI_180202_Mouse/XY.cpp
Github Open Source
Open Source
MIT
null
Game_Programing
ChoiChangYong
C++
Code
95
341
#include "XY.h" void XY::setXY_Start(int x, int y) { m_iX_Start = x; m_iY_Start = y; } void XY::setXY_End(int x, int y) { m_iX_End = x; m_iY_End = y; } int XY::getX_Start() { return m_iX_Start; } int XY::getX_End() { return m_iX_End; } int XY::getY_Start() { return m_iY_Start; } int XY::getY_End() { return m_iY_End; } XY::XY() { m_iX_Start = 0; m_iY_Start = 0; m_iX_End = 0; m_iY_End = 0; } XY::~XY() { } /* void XY::setXY(int x_s, int y_s, int x_e, int y_e) { m_iX_Start = x_s; m_iY_Start = y_s; m_iX_End = x_e; m_iY_End = y_e; } */
37,361
https://github.com/jianlong108/WebView/blob/master/wkwebviewDemo/wkwebviewDemo/DataBaseCell.h
Github Open Source
Open Source
MIT
null
WebView
jianlong108
C
Code
50
179
// // DataBaseCell.h // wkwebviewDemo // // Created by Wangjianlong on 2017/1/11. // Copyright © 2017年 JL. All rights reserved. // #import <UIKit/UIKit.h> @class Betcompany,DataBaseCell; @protocol DataBaseCellDelegate <NSObject> @optional - (void)cell:(DataBaseCell *)cell ClickDetailBtn:(NSString *)str; @end @interface DataBaseCell : UITableViewCell /**数据*/ @property (nonatomic, strong)Betcompany *model; /**<#说明#>*/ @property (nonatomic, weak)id<DataBaseCellDelegate> delegate; @end
41,084
https://github.com/kishoremn/natural/blob/master/src/main/java/com/kb/natural/service/SubCategoryService.java
Github Open Source
Open Source
Apache-2.0
2,018
natural
kishoremn
Java
Code
108
266
package com.kb.natural.service; import com.kb.natural.domain.SubCategory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; /** * Service Interface for managing SubCategory. */ public interface SubCategoryService { /** * Save a subCategory. * * @param subCategory the entity to save * @return the persisted entity */ SubCategory save(SubCategory subCategory); /** * Get all the subCategories. * * @param pageable the pagination information * @return the list of entities */ Page<SubCategory> findAll(Pageable pageable); /** * Get the "id" subCategory. * * @param id the id of the entity * @return the entity */ SubCategory findOne(Long id); /** * Delete the "id" subCategory. * * @param id the id of the entity */ void delete(Long id); }
17,226
https://github.com/Seanstoppable/apidoc/blob/master/core/src/test/scala/core/ImporterSpec.scala
Github Open Source
Open Source
MIT
null
apidoc
Seanstoppable
Scala
Code
174
585
package core import com.bryzek.apidoc.spec.v0.models.{Application, Organization, Import} import org.scalatest.{FunSpec, Matchers} class ImporterSpec extends FunSpec with Matchers { describe("with an invalid service") { val json = """ { "name": "Import Shared", "apidoc": { "version": "0.9.6" } } """ val path = TestHelper.writeToTempFile(json) val imp = Importer(FileServiceFetcher(), s"file://$path") imp.validate.size should be > 0 } describe("with a valid service") { val json = """ { "name": "Import Shared", "apidoc": { "version": "0.9.6" }, "organization": { "key": "test" }, "application": { "key": "import-shared" }, "namespace": "test.apidoc.import-shared", "version": "1.0.0", "attributes": [], "imports": [], "headers": [], "unions": [], "enums": [], "resources": [], "info": {}, "models": [ { "name": "user", "plural": "users", "fields": [ { "name": "id", "type": "long", "required": true, "attributes": [] } ], "attributes": [] } ] } """ it("parses service") { val path = TestHelper.writeToTempFile(json) val imp = Importer(FileServiceFetcher(), s"file://$path") imp.validate should be(Seq.empty) val service = imp.service service.name should be("Import Shared") service.organization should be(Organization(key = "test")) service.application should be(Application(key = "import-shared")) service.namespace should be("test.apidoc.import-shared") service.models.map(_.name) should be(Seq("user")) val user = service.models.find(_.name == "user").get user.fields.map(_.name) should be(Seq("id")) } } }
9,507
https://github.com/MWPainter/Spectral-Image-Analysis-for-Medical-Imaging/blob/master/.gitignore
Github Open Source
Open Source
Apache-2.0
2,016
Spectral-Image-Analysis-for-Medical-Imaging
MWPainter
Ignore List
Code
74
202
.icon? /image (1)/ /Data Part1.1/ /Teng Images/ /Reading (additional papers)/ /Spectral Image Analysis for Medical Imaging/SIC.jar /Spectral Image Analysis for Medical Imaging/bin/ /Spectral Image Analysis for Medical Imaging/demo/ /Spectral Image Analysis for Medical Imaging/Encog apidocs/ /Spectral Image Analysis for Medical Imaging/boofcv* /Spectral Image Analysis for Medical Imaging/Data Sets/ /Spectral Image Analysis for Medical Imaging/Spectral Image Analysis for Medical Imaging.iml icon /Reading* /Siri Test/ /Spectral Image Analysis for Medical Imaging/encog-core-3.3.0-release.zip /Documentation/Dissertation Example/ /Documentation/Dissertation CL Example/
26,275
https://github.com/anthonykempka/Integrity-Instruments-Products/blob/master/Software/Windows/DataAquisitionUtilities/USBM300 Class/USBM300.cpp
Github Open Source
Open Source
BSD-3-Clause
null
Integrity-Instruments-Products
anthonykempka
C++
Code
3,086
9,741
/////////////////////////////////////////////////////////////////////////////////////////////////// // // USBM300.cpp: implementation of the USBM300 class. // // Copyright (c) 2003, Integrity Instruments, Inc. // // 1-800-450-2001 // // http://www.integrityusa.com // /////////////////////////////////////////////////////////////////////////////////////////////////// // // Version 1.4 // Moved code to library form // #include <windows.h> #include <stdio.h> #include <stdarg.h> #include "USBM300.h" // // Setup API stuff. // // NOTE: You must have the SDK include and library paths defined in Visual Studio // #include <setupapi.h> // // USBM300 IOCTL and GUID includes // #include "devioctl.h" #include "guid_usbm300.h" #include "ioctl_usbm300.h" // // Setup API library. Inform linker to use "SetupAPI.lib" library // #pragma comment(lib,"SetupAPI.lib") #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif CHAR sCopyrightNotification[] = "Copyright (c) 2003-2004, Integrity Instruments, Inc."; /////////////////////////////////////////////////////////////////////////////////////////////////// // DbgOut // // Prints a variable argument debug string to the debugger // Use like printf().. For example: DbgOut("Output string index = %i\n", i); // // Parameters // ---------- // FormatString Format string like printf // ... Variable argument list // VOID DbgOut(LPSTR FormatString, ...) { TCHAR szString[1024]; va_list ap; va_start(ap, FormatString); _vsnprintf(szString, 1024, FormatString, ap); OutputDebugString(szString); va_end(ap); return; } ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// USBM300::USBM300() { DWORD i; // Dump out class version GetClassVersion(); // Initialize device structures for (i=0; i<MAX_USBM300_DEVICES; i++) { // NULL device name and handle m_sDeviceName[i] = NULL; m_hDevice[i] = INVALID_HANDLE_VALUE; // Zero out thread handle and ID m_hStreamThread[i] = INVALID_HANDLE_VALUE; m_dwStreamThreadId[i] = 0; // // Initial thread control settings // m_UsbStreamCtrl[i].dwDeviceIndex = 0; m_UsbStreamCtrl[i].hUsbDevice = INVALID_HANDLE_VALUE; m_UsbStreamCtrl[i].dwUsbStreamingState = USB_THREAD_NOT_STARTED; m_UsbStreamCtrl[i].dwStreamThreadIoError = 0; m_UsbStreamCtrl[i].dwQueueBlocksToAllocate = 0; m_UsbStreamCtrl[i].hDataReadyEvent = NULL; m_UsbStreamCtrl[i].lQueueCount = 0; m_UsbStreamCtrl[i].pQueue = NULL; m_UsbStreamCtrl[i].pHead = NULL; m_UsbStreamCtrl[i].pTail = NULL; } m_dwUSBM300DeviceCount = 0; // Perform the initial USBM300 device enumeration Enum_USBM300_Devices(); return; } USBM300::~USBM300() { DbgOut("USBM300 destructor called. Bye!\n"); // Free all memory and handles FreeMemoryAndHandles(); return; } /////////////////////////////////////////////////////////////////////////////////////////////////// // Returns version number of the class // // Arguments: // ----------- // none // // Return Value: // -------------- // 0xAAAABBBB Class version vAAAA.BBBB // ULONG USBM300::GetClassVersion() { // Version 1.4 // Major version is upper 16 bits // Minor version is lower 16 bits // ULONG ulVersion = 0x00010004; ULONG ulMajorVersion, ulMinorVersion; ulMajorVersion = ((ulVersion & 0xFFFF0000) >> 16); ulMinorVersion = (ulVersion & 0x0000FFFF); DbgOut("USBM300 Class version %i.%i\n", ulMajorVersion, ulMinorVersion); DbgOut("%s\n", sCopyrightNotification); return (ulVersion); } /////////////////////////////////////////////////////////////////////////////////////////////////// // Free memory and handles used. // // NOTE: All streaming threads are stopped as a result of this function // void USBM300::FreeMemoryAndHandles() { DWORD i; for (i=0; i<MAX_USBM300_DEVICES; i++) { // TODO: Stop all stream threads // Close all thread handles if (m_hStreamThread[i] != INVALID_HANDLE_VALUE) { CloseHandle(m_hStreamThread[i]); m_hStreamThread[i] = INVALID_HANDLE_VALUE; } // Free all device names if (m_sDeviceName[i] != NULL) { free(m_sDeviceName[i]); m_sDeviceName[i] = NULL; } // Close all device handles if (m_hDevice[i] != INVALID_HANDLE_VALUE) { CloseHandle(m_hDevice[i]); m_hDevice[i] = INVALID_HANDLE_VALUE; } } return; } /////////////////////////////////////////////////////////////////////////////////////////////////// // Enumerates all USBM300 devices currently connected to the system. // // NOTE: All streaming threads are stopped as a result of this function // void USBM300::Enum_USBM300_Devices() { HDEVINFO hDevInfo; SP_INTERFACE_DEVICE_DATA DeviceInterfaceData; ULONG i=0; PSP_INTERFACE_DEVICE_DETAIL_DATA DeviceInterfaceDetailData = NULL; ULONG predictedLength = 0; ULONG requiredLength = 0; ULONG DeviceIndex = 0; ULONG DeviceNameLength; // Free all strings, close all handles, etc. FreeMemoryAndHandles(); // // Get the USBM300 device list // hDevInfo = SetupDiGetClassDevs ((LPGUID)&GUID_CLASS_USBM400, NULL, // Define no enumerator (global) NULL, // Define no (DIGCF_PRESENT | // Only Devices present DIGCF_INTERFACEDEVICE)); // Function class devices. if (hDevInfo == INVALID_HANDLE_VALUE) { return; } // // Loop through each device in the enumeration list // DeviceInterfaceData.cbSize = sizeof(DeviceInterfaceData); for(i=0; SetupDiEnumDeviceInterfaces (hDevInfo, 0, // No care about specific PDOs (LPGUID)&GUID_CLASS_USBM400, i, // &DeviceInterfaceData); i++ ) { // // Establish the required structure length for the DeviceInterfaceData // SetupDiGetInterfaceDeviceDetail ( hDevInfo, &DeviceInterfaceData, NULL, // probing so no output buffer yet 0, // probing so output buffer length of zero &requiredLength, NULL); // not interested in the specific dev-node predictedLength = requiredLength; DeviceInterfaceDetailData = (PSP_INTERFACE_DEVICE_DETAIL_DATA)malloc(predictedLength); DeviceInterfaceDetailData->cbSize = sizeof (SP_INTERFACE_DEVICE_DETAIL_DATA); // // Retrieve the information from Plug and Play. // if (SetupDiGetInterfaceDeviceDetail ( hDevInfo, &DeviceInterfaceData, DeviceInterfaceDetailData, predictedLength, &requiredLength, NULL)) { // // Save off the device path - the name used in CreateFile() // DeviceNameLength = strlen(DeviceInterfaceDetailData->DevicePath) + 2; m_sDeviceName[DeviceIndex] = (LPSTR)malloc(DeviceNameLength); ZeroMemory(m_sDeviceName[DeviceIndex], DeviceNameLength); strcpy(m_sDeviceName[DeviceIndex], DeviceInterfaceDetailData->DevicePath); // Open the device OpenDevice(DeviceIndex); DeviceIndex++; } free(DeviceInterfaceDetailData); } // Save off new device count m_dwUSBM300DeviceCount = DeviceIndex; DbgOut("%i USBM300 devices found.\n", m_dwUSBM300DeviceCount); // Free setup memory SetupDiDestroyDeviceInfoList (hDevInfo); return; } /////////////////////////////////////////////////////////////////////////////////////////////////// // Opens a handle to the USBM300 device // // Arguments: // ----------- // dwDeviceIndex Zero based USBM300 device index // // Return Value: // -------------- // TRUE Success // FAIL Error // BOOLEAN USBM300::OpenDevice(DWORD dwDeviceIndex) { // Device index range check if (dwDeviceIndex > MAX_USBM300_DEVICES) { DbgOut("Error opening USBM300 device. Index %i out of range.\n", dwDeviceIndex); return (FALSE); } // Is there a device name associated with this index if (m_sDeviceName[dwDeviceIndex] == NULL) { DbgOut("Error opening USBM300 device. Index %i has NULL device name.\n", dwDeviceIndex); return (FALSE); } // Close the device handle, if already opened if (m_hDevice[dwDeviceIndex] != INVALID_HANDLE_VALUE) { CloseHandle(m_hDevice[dwDeviceIndex]); m_hDevice[dwDeviceIndex] = INVALID_HANDLE_VALUE; } m_hDevice[dwDeviceIndex] = CreateFile ( m_sDeviceName[dwDeviceIndex], GENERIC_READ | GENERIC_WRITE, 0, // FIX: v1.2 No share -- was FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, // no SECURITY_ATTRIBUTES structure OPEN_EXISTING, // No special create flags FILE_ATTRIBUTE_NORMAL, // No special attributes NULL); // No template file if (m_hDevice[dwDeviceIndex] == INVALID_HANDLE_VALUE) { DbgOut("Error opening USBM300 device index %i name %s\n", dwDeviceIndex, m_sDeviceName[dwDeviceIndex]); return (FALSE); } else { DbgOut("Opened USBM300 device index %i with handle 0x%08X\n", dwDeviceIndex, m_hDevice[dwDeviceIndex]); } return (TRUE); } /////////////////////////////////////////////////////////////////////////////////////////////////// // 'C' Interface - needed by UsbThread // // Sends a command and returns the response. // // Arguments: // ----------- // hDevice Handle to opened USBM300 device // sCmd Command string to send to module // sResp Response received from module // // Return Value: // -------------- // TRUE Success // FAIL Error // BOOLEAN C_SendCommand(HANDLE hDevice, LPSTR sCmd, LPSTR sResp) { PVOID pDataBuffer = NULL; PCHAR pcCommand; PCHAR pOutBuffer; PULONG pulPipeNumber; DWORD dwBytesReturned; DWORD dwLength; BOOLEAN bStatus; DWORD dwError; // Check for valid device handle if (hDevice == INVALID_HANDLE_VALUE) { DbgOut("Error sending USBM300 command. Handle %i is invalid.\n", hDevice); return (FALSE); } dwLength = strlen(sCmd); // Check for zero length command if (dwLength == 0) { strncpy(sResp, "no data", MAX_CMD_RESP); return (TRUE); } // FIX: v1.2 Check command length too long if (dwLength > 7) { DbgOut("Error sending USBM300 command. Command too long %i\n", dwLength); strncpy(sResp, "no data", MAX_CMD_RESP); return (FALSE); } // Allocate device I/O buffers pDataBuffer = malloc(1024); pOutBuffer = (PCHAR)malloc (1024); ZeroMemory(pDataBuffer, 1024); ZeroMemory(pOutBuffer, 1024); // // Copy the command string into the data buffer and send to USB device // pulPipeNumber = (PULONG)pDataBuffer; *pulPipeNumber = 1; // PIPE1: Host PC->PIC pcCommand = (PCHAR)pDataBuffer+4; strncpy(pcCommand, sCmd, MAX_CMD_RESP); dwLength = 4 + strlen(sCmd); bStatus = DeviceIoControl(hDevice, IOCTL_Eval_BULK_WRITE, pDataBuffer, dwLength, NULL, 0, &dwBytesReturned, NULL); if (!bStatus) { // Error dwError = GetLastError(); DbgOut("Error sending USBM300 command. Handle %i DeviceIoControl error code %i.\n", hDevice, dwError); free(pDataBuffer); free(pOutBuffer); return (FALSE); } // // Receive any data // ZeroMemory(pDataBuffer, 1024); ZeroMemory(pOutBuffer, 1024); pulPipeNumber = (PULONG)pDataBuffer; *pulPipeNumber = 0; // PIPE0: PIC->Host PC bStatus = DeviceIoControl(hDevice, IOCTL_Eval_BULK_OR_INTERRUPT_READ, pDataBuffer, 4, pOutBuffer, 20, &dwBytesReturned, NULL); if (!bStatus) { // Error dwError = GetLastError(); DbgOut("Error receiving USBM300 response. Handle %i DeviceIoControl error code %i.\n", hDevice, dwError); free(pDataBuffer); free(pOutBuffer); return (FALSE); } // Save response off pOutBuffer[dwBytesReturned] = 0; // Null terminate strncpy(sResp, pOutBuffer, MAX_CMD_RESP); // Cleanup free(pDataBuffer); free(pOutBuffer); return (TRUE); } /////////////////////////////////////////////////////////////////////////////////////////////////// // Sends a command and returns the response. // // Arguments: // ----------- // dwDeviceIndex Zero based USBM300 device index // sCmd Command string to send to module // sResp Response received from module // // Return Value: // -------------- // TRUE Success // FAIL Error // BOOLEAN USBM300::SendCommand(DWORD dwDeviceIndex, LPSTR sCmd, LPSTR sResp) { BOOLEAN bStatus; // Device index range check if (dwDeviceIndex > MAX_USBM300_DEVICES) { DbgOut("Error sending USBM300 command. Index %i out of range.\n", dwDeviceIndex); return (FALSE); } // Check for valid device handle if (m_hDevice[dwDeviceIndex] == INVALID_HANDLE_VALUE) { DbgOut("Error sending USBM300 command. Index %i handle is invalid.\n", dwDeviceIndex); return (FALSE); } // Send the command bStatus = ::C_SendCommand(m_hDevice[dwDeviceIndex], sCmd, sResp); return (bStatus); } /////////////////////////////////////////////////////////////////////////////////////////////////// // Obtains the module address for a given device by reading EEPROM address 0x00 // // Arguments: // ----------- // dwDeviceIndex Zero based USBM300 device index // // Return Value: // -------------- // -1 No module address found // 0...255 Module address // LONG USBM300::GetModuleAddress(DWORD dwDeviceIndex) { CHAR sCmd[MAX_CMD_RESP]; CHAR sResp[MAX_CMD_RESP]; // UCHAR ucModuleAddress; LONG lModuleAddress = 0; // Device index range check if (dwDeviceIndex > MAX_USBM300_DEVICES) { DbgOut("GetModuleAddress failed. Index %i out of range.\n", dwDeviceIndex); return (-1); } // Check for valid device handle if (m_hDevice[dwDeviceIndex] == INVALID_HANDLE_VALUE) { DbgOut("GetModuleAddress failed. Index %i handle is invalid.\n", dwDeviceIndex); return (-1); } // Zero out the command and response buffers ZeroMemory(sCmd, MAX_CMD_RESP); ZeroMemory(sResp, MAX_CMD_RESP); // Send the Read EEPROM address 0 command strcpy(sCmd, "R00"); if (SendCommand(dwDeviceIndex, sCmd, sResp)) { //if (sscanf(&sResp[1], "%x", &ucModuleAddress) == 1) { if (sscanf(&sResp[1], "%x", &lModuleAddress) == 1) { //lModuleAddress = ucModuleAddress; return (lModuleAddress); } else { // sscanf(0 error DbgOut("GetModuleAddress failed. sscanf failure\n"); return (-1); } } else { // SendCommand error DbgOut("GetModuleAddress failed. SendCommand failure.\n"); return (-1); } } /////////////////////////////////////////////////////////////////////////////////////////////////// // Determines if a duplicate module address is present among the USBM300 devices currently // attached to the system. // // Arguments: // ----------- // none // // Return Value: // -------------- // TRUE Duplicate module address found in modules currently attached // FAIL Not duplicate module address found // BOOLEAN USBM300::DuplicateAddressPresent() { ULONG i, j; PLONG pAddresses; BOOLEAN bDuplicateFound = FALSE; // Alocate a buffer for the module addresses pAddresses = (PLONG)malloc(sizeof(LONG)*m_dwUSBM300DeviceCount); // Get the module addresses for (i=0; i<m_dwUSBM300DeviceCount; i++) { pAddresses[i] = GetModuleAddress(i); } // Check for a duplicate for (i=0; i<m_dwUSBM300DeviceCount; i++) { for (j=0; j<m_dwUSBM300DeviceCount; j++) { // Look for mathing address in locations other than the current if (i != j) { // Match found if (pAddresses[i] == pAddresses[j]) { bDuplicateFound = TRUE; } } } } // Cleanup free(pAddresses); return(bDuplicateFound); } /////////////////////////////////////////////////////////////////////////////////////////////////// // USBM300 stream mode thread // // DWORD WINAPI UsbStreamThread(LPVOID lpParameter) { PVOID pDataBuffer = NULL; PUSHORT pOutBuffer; PULONG pulPipeNumber; DWORD dwBytesReturned; BOOLEAN bStatus; DWORD dwError = 0; DWORD dwCount = 0; DWORD dwStartTime, dwEndTime, i; CHAR sCmd[MAX_CMD_RESP]; CHAR sResp[MAX_CMD_RESP]; // Parameter block PUSB_STREAM_CONTROL pUsbCtrl = (PUSB_STREAM_CONTROL)lpParameter; DbgOut ("UsbStreamThread device index %i started\n", pUsbCtrl->dwDeviceIndex); // Clear the command and response buffers ZeroMemory(sCmd, MAX_CMD_RESP); ZeroMemory(sResp, MAX_CMD_RESP); // Allocate the queue buffer pUsbCtrl->pQueue = (PUSBM300_STREAM_BLOCK_QUEUE)malloc(pUsbCtrl->dwQueueBlocksToAllocate * sizeof(USBM300_STREAM_BLOCK_QUEUE)); // Setup the queue element pointers for (i=0; i < (pUsbCtrl->dwQueueBlocksToAllocate-1); i++) { pUsbCtrl->pQueue[i].NextElement = &pUsbCtrl->pQueue[i+1]; } pUsbCtrl->pQueue[i].NextElement = &pUsbCtrl->pQueue[0]; // Head and tail to start of queue pUsbCtrl->pHead = &pUsbCtrl->pQueue[0]; pUsbCtrl->pTail = &pUsbCtrl->pQueue[0]; // Data buffers for DeviceIoControl() to USBM300 driver pDataBuffer = malloc(256); pOutBuffer = (PUSHORT)malloc (256); // Data ready event pUsbCtrl->hDataReadyEvent = CreateEvent(NULL, FALSE, // Automatic event reset FALSE, // Initial state not signaled NULL); // not named // Send the start streaming command strcpy(sCmd, "S"); if (C_SendCommand(pUsbCtrl->hUsbDevice, sCmd, sResp)) { // Nothing to do on success } else { // SendCommand error DbgOut("UsbStreamThread index %i Start stream SendCommand failure.\n", pUsbCtrl->dwDeviceIndex); pUsbCtrl->dwUsbStreamingState |= USB_THREAD_TERMINATE; return (1); } // Indicate the thread is running pUsbCtrl->dwUsbStreamingState |= USB_THREAD_RUNNING; // Performance calculations dwStartTime = GetTickCount(); pUsbCtrl->dwTotalBytes = 0; // Check state variable for USB_THREAD_TERMINATE while (!(pUsbCtrl->dwUsbStreamingState & USB_THREAD_TERMINATE)) { // DbgOut ("\nUsbStreamThread getting packet %i\n", dwCount++); // // Receive any data from PIPE2 // ZeroMemory(pDataBuffer, 256); ZeroMemory(pOutBuffer, 256); pulPipeNumber = (PULONG)pDataBuffer; *pulPipeNumber = 2; // PIPE2: PIC->Host PC bStatus = DeviceIoControl(pUsbCtrl->hUsbDevice, IOCTL_Eval_BULK_OR_INTERRUPT_READ, pDataBuffer, 4, pOutBuffer, 64, &dwBytesReturned, NULL); if (!bStatus) { // Error dwError = GetLastError(); DbgOut("UsbStreamThread %i Error receiving stream packet from USBM300. Error code = 0x%08X\n", pUsbCtrl->dwDeviceIndex, dwError); DbgOut("UsbStreamThread %i Error handle = 0x%08X\n", pUsbCtrl->dwDeviceIndex, pUsbCtrl->hUsbDevice); // Out of the loop // break; continue; } else { // DbgOut ("\nUsbStreamThread getting packet %i, bytes returned = %i\n", dwCount++, dwBytesReturned); pUsbCtrl->dwTotalBytes += dwBytesReturned; // Check queue full status if (pUsbCtrl->pHead->NextElement == pUsbCtrl->pTail) { DbgOut("UsbStreamThread %i queue full!\n", pUsbCtrl->dwDeviceIndex); continue; } // USBM300 Data is sent in the following format // (24) 16 bit A/D sample // (1) 16 bit digital input // (1) 32 bit Pulse counter // USBM400 Data is sent in the following format // (32) 16 bit A/D samples // Get A/D data from pOutBuffer and put into queue for (i=0; i<ADC_SAMPLE_COUNT; i++) { pUsbCtrl->pHead->Data.usAdcSamples[i] = pOutBuffer[i]; } // Increment queue count and move queue head pointer InterlockedIncrement(&pUsbCtrl->lQueueCount); pUsbCtrl->pHead = pUsbCtrl->pHead->NextElement; // Signal event to GetStreamingData() SetEvent(pUsbCtrl->hDataReadyEvent); } } // Performance calculations dwEndTime = GetTickCount(); pUsbCtrl->dwTotalMs = dwEndTime - dwStartTime; // Send the halt streaming command strcpy(sCmd, "H"); if (C_SendCommand(pUsbCtrl->hUsbDevice, sCmd, sResp)) { // // Receive any REMAINING data from PIPE2 // ZeroMemory(pDataBuffer, 256); ZeroMemory(pOutBuffer, 256); pulPipeNumber = (PULONG)pDataBuffer; *pulPipeNumber = 2; // PIPE2: PIC->Host PC bStatus = DeviceIoControl(pUsbCtrl->hUsbDevice, IOCTL_Eval_BULK_OR_INTERRUPT_READ, pDataBuffer, 4, pOutBuffer, 64, &dwBytesReturned, NULL); if (!bStatus) { // Error dwError = GetLastError(); DbgOut("UsbStreamThread %i Error receiving last stream packet from USBM300. Error code = 0x%08X\n", pUsbCtrl->dwDeviceIndex, dwError); DbgOut("UsbStreamThread %i Error handle = 0x%08X\n", pUsbCtrl->dwDeviceIndex, pUsbCtrl->hUsbDevice); } } else { // SendCommand error DbgOut("UsbStreamThread index %i Halt stream SendCommand failure.\n", pUsbCtrl->dwDeviceIndex); } // Free the event if (pUsbCtrl->hDataReadyEvent != NULL) { CloseHandle(pUsbCtrl->hDataReadyEvent); pUsbCtrl->hDataReadyEvent = NULL; } // Free DeviceIoControl() buffers free(pDataBuffer); free(pOutBuffer); // Free queue buffer if (pUsbCtrl->pQueue != NULL) { free(pUsbCtrl->pQueue); pUsbCtrl->pQueue = NULL; } // Return any error code pUsbCtrl->dwStreamThreadIoError = dwError; // Clear streaming state flags pUsbCtrl->dwUsbStreamingState &= (~USB_THREAD_RUNNING); pUsbCtrl->dwUsbStreamingState &= (~USB_THREAD_TERMINATE); DbgOut ("UsbStreamThread %i EXIT. dwError = %i\n\n", pUsbCtrl->dwDeviceIndex, dwError); return (0); } /////////////////////////////////////////////////////////////////////////////////////////////////// // Starts or stops the streaming thread // // Arguments: // ----------- // dwDeviceIndex Zero based USBM300 device index // bStart TRUE to start stream thread, FALSE to stop // dwQueueBlocksToAllocate Number of stream blocks to allocate for the queue FIFO. // See USBM300_STREAM_BLOCK definition in USBM300.H // // Return Value: // -------------- // TRUE Success // FAIL Error // BOOLEAN USBM300::ControlStreaming(DWORD dwDeviceIndex, BOOLEAN bStart, DWORD dwQueueBlocksToAllocate) { DWORD dwError, dwWait, i; double fBytes, fSeconds, fBytesPerSecond; DbgOut("ControlStreaming enter\n"); // Device index range check if (dwDeviceIndex > MAX_USBM300_DEVICES) { DbgOut("ControlStreaming failed. Index %i out of range.\n", dwDeviceIndex); return (FALSE); } // Check for valid device handle if (m_hDevice[dwDeviceIndex] == INVALID_HANDLE_VALUE) { DbgOut("ControlStreaming failed. Index %i handle is invalid.\n", dwDeviceIndex); return (FALSE); } if (bStart) { // Is the thread already running? if (m_UsbStreamCtrl[dwDeviceIndex].dwUsbStreamingState & USB_THREAD_RUNNING) { DbgOut("ControlStreaming index %i thread already started.\n", dwDeviceIndex); return (TRUE); } // Setup parameter variables m_UsbStreamCtrl[dwDeviceIndex].dwDeviceIndex = dwDeviceIndex; m_UsbStreamCtrl[dwDeviceIndex].dwQueueBlocksToAllocate = dwQueueBlocksToAllocate; m_UsbStreamCtrl[dwDeviceIndex].dwUsbStreamingState = USB_THREAD_NOT_STARTED; m_UsbStreamCtrl[dwDeviceIndex].hUsbDevice = m_hDevice[dwDeviceIndex]; m_UsbStreamCtrl[dwDeviceIndex].lQueueCount = 0; // Create the thread m_hStreamThread[dwDeviceIndex] = CreateThread(NULL, 0, UsbStreamThread, &m_UsbStreamCtrl[dwDeviceIndex], 0, &m_dwStreamThreadId[dwDeviceIndex]); // Check for thread creation error if (m_hStreamThread[dwDeviceIndex] == NULL) { dwError = GetLastError(); DbgOut("ControlStreaming failed creating thread. Index %i error status = %i\n", dwDeviceIndex, dwError); return (FALSE); } else { // Wait for thread to start before returning i = 0; while (!(m_UsbStreamCtrl[dwDeviceIndex].dwUsbStreamingState & USB_THREAD_RUNNING)) { DbgOut("ControlStreaming waiting for thread to start count %i\n", i); Sleep(100); if (m_UsbStreamCtrl[dwDeviceIndex].dwUsbStreamingState & USB_THREAD_TERMINATE) { // The thread killed itself DbgOut("ControlStreaming index %i thread failed to start\n", dwDeviceIndex); break; } i++; if (i > 50) { DbgOut("ControlStreaming index %i bail waiting for thread to start\n", dwDeviceIndex); break; } } } } else { // Stop the streaming thread // Is the thread already stopped? if (m_UsbStreamCtrl[dwDeviceIndex].dwUsbStreamingState & USB_THREAD_RUNNING) { // Flag the thread to terminate m_UsbStreamCtrl[dwDeviceIndex].dwUsbStreamingState |= USB_THREAD_TERMINATE; // Cancel any I/O in progress CancelIo(m_UsbStreamCtrl[dwDeviceIndex].hUsbDevice); // Wait for thread to exit. Timeout is 5 seconds (5,000 milliseconds) dwWait = WaitForSingleObject(m_hStreamThread[dwDeviceIndex], 5000); if (dwWait == WAIT_TIMEOUT) { DbgOut("ControlStreaming thread terminate wait timeout. Index %i \n", dwDeviceIndex); return (FALSE); } else { // Performance data calculations fBytes = m_UsbStreamCtrl[dwDeviceIndex].dwTotalBytes; fSeconds = m_UsbStreamCtrl[dwDeviceIndex].dwTotalMs; fSeconds = fSeconds / 1000.0; fBytesPerSecond = fBytes / fSeconds; // Display results DbgOut("Thread performance for index %i:\n", dwDeviceIndex); DbgOut("-> %i total bytes\n-> %i milliseconds\n", m_UsbStreamCtrl[dwDeviceIndex].dwTotalBytes, m_UsbStreamCtrl[dwDeviceIndex].dwTotalMs); DbgOut("-> %f bytes per second\n", fBytesPerSecond); // Close thread handle CloseHandle(m_hStreamThread[dwDeviceIndex]); m_hStreamThread[dwDeviceIndex] = INVALID_HANDLE_VALUE; // Reset thread state m_UsbStreamCtrl[dwDeviceIndex].dwUsbStreamingState = USB_THREAD_NOT_STARTED; } } else { // Thread is already stopped DbgOut("ControlStreaming thread already stopped. Index %i \n", dwDeviceIndex); } } return (TRUE); } /////////////////////////////////////////////////////////////////////////////////////////////////// // Returns the streaming thread status and blocks ready to be read from FIFO queue // // Arguments: // ----------- // dwDeviceIndex Zero based USBM300 device index // *dwQueueBlocksReady Number of stream data blocks ready in the queue FIFO // *dwUsbStreamingState Current stream thread state. See USB_THREAD_RUNNING, USB_THREAD_BUFFER_FULL // // Return Value: // -------------- // TRUE Success // FAIL Error // BOOLEAN USBM300::GetStreamingStatus(DWORD dwDeviceIndex, DWORD *dwQueueBlocksReady, DWORD *dwUsbStreamingState) { // Device index range check if (dwDeviceIndex > MAX_USBM300_DEVICES) { DbgOut("GetStreamingStatus failed. Index %i out of range.\n", dwDeviceIndex); return (FALSE); } // Check for valid device handle if (m_hDevice[dwDeviceIndex] == INVALID_HANDLE_VALUE) { DbgOut("GetStreamingStatus failed. Index %i handle is invalid.\n", dwDeviceIndex); return (FALSE); } // Blocks ready to be copied out *dwQueueBlocksReady = m_UsbStreamCtrl[dwDeviceIndex].lQueueCount; // Thread status *dwUsbStreamingState = m_UsbStreamCtrl[dwDeviceIndex].dwUsbStreamingState; return (TRUE); } /////////////////////////////////////////////////////////////////////////////////////////////////// // Retrieves data from the Stream Data FIFO queue // // Arguments: // ----------- // dwDeviceIndex Zero based USBM300 device index // bWait TRUE thread waits for dwBlocksRequested, FALSE returns data currently available // pData Array of USBM300_STREAM_BLOCK structures to be filled // Caller must allocate enough // dwBlocksRequested Number of block requested. Must match pData array length // *dwBlocksReturned Number of blocks copied into pData // // Return Value: // -------------- // TRUE Success // FAIL Error // BOOLEAN USBM300::GetStreamingData(DWORD dwDeviceIndex, BOOLEAN bWait, PUSBM300_STREAM_BLOCK pData, DWORD dwBlocksRequested, DWORD *dwBlocksReturned) { DWORD i, j, k, dwWait; DWORD dwBlocksCopied = 0; // Device index range check if (dwDeviceIndex > MAX_USBM300_DEVICES) { DbgOut("GetStreamingStatus failed. Index %i out of range.\n", dwDeviceIndex); return (FALSE); } // Check for valid device handle if (m_hDevice[dwDeviceIndex] == INVALID_HANDLE_VALUE) { DbgOut("GetStreamingStatus failed. Index %i handle is invalid.\n", dwDeviceIndex); return (FALSE); } if (dwBlocksRequested < 1) { // Nothing to do. Exit success return (TRUE); } if (bWait) { // Wait for enough data to arrive while (dwBlocksRequested > (DWORD)m_UsbStreamCtrl[dwDeviceIndex].lQueueCount) { // Wait for 30 seconds. Fail otherwise. dwWait = WaitForSingleObject(m_UsbStreamCtrl[dwDeviceIndex].hDataReadyEvent, 30000); if (dwWait == WAIT_TIMEOUT) { DbgOut("GetStreamingData thread data ready event timeout. Index %i \n", dwDeviceIndex); *dwBlocksReturned = 0; return (FALSE); } } j = dwBlocksRequested; } else { // Return what data is currently available if (dwBlocksRequested > (DWORD)m_UsbStreamCtrl[dwDeviceIndex].lQueueCount) { j = m_UsbStreamCtrl[dwDeviceIndex].lQueueCount; } else { j = dwBlocksRequested; } } // Dequeue data and copy into user's pData buffer for (i=0; i<j; i++) { // Check queue empty (head == tail) if (m_UsbStreamCtrl[dwDeviceIndex].pTail == m_UsbStreamCtrl[dwDeviceIndex].pHead) { DbgOut("GetStreamingData unexpected queue empty.\n", dwDeviceIndex); break; } // Data copy for (k=0; k<ADC_SAMPLE_COUNT; k++) { pData[i].usAdcSamples[k] = m_UsbStreamCtrl[dwDeviceIndex].pTail->Data.usAdcSamples[k]; } // Queue tail move m_UsbStreamCtrl[dwDeviceIndex].pTail = m_UsbStreamCtrl[dwDeviceIndex].pTail->NextElement; // Decrement queue count InterlockedDecrement(&m_UsbStreamCtrl[dwDeviceIndex].lQueueCount); // Another block copied dwBlocksCopied++; } *dwBlocksReturned = dwBlocksCopied; return (TRUE); }
33,627
https://github.com/jpaoletti/java-presentation-manager-2/blob/master/modules/jpm2-web-core/src/main/java/jpaoletti/jpm2/web/converter/WebEditCollection2.java
Github Open Source
Open Source
MIT
2,019
java-presentation-manager-2
jpaoletti
Java
Code
227
704
package jpaoletti.jpm2.web.converter; import java.util.Collection; import jpaoletti.jpm2.core.exception.ConfigurationException; import jpaoletti.jpm2.core.exception.ConverterException; import jpaoletti.jpm2.core.model.ContextualEntity; import jpaoletti.jpm2.core.model.Field; import jpaoletti.jpm2.util.JPMUtils; /** * * @author jpaoletti */ public class WebEditCollection2 extends WebEditObject { public WebEditCollection2() { super(); } @Override public Object visualize(ContextualEntity contextualEntity, Field field, Object object, String instanceId) throws ConverterException, ConfigurationException { final Collection<Object> value = (Collection<Object>) ((object == null) ? null : getValue(object, field)); final String res = getBaseJsp() + "?entityId=" + getEntity().getId() + "&textField=" + getTextField() + "&related=" + getRelated() + "&currentId=" + instanceId + "&filter=" + ((getFilter() != null) ? getFilter().getId() : "") + "&pageSize=" + getPageSize() + "&addable=" + isAddable() + "&minSearch=" + getMinSearch(); if (value == null || value.isEmpty()) { return res; } else { final StringBuilder sb = new StringBuilder(); for (Object o : value) { sb.append(getEntity().getDao().getId(o)).append(","); } return res + "&value=" + sb.toString().substring(0, sb.toString().length() - 1); } } protected String getBaseJsp() { return "@page:collection-converter2.jsp"; } @Override public Object build(ContextualEntity contextualEntity, Field field, Object object, Object newValue) throws ConverterException { if (newValue == null || "".equals(newValue)) { return null; } else { try { final Collection<Object> c = (Collection<Object>) getValue(object, field); c.clear(); final String[] split = splitValues(newValue); for (String s : split) { c.add(getEntity().getDao().get(s)); } return c; } catch (Exception ex) { JPMUtils.getLogger().error("", ex); throw new ConverterException("error.converting.collection"); } } } protected String[] splitValues(Object newValue) { return (newValue instanceof String) ? (new String[]{newValue.toString()}) : (String[]) newValue; } }
36,680
https://github.com/wikimatze/vimfiles/blob/master/colors/github.vim
Github Open Source
Open Source
MIT
2,022
vimfiles
wikimatze
Vim Script
Code
375
1,425
" Vim color file " Maintainer: Ricardo Valeriano <ricardo.valeriano@gmail.com> " Based on the work by: Bruno Michel <bmichel@menfin.info> " Last Change: July, 10, 2014 " Version: 0.2 " Homepage: http://github.com/ricardovaleriano/vim-github-theme " It's a work from https://github.com/nono/github_vim_theme " It is improved be @wikimatze to have orange color in visual mode " This is a ViM's version of the github color theme. set background=light hi clear if exists("syntax_on") syntax reset endif let g:colors_name = "github" set t_Co=256 hi Comment guifg=#999988 ctermfg=102 gui=italic hi Constant guifg=#008080 ctermfg=30 hi String guifg=#dd1144 ctermfg=161 hi Character guifg=#dd1144 ctermfg=161 hi Number guifg=#009999 ctermfg=30 hi Boolean gui=bold cterm=bold hi Float guifg=#009999 ctermfg=30 hi RubySymbol guifg=#990073 ctermfg=90 hi Identifier guifg=#008080 ctermfg=30 hi Function guifg=#990000 ctermfg=88 gui=bold cterm=bold hi Statement guifg=#000000 ctermfg=16 gui=bold cterm=bold hi Conditional guifg=#000000 ctermfg=16 gui=bold cterm=bold hi Repeat guifg=#000000 ctermfg=16 gui=bold cterm=bold hi Label guifg=#000000 ctermfg=16 gui=bold cterm=bold hi Operator guifg=#000000 ctermfg=16 gui=bold cterm=bold hi Keyword guifg=#000000 ctermfg=16 gui=bold cterm=bold hi Exception guifg=#990000 ctermfg=88 gui=bold cterm=bold hi PreProc guifg=#999999 ctermfg=102 gui=bold cterm=bold hi Include guifg=#999999 ctermfg=102 gui=bold cterm=bold hi Define guifg=#000000 ctermfg=16 gui=bold cterm=bold hi Macro guifg=#999999 ctermfg=102 gui=bold cterm=bold hi PreCondit guifg=#999999 ctermfg=102 gui=bold cterm=bold hi Type guifg=#445588 ctermfg=60 gui=bold cterm=bold hi StorageClass guifg=#000000 ctermfg=16 gui=bold cterm=bold hi Structure guifg=#000000 ctermfg=16 gui=bold cterm=bold hi Typedef guifg=#000000 ctermfg=16 gui=bold cterm=bold hi Special guifg=#dd1144 ctermfg=161 hi SpecialChar guifg=#dd1144 ctermfg=161 hi Tag guifg=#000080 ctermfg=18 hi Delimiter guifg=#dd1144 ctermfg=161 hi SpecialComment guifg=#999999 ctermfg=102 gui=bold,italic cterm=bold,italic hi Debug guifg=#aa0000 ctermfg=124 hi Underlined gui=underline cterm=underline hi Ignore guifg=bg hi Error guifg=#a61717 ctermfg=124 guibg=#e3d2d2 ctermbg=188 hi Todo guifg=#999988 ctermfg=102 gui=italic cterm=italic hi Cursor guifg=NONE ctermfg=NONE guibg=#ff9900 ctermbg=227 hi CursorLine guifg=NONE ctermfg=NONE guibg=#ffffcc ctermbg=230 hi Directory guifg=#4183c4 ctermfg=68 hi DiffAdd guifg=#000000 ctermfg=16 guibg=#ddffdd ctermbg=194 hi DiffDelete guifg=#000000 ctermfg=16 guibg=#ffdddd ctermbg=224 hi DiffText guibg=#666666 ctermbg=59 hi ErrorMsg guifg=#a61717 ctermfg=124 guibg=#e3d2d2 ctermbg=188 gui=bold cterm=bold hi VertSplit guifg=#666666 ctermfg=59 guibg=#eaeaea ctermbg=188 hi LineNr guifg=#666666 ctermfg=59 guibg=#eaeaea ctermbg=188 hi ModeMsg gui=bold cterm=bold hi Normal guifg=#000000 ctermfg=16 guibg=#f8f8ff ctermbg=231 hi Pmenu guibg=#babdb6 ctermbg=145 guifg=#555753 ctermfg=59 hi StatusLine guifg=#666666 ctermfg=59 guibg=#eaeaea ctermbg=188 hi Visual guifg=NONE ctermfg=NONE guibg=#ffffcc ctermbg=220 "this is a workaround to show the cursor on the Terminal.app "thanks to: http://www.damtp.cam.ac.uk/user/rbw/vim-osx-cursor.html if $TERM_PROGRAM == "Apple_Terminal" && !has("gui_running") hi CursorLine term=none cterm=none "Invisible CursorLine hi Cursor ctermfg=none ctermbg=85 set cursorline match Cursor /\%#/ endif
4,902
https://github.com/aonomike/Human-Connection/blob/master/webapp/components/Registration/CreateUserAccount.vue
Github Open Source
Open Source
MIT
null
Human-Connection
aonomike
Vue
Code
341
1,481
<template> <ds-container width="small"> <ds-card v-if="success" class="success"> <ds-space> <sweetalert-icon icon="success" /> <ds-text align="center" bold color="success"> {{ $t('registration.create-user-account.success') }} </ds-text> </ds-space> </ds-card> <ds-card v-else class="create-account-card"> <client-only> <locale-switch /> </client-only> <ds-space centered> <img class="create-account-image" alt="Create an account for Human Connection" src="/img/sign-up/nicetomeetyou.svg" /> </ds-space> <ds-space> <ds-heading size="h3"> {{ $t('registration.create-user-account.title') }} </ds-heading> </ds-space> <ds-form class="create-user-account" v-model="formData" :schema="formSchema" @submit="submit"> <template v-slot="{ errors }"> <ds-flex gutter="base"> <ds-flex-item width="100%"> <ds-input id="name" model="name" icon="user" :label="$t('settings.data.labelName')" :placeholder="$t('settings.data.namePlaceholder')" /> <ds-input id="about" model="about" type="textarea" rows="3" :label="$t('settings.data.labelBio')" :placeholder="$t('settings.data.labelBio')" /> <ds-input id="password" model="password" type="password" autocomplete="off" :label="$t('settings.security.change-password.label-new-password')" /> <ds-input id="passwordConfirmation" model="passwordConfirmation" type="password" autocomplete="off" :label="$t('settings.security.change-password.label-new-password-confirm')" /> <password-strength :password="formData.password" /> <ds-text> <input id="checkbox" type="checkbox" v-model="termsAndConditionsConfirmed" :checked="termsAndConditionsConfirmed" /> <label for="checkbox" v-html="$t('termsAndConditions.termsAndConditionsConfirmed')" ></label> </ds-text> </ds-flex-item> <ds-flex-item width="100%"> <ds-space class="backendErrors" v-if="backendErrors"> <ds-text align="center" bold color="danger">{{ backendErrors.message }}</ds-text> </ds-space> <ds-button style="float: right;" icon="check" type="submit" :loading="$apollo.loading" :disabled="errors || !termsAndConditionsConfirmed" primary > {{ $t('actions.save') }} </ds-button> </ds-flex-item> </ds-flex> </template> </ds-form> </ds-card> </ds-container> </template> <script> import PasswordStrength from '../Password/Strength' import { SweetalertIcon } from 'vue-sweetalert-icons' import PasswordForm from '~/components/utils/PasswordFormHelper' import { VERSION } from '~/constants/terms-and-conditions-version.js' import { SignupVerificationMutation } from '~/graphql/Registration.js' import LocaleSwitch from '~/components/LocaleSwitch/LocaleSwitch' export default { components: { PasswordStrength, SweetalertIcon, LocaleSwitch, }, data() { const passwordForm = PasswordForm({ translate: this.$t }) return { formData: { name: '', about: '', ...passwordForm.formData, }, formSchema: { name: { type: 'string', required: true, min: 3, }, about: { type: 'string', required: false, }, ...passwordForm.formSchema, }, disabled: true, success: null, backendErrors: null, // TODO: Our styleguide does not support checkmarks. // Integrate termsAndConditionsConfirmed into `this.formData` once we // have checkmarks available. termsAndConditionsConfirmed: false, } }, props: { nonce: { type: String, required: true }, email: { type: String, required: true }, }, methods: { async submit() { const { name, password, about } = this.formData const { email, nonce } = this const termsAndConditionsAgreedVersion = VERSION try { await this.$apollo.mutate({ mutation: SignupVerificationMutation, variables: { name, password, about, email, nonce, termsAndConditionsAgreedVersion }, }) this.success = true setTimeout(() => { this.$emit('userCreated', { email, password, }) }, 3000) } catch (err) { this.backendErrors = err } }, }, } </script> <style lang="scss" scoped> .create-account-image { width: 50%; max-width: 200px; } </style>
38,057
https://github.com/FreeSunny/WisdomEducation/blob/master/Wisdom_Education_iOS/Modules/EduLogic/EduLogic/NEEduManager/Model/NEEduKitOptions.h
Github Open Source
Open Source
MIT
2,021
WisdomEducation
FreeSunny
Objective-C
Code
60
157
// // NEEduInitOption.h // EduLogic // // Created by Groot on 2021/5/13. // Copyright © 2021 NetEase. All rights reserved. // Use of this source code is governed by a MIT license that can be found in the LICENSE file // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface NEEduKitOptions : NSObject @property (nonatomic, copy) NSString *authorization; @property (nullable, nonatomic,copy) NSString *baseURL; @end NS_ASSUME_NONNULL_END
2,355
https://github.com/wendiNurhermansah/apotek/blob/master/app/Http/Controllers/asyfa/DatabarangController.php
Github Open Source
Open Source
MIT
null
apotek
wendiNurhermansah
PHP
Code
461
1,899
<?php namespace App\Http\Controllers\asyfa; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Models\Data_barang; use App\Models\Jenis_barang; use App\Models\Satuan; use App\Models\Supplier; use Yajra\DataTables\DataTables; class DatabarangController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $jenis_barang = Jenis_barang::all(); $satuan = Satuan::all(); $supplier = Supplier::all(); return view ('Data_barang.dataBarang', compact('jenis_barang', 'satuan', 'supplier')); } public function api(){ $D_barang = Data_barang::all(); return DataTables::of($D_barang) ->addColumn('action', function ($p) { return " <a href='" . route( 'Asyfa.Data_barang.edit', $p->id) . "' onclick='edit(" . $p->id . ")' title='Edit'><i class='icon-pencil mr-1'></i></a> <a href='#' onclick='remove(" . $p->id . ")' class='text-danger' title='Hapus'><i class='icon-remove'></i></a>"; }) ->editColumn('jenis_barang_id', function($p){ return $p->JenisBarang->n_jenis_barang; }) ->editColumn('satuan', function($p){ return $p->Satuan->n_satuan; }) ->editColumn('supplier_id', function($p){ return $p->Supplier->n_supplier; }) ->addIndexColumn() ->rawColumns(['action', 'jenis_barang','satuan']) ->toJson(); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $request->validate([ 'nama_barang' => 'required', 'jenis_barang_id' => 'required', 'harga_barang' => 'required', 'harga_perawat' => 'required', 'harga_jual' => 'required', 'jumlah_barang' => 'required', 'satuan' => 'required', ]); $nama_barang = $request->nama_barang; $jenis = $request->jenis_barang_id; $sup = $request->supplier_id; $satuan = $request->satuan; $beli = str_replace(".", "", $request->harga_barang); $qty = $request->jumlah_barang; $jual = str_replace(".", "", $request->harga_jual); $nakes = str_replace(".", "", $request->harga_perawat); $Data_barang = new Data_barang(); $Data_barang->nama_barang = $nama_barang; $Data_barang->jenis_barang_id = $jenis; $Data_barang->satuan = $satuan; $Data_barang->supplier_id = $sup; $Data_barang->harga_barang = $beli; $Data_barang->jumlah_barang = $qty; $Data_barang->harga_jual = $jual; $Data_barang->harga_perawat = $nakes; $Data_barang->save(); return response()->json([ 'message' => 'Data berhasil tersimpan.' ]); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $Data_barang = Data_barang::find($id); $jenis_barang = Jenis_barang::all(); $satuan = Satuan::all(); $supplier = Supplier::all(); return view('Data_barang.editBarang', compact('Data_barang','jenis_barang','satuan', 'supplier')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $Data_barang = Data_barang::find($id); $request->validate([ 'nama_barang' => 'required', 'jenis_barang_id' => 'required', 'harga_barang' => 'required', 'harga_perawat' => 'required', 'harga_jual' => 'required', 'jumlah_barang' => 'required', 'satuan' => 'required', ]); $nama = $request->nama_barang; // dd($nama_barang); $jenis = $request->jenis_barang_id; $sup = $request->supplier_id; // dd($jenis); $satuan = $request->satuan; $beli = $request->harga_barang; $qty = $request->jumlah_barang; // dd($qty); $jual = $request->harga_jual; $nakes = $request->harga_perawat; $Data_barang->update([ 'nama_barang' => $nama, 'jenis_barang_id' => $jenis, 'harga_barang' => $beli, 'jumlah_barang' => $qty, 'harga_perawat' => $nakes, 'harga_jual' => $jual, 'supplier_id' => $sup, 'satuan' => $satuan ]); return redirect('Asyfa/Data_barang')->with('status', 'data berhasil di Rubah'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { Data_barang::destroy($id); return response()->json([ 'massage' => 'data berhasil di hapus.' ]); } }
35,359
https://github.com/toluolubajo/F1-Guest-Entry/blob/master/lib/Autoloader.php
Github Open Source
Open Source
MIT
2,013
F1-Guest-Entry
toluolubajo
PHP
Code
86
252
<?php /** * Classes source autoload */ class Autoloader { static protected $_instance; /** * Singleton pattern implementation * * @return Varien_Autoload */ static public function instance() { if (!self::$_instance) { self::$_instance = new Autoloader(); } return self::$_instance; } /** * Register SPL autoload function */ static public function register() { spl_autoload_register(array(self::instance(), 'autoload')); } /** * Load class source code * * @param string $class */ public function autoload($class) { $classFile = str_replace(' ', DIRECTORY_SEPARATOR, ucwords(str_replace('_', ' ', $class))); $classFile.= '.php'; return include $classFile; } }
10,759
https://github.com/jmscshipp/GAM-372-Centipede/blob/master/CentipedeGame/ExplosionTwoTiles.h
Github Open Source
Open Source
MIT
null
GAM-372-Centipede
jmscshipp
C
Code
47
167
#ifndef _ExplosionTwoTiles #define _ExplosionTwoTiles #include "TEAL/CommonElements.h" #include "Explosion.h" class ExplosionTwoTiles : public Explosion { public: ExplosionTwoTiles(); // big four ExplosionTwoTiles(const ExplosionTwoTiles&) = delete; ExplosionTwoTiles& operator = (const ExplosionTwoTiles&) = delete; ~ExplosionTwoTiles(); void Initialize(sf::Vector2f location); virtual void Draw(); virtual void Update(); virtual void Destroy(); private: }; #endif _ExplosionTwoTiles
25,604
https://github.com/coolafabbe/AdventOfCode2021/blob/master/Aron/Day5/answer.py
Github Open Source
Open Source
MIT
null
AdventOfCode2021
coolafabbe
Python
Code
340
1,135
import time, sys GREEN = '\033[92m' GRAY = '\033[90m' END_COLOR = '\033[0m' CLR = '\x1B[0K' g=100 def print_graph(graph, graph_dim, visualize): danger_points = 0 for y in range(len(graph)): for x in range(len(graph[0])): if graph[x][y] == 0: if visualize: print(f'{GRAY}{graph[x][y]}{END_COLOR}', end=' ') pass elif graph[x][y] == 1: if visualize: print(f'{graph[x][y]}', end=' ') pass else: danger_points += 1 if visualize: print(f'{GREEN}{graph[x][y]}{END_COLOR}', end=' ') if visualize: print(CLR) return danger_points if __name__ == "__main__": if len(sys.argv) == 1: print(f'Please provide an input file as second argument: python {__file__} input') exit() with open(sys.argv[1], "r") as file: entries = file.read().splitlines() print(f'Analyzing {len(entries)} entries') lines = [[[int(c) for c in l.split(',')] for l in e.split(' -> ')] for e in entries] graph_dim = [0, 0] for line in lines: for x, y in line: if x+1 > graph_dim[0]: graph_dim[0] = x+1 if y+1 > graph_dim[1]: graph_dim[1] = y+1 print(f'Graph max coords: {graph_dim}\n') if graph_dim[0] > g: print(f'Graph larger than {g} columns, not visualizing output.') graph = [[0 for x in range(graph_dim[0])] for y in range(graph_dim[1])] if graph_dim[0] < g: print_graph(graph, graph_dim, True) print(f'Danger points: {GREEN}0{END_COLOR}') for id, line in enumerate(lines): if graph_dim[0] < g: time.sleep(1) x1, y1 = line[0] x2, y2 = line[1] x_min, x_max = min(x1, x2), max(x1, x2) y_min, y_max = min(y1, y2), max(y1, y2) if graph_dim[0] < g: print(f'\x1B[{graph_dim[1]+3}A') if x_min == x_max: print(f'Adding vertical line: ({x1}, {y1}) -> ({x2}, {y2}){CLR}') for y in range(y_min, y_max+1): graph[x_min][y] += 1 elif y_min == y_max: print(f'Adding horizontal line: ({x1}, {y1}) -> ({x2}, {y2}){CLR}') for x in range(x_min, x_max+1): graph[x][y_min] += 1 else: if not 'no-diagonals' in sys.argv: print(f'Adding diagonal line: ({x1}, {y1}) -> ({x2}, {y2}){CLR}') for d in range(x_max + 1 - x_min): x = x1 + d if x1 < x2 else x1 - d y = y1 + d if y1 < y2 else y1 - d graph[x][y] += 1 else: print(f'Omitting diagonal line: ({x1}, {y1}) -> ({x2}, {y2}){CLR}') danger_points = print_graph(graph, graph_dim, graph_dim[0] < g) print(f'Danger points: {GREEN}{danger_points}{END_COLOR}{CLR}') if graph_dim[0] > g and id+1 < len(lines): print('\x1B[3A') if 'visualize-final' in sys.argv: print_graph(graph, graph_dim, True)
41,695
https://github.com/acv/sr_tools/blob/master/shooting_mc.py
Github Open Source
Open Source
BSD-3-Clause
2,013
sr_tools
acv
Python
Code
829
2,457
#!/usr/bin/env python import optparse from lib.damage import DamageValue from lib.shooting import * def monte_carlo(shooter, target, columns, rolls, damage_value, accuracy, ap, defensive_modifier, attack_modifier): raw_results = [] for bonus in xrange(columns): raw_results.append({}) for i in xrange(rolls): result = shoot(shooter, target, damage_value, accuracy, ap, defense_modifier = defensive_modifier, attack_modifier = (bonus + attack_modifier)) damage = str(result.damage) if result.critical_glitch: damage = 'Critical Glitch!' elif result.effect != 'damaged': damage = result.effect.capitalize() + '!' if damage not in raw_results[bonus]: raw_results[bonus][damage] = 0 raw_results[bonus][damage] += 1 if result.effect == 'damaged': if 'Hit!' not in raw_results[bonus]: raw_results[bonus]['Hit!'] = 0 raw_results[bonus]['Stun!'] = 0 raw_results[bonus]['Physical!'] = 0 raw_results[bonus]['Hit!'] += 1 if damage.endswith('P'): raw_results[bonus]['Physical!'] += 1 elif damage.endswith('S'): raw_results[bonus]['Stun!'] += 1 return raw_results def print_table(shooter, raw_results, rolls, attack_modifier): columns = len(raw_results) rows = set() longest = 0 for bonus in xrange(columns): for label in raw_results[bonus]: if label not in rows: rows.add(label) if len(label) > longest: longest = len(label) def print_full_bar(): print "\t+-" + ('-' * longest) + '-+' + ((('-' * 10) + '+') * columns) format_str = "\t| %" + str(longest) + "s |" + (' %8.8s |' * columns) print "\n\t+-" + ('-' * longest) + '-+' + (('-' * ((10 * columns) + columns - 1)) + '+') label = ' Attack Pool Size' print "\t| " + (' ' * longest) + ' |' + (label + (' ' * ((10 * columns) + columns - 1 - len(label))) + '|') print "\t| " + (' ' * longest) + ' +' + ((('-' * 10) + '+') * columns) raw_pool = shooter.agility + shooter.firearm + attack_modifier args = [''] for i in xrange(columns): args.append(str(raw_pool + i)) print format_str % tuple(args) print_full_bar() words = [] stun = [] physical = [] for row in rows: if row.endswith('S'): stun.append(int(row[:-1])) elif row.endswith('P'): physical.append(int(row[:-1])) else: words.append(row) result = [] for row in sorted(words): result.append(row) words = result result = [] for row in sorted(stun): result.append(str(row) + 'S') stun = result result = [] for row in sorted(physical): result.append(str(row) + 'P') physical = result def print_rows(rows): for label in rows: args = [label] for i in xrange(columns): if label in raw_results[i]: args.append(str(float(raw_results[i][label]) / rolls * 100)) else: args.append(' -') print format_str % tuple(args) print_full_bar() print_rows(words) if len(stun) > 0: print_rows(stun) if len(physical) > 0: print_rows(physical) def print_sim_details(shooter, target, accuracy, ap, dv, columns, rolls, defensive_modifier, attack_modifier): print "\nShadowrun 5 Firearms Combat Damage Simulator\n" print "Simulation Details:" print "\tNumber of columns: %d" % (columns,) print "\tNumber of rolls per columns: %d" % (rolls,) print "\nAttacker Details:" print "\tBase Attack Pool: %d" % ((shooter.agility + shooter.firearm),) print "\tAttack Modifier: %d" % (attack_modifier,) print "\tWeapon Damage Value: %s" % (str(dv),) print "\tWeapon Accuracy: %d" % (accuracy,) print "\tWeapon Armor Piercing: %d" % (ap,) print "\nDefender Details:" print "\tArmor: %d" % (target.armor,) print "\tBody: %d" % (target.body,) print "\tIntuition: %d" % (target.intuition,) print "\tReaction: %d" % (target.reaction,) print "\tDefensive Modifier: %d" % (defensive_modifier,) def parse_cmd_line(): usage = """%prog [options] This program runs a monte-carlo simulation to evaluate the effect of various attack pool size when shooting a specific weapon against a runner. The stats are provided through command-line arguments and an ASCII table is printed summarizing the stats (expressed as % of attacks). """ parser = optparse.OptionParser(usage = usage) shooter = optparse.OptionGroup(parser, 'Attacker options') shooter.add_option("-A", "--accuracy", help = "Accuracy of weapon (default = 7)", default = "7") shooter.add_option("-d", "--damage", help = "Base damage value of weapon " + "(default = 7P)", default = "7P") shooter.add_option("-M", "--attack_modifier", default = "0", help = "Modifiers to the attack roll (default = 0)") shooter.add_option("-p", "--attack_pool", help = "Attack pool starting size " + "(default = 6)", default = "6") shooter.add_option("-P", "--armor_piercing", help = "Armor piercing value for " + "firearm (default = 0)", default = "0") parser.add_option_group(shooter) target = optparse.OptionGroup(parser, "Defender options") target.add_option("-a", "--armor", help = "Defender armor value (default = 12)", default = "12") target.add_option("-b", "--body", help = "Defender body (default = 4)", default = "4") target.add_option("-i", "--intuition", help = "Defender intuition (default = 4)", default = "4") target.add_option("-m", "--defensive_modifier", default = "0", help = "Defensive modifier (default = 0)") target.add_option("-r", "--reaction", help = "Defender reaction (default = 7)", default = "7") parser.add_option_group(target) sim = optparse.OptionGroup(parser, "Simulation options") sim.add_option("-c", "--columns", help = "Number of columns (attack pool " + "steps) to plot (default = 8)", default = "8") sim.add_option("-I", "--iterations", help = "Number of iterations of the " + "simulation to run for each column. (default = 10000)", default = "10000") parser.add_option_group(sim) (options, args) = parser.parse_args() try: DamageValue(options.damage) except Exception as e: parser.error("Invalid damage value [%s] (%s)" % (options.damage, str(e))) return options def main(): options = parse_cmd_line() shooter = ShootingCharacter(agility = 0, firearm = int(options.attack_pool)) target = ShootingCharacter(intuition = int(options.intuition), reaction = int(options.reaction), armor = int(options.armor), body = int(options.body)) columns = int(options.columns) rolls = int(options.iterations) accuracy = int(options.accuracy) ap = int(options.armor_piercing) dv = DamageValue(options.damage) attack_modifier = int(options.attack_modifier) defensive_modifier = int(options.defensive_modifier) print_sim_details(shooter, target, accuracy, ap, dv, columns, rolls, defensive_modifier, attack_modifier) raw_results = monte_carlo(shooter, target, columns, rolls, dv, accuracy, ap, defensive_modifier, attack_modifier) print_table(shooter, raw_results, rolls, attack_modifier) if __name__ == '__main__': main()
35,920
https://github.com/art-community/art-react/blob/master/widgets/Form.tsx
Github Open Source
Open Source
Apache-2.0
2,021
art-react
art-community
TypeScript
Code
30
100
import React, {DetailedHTMLProps, HTMLAttributes} from "react"; import {Widget} from "./Widget"; import {proxy} from "./Proxy"; export const form = (widget: Widget<any>, properties?: DetailedHTMLProps<HTMLAttributes<HTMLFormElement>, HTMLFormElement>) => proxy( <form {...properties}> {widget.render()} </form> );
28,117
https://github.com/sopian27/sobat-daging-cms/blob/master/application/controllers/auth/ReturnCancel.php
Github Open Source
Open Source
MIT
null
sobat-daging-cms
sopian27
PHP
Code
340
1,759
<?php class ReturnCancel extends CI_Controller { public function __construct() { parent::__construct(); date_default_timezone_set('Asia/Jakarta'); $this->load->model('auth/TRXReturnModel', 'trx_ret_model'); } public function index() { //$tgl_trx = date("Y-m-d"); $data['judul'] = 'Return Item'; $data['subMenu'] = "Return/Cancel"; $t = time(); $data['date'] = date("d F Y", $t); //$current_date = date("d/m/Y", $t); //$trxData = $this->trx_ret_model->getTrxId($tgl_trx); /* $trxId = $trxData[0]->trx_id; $lastNoUrut = substr($trxId, 5, 4); $nextNoUrut = intval($lastNoUrut) + 1; $kodePo = 'RRI-' . sprintf('%04s', $nextNoUrut) . "/" . $current_date; */ /* $datax = $trxData[0]->trx_id; $lastNoUrut = substr($datax, 4,5); $nextNoUrut = intval($lastNoUrut)+1; $kodePo = 'RRI-' . sprintf('%05s',$nextNoUrut)."/". date('d/m/Y',strtotime($tgl_trx)); */ //$data['kode_po'] = $kodePo; $this->load->view('auth/templates/header', $data); $this->load->view('auth/templates/return/sidemenu', $data); $this->load->view('auth/return/return-item', $data); $this->load->view('auth/templates/footer'); } public function getInvoiceData() { $data_post = $_POST; $tgl_trx = date("Y-m-d"); $trxData = $this->trx_ret_model->getTrxId($tgl_trx); $datax = $trxData[0]->trx_id; $lastNoUrut = substr($datax, 4,5); $nextNoUrut = intval($lastNoUrut)+1; $kodePo = 'RRI-' . sprintf('%05s',$nextNoUrut)."/". date('d/m/Y',strtotime($tgl_trx)); $batasTampilData = $_POST['batastampil']; $halaman = (isset($_POST['halaman'])) ? $halaman = $_POST['halaman'] : $halaman = 1; $halamanAwal = ($halaman > 1) ? ($halaman * $batasTampilData) - $batasTampilData : 0; $data = $this->trx_ret_model->getInvoiceData($data_post['no_invoice'], $halamanAwal, $batasTampilData); $dataCounter = $this->trx_ret_model->getInvoiceDataCount($data_post['no_invoice']); $output = array( "length" => count($data), "data" => $data, "length_paging" => count($dataCounter), "kode_po" => $kodePo ); echo json_encode($output); } /* public function saveData(){ $data=array(); for($i=0;$i<count($_POST['id_trx_po']);$i++){ $id_barang = $_POST['id_trx_po'][$i]; $data= array( "no_invoice"=> $_POST['no_invoice'], "quantity_return"=> $_POST['quantity_return'][$i], "quantity_before"=> $_POST['quantity_before'][$i], "note"=> $_POST['note'][$i], "id_trx_return"=> $_POST['id_trx_return'], "satuan"=> $_POST['satuan_return'][$i], "id_trx_po"=> $_POST['id_trx_po'][$i], "tgl_return"=> $_POST['tgl_return'], "create_date"=>date('YmdHis'), "update_date"=>date('YmdHis') ); if($id_barang != ""){ $this->trx_ret_model->insertData($data); } } redirect('return-cancel'); } */ public function saveData() { $where = array( "no_invoice" => $_POST['no_invoice'] ); $data = array( "status" => "1", "update_date" => date('YmdHis'), "tgl_return" => $_POST['tgl_return'] ); $this->trx_ret_model->update($data, $where); echo json_encode("success"); } public function isConfirmed(){ $where = array( "no_invoice" => $_POST['no_invoice'], "status" => "0" ); $getDetailTrx = $this->trx_ret_model->getWhere($where); $output = array( "length" => count($getDetailTrx) ); echo json_encode($output); } public function insertData() { $data = array( "no_invoice" => $_POST['no_invoice'], "quantity_return" => $_POST['quantity_return'], "quantity_before" => $_POST['quantity_before'], "note" => $_POST['note'], "id_trx_return" => $_POST['id_trx_return'], "satuan" => $_POST['satuan_return'], "id_trx_po" => $_POST['id_trx_po'], "tgl_return" => $_POST['tgl_return'], "create_date" => date('YmdHis'), "update_date" => date('YmdHis'), "status" => "0" ); $this->trx_ret_model->insertData($data); echo json_encode("success"); } public function clearAll() { $where = array( "no_invoice" => $_POST['no_invoice'], "status" => "0" ); $this->trx_ret_model->deleteData($where); echo json_encode("success"); } }
3,827
https://github.com/badiozam/concord/blob/master/src/main/java/com/i4one/base/web/controller/admin/members/MembershipReportController.java
Github Open Source
Open Source
MIT
2,020
concord
badiozam
Java
Code
543
1,803
/* * MIT License * * Copyright (c) 2018 i4one Interactive, LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.i4one.base.web.controller.admin.members; import com.i4one.base.model.balance.BalanceManager; import com.i4one.base.model.client.SingleClient; import com.i4one.base.model.client.SingleClientManager; import com.i4one.base.model.client.reports.UserMembershipClassification; import com.i4one.base.model.client.reports.UserMembershipZipClassification; import com.i4one.base.model.user.UserBalance; import com.i4one.base.model.user.UserBalanceManager; import com.i4one.base.model.user.UserManager; import com.i4one.base.web.controller.Model; import com.i4one.base.web.controller.admin.BaseAdminReportViewController; import com.i4one.base.web.interceptor.ClientInterceptor; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * @author Hamid Badiozamani */ @Controller public class MembershipReportController extends BaseAdminReportViewController { private SingleClientManager singleClientManager; private BalanceManager balanceManager; private UserBalanceManager userBalanceManager; private UserManager userManager; @ModelAttribute public MemberReportSettings getModelAttribute(HttpServletRequest request) { MemberReportSettings retVal = new MemberReportSettings(ClientInterceptor.getSingleClient(request)); return retVal; } @RequestMapping(value = "**/admin/members/reports/membership", method = RequestMethod.GET ) public Model membershipClassificationReport(@ModelAttribute("reportSettings") MemberReportSettings reportSettings, HttpServletRequest request, HttpServletResponse response) throws IOException { return membershipClassificationReportRange(reportSettings, null, request, response); } @RequestMapping(value = "**/admin/members/reports/membership", method = RequestMethod.POST ) public Model membershipClassificationReportRange(@ModelAttribute("reportSettings") MemberReportSettings reportSettings, BindingResult result, HttpServletRequest request, HttpServletResponse response) throws IOException { Model model = initRequest(request, reportSettings); SingleClient client = model.getSingleClient(); UserBalance userBalance = new UserBalance(); userBalance.setBalance(getBalanceManager().getDefaultBalance(client)); UserMembershipClassification userClassification = new UserMembershipClassification(client.getCalendar()); return classificationReport(model, reportSettings, userClassification, () -> { return getUserBalanceManager().getReport(userBalance, userClassification, reportSettings.getPagination()); }, response); } @RequestMapping(value = "**/admin/members/reports/postalranking", method = RequestMethod.GET ) public Model zipClassificationReport(@ModelAttribute("reportSettings") MemberReportSettings reportSettings, HttpServletRequest request, HttpServletResponse response) throws IOException { return zipClassificationReportRange(reportSettings, null, request, response); } @RequestMapping(value = "**/admin/members/reports/postalranking", method = RequestMethod.POST ) public Model zipClassificationReportRange(@ModelAttribute("reportSettings") MemberReportSettings reportSettings, BindingResult result, HttpServletRequest request, HttpServletResponse response) throws IOException { Model model = initRequest(request, reportSettings); SingleClient client = model.getSingleClient(); UserBalance userBalance = new UserBalance(); userBalance.setBalance(getBalanceManager().getDefaultBalance(client)); UserMembershipZipClassification userClassification = new UserMembershipZipClassification(3); return classificationReport(model, reportSettings, userClassification, () -> { return getUserBalanceManager().getReport(userBalance, userClassification, reportSettings.getPagination()); }, response); } @RequestMapping(value = "**/admin/members/reports/membership", produces = "text/csv", method = RequestMethod.GET ) public void membershipReportCSV(@ModelAttribute("reportSettings") MemberReportSettings reportSettings, HttpServletRequest request, HttpServletResponse response) throws IOException { Model model = initRequest(request, reportSettings); SingleClient client = model.getSingleClient(); reportSettings.setShowRawData(true); reportSettings.setCsv(true); reportSettings.setCSVExportUsageType(new MemberCSVExportUsageType(client)); membershipClassificationReportRange(reportSettings, null, request, response); } public UserManager getUserManager() { return userManager; } @Autowired public void setUserManager(UserManager userManager) { this.userManager = userManager; } public SingleClientManager getSingleClientManager() { return singleClientManager; } @Autowired public void setSingleClientManager(SingleClientManager singleClientManager) { this.singleClientManager = singleClientManager; } public UserBalanceManager getUserBalanceManager() { return userBalanceManager; } @Autowired public void setUserBalanceManager(UserBalanceManager userBalanceManager) { this.userBalanceManager = userBalanceManager; } public BalanceManager getBalanceManager() { return balanceManager; } @Autowired public void setBalanceManager(BalanceManager balanceManager) { this.balanceManager = balanceManager; } }
1,511
https://github.com/missilerider/blockbrain/blob/master/plugins/blocklibs/domotic/homeAssistant/homeAssistant.js
Github Open Source
Open Source
MIT
null
blockbrain
missilerider
JavaScript
Code
603
1,801
'use strict'; const ha = require('./homeAssistant.lib.js'); const blocks = require('./homeAssistant.blocks.lib.js'); const debug = require('debug')('blockbrain:service:homeAssistant'); const log = global.log; const sleep = (milliseconds) => { return new Promise(resolve => setTimeout(resolve, milliseconds)) } var runPromise = null; var runPromiseResolve = null; var tools = null; function getInfo(env) { return { "id": "homeAssistant", "name": "Home Assistant API integration", "author": "Alfonso Vila" } } async function getBlocks() { var blocks = { "onChange": onChangeBlock, "setState": setStateBlock, "setAttributes": setAttributesBlock, "getState": getStateBlock, "getAttributes": getAttributesBlock }; return blocks; } function entitiesCombo(base) { let ret = { ... base }; let things = ha.getEntities(); let thingIds = Object.keys(things).sort(); let combo = []; for(let n = 0; n < thingIds.length; n++) { combo.push([ thingIds[n], thingIds[n] ]); } ret.args0[0].options = combo; if(ret.args0[0].options.length == 0) ret.args0[0].options = [[ "<no entities>", "___NONE___" ]]; return ret; } var onChangeBlock = { "block": function(services) { return entitiesCombo(blocks.onChange); }, "run": async (context) => { context.blockIn(); var entity = context.getField('THING'); var oldState = context.getField('OLDSTATE'); var newState = context.getField('NEWSTATE'); if(entity == context.params.entity) { context.setVar(newState, context.params.state); context.setVar(oldState, context.params.oldState); return await context.continue('CMD'); } } } var setStateBlock = { "block": function(services) { return entitiesCombo(blocks.setState); }, "run": async (context) => { context.blockIn(); var entity = context.getField('THING'); var newState = await context.getValue('NEWSTATE'); ha.setState(entity, newState); } } var setAttributesBlock = { "block": function(services) { return entitiesCombo(blocks.setAttributes); }, "run": async (context) => { context.blockIn(); var entity = context.getField('THING'); var newState = await context.getValue('NEWSTATE'); var newAttr = await context.getValue('NEWATTR'); ha.setState(entity, newState, newAttr); } } var getStateBlock = { "block": function(services) { return entitiesCombo(blocks.getState); }, "run": async (context) => { context.blockIn(); var entity = context.getField('THING'); var entities = ha.getEntities(); if(entity in entities) return entities[entity].state; log.e(`Home Assistant entity ${entity} not found!`); return ""; } } var getAttributesBlock = { "block": function(services) { return entitiesCombo(blocks.getAttributes); }, "run": async (context) => { context.blockIn(); var entity = context.getField('THING'); var entities = ha.getEntities(); if(entity in entities) return entities[entity].attributes; log.e(`Home Assistant entity ${entity} not found!`); return ""; } } function getToolbox() { return { "home assistant": { "Sensor": '', "Switch": '', "General": ' \ <block type="homeAssistant.onChange"></block> \ <block type="homeAssistant.setState"></block> \ <block type="homeAssistant.setAttributes"></block> \ <block type="homeAssistant.getState"></block> \ <block type="homeAssistant.getAttributes"></block>' } } } var haService = { getInfo: () => { return { methods: ["start", "stop"], name: "Home Assistant API integration", description: "Connects directly to a Home Assistant instance and exposes events and things" }}, status: () => { return "TODO"; }, start: (srv) => { return true; }, stop: async (srv) => { if(!runPromise || !runPromiseResolve) return false; runPromiseResolve(); runPromise = null; runPromiseResolve = null; }, run: async (srv, srvTools) => { tools = srvTools; if(runPromise || runPromiseResolve) return false; // Must stop before runPromise = new Promise(resolve => { runPromiseResolve = resolve; }); let haHost = srv.config.secure ? "https://" : "http://"; haHost += srv.config.host; haHost += srv.config.port ? ":" + srv.config.port : ":8123"; let apiToken = srv.config.apiToken; if(!haHost || !apiToken) { log.f("homeAssistant.json host and apiToken fields must be defined at least for Home Assistant integration"); srv.status = 0; return; } ha.config({ host: haHost, apiToken: apiToken, thingChanged: thingChanged }); debug("Checking connection to Home Assistant instance " + srv.config.host); if(!await ha.ping()) { srv.status = 0; log.e("Home Assistant connection error. Please check configuration and connectivity"); debug("Home Assistant API service stopped"); return; } srv.status = 1; debug("Home Assistant connection correct!"); var intervalHandler = setInterval(async () => { ha.tick(ha); }, 2000); await runPromise; clearInterval(intervalHandler); srv.status = 0; debug("Home Assistant API service stopped"); } } async function thingChanged(entity, state, oldState) { debug(`HA ${entity}: ${oldState} => ${state}`); tools.executeEvent('homeAssistant.onChange', { entity: entity }, { entity: entity, oldState: oldState, state: state }); } module.exports = { getInfo: getInfo, getBlocks: getBlocks, getServices: () => { return { "homeAssistant": haService } }, getToolbox: getToolbox }
50,764
https://github.com/SilasReinagel/HomeTaskManagement/blob/master/HomeTaskManagement.App/Common/EventSource/EventStoreExtensions.cs
Github Open Source
Open Source
MIT
2,018
HomeTaskManagement
SilasReinagel
C#
Code
70
214
 using System; using System.Collections.Generic; using System.Linq; namespace HomeTaskManagement.App.Common { public static class EventStoreExtensions { public static Response Commit(this IEventStore events, params Event[] e) { events.Commit(e); return Response.Success(); } public static IEnumerable<T> GetAll<T>(this IEventStore eventStore, Func<EventStream, T> createEntity) { return eventStore.GetEvents<T>() .Select(createEntity) .Finalize(); } public static T Get<T>(this IEventStore eventStore, string id, Func<EventStream, T> createEntity) { return createEntity(new EventStream { Id = id, Events = eventStore.GetEvents<T>(id) }); } } }
14,393
https://github.com/PHELAT/DVDLiveWallpaper/blob/master/app/src/main/java/com/phelat/dvdlogo/state/DvdLogoState.kt
Github Open Source
Open Source
Apache-2.0
2,021
DVDLiveWallpaper
PHELAT
Kotlin
Code
18
63
package com.phelat.dvdlogo.state data class DvdLogoState( var dimensionInSafeArea: Int, var bitmapDimension: Int, var screenDimension: Int, var movementSpeed: Int )
1,703
https://github.com/ShaliniThiyagarajan/Datastructure_and_Algorithm/blob/master/recursive/Recursion/src/sumofnaturalnumber.cpp
Github Open Source
Open Source
MIT
null
Datastructure_and_Algorithm
ShaliniThiyagarajan
C++
Code
67
231
/* * sumofnaturalnumber.cpp * * Created on: 16-Dec-2021 * Author: acer */ #include<iostream> #include<stdio.h> using namespace std; int sum1(int n) { return n*(n+1)/2; } int sum(int n) { if(n >0) { return n+sum(n-1); } return 0; } int sum2(int n) { int sum=0; for(int i=10;i>0; i--) { sum=sum+i; } return sum; } int main() { int n=10; printf("%d \n", sum(n)); printf("%d \n", sum1(n)); printf("%d \n", sum2(n)); }
10,568
https://github.com/magnuseklund/materials/blob/master/MaterialsDomain/Capacitance/CapacitanceNumberingSystem.cs
Github Open Source
Open Source
Apache-2.0
null
materials
magnuseklund
C#
Code
239
754
using System; using System.Collections.Generic; using System.Linq; namespace MaterialsDomain { public struct CapacitanceNumberingSystem { public CapacitanceNumberingSystem(int value) { // Example: 473 = 47pF * 1000 (3 zeroes) = 47 000pf, 47nF, 0,047uF CapacitanceCode = value; } public int CapacitanceCode { get; } public static implicit operator CapacitanceNumberingSystem(MicroFarads mf) { var pf = (PicoFarads)mf; return FromPf(pf); } public static implicit operator CapacitanceNumberingSystem(PicoFarads pf) { return FromPf(pf); } public static implicit operator CapacitanceNumberingSystem(NanoFarads nf) { var pf = (PicoFarads)nf; return FromPf(pf); } private static CapacitanceNumberingSystem FromPf(PicoFarads pf) { // 47000pF var parts = pf.Value.GetLongArray(); // 47 var capValue = parts.Take(2).Select(x => Convert.ToInt32(x)).ToArray().ConcatNumbers(); // 3 var zeroes = parts.Skip(2).Count(); return new CapacitanceNumberingSystem(new[] { capValue, zeroes}.ConcatNumbers()); } public static implicit operator PicoFarads(CapacitanceNumberingSystem c) { // 47000pF // 4,7,3 var parts = c.CapacitanceCode.GetIntArray(); // 47 var capValue = parts.Take(2).ToArray().ConcatNumbers(); // 3 var zeroes = parts.Skip(2).Count(); for(int i = 0; i < 3; i++) { capValue = capValue * 10; } return new PicoFarads(capValue); } public static implicit operator MicroFarads(CapacitanceNumberingSystem c) { var pf = (PicoFarads)c; return (MicroFarads)pf; } public static implicit operator NanoFarads(CapacitanceNumberingSystem c) { var pf = (PicoFarads)c; return (NanoFarads)pf; } private static IEnumerable<long> LTR(long x) { // if (x < 10) return ??; long bound = x/10; long lastPowerOfTen = 1; while(lastPowerOfTen <= bound) { lastPowerOfTen *= 10; // doesn't overflow } long powerOfTen = 1; do { powerOfTen *= 10; yield return x % powerOfTen; } while(powerOfTen < lastPowerOfTen); } } }
41,207
https://github.com/dhenson02/hl7js/blob/master/lib/grammar.js
Github Open Source
Open Source
MIT
2,017
hl7js
dhenson02
JavaScript
Code
57
126
/** * Author : Ramesh R * Created : 8/6/2015 12:04 AM * ---------------------------------------------------------------------- * This file is subject to the terms and conditions defined in * file 'LICENSE', which is part of this source code package. * ---------------------------------------------------------------------- */ 'use strict'; module.exports = { 'ADT^A04': 'MSH PID [{NK1}] PV1 [PV2]', 'ORU^R01': 'MSH PID [{OBR {OBX}}]' };
33,409
https://github.com/FRC6004/2021-Thor/blob/master/src/main/java/frc/robot/Subsystems/Index.java
Github Open Source
Open Source
BSD-3-Clause
null
2021-Thor
FRC6004
Java
Code
133
335
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2017-2018 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package frc.robot.Subsystems; import edu.wpi.first.wpilibj.command.Subsystem; import com.ctre.phoenix.motorcontrol.can.WPI_VictorSPX; import frc.robot.RobotMap; import frc.robot.Commands.*; /** * An example subsystem. You can replace me with your own Subsystem. */ public class Index extends Subsystem { // Put methods for controlling this subsystem // here. Call these from Commands. WPI_VictorSPX VictorSPX = new WPI_VictorSPX(RobotMap.INDEX); public Index() { } @Override public void initDefaultCommand() { // Set the default command for a subsystem here. setDefaultCommand(new IndexCmd(0)); } public void update(double motorSpeed) { // Update motor speed to passed in value VictorSPX.set(motorSpeed); //System.out.print(); } }
23,614
https://github.com/vincentcrowe4airelogic/MockApi/blob/master/Server/HttpRequestExtensions.cs
Github Open Source
Open Source
MIT
null
MockApi
vincentcrowe4airelogic
C#
Code
146
522
using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading.Tasks; using Microsoft.AspNetCore.Http.Features; using Microsoft.Extensions.Primitives; namespace MockApi.Server { public static class HttpRequestExtensions { public static MockApiAction GetMockApiAction(this IHttpRequestFeature request) { Func<string, MockApiAction> parseAction = (s) => (MockApiAction)Enum.Parse(typeof(MockApiAction), s); const string header = "MockApi-Action"; return request.Headers.ContainsKey(header) ? parseAction(request.Headers[header]) : MockApiAction.Call; } public static HttpMethod GetMockApiMethod(this IHttpRequestFeature request) { const string header = "MockApi-Method"; if (request.Headers.ContainsKey(header)) { return new HttpMethod(request.Headers[header]); } return HttpMethod.Get; } public static int GetMockApiStatus(this IHttpRequestFeature request) { const string header = "MockApi-Status"; if (request.Headers.ContainsKey(header)) { return int.Parse(request.Headers[header], null); } return 200; } public static bool GetMockApiFlag(this IHttpRequestFeature request, string flag) { string header = $"MockApi-Flag-{flag}"; if (request.Headers.ContainsKey(header)) { return bool.Parse(request.Headers[header]); } return false; } public static Dictionary<string, StringValues> GetQuery(this IHttpRequestFeature request) { return Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(request.QueryString); } public static Task<string> ReadAsTextAsync(this Stream stream) { using (var streamReader = new StreamReader(stream)) { return streamReader.ReadToEndAsync(); } } } }
38,405
https://github.com/radtek/PInvoke-Printer-Example/blob/master/.gitignore
Github Open Source
Open Source
MIT
2,018
PInvoke-Printer-Example
radtek
Ignore List
Code
3
23
ESCPOSTester/bin/ ESCPOSTester/obj/ *.pfx
3,273
https://github.com/weiweitoo/EmoMap/blob/master/coling18/main/ablation/results/be2vad/lm/German/diff_Disgust.tsv
Github Open Source
Open Source
MIT
2,020
EmoMap
weiweitoo
TSV
Code
64
286
Valence Arousal Dominance Average 1 -0.0072 -0.0039 -0.0006 -0.0039 2 0.0064 0.0113 0.0046 0.0075 3 -0.0036 -0.0039 -0.0005 -0.0026 4 0.0031 0.0069 -0.0011 0.003 5 -0.0015 -0.002 -0.0002 -0.0013 6 -0.0026 -0.0007 0.0028 -0.0002 7 -0.0128 0.0019 -0.0012 -0.004 8 0.0032 0.0073 0.0204 0.0103 9 -0.0046 -0.0094 0.0019 -0.004 10 -0.0026 0.0082 0.0015 0.0024 SD 0.0011 0.0 -0.0007 0.0002 Average -0.0022 0.0016 0.0027 0.0007
33,248
https://github.com/matteocoletta/windows_sdk/blob/master/IntegrationTesting/TestApp/CommandListener.cs
Github Open Source
Open Source
MIT
2,019
windows_sdk
matteocoletta
C#
Code
66
218
using System.Collections.Generic; using TestLibrary; namespace TestApp { public class CommandListener : ICommandListener { private readonly AdjustCommandExecutor _adjustCommandExecutor; public CommandListener() { _adjustCommandExecutor = new AdjustCommandExecutor(); } public void SetTestLibrary(TestLibrary.TestLibrary testLibrary) { _adjustCommandExecutor?.SetTestLibrary(testLibrary); } public void ExecuteCommand(string className, string methodName, Dictionary<string, List<string>> parameters) { switch (className.ToLower()) { case "adjust": _adjustCommandExecutor.ExecuteCommand(new Command(className, methodName, parameters)); break; default: Log.Debug("Could not find {0} class to execute", className); break; } } } }
31,946
https://github.com/octoi/wb-ui-clone/blob/master/app/lib/widgets/chat_card.dart
Github Open Source
Open Source
MIT
2,021
wb-ui-clone
octoi
Dart
Code
192
678
import 'package:app/utils/constants.dart'; import 'package:flutter/material.dart'; class ChatCard extends StatelessWidget { final String image; final String groupName; final String lastMessage; final bool hasNewMessage; final String time; final int remainingMessage; const ChatCard({ Key? key, required this.image, required this.groupName, required this.lastMessage, required this.time, this.hasNewMessage = false, this.remainingMessage = 0, }) : super(key: key); @override Widget build(BuildContext context) { return Column( children: [ InkWell( onTap: () {}, child: Padding( padding: const EdgeInsets.symmetric(vertical: 15.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Row( // crossAxisAlignment: CrossAxisAlignment.start, children: [ CircleAvatar( backgroundImage: NetworkImage(image), radius: 30.0, ), const SizedBox(width: 10.0), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( groupName, style: const TextStyle( color: appWhite, fontSize: 18.0, fontWeight: FontWeight.w600, ), ), const SizedBox(height: 8.0), Text( lastMessage, style: const TextStyle( color: appGrey, fontSize: 16.0, ), ), ], ) ], ), Column( crossAxisAlignment: CrossAxisAlignment.end, children: [ Text( time, style: TextStyle( color: hasNewMessage ? appBlue : appGrey, ), ), if (hasNewMessage) const SizedBox(height: 5.0), if (hasNewMessage) Container( width: 25.0, height: 25.0, decoration: BoxDecoration( color: appBlue, borderRadius: BorderRadius.circular(50.0), ), child: Center( child: Text( '$remainingMessage', style: const TextStyle( color: appBlack, ), ), ), ) ], ) ], ), ), ), const Divider( height: 2.0, color: appDarkGrey, ), ], ); } }
39,208
https://github.com/crucially/timesplicedb/blob/master/perl/TSDB/t/agg.t
Github Open Source
Open Source
BSD-2-Clause
2,017
timesplicedb
crucially
Perl
Code
295
939
use Test::More tests => 40; BEGIN { use_ok('TSDB') }; use strict; unlink("aggtest.tsdb"); my $ct = 1258091219; my $it = $ct; my $tsdb = TSDB->new('aggtest.tsdb', clobber => 1, resolution => 60, columns => 'test', create_time => $ct); foreach(1..9) { $tsdb->insert('test' => $_, $it); $it += 60; } is($tsdb->rows, 9); my $range = $tsdb->timespan($ct, $it - 60); isa_ok($range, "TSDB::Range"); is($range->rows, 9); for(1..9) { my $cell = $range->cell($_-1, 'test'); is_deeply($cell, { stddev => 0, min => $_, value => $_, max => $_, avg => $_, row => $_-1, time => 0, rows_averaged => 0, }, "row, this is not aggregated"); } my $agg = $range->aggregate(120); isa_ok($range, "TSDB::Range"); is($agg->rows, 5); { my $cell = $agg->cell(0, 'test'); is($cell->{stddev}, 0.5, "stddev"); is($cell->{min}, 1, "lowest we have seen"); is($cell->{max}, 2, "highest we have seen"); is($cell->{avg}, 1.5 , "between 1 and 2"); is($cell->{rows_averaged}, 2, "this bucket should have two entries!"); } { my $cell = $agg->cell(1, 0); is($cell->{stddev}, 0.5, "stddev"); is($cell->{min}, 3, "lowest we have seen"); is($cell->{max}, 4, "highest we have seen"); is($cell->{avg}, 3.5 , "between 3 and 4"); is($cell->{rows_averaged}, 2, "this bucket should have two entries!"); } { my $cell = $agg->cell(2, 'test'); is($cell->{stddev}, 0.5, "stddev"); is($cell->{min}, 5, "lowest we have seen"); is($cell->{max}, 6, "highest we have seen"); is($cell->{avg}, 5.5 , "between 5 and 6"); is($cell->{rows_averaged}, 2, "this bucket should have two entries!"); } { my $cell = $agg->cell(3, 0); is($cell->{stddev}, 0.5, "stddev"); is($cell->{min}, 7, "lowest we have seen"); is($cell->{max}, 8, "highest we have seen"); is($cell->{avg}, 7.5 , "between 7 and 8"); is($cell->{rows_averaged}, 2, "this bucket should have two entries!"); } { my $cell = $agg->cell(4, 'test'); is($cell->{stddev}, 0, "no stddev"); is($cell->{min}, 9, "lowest we have seen"); is($cell->{max}, 9, "highest we have seen"); is($cell->{avg}, 9 , "only one in this bucket 9"); is($cell->{rows_averaged}, 1, "this bucket should have two entries!"); }
15,428
https://github.com/KevinBlack/ele-admin/blob/master/src/views/example/detail-layout/components/pop-tab-gang.vue
Github Open Source
Open Source
MIT
null
ele-admin
KevinBlack
Vue
Code
481
2,390
<template> <div class="detailsContainer"> <el-tabs v-model="activeName" @tab-click="handleClick"> <el-tab-pane label="用户管理" name="princeInfo"> <!-- part1 --> <el-row :gutter="10"> <el-col :span="24"> <h5 class="dtl-title-line">公共信息</h5> </el-col> </el-row> <el-form ref="ruleForm" label-width="100px" size="mini"> <el-row :gutter="20"> <el-col :span="6"> <el-form-item label="信息编号" prop="number"> <el-input /> </el-form-item> </el-col> <el-col :span="6"> <el-form-item label="业务人员" prop="number"> <el-select v-model="value" placeholder="请选择" style="width: 100%;"> <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"> </el-option> </el-select> </el-form-item> </el-col> <el-col :span="12"> <el-form-item label="公司" prop="number"> <el-input /> </el-form-item> </el-col> </el-row> </el-form> <!-- part2 --> <el-row :gutter="10"> <el-col :span="12"> <h5 class="dtl-title-line">基本信息</h5> </el-col> <el-col :span="12" style="text-align:right;margin-top:20px;"> <el-button type="success" icon="el-icon-edit" size="mini">按钮1</el-button> <el-button type="success" icon="el-icon-share" size="mini">刷新</el-button> </el-col> </el-row> <el-form ref="ruleForm" label-width="100px" size="mini"> <el-row :gutter="20"> <el-col :span="12"> <el-form-item label="客户" prop="number"> <el-input /> </el-form-item> </el-col> <el-col :span="6"> <el-form-item label="所在地区" prop="number"> <el-input /> </el-form-item> </el-col> <el-col :span="6"> <el-form-item label="联系人" prop="number"> <el-input /> </el-form-item> </el-col> </el-row> <el-row :gutter="20"> <el-col :span="6"> <el-form-item label="报价日期" prop="number"> <el-time-picker is-range arrow-control v-model="value5" start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围" style="width: 100%;" /> </el-form-item> </el-col> <el-col :span="6"> <el-form-item label="有效日期" prop="number"> <el-checkbox-group v-model="checkList"> <el-checkbox label="一周"></el-checkbox> <el-checkbox label="一月"></el-checkbox> <el-checkbox label="一年"></el-checkbox> </el-checkbox-group> </el-form-item> </el-col> <el-col :span="6"> <el-form-item label="是否缩写" prop="number"> <el-switch v-model="value3" active-color="#13ce66" inactive-color="#ff4949" style="width: 100%;" /> </el-form-item> </el-col> <el-col :span="6"> <el-form-item label="拼音大写"> <el-input /> </el-form-item> </el-col> </el-row> <el-row :gutter="20"> <el-col :span="6"> <el-form-item label="币种" prop="number"> <el-radio v-model="radio" label="1">人民币</el-radio> <el-radio v-model="radio" label="2">欧元</el-radio> </el-form-item> </el-col> <el-col :span="6"> <el-form-item label="汇率" prop="number"> <el-input /> </el-form-item> </el-col> <el-col :span="6"> <el-form-item label="价格条件" prop="number"> <el-input /> </el-form-item> </el-col> <el-col :span="6"> <el-form-item label="付款日期" prop="number"> <el-date-picker v-model="value2" type="daterange" align="right" unlink-panels start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions" style="width: 100%" /> </el-form-item> </el-col> <el-col :span="24"> <el-form-item label="备注" prop="number"> <el-input /> </el-form-item> </el-col> </el-row> </el-form> </el-tab-pane> <el-tab-pane label="配置管理" name="princeList">报价单</el-tab-pane> </el-tabs> <div slot="footer" class="dialog-footer"> <el-button @click="dialogFormVisible = false">取 消</el-button> <el-button type="primary" @click="dialogFormVisible = false">保 存</el-button> </div> </div> </template> <script> export default { data() { return { activeName: 'princeInfo', checkList: ['一周'], radio: '1', pickerOptions: { shortcuts: [{ text: '最近一周', onClick(picker) { const end = new Date(); const start = new Date(); start.setTime(start.getTime() - 3600 * 1000 * 24 * 7); picker.$emit('pick', [start, end]); } }, { text: '最近一个月', onClick(picker) { const end = new Date(); const start = new Date(); start.setTime(start.getTime() - 3600 * 1000 * 24 * 30); picker.$emit('pick', [start, end]); } }, { text: '最近三个月', onClick(picker) { const end = new Date(); const start = new Date(); start.setTime(start.getTime() - 3600 * 1000 * 24 * 90); picker.$emit('pick', [start, end]); } }] }, value1: '', value2: '', value3: true, value5: [new Date(2016, 9, 10, 8, 40), new Date(2016, 9, 10, 9, 40)], options: [{ value: '选项1', label: '张三' }, { value: '选项2', label: '李四' }, { value: '选项3', label: '王五' }, { value: '选项4', label: '赵六' }, { value: '选项5', label: '刘七' }], value: '' } }, methods: { handleClick(tab, event) { console.log(tab, event) }, handleShow() { console.log(1) } } } </script> <style scoped> *{ font-weight: normal; } .detailsContainer { margin: 0; } .dtl-title-line { display: inline-block; border-left: 3px solid #409EFF; padding-left: 5px; } .el-table__fixed-right::before { background-color: none; } .dialog-footer { border-top: 1px solid #e6e6e6; margin-top: 30px; padding-top: 10px; text-align: right; } </style>
10,895
https://github.com/ruigil/shaders/blob/master/pixelspirit/00-TheVoid.glsl
Github Open Source
Open Source
MIT
2,021
shaders
ruigil
GLSL
Code
108
196
#version 300 es precision highp float; // Pixel Spirit Deck // https://patriciogonzalezvivo.github.io/PixelSpiritDeck/ // A pixel shader is a function executed for every pixel. // So if the image has 1280x720 pixels and refreshes 60 times per second... // the function is executed 55 million times per second ! (1280x720x60 = 55.296.000) // The function receives a pixel coordinate a must produce a color, (x,y) => color // Color is a 'vector' of 4 components (Red, Green, Blue, Alpha) // Values go from 0. to 1. This shader produces one opaque black pixel for every coordinate. out vec4 pixel; void main() { pixel = vec4(0., 0., 0., 1.); }
28,378
https://github.com/sillywalk/grazz/blob/master/tests/binutils-2.30/src/ld/testsuite/ld-elf/group3b.s
Github Open Source
Open Source
Apache-2.0
2,021
grazz
sillywalk
GAS
Code
11
47
.section .data,"awG",%progbits,foo_group,comdat .hidden foo .globl foo .type foo,%object foo: .word 0
50,003
https://github.com/3sidedcube/ThunderCloud/blob/master/ThunderCloud/Utilities.swift
Github Open Source
Open Source
Apache-2.0
2,020
ThunderCloud
3sidedcube
Swift
Code
70
146
// // Utilities.swift // ThunderCloud // // Created by Ben Shutt on 20/12/2019. // Copyright © 2019 threesidedcube. All rights reserved. // import Foundation /// Bound `value`between `lower` and `upper` /// /// - Parameters: /// - value: Value to bound /// - lower: Lower bound /// - upper: Upper bound func bounded<T>(_ value: T, lower: T, upper: T) -> T where T : Comparable { return max(lower, min(upper, value)) }
5,259
https://github.com/sniperkit/colly/blob/master/plugins/data/parser/ql/pzp26/term.go
Github Open Source
Open Source
Apache-2.0
null
colly
sniperkit
Go
Code
38
109
package PZP26 type TermNode struct { Right interface{} Operator TermOperator Left interface{} } func (t TermNode) String() string { return "TODO" } func ParseTerm(term string) (TermNode, []error, []error) { //return TermNode{}, []error{}, []error{errors.New("TODO")} return TermNode{}, []error{}, []error{} }
13,946
https://github.com/dobryy/rector/blob/master/packages/BetterPhpDocParser/Contract/BasePhpDocNodeVisitorInterface.php
Github Open Source
Open Source
MIT
null
rector
dobryy
PHP
Code
13
100
<?php declare (strict_types=1); namespace Rector\BetterPhpDocParser\Contract; use RectorPrefix20211109\Symplify\SimplePhpDocParser\Contract\PhpDocNodeVisitorInterface; interface BasePhpDocNodeVisitorInterface extends \RectorPrefix20211109\Symplify\SimplePhpDocParser\Contract\PhpDocNodeVisitorInterface { }
34,290
https://github.com/xpucmon/JavaExams/blob/master/190414 JavaSpringWeb/ebankdemoproject/src/main/java/org/softuni/ebankdemoproject/domain/entities/bankaccounts/BankAccount.java
Github Open Source
Open Source
MIT
null
JavaExams
xpucmon
Java
Code
204
661
package org.softuni.ebankdemoproject.domain.entities.bankaccounts; import org.softuni.ebankdemoproject.domain.entities.BaseEntity; import org.softuni.ebankdemoproject.domain.entities.users.User; import javax.persistence.*; import java.math.BigDecimal; import java.time.LocalDateTime; @Entity(name = "bank_accounts") public class BankAccount extends BaseEntity { private String iban; private AccountType accountType; private AccountStatus accountStatus; private User accountOwner; private LocalDateTime dateOpened; private BigDecimal balance; private BigDecimal interestRate; public BankAccount() { } @Column(nullable = false, unique = true, updatable = false) public String getIban() { return iban; } public void setIban(String iban) { this.iban = iban; } @Enumerated(value = EnumType.STRING) @Column(name = "account_type") public AccountType getAccountType() { return accountType; } public void setAccountType(AccountType accountType) { this.accountType = accountType; } @Enumerated(value = EnumType.STRING) @Column(name = "account_status") public AccountStatus getAccountStatus() { return accountStatus; } public void setAccountStatus(AccountStatus accountStatus) { this.accountStatus = accountStatus; } @ManyToOne(targetEntity = User.class) @JoinColumn(name = "account_owner", referencedColumnName = "id", nullable = false) public User getAccountOwner() { return accountOwner; } public void setAccountOwner(User accountOwner) { this.accountOwner = accountOwner; } @Column(name = "date_opened", nullable = false) public LocalDateTime getDateOpened() { return dateOpened; } public void setDateOpened(LocalDateTime dateOpened) { this.dateOpened = dateOpened; } @Column(nullable = false) public BigDecimal getBalance() { return balance; } public void setBalance(BigDecimal balance) { this.balance = balance; } @Column(name = "interest_rate") public BigDecimal getInterestRate() { return interestRate; } public void setInterestRate(BigDecimal interestRate) { this.interestRate = interestRate; } }
4,846
https://github.com/A-Pujo/NAC/blob/master/app/Views/dashboard/pages/acara/sma/2_berkas_bts.php
Github Open Source
Open Source
Apache-2.0
2,021
NAC
A-Pujo
PHP
Code
74
325
<table class="tabel" id="tabel"> <thead> <tr> <th>#</th> <th>Nama Tim</th> <th>Berkas</th> </tr> </thead> <tbody> <?php $no=1; foreach(md('sma')->getAll('prelim', 1) as $peserta) : ?> <tr> <?php if($peserta['berkas_1'] != ''){ list($tgl, $file) = explode('|', $peserta['berkas_1']); } else { $tgl = ''; $file = '#'; } ?> <td><?= $no++ ?></td> <td><?= $peserta['nama_tim'] ?></td> <td><?= $tgl ?></td> <td><a class="btn btn-sm btn-primary <?= $peserta['berkas_1'] != '' ? '' : 'btn-disabled' ?>" href="<?= base_url('uploads/partisipan/lomba/berkas/'.$file) ?>" download>Unduh berkas</a></td> </tr> <?php endforeach ?> </tbody> </table>
28,230
https://github.com/aingaRamangalahy/fanadinana/blob/master/src/app/core/services/auth.service.ts
Github Open Source
Open Source
MIT
null
fanadinana
aingaRamangalahy
TypeScript
Code
42
121
import { Injectable } from '@angular/core'; import { User } from '../interfaces'; import { MainService } from './main.service'; @Injectable({ providedIn: 'root' }) export class AuthService { apiUrl = "/api/v1/auth" constructor(private mainService: MainService) { } login(user: User) { return this.mainService._POST(`${this.apiUrl}/login`, user); } }
32,888