hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
98 values
lang
stringclasses
21 values
max_stars_repo_path
stringlengths
3
945
max_stars_repo_name
stringlengths
4
118
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
368k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
945
max_issues_repo_name
stringlengths
4
118
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
945
max_forks_repo_name
stringlengths
4
135
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
5
1.05M
avg_line_length
float64
1
1.03M
max_line_length
int64
2
1.03M
alphanum_fraction
float64
0
1
0dbacd7459d5371ceb5bee821333e4ba71be9e4d
195
rb
Ruby
components/old_sponsored_benefits/spec/factories/sponsored_benefits_benefit_applications_benefit_application_renewers.rb
ideacrew/opm_enroll
fc7fd7ae75baa6497a55118a9c54b9d9033c72b3
[ "Unlicense", "MIT" ]
5
2017-04-07T12:28:47.000Z
2022-03-23T19:12:19.000Z
components/old_sponsored_benefits/spec/factories/sponsored_benefits_benefit_applications_benefit_application_renewers.rb
ideacrew/opm_enroll
fc7fd7ae75baa6497a55118a9c54b9d9033c72b3
[ "Unlicense", "MIT" ]
386
2017-04-07T16:00:48.000Z
2022-03-31T19:59:53.000Z
components/old_sponsored_benefits/spec/factories/sponsored_benefits_benefit_applications_benefit_application_renewers.rb
ideacrew/opm_enroll
fc7fd7ae75baa6497a55118a9c54b9d9033c72b3
[ "Unlicense", "MIT" ]
6
2017-04-07T15:20:18.000Z
2020-08-14T14:34:19.000Z
FactoryGirl.define do factory :sponsored_benefits_benefit_applications_benefit_application_renewer, class: 'SponsoredBenefits::BenefitApplications::BenefitApplicationRenewer' do end end
32.5
157
0.85641
b74bf15f46745c90202343ea77a3026b857f93c9
784
cpp
C++
Software/app/nixie_state.cpp
gotlaufs/rtu-nixie-clock
7fe43f13deb8f5314ce19d00fe6623337c0d0df7
[ "MIT" ]
null
null
null
Software/app/nixie_state.cpp
gotlaufs/rtu-nixie-clock
7fe43f13deb8f5314ce19d00fe6623337c0d0df7
[ "MIT" ]
5
2019-02-19T22:23:19.000Z
2019-02-19T22:27:27.000Z
Software/app/nixie_state.cpp
gotlaufs/rtu-nixie-clock
7fe43f13deb8f5314ce19d00fe6623337c0d0df7
[ "MIT" ]
null
null
null
// Nixie state class implementation #include "nixie_state.h" NixieState::NixieState(NixieClock & app_) : app(app_) { memset(&nixie_data, 0, sizeof(nixie_data_type)); } void NixieState::writeTimeToNixie() { if (sec > 99) { // Blank tubes if too big digit nixie_data.N6 = 10; nixie_data.N5 = 10; } else { nixie_data.N6 = sec % 10; nixie_data.N5 = sec / 10; } if (min > 99) { nixie_data.N4 = 10; nixie_data.N3 = 10; } else { nixie_data.N4 = min % 10; nixie_data.N3 = min / 10; } if (hour > 99) { nixie_data.N2 = 10; nixie_data.N1 = 10; } else { nixie_data.N2 = hour % 10; nixie_data.N1 = hour / 10; } }
17.422222
53
0.512755
7cb9a8db907ea979f0d3d0ec736926e262f06dd6
594
swift
Swift
BookRoom/BookView.swift
XcqRomance/BookRoom-complete-
4e6387fb7c72dc620c51fb6f50a41843b9109521
[ "MIT" ]
3
2017-08-29T07:56:31.000Z
2017-11-24T02:07:56.000Z
BookRoom/BookView.swift
XcqRomance/BookRoom-complete-
4e6387fb7c72dc620c51fb6f50a41843b9109521
[ "MIT" ]
null
null
null
BookRoom/BookView.swift
XcqRomance/BookRoom-complete-
4e6387fb7c72dc620c51fb6f50a41843b9109521
[ "MIT" ]
null
null
null
// // BookView.swift // BookRoom // // Created by romance on 2017/5/4. // Copyright © 2017年 romance. All rights reserved. // import UIKit final class BookView: UICollectionView { override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) let nib = UINib(nibName: "BookCell", bundle: nil) register(nib, forCellWithReuseIdentifier: "BookCell") backgroundColor = UIColor.hexColor(0x176DA6) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
22
85
0.700337
23f74aadb31db09e625a39e76c9045bf7f84cd7c
900
js
JavaScript
webapp/routes/api.js
kongchun/mapRoute
94bcd9145f85104f796c8cb52f46b67369f541a1
[ "MIT" ]
null
null
null
webapp/routes/api.js
kongchun/mapRoute
94bcd9145f85104f796c8cb52f46b67369f541a1
[ "MIT" ]
null
null
null
webapp/routes/api.js
kongchun/mapRoute
94bcd9145f85104f796c8cb52f46b67369f541a1
[ "MIT" ]
null
null
null
var express = require('express'); var router = express.Router(); var app = express(); var read = require('../server/read.js'); var write = require('../server/write.js'); /* GET users listing. */ router.get('/', function(req, res, next) { res.send({ result: false }); }); router.get('/route', function(req, res, next) { res.send({ result: false }); }); router.post('/route/line', function(req, res, next) { var _id = (req.body._id); var line = JSON.parse(req.body.line); write.routeLine(_id, line).then(function() { res.send({ result: true }); }); }) router.get('/route/:id/:date', function(req, res, next) { var id = (req.params.id); var date = (req.params.date); read.getWithDateAndId(id, date).then(function(data) { res.send({ result: true, data: data }) }).catch(function(e) { res.send({ result: false, data: e }) }) }); module.exports = router;
18.367347
57
0.611111
72abc4885e0d3a2922d51a34be079d6ad33aa653
2,660
cs
C#
parts/0000-TLPLib/Assets/Vendor/TLPLib/Editor/Utils/CodePreprocessor.cs
tinylabproductions/tlplib
8e54b6ddbd0f4e037e61437142902b357f13679d
[ "MIT" ]
74
2015-01-27T14:49:12.000Z
2022-01-11T11:16:25.000Z
parts/0000-TLPLib/Assets/Vendor/TLPLib/Editor/Utils/CodePreprocessor.cs
tinylabproductions/tlplib
8e54b6ddbd0f4e037e61437142902b357f13679d
[ "MIT" ]
20
2016-07-07T11:14:49.000Z
2021-01-25T08:51:32.000Z
parts/0000-TLPLib/Assets/Vendor/TLPLib/Editor/Utils/CodePreprocessor.cs
tinylabproductions/tlplib
8e54b6ddbd0f4e037e61437142902b357f13679d
[ "MIT" ]
18
2015-02-27T04:02:43.000Z
2020-11-13T09:27:30.000Z
using System; using System.Collections.Immutable; using System.IO; using System.Linq; using com.tinylabproductions.TLPLib.Extensions; using pzd.lib.exts; using pzd.lib.functional; namespace com.tinylabproductions.TLPLib.Editor.Utils { public static class CodePreprocessor { public const string PRAG_STR = "#pragma warning disable"; public const string DIRECTIVES_STR = "#"; public static void processFile(string path, bool add) { var lines = File.ReadAllLines(path).ToImmutableList(); var editedText = (add ? checkAndWritePragma(lines) : checkAndRemovePragma(lines)).ToArray(); File.WriteAllLines(path, editedText); } public static ImmutableList<string> checkAndRemovePragma(ImmutableList<string> lines) => lines.process( onNoPragma: _ => lines, onNoDirectives: () => lines, onPragmaExists: (pragmaLineIdx, _) => lines.RemoveAt(pragmaLineIdx) ); public static ImmutableList<string> checkAndWritePragma(ImmutableList<string> lines) => lines.process( onNoPragma: lastDirectiveLineIdx => lines.addPragmaAt(lastDirectiveLineIdx + 1), onNoDirectives: () => lines.addPragmaAt(0), onPragmaExists: (pragmaLineIdx, lastDirectiveIdx) => pragmaLineIdx == lastDirectiveIdx ? lines : lines.reformatPragmas(pragmaLineIdx, lastDirectiveIdx) ); public static ImmutableList<string> process( this ImmutableList<string> lines, Func<int, ImmutableList<string>> onNoPragma, Func<int, int, ImmutableList<string>> onPragmaExists, Func<ImmutableList<string>> onNoDirectives ) => getLastDirectiveIndex(lines).fold( onNoDirectives, lastDirectiveIdx => pragmaLineNumber(lines.GetRange(0, lastDirectiveIdx + 1)).fold( () => onNoPragma(lastDirectiveIdx), pragmaLineIdx => onPragmaExists(pragmaLineIdx, lastDirectiveIdx) ) ); static ImmutableList<string> addPragmaAt(this ImmutableList<string> lines, int lineIndex) => lines.Insert(lineIndex, PRAG_STR); static ImmutableList<string> reformatPragmas( this ImmutableList<string> lines, int currentPragmaLineIdx, int lastDirectiveLineIdx ) => lines.addPragmaAt(lastDirectiveLineIdx + 1).RemoveAt(currentPragmaLineIdx); public static Option<int> getLastDirectiveIndex(this ImmutableList<string> lines) => lines.indexWhere(line => !line.StartsWithFast(DIRECTIVES_STR)).flatMap(idx => (idx > 0).opt(idx - 1)); public static Option<int> pragmaLineNumber(this ImmutableList<string> lines) => lines.indexWhere(line => line.StartsWithFast(PRAG_STR)); } }
40.923077
108
0.710526
6d2caa6087abf5b900ff7f1912e9c6c3e9e44752
738
ts
TypeScript
web/ts/Symbol.ts
xjpstar/web
fb1bc574f7431131affc9696d5967a65371fdbe4
[ "Apache-2.0" ]
null
null
null
web/ts/Symbol.ts
xjpstar/web
fb1bc574f7431131affc9696d5967a65371fdbe4
[ "Apache-2.0" ]
19
2021-10-31T03:17:09.000Z
2022-03-08T23:37:36.000Z
web/ts/Symbol.ts
xjpstar/web
fb1bc574f7431131affc9696d5967a65371fdbe4
[ "Apache-2.0" ]
null
null
null
// let sym1 = Symbol(); // Symbol.hasInstance // 方法,会被instanceof运算符调用。构造器对象用来识别一个对象是否是其实例。 // Symbol.isConcatSpreadable // 布尔值,表示当在一个对象上调用Array.prototype.concat时,这个对象的数组元素是否可展开。 // Symbol.iterator // 方法,被for-of语句调用。返回对象的默认迭代器。 // Symbol.match // 方法,被String.prototype.match调用。正则表达式用来匹配字符串。 // Symbol.replace // 方法,被String.prototype.replace调用。正则表达式用来替换字符串中匹配的子串。 // Symbol.search // 方法,被String.prototype.search调用。正则表达式返回被匹配部分在字符串中的索引。 // Symbol.species // 函数值,为一个构造函数。用来创建派生对象。 // Symbol.split // 方法,被String.prototype.split调用。正则表达式来用分割字符串。 // Symbol.toPrimitive // 方法,被ToPrimitive抽象操作调用。把对象转换为相应的原始值。 // Symbol.toStringTag // 方法,被内置方法Object.prototype.toString调用。返回创建对象时默认的字符串描述。 // Symbol.unscopables // 对象,它自己拥有的属性会被with作用域排除在外。
21.705882
57
0.776423
2c470423c4a8650554753ce996f049443bea42d2
280
lua
Lua
scripts/globals/items/scroll_of_enwater.lua
PaulAnthonyReitz/topaz
ffa3a785f86ffdb2f6a5baf9895b649e3e3de006
[ "FTL" ]
6
2021-06-01T04:17:10.000Z
2021-06-01T04:32:21.000Z
scripts/globals/items/scroll_of_enwater.lua
PaulAnthonyReitz/topaz
ffa3a785f86ffdb2f6a5baf9895b649e3e3de006
[ "FTL" ]
5
2020-04-10T19:33:53.000Z
2021-06-27T17:50:05.000Z
scripts/globals/items/scroll_of_enwater.lua
PaulAnthonyReitz/topaz
ffa3a785f86ffdb2f6a5baf9895b649e3e3de006
[ "FTL" ]
2
2020-04-11T16:56:14.000Z
2021-06-26T12:21:12.000Z
----------------------------------------- -- ID: 4713 -- Scroll of Enwater -- Teaches the white magic Enwater ----------------------------------------- function onItemCheck(target) return target:canLearnSpell(105) end function onItemUse(target) target:addSpell(105) end
20
41
0.525
57cb235e4384a3590da86301b7d6eb59941592e4
11,829
dart
Dart
lib/view/rating/rating_page.dart
Lend-it/Front
b93f53f90cdcd295b4b0664eeee714378bbfe5bb
[ "MIT" ]
3
2021-02-15T00:10:33.000Z
2021-02-17T12:05:49.000Z
lib/view/rating/rating_page.dart
g1-project/front
b93f53f90cdcd295b4b0664eeee714378bbfe5bb
[ "MIT" ]
3
2021-03-14T22:30:38.000Z
2021-03-28T01:56:38.000Z
lib/view/rating/rating_page.dart
g1-project/front
b93f53f90cdcd295b4b0664eeee714378bbfe5bb
[ "MIT" ]
null
null
null
import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; import 'package:front/controller/rating.controller.dart'; import 'package:front/model/rating.model.dart'; import 'package:front/model/session.model.dart'; import 'package:front/theme/colors.dart'; import 'package:front/widgets/button.dart'; import 'package:front/widgets/rating_stars.dart'; import 'package:provider/provider.dart'; class RatingPage extends StatefulWidget { @override _RatingPageState createState() => _RatingPageState(); } class _RatingPageState extends State<RatingPage> { TextEditingController _descriptionController; int rate; bool report; bool isSelectedY = false; bool isSelectedN = false; @override void initState() { super.initState(); _descriptionController = TextEditingController(); } @override void dispose() { _descriptionController.dispose(); super.dispose(); } void _createRating( BuildContext context, int rate, bool report, SessionModel session) { print(_descriptionController); final RatingModel rating = new RatingModel( stars: rate, review: _descriptionController.text, report: report, reviewer: session.user.email, reviewed: 'rogerio@email.com', requestid: '8d27b6c1-ac8a-4f29-97b0-96cef6938267', ); new RatingController().createNewRating(rating, context); } @override Widget build(BuildContext context) { final session = Provider.of<SessionModel>(context, listen: false); Color chipColor = secondaryColor; Duration animationDuration = Duration(milliseconds: 300); return Scaffold( extendBodyBehindAppBar: true, appBar: AppBar( backgroundColor: Colors.transparent, elevation: 0, ), body: SingleChildScrollView( child: Container( child: Column( children: [ Stack( clipBehavior: Clip.none, children: [ Stack( children: [ Container( width: double.infinity, height: 350, child: Image( colorBlendMode: BlendMode.darken, fit: BoxFit.fitWidth, image: NetworkImage( 'https://avatars.githubusercontent.com/u/31940073?v=4', ), ), ), ], ), ], ), Container( padding: EdgeInsets.symmetric( horizontal: 20, vertical: 20, ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Avalie sua experiência com o Lucas, ao emprestar um Banco Imobiliário.', style: Theme.of(context).textTheme.subtitle1.copyWith( color: darkColor, ), ), SizedBox(height: 10), Row( children: <Widget>[ Chip( label: Text( 'category', style: TextStyle(color: lightColor), ), backgroundColor: secondaryLightColor, ), VerticalDivider( width: 20, color: grayColor, thickness: 2, endIndent: 17, indent: 17, ), Row( children: <Widget>[ Icon( Icons.calendar_today_outlined, size: 20, ), Padding( padding: EdgeInsets.symmetric(horizontal: 7.0), child: Text('20/04 até 22/04'), ), ], ), ], ), SizedBox(height: 15), Text( 'Qual nota você daria para Lucas ?', style: Theme.of(context).textTheme.subtitle2.copyWith( color: darkColor, ), ), SizedBox(height: 10), RatingStars((rating) { rate = rating; }), SizedBox(height: 30), Text( 'Fale mais sobre sua experiência', style: Theme.of(context).textTheme.subtitle2.copyWith( color: darkColor, ), ), SizedBox(height: 15), TextField( style: Theme.of(context).textTheme.bodyText2.copyWith( color: darkColor, fontSize: 14, ), controller: _descriptionController, maxLines: 4, decoration: InputDecoration( enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(4.0), borderSide: BorderSide(color: whiteDarkColor), ), hintText: 'Descrição', hintStyle: Theme.of(context).textTheme.bodyText2.copyWith( color: darkColor, fontSize: 14, ), focusedBorder: OutlineInputBorder( borderSide: BorderSide( color: whiteDarkColor, width: 2.0, ), ), border: OutlineInputBorder( borderSide: BorderSide(color: whiteDarkColor), ), ), ), SizedBox(height: 25), Text( 'Deseja reportar a Lucas por algo grave?', style: Theme.of(context).textTheme.subtitle2.copyWith( color: darkColor, ), ), SizedBox(height: 10), Row( children: [ Container( height: 32, child: InkWell( onTap: () { setState(() { isSelectedY = true; isSelectedN = false; }); report = true; }, child: AnimatedContainer( duration: animationDuration, padding: EdgeInsets.symmetric(horizontal: 12), child: Center( child: AnimatedDefaultTextStyle( duration: animationDuration, style: Theme.of(context) .textTheme .caption .copyWith( color: chipColor, ), child: Text( 'Sim', style: Theme.of(context) .textTheme .bodyText2 .copyWith( color: isSelectedY ? lightColor : secondaryColor, ), ), ), ), decoration: BoxDecoration( color: isSelectedY ? secondaryColor : lightColor, border: Border.all( color: secondaryColor, ), borderRadius: BorderRadius.circular(6), ), ), ), ), SizedBox(width: 10), Container( height: 32, child: InkWell( onTap: () { setState(() { isSelectedY = false; isSelectedN = true; }); report = false; }, child: AnimatedContainer( duration: animationDuration, padding: EdgeInsets.symmetric(horizontal: 12), child: Center( child: AnimatedDefaultTextStyle( duration: animationDuration, style: Theme.of(context) .textTheme .caption .copyWith( color: chipColor, ), child: Text( 'Não', style: Theme.of(context) .textTheme .bodyText2 .copyWith( color: isSelectedN ? lightColor : secondaryColor, ), ), ), ), decoration: BoxDecoration( color: isSelectedN ? secondaryColor : null, border: Border.all( color: secondaryColor, ), borderRadius: BorderRadius.circular(6), ), ), ), ), ], ), SizedBox(height: 30), Button( title: 'Enviar avaliação', onPressedHandler: () { _createRating(context, rate, report, session); }, ) ], ), ) ], ), ), ), ); } }
39.43
95
0.346859
8340d9c594f1685b5e7e931490fcdfbfb88f50da
1,486
ts
TypeScript
openconcertclient/src/app/components/profile/profile.module.ts
didacusAbella/OpenStore
1b0163ef15e4eed10349f7b99f9e44409b4588d7
[ "MIT" ]
1
2019-02-01T11:10:32.000Z
2019-02-01T11:10:32.000Z
openconcertclient/src/app/components/profile/profile.module.ts
didacusAbella/OpenStore
1b0163ef15e4eed10349f7b99f9e44409b4588d7
[ "MIT" ]
1
2019-06-06T12:55:06.000Z
2019-06-06T12:55:06.000Z
openconcertclient/src/app/components/profile/profile.module.ts
didacusAbella/OpenConcert
1b0163ef15e4eed10349f7b99f9e44409b4588d7
[ "MIT" ]
null
null
null
import { CommonModule } from "@angular/common"; import { ReactiveFormsModule } from "@angular/forms"; import { RouterModule, Routes } from "@angular/router"; import { NgModule } from '@angular/core'; import { InputTextModule } from 'primeng/inputtext'; import { PasswordModule } from 'primeng/password'; import { ButtonModule } from 'primeng/button'; import { PanelModule } from "primeng/panel"; import {PickListModule} from 'primeng/picklist'; import { ProfileComponent } from './profile.component'; import { AuthGuardService } from 'src/app/shared/guards/auth-guard.service'; import { UserService } from 'src/app/shared/services/user.service'; import { DropdownModule } from 'primeng/dropdown'; import { LocaleService } from 'src/app/shared/services/locale.service'; import { GenreService } from 'src/app/shared/services/genre.service'; import { MessageService } from 'primeng/api'; import { ToastModule} from "primeng/toast"; const PROFILE_ROUTE: Routes = [ { path: 'profile', component: ProfileComponent, canActivate: [AuthGuardService] } ]; @NgModule({ declarations: [ProfileComponent], imports: [ CommonModule, ReactiveFormsModule, InputTextModule, PasswordModule, ButtonModule, PanelModule, DropdownModule, PickListModule, ToastModule, RouterModule.forChild(PROFILE_ROUTE) ], providers: [ UserService, LocaleService, GenreService, MessageService, AuthGuardService ], exports: [ RouterModule ] }) export class ProfileModule { }
36.243902
83
0.74428
1acc417503eda8cb36e11f601a96e7e8174b298e
1,878
py
Python
async_couch/clients/designs/responses.py
quantori/async-couch
c46ce8da6f058024c95db67151a4498042280206
[ "MIT" ]
null
null
null
async_couch/clients/designs/responses.py
quantori/async-couch
c46ce8da6f058024c95db67151a4498042280206
[ "MIT" ]
null
null
null
async_couch/clients/designs/responses.py
quantori/async-couch
c46ce8da6f058024c95db67151a4498042280206
[ "MIT" ]
null
null
null
import typing from dataclasses import dataclass from async_couch.types import EmptyResponse @dataclass class SizeObj: active: int """The size of live data inside the view, in bytes""" external: int """The uncompressed size of view contents in bytes""" file: int """Size in bytes of the view as stored on disk""" @dataclass class DesignViewIndex: compact_running: bool """Indicates whether a compaction routine is currently running on the view""" sizes: SizeObj """Sized of stored data""" language: str """Language for the defined views""" purge_seq: int """The purge sequence that has been processed""" signature: str """MD5 signature of the views for the design document""" update_seq: int or str """The update sequence of the corresponding database that has been indexed""" updater_running: bool """Indicates if the view is currently being updated""" waiting_clients: int """Number of clients waiting on views from this design document""" waiting_commit: bool """Indicates if there are outstanding commits to the underlying database that need to processed""" @dataclass class DesignInfoResponse(EmptyResponse): name: str """Design document name""" view_index: DesignViewIndex """View Index Information""" @dataclass class ExecuteViewRow: id: str key: str value: dict @dataclass class ExecuteViewResponse(EmptyResponse): offset: int = None """Offset where the document list started""" rows: typing.List[ExecuteViewRow] = None """Array of view row objects. By default the information returned contains only the document ID and revision""" total_rows: int = None """Number of documents in the database/view""" update_seq: dict = None """Current update sequence for the database."""
22.902439
76
0.692758
c9bffe0dae3a4e0bb59586f723d6085bf055a484
59,087
ts
TypeScript
packages/pytea/src/frontend/torchFrontend.ts
twstella/PyForensic
59fdfd05793484e5aa4a96e3d4e0ce5e675369f9
[ "MIT" ]
null
null
null
packages/pytea/src/frontend/torchFrontend.ts
twstella/PyForensic
59fdfd05793484e5aa4a96e3d4e0ce5e675369f9
[ "MIT" ]
null
null
null
packages/pytea/src/frontend/torchFrontend.ts
twstella/PyForensic
59fdfd05793484e5aa4a96e3d4e0ce5e675369f9
[ "MIT" ]
null
null
null
/* * torchValues.ts * Copyright (c) Seoul National University. * Licensed under the MIT license. * Author: Ho Young Jhoo (mersshs@gmail.com) * * Python scripts to PyTea internal languages. */ import { inspect } from 'util'; import { ArgumentCategory, AssertNode, AssignmentNode, AugmentedAssignmentNode, BinaryOperationNode, BreakNode, CallNode, ClassNode, ConstantNode, ContinueNode, DelNode, DictionaryNode, EllipsisNode, ExpressionNode, ForNode, FunctionNode, GlobalNode, IfNode, ImportAsNode, ImportFromNode, ImportNode, IndexNode, LambdaNode, ListComprehensionNode, ListNode, MemberAccessNode, ModuleNode, NameNode, NonlocalNode, NumberNode, ParameterCategory, ParseNode, ParseNodeArray, ParseNodeType, PassNode, RaiseNode, ReturnNode, SliceNode, StatementListNode, StringListNode, StringNode, TernaryNode, TryNode, TupleNode, UnaryOperationNode, WhileNode, WithNode, ExceptNode, } from 'pyright-internal/parser/parseNodes'; import { KeywordType, OperatorType } from 'pyright-internal/parser/tokenizerTypes'; import { PyteaService } from '../service/pyteaService'; import { extractIds, extractLocalDef, extractUnexportedGlobal, flattenNodeArray, getFullAttrPath, parseBinOp, parseUnaryOp, toQualPath, } from './frontUtils'; import { LibCallType, TEAttr, TEBinOp, TEBopType, TECall, TEConst, TEConstType, TEExcpt, TELibCall, TEName, TEObject, TESubscr, TETuple, TEType, TEUnaryOp, TEUopType, ThExpr, ThLeftExpr, ThStmt, TSAssign, TSBreak, TSContinue, TSExpr, TSForIn, TSFunDef, TSIf, TSLet, TSPass, TSRaise, TSReturn, TSSeq, TSTry, } from './torchStatements'; import { node, sources } from 'webpack'; import { throws } from 'assert'; import { printArgument } from 'pyright-internal/analyzer/parseTreeUtils'; export class TorchIRFrontend { private _immId: number; // temporary fundef before each stmt translation. // each means function name, function parameters, and function body private _preStmtStack: [string, string[], ThStmt][]; constructor() { this._immId = 0; this._preStmtStack = []; } translate(node: ParseNode): ThStmt { this._immId = 0; const parser = new TorchIRFrontend(); const stmt = parser.visitNode(node); if ('stype' in stmt) { return stmt; } else { return TSExpr.create(stmt); } } visitArray(nodes: ParseNodeArray): ThStmt { const arr = flattenNodeArray(nodes); const localStack: ThStmt[] = []; for (const [idx, node] of arr.entries()) { if (!node) continue; if (node.nodeType === ParseNodeType.Function) { const [name, params, body] = this.visitFunction(node); const tempName = TEName.create(`${name}$TMP$`, node.name); let stmt = this.visitArray(arr.slice(idx + 1)); // varargs and kwargs const setDefaultParams: [string, ThExpr][] = [ ['$func', tempName], ...node.parameters .filter((param) => param.defaultValue !== undefined) .map( (param) => [param.name!.value, this.visitExprNode(param.defaultValue!)] as [string, ThExpr] ), ]; const varargs = node.parameters.findIndex((param) => param.category === ParameterCategory.VarArgList); const kwargs = node.parameters.findIndex( (param) => param.category === ParameterCategory.VarArgDictionary ); let keyOnlyNum = 0; if (varargs >= 0) { setDefaultParams.push(['$varargsName', TEConst.genStr(node.parameters[varargs].name!.value)]); keyOnlyNum = node.parameters.length - varargs - 1; } if (kwargs >= 0) { setDefaultParams.push(['$kwargsName', TEConst.genStr(node.parameters[kwargs].name!.value)]); keyOnlyNum -= 1; } if (keyOnlyNum > 0) setDefaultParams.push(['$keyOnlyNum', TEConst.genInt(keyOnlyNum)]); const resetStmts = [stmt]; if (setDefaultParams.length > 1) { const setDefault = TELibCall.create(LibCallType.setDefault, setDefaultParams, node); resetStmts.unshift(TSAssign.create(TEName.create(name, node.name), setDefault)); } else { resetStmts.unshift(TSAssign.create(TEName.create(name, node.name), tempName)); } stmt = this._mergeStmt(resetStmts); localStack.push(TSFunDef.create(tempName.ident, params, body, stmt, node)); break; } let stmt = this.visitNode(node); if ('etype' in stmt) { stmt = TSExpr.create(stmt); } localStack.push(stmt); } return this._mergeStmt(localStack); } visitModule(node: ModuleNode): ThStmt { const localDef = extractLocalDef(node.statements); const importNames = extractUnexportedGlobal(node.statements); const stmt = this.visitArray(node.statements); stmt.source = node; // assign global variables and functions to '$module' localDef.delete('LibCall'); const exportSet = new Set(localDef); importNames.forEach((im) => { exportSet.delete(im); }); const moduleName = TEName.create('$module'); const moduleExport = TSSeq.create( stmt, this._mergeStmt( // CAVEAT: do not import global variables that has name starting with '__' [...exportSet.values()] .filter((name) => !name.startsWith('__')) .map((name) => TSExpr.create( TELibCall.create(LibCallType.exportGlobal, [ ['$module', moduleName], [name, TEName.create(name)], ]) ) ) ) ); return TSLet.create('$module', this._mergeLocalDef(localDef, moduleExport), TEObject.create()); } visitNonlocal(node: NonlocalNode): ThStmt { return TSPass.get(node); } visitGlobal(node: GlobalNode): ThStmt { return TSPass.get(node); } visitImport(node: ImportNode): ThStmt { return this._mergeStmt(node.list.map((n) => this.visitImportAs(n))); } visitImportAs(node: ImportAsNode): ThStmt { // import(qualifiedPath: string) -> return PyModule like object // importQualified(qualifiedPath: string) -> Assign PyModule like object to qualified path // LibCall check // TODO: pyright based LibCall path check. const nameParts = node.module.nameParts; if (nameParts.length > 0 && nameParts[nameParts.length - 1].value === 'LibCall') { // each LibCall will be replaced in-place return TSPass.get(); } const path = TEConst.genStr(toQualPath(node.module)); if (!node.alias && node.module.nameParts.length >= 2) { // TODO: should check leading dots? const stmts: ThStmt[] = []; let nameStr: string = '.'.repeat(node.module.leadingDots); let nameObj: ThLeftExpr | undefined; node.module.nameParts.forEach((nameNode, id) => { const tempName = this._getImm() + '_imp'; nameStr = nameStr + (id === 0 ? '' : '.') + nameNode.value; nameObj = nameObj ? TEAttr.create(nameObj, nameNode.value, nameNode) : TEName.create(nameNode.value, nameNode); const path: [string, ThExpr][] = [ ['qualPath', TEConst.genStr(nameStr, nameNode)], ['assignTo', TEConst.genStr(tempName)], ]; stmts.push( TSSeq.create( TSExpr.create(TELibCall.create(LibCallType.import, path, nameNode)), TSAssign.create(nameObj, TEName.create(tempName)) ) ); }); return this._mergeStmt(stmts); } else { const qualPath: [string, ThExpr][] = [['qualPath', path]]; const nameNode = node.alias ? node.alias : node.module.nameParts[0]; const name = TEConst.genStr(nameNode.value, nameNode); qualPath.push(['assignTo', name]); return TSExpr.create(TELibCall.create(LibCallType.import, qualPath, node)); } } visitImportFrom(node: ImportFromNode): ThStmt { const imports = node.imports; if (imports.length > 0 && imports[imports.length - 1].name.value === 'LibCall') { // each LibCall will be replaced in-place return TSPass.get(); } let basepath = toQualPath(node.module); if (basepath.endsWith('.')) { basepath = basepath.substr(0, basepath.length - 1); } const stmts: ThStmt[] = []; const isWild = node.isWildcardImport; if (isWild) { const qualPath: [string, ThExpr][] = [['qualPath', TEConst.genStr(`${basepath}.*`, node.module)]]; stmts.push(TSExpr.create(TELibCall.create(LibCallType.import, qualPath, node.module))); } else { node.imports.forEach((from) => { const qualPath: [string, ThExpr][] = [ ['qualPath', TEConst.genStr(`${basepath}.${from.name.value}`, from.name)], ]; const nameNode = from.alias ? from.alias : from.name; const name = nameNode.value; qualPath.push(['assignTo', TEConst.genStr(name, nameNode)]); stmts.push(TSExpr.create(TELibCall.create(LibCallType.import, qualPath, node))); }); } return this._mergeStmt(stmts); } visitClass(node: ClassNode): ThStmt { // TODO: resolve MRO const name = TEName.create(node.name.value, node.name); const suite = flattenNodeArray(node.suite.statements); const stmts: ThStmt[] = []; const props: AssignmentNode[] = []; const methods: FunctionNode[] = []; let initFunc: FunctionNode | undefined = undefined; let hasCall = false; suite.forEach((inner) => { if (inner.nodeType === ParseNodeType.Assignment) { stmts.push(this._visitClassProp(node, inner)); props.push(inner); } else if (inner.nodeType === ParseNodeType.Function) { if (inner.name.value === '__init__') { initFunc = inner; stmts.unshift(this._genClassInit(node, inner)); methods.push(inner); } else if (inner.name.value !== '__new__') { // ignore user defined __new__ and __call__ if (inner.name.value === '__call__') { hasCall = true; } stmts.push(this._visitClassMethod(node, inner, inner.name.value === '__call__')); methods.push(inner); } } }); if (!initFunc) { stmts.unshift(this._genClassInit(node)); } stmts.push(this._genClassNew(node, hasCall)); stmts.push(this._genClassCall(node, initFunc)); const superClasses = [ name, ...node.arguments.map((arg) => this.visitExprNode(arg.valueExpression)), TEName.create('object'), ]; return this._mergeStmt([ TSAssign.create(name, TEObject.create(), node.name), ...stmts, TSAssign.create(TEAttr.create(name, '__mro__'), TETuple.create(superClasses)), TSAssign.create(TEAttr.create(name, '__name__'), TEConst.genStr(node.name.value, node.name)), ]); } private _visitClassMethod(node: ClassNode, method: FunctionNode, isCall?: boolean): ThStmt { // TODO: staticmethod const funcRawName = isCall ? 'self$call' : method.name.value; const funcName = TEName.create(`${node.name.value}$${funcRawName}`, method.name); const className = TEName.create(node.name.value, node.name); const selfParam = method.parameters[0].name!; const selfName = TEName.create(selfParam.value, selfParam); const localDef = extractLocalDef( method.suite.statements, method.parameters.map((p) => p.name?.value) ); const stmt = TSLet.create( '__class__', TSLet.create( '__self__', TSSeq.create(this.visitArray(method.suite.statements), TSReturn.create(TEConst.genNone())), selfName ), className ); let setStmt: ThStmt; if ( method.parameters.some( (param) => param.category === ParameterCategory.VarArgDictionary || param.category === ParameterCategory.VarArgList || param.defaultValue !== undefined ) ) { const paramNames: [string, ThExpr][] = [['$func', funcName]]; let keyOnlyNum = -1; method.parameters.forEach((param) => { const paramName = param.name; if (paramName) { if (param.category === ParameterCategory.VarArgList) { paramNames.push(['$varargsName', TEConst.genStr(paramName.value)]); } else if (param.category === ParameterCategory.VarArgDictionary) { paramNames.push(['$kwargsName', TEConst.genStr(paramName.value)]); } else if (param.defaultValue !== undefined) { paramNames.push([paramName.value, this.visitExprNode(param.defaultValue)]); } } if (param.category === ParameterCategory.VarArgList) keyOnlyNum = 0; else if (param.category !== ParameterCategory.VarArgDictionary && keyOnlyNum >= 0) keyOnlyNum += 1; }); if (keyOnlyNum > 0) paramNames.push(['$keyOnlyNum', TEConst.genInt(keyOnlyNum)]); setStmt = TSAssign.create( TEAttr.create(className, funcRawName), TELibCall.create(LibCallType.setDefault, paramNames), method ); } else { setStmt = TSAssign.create(TEAttr.create(className, funcRawName), funcName); } return TSFunDef.create( funcName.ident, method.parameters.map((param) => param.name!.value), this._mergeLocalDef(localDef, stmt), setStmt ); } private _visitClassProp(node: ClassNode, prop: AssignmentNode): ThStmt { // TODO: assign non-name property if (prop.leftExpression.nodeType === ParseNodeType.Name) { return TSAssign.create( TEAttr.create(TEName.create(node.name.value, node.name), prop.leftExpression.value), this.visitExprNode(prop.rightExpression) ); } else { return TSPass.get(prop); } } private _genClassInit(node: ClassNode, func?: FunctionNode): ThStmt { const className = TEName.create(node.name.value, node.name); const funcName = TEName.create(`${node.name.value}$__init__`, func?.name); const params = func ? func.parameters.map((p) => p.name!.value) : ['self', '$args', '$kwargs']; const selfName = TEName.create(params[0]); const hasSuperClass = !( node.arguments.length === 0 || (node.arguments[0].valueExpression.nodeType === ParseNodeType.Name && node.arguments[0].valueExpression.value === 'object') ); const localDef = func ? extractLocalDef( func.suite.statements, func.parameters.map((p) => p.name?.value) ) : undefined; let initBody: ThStmt; if (!func) { if (hasSuperClass) { initBody = TSLet.create( '__class__', TSLet.create( '__self__', TSSeq.create( TSExpr.create( TELibCall.create(LibCallType.callKV, [ [ '$func', TEAttr.create( TECall.create(TEName.create('super'), [ TEName.create('__class__'), TEName.create('__self__'), ]), '__init__' ), ], ['$varargs', TEName.create('$args')], ['$kwargs', TEName.create('$kwargs')], ]) ), TSReturn.create(TEConst.genNone()) ), selfName ), className ); } else { initBody = TSReturn.create(TEConst.genNone()); } } else { initBody = TSLet.create( '__class__', TSLet.create( '__self__', TSSeq.create(this.visitArray(func.suite.statements), TSReturn.create(TEConst.genNone())), selfName ), className ); } initBody = localDef ? this._mergeLocalDef(localDef, initBody) : initBody; let setStmt: ThStmt; if (!func) { setStmt = TSAssign.create( TEAttr.create(className, '__init__'), TELibCall.create(LibCallType.setDefault, [ ['$func', funcName], ['$varargsName', TEConst.genStr('$args')], ['$kwargsName', TEConst.genStr('$kwargs')], ]), func ); } else if ( func.parameters.some( (param) => param.category === ParameterCategory.VarArgDictionary || param.category === ParameterCategory.VarArgList || param.defaultValue !== undefined ) ) { const paramNames: [string, ThExpr][] = [['$func', funcName]]; let keyOnlyNum = -1; func.parameters.forEach((param) => { const paramName = param.name; if (paramName) { if (param.category === ParameterCategory.VarArgList) { paramNames.push(['$varargsName', TEConst.genStr(paramName.value)]); } else if (param.category === ParameterCategory.VarArgDictionary) { paramNames.push(['$kwargsName', TEConst.genStr(paramName.value)]); } else if (param.defaultValue !== undefined) { paramNames.push([paramName.value, this.visitExprNode(param.defaultValue)]); } } if (param.category === ParameterCategory.VarArgList) keyOnlyNum = 0; else if (param.category !== ParameterCategory.VarArgDictionary && keyOnlyNum >= 0) keyOnlyNum += 1; }); if (keyOnlyNum > 0) paramNames.push(['$keyOnlyNum', TEConst.genInt(keyOnlyNum)]); setStmt = TSAssign.create( TEAttr.create(className, '__init__'), TELibCall.create(LibCallType.setDefault, paramNames), func ); } else { setStmt = TSAssign.create(TEAttr.create(className, '__init__'), funcName, func); } return TSFunDef.create(funcName.ident, params, initBody, setStmt, func); } private _genClassNew(node: ClassNode, hasCall: boolean): ThStmt { const className = TEName.create(node.name.value, node.name); const funcName = TEName.create(`${node.name.value}$__new__`); const selfName = TEName.create(`${node.name.value}$$self`); const hasSuperClass = !( node.arguments.length === 0 || (node.arguments[0].valueExpression.nodeType === ParseNodeType.Name && node.arguments[0].valueExpression.value === 'object') ); const mainBody: ThStmt[] = []; if (hasCall) { mainBody.push( TSFunDef.create( `${node.name.value}$self$__call__`, ['$args', '$kwargs'], TSReturn.create( TELibCall.create(LibCallType.callKV, [ ['$func', TEAttr.create(className, 'self$call')], ['', selfName], ['$varargs', TEName.create('$args')], ['$kwargs', TEName.create('$kwargs')], ]) ), TSAssign.create( TEAttr.create(selfName, '__call__'), TELibCall.create(LibCallType.setDefault, [ ['$func', TEName.create(`${node.name.value}$self$__call__`)], ['$varargsName', TEConst.genStr('$args')], ['$kwargsName', TEConst.genStr('$kwargs')], ]) ) ) ); } const newObject = hasSuperClass ? TECall.create( TEAttr.create( TECall.create(TEName.create('super'), [TEName.create('__class__'), TEConst.genNone()]), '__new__' ), [className] ) : TEObject.create(node.name); const newBody = TSLet.create( '__class__', TSLet.create(selfName.ident, this._mergeStmt([...mainBody, TSReturn.create(selfName)]), newObject), className ); return TSFunDef.create( funcName.ident, ['cls'], newBody, TSAssign.create(TEAttr.create(className, '__new__'), funcName) ); } private _genClassCall(node: ClassNode, initFunc?: FunctionNode): ThStmt { const className = TEName.create(node.name.value, node.name); const funcName = TEName.create(`${node.name.value}$__call__`); const selfName = TEName.create(`${node.name.value}$$self`); const inheritParams = initFunc && !initFunc.parameters.some((p) => p.defaultValue !== undefined || p.category !== ParameterCategory.Simple); let params = inheritParams ? initFunc!.parameters.slice(1).map((p) => p.name!.value) : []; let initCall: ThExpr; if (!inheritParams) { initCall = TELibCall.create(LibCallType.callKV, [ ['$func', TEAttr.create(className, '__init__')], ['', selfName], ['$varargs', TEName.create('$args')], ['$kwargs', TEName.create('$kwargs')], ]); } else { initCall = TECall.create(TEAttr.create(className, '__init__'), [ selfName, ...params.map((p) => TEName.create(p)), ]); } const callBody = TSLet.create( selfName.ident, TSSeq.create( TSAssign.create(TEAttr.create(selfName, '__mro__'), TEAttr.create(className, '__mro__')), TSSeq.create(TSExpr.create(initCall), TSReturn.create(selfName)) ), TECall.create(TEAttr.create(className, '__new__'), [className]) ); let callFunc: ThExpr = funcName; if (!inheritParams) { callFunc = TELibCall.create(LibCallType.setDefault, [ ['$func', funcName], ['$varargsName', TEConst.genStr('$args')], ['$kwargsName', TEConst.genStr('$kwargs')], ]); params = ['$args', '$kwargs']; } return TSFunDef.create( funcName.ident, params, callBody, TSAssign.create(TEAttr.create(className, '__call__'), callFunc) ); } visitWith(node: WithNode): ThStmt { // TODO: item.target = item.expression; item.target.__enter__(); statements; item.target.__exit__() return this._mergeStmt([ ...node.withItems.map((item) => { if (item.target) { return TSAssign.create( this.visitExprNode(item.target) as ThLeftExpr, this.visitExprNode(item.expression), item ); } else { return TSExpr.create(this.visitExprNode(item.expression)); } }), this.visitArray(node.suite.statements), ]); } visitWhile(node: WhileNode): ThStmt { // TODO: precise loop condition // currently, loop 300 times and break. const bodyStmt = this._mergeStmt([ TSIf.create( this.visitExprNode(node.testExpression), this.visitArray(node.whileSuite.statements), TSBreak.create() ), ]); return TSForIn.create(this._getImm(), TECall.create(TEName.create('range'), [TEConst.genInt(300)]), bodyStmt); } visitDel(node: DelNode): ThStmt { // TODO: del x[0] (subscription) // TODO: assign undef (temporarily, set None) const stmts: ThStmt[] = []; node.expressions.forEach((del) => { if (del.nodeType === ParseNodeType.Name) { stmts.push(TSAssign.create(TEName.create(del.value, del), TEConst.genNone())); } }); return this._mergeStmt(stmts); } visitList(node: ListNode): ThExpr { if (node.entries.length === 1 && node.entries[0].nodeType === ParseNodeType.ListComprehension) { return this.visitListComprehension(node.entries[0]); } const entries = node.entries.map((expr) => this.visitExprNode(expr)); return TELibCall.create( LibCallType.genList, entries.map((v, i) => [`param$${i}`, v]), node ); } visitDict(node: DictionaryNode): ThExpr { // TODO: implement it. const entries = node.entries .map((expr) => { switch (expr.nodeType) { case ParseNodeType.DictionaryKeyEntry: return TETuple.create( [this.visitExprNode(expr.keyExpression), this.visitExprNode(expr.valueExpression)], expr.valueExpression ); case ParseNodeType.DictionaryExpandEntry: return; case ParseNodeType.ListComprehension: return; } }) .filter((v) => v !== undefined) as TETuple[]; return TELibCall.create( LibCallType.genDict, entries.map((v, i) => [`param$${i}`, v]), node ); } visitStatementList(node: StatementListNode): ThStmt { return this.visitArray(node.statements); } visitAssignment(node: AssignmentNode): ThStmt { // handle multiple assignment let right: ThExpr; let double: ThStmt | undefined; if (node.rightExpression.nodeType === ParseNodeType.Assignment) { double = this.visitStmtNode(node.rightExpression); right = this.visitExprNode(node.rightExpression.leftExpression); } else { right = this.visitExprNode(node.rightExpression); } if (node.leftExpression.nodeType === ParseNodeType.Tuple) { return this._assignTuple(node.leftExpression, right, node); } else if (node.leftExpression.nodeType === ParseNodeType.List) { return this._assignList(node.leftExpression, right, node); } let retVal: ThStmt = TSAssign.create(this.visitExprNode(node.leftExpression) as ThLeftExpr, right, node); if (double) { retVal = TSSeq.create(double, retVal, node); } return retVal; } visitAugmentedAssignment(node: AugmentedAssignmentNode): ThStmt { const left = this.visitExprNode(node.leftExpression); const right = this.visitExprNode(node.rightExpression); const leftType = left.etype; if (!(leftType === TEType.Name || leftType === TEType.Attr || leftType === TEType.Subscr)) { this.fail(node); } let op = node.operator; switch (op) { case OperatorType.AddEqual: op = OperatorType.Add; break; case OperatorType.SubtractEqual: op = OperatorType.Subtract; break; case OperatorType.MultiplyEqual: op = OperatorType.Multiply; break; case OperatorType.DivideEqual: op = OperatorType.Divide; break; case OperatorType.FloorDivideEqual: op = OperatorType.FloorDivide; break; case OperatorType.ModEqual: op = OperatorType.Mod; break; default: this.fail(node); } const bop = parseBinOp(op)!; return TSAssign.create(left as ThLeftExpr, TEBinOp.create(bop, left, right, node), node); } private _assignTuple(left: TupleNode, right: ThExpr, node?: AssignmentNode): ThStmt { let stmt: ThStmt | undefined; const tempVar = TEName.create(this._getImm(), node?.leftExpression); left.expressions.forEach((e, i) => { let next: ThStmt | undefined; if ( e.nodeType === ParseNodeType.Name || e.nodeType === ParseNodeType.MemberAccess || e.nodeType === ParseNodeType.Index ) { next = TSAssign.create( this.visitExprNode(e) as ThLeftExpr, TESubscr.create(tempVar, TEConst.genInt(i), e) ); } else if (e.nodeType === ParseNodeType.List) { next = this._assignList(e, TESubscr.create(tempVar, TEConst.genInt(i), e)); } else if (e.nodeType === ParseNodeType.Tuple) { next = this._assignTuple(e, TESubscr.create(tempVar, TEConst.genInt(i), e)); } stmt = stmt ? (next ? TSSeq.create(stmt, next) : stmt) : next; }); return TSLet.create(tempVar.ident, stmt!, right, node); // return TSLet.create(this._getImm(), stmt!, right, node); } private _assignList(left: ListNode, right: ThExpr, node?: AssignmentNode): ThStmt { let stmt: ThStmt | undefined; const tempVar = TEName.create(this._getImm(), node?.leftExpression); left.entries.forEach((e, i) => { let next: ThStmt | undefined; if ( e.nodeType === ParseNodeType.Name || e.nodeType === ParseNodeType.MemberAccess || e.nodeType === ParseNodeType.Index ) { next = TSAssign.create( this.visitExprNode(e) as ThLeftExpr, TESubscr.create(tempVar, TEConst.genInt(i), e) ); } else if (e.nodeType === ParseNodeType.List) { next = this._assignList(e, TESubscr.create(right, TEConst.genInt(i), e)); } else if (e.nodeType === ParseNodeType.Tuple) { next = this._assignTuple(e, TESubscr.create(right, TEConst.genInt(i), e)); } stmt = stmt ? (next ? TSSeq.create(stmt, next) : stmt) : next; }); return TSLet.create(tempVar.ident, stmt!, right, node); } visitBinaryOperation(node: BinaryOperationNode): ThExpr { let op = node.operator; let leftNode = node.leftExpression; let rightNode = node.rightExpression; // flip gt(e) to lt(e) if (op === OperatorType.GreaterThan || op === OperatorType.GreaterThanOrEqual) { leftNode = node.rightExpression; rightNode = node.leftExpression; if (op === OperatorType.GreaterThan) { op = OperatorType.LessThan; } else { op = OperatorType.LessThanOrEqual; } } const bop = parseBinOp(op); if (bop === undefined) { this.fail(node); } const left = this.visitExprNode(leftNode); const right = this.visitExprNode(rightNode); if (bop === TEBopType.IsNot) { return TEUnaryOp.create(TEUopType.Not, TEBinOp.create(TEBopType.Is, left, right, node), node); } else if (bop === TEBopType.NotIn) { return TEUnaryOp.create(TEUopType.Not, TEBinOp.create(TEBopType.In, left, right, node), node); } return TEBinOp.create(bop, left, right, node); } visitTernary(node: TernaryNode): ThExpr { const tempFun = this._getImm() + '_TERNARY'; const cond = this.visitExprNode(node.testExpression); const left = this.visitExprNode(node.ifExpression); const right = this.visitExprNode(node.elseExpression); const funBody = TSIf.create( cond, TSReturn.create(left, node.ifExpression), TSReturn.create(right, node.elseExpression), node ); this._preStmtStack.push([tempFun, [], funBody]); return TECall.create(TEName.create(tempFun, node), [], node); } visitBreak(node: BreakNode): ThStmt { return TSBreak.create(node); } visitCall(node: CallNode): ThExpr { const args = node.arguments.map((arg) => this.visitExprNode(arg.valueExpression)); const left = this.visitExprNode(node.leftExpression); // resolve explicit LibCall.\ // also inline sys.exit if (left.etype === TEType.Attr) { const leftPath = getFullAttrPath(left); if (leftPath && leftPath[0] === 'LibCall') { if (leftPath.length === 2) { if (leftPath[1] === 'DEBUG') { return TELibCall.create( LibCallType.DEBUG, args.map((arg) => ['', arg]), node ); } else if (leftPath[1] === 'objectClass') { return TELibCall.create(LibCallType.objectClass, [], node); } else if (leftPath[1] === 'rawObject') { return TEObject.create(node); } } return TELibCall.create( LibCallType.explicit, [ ['$func', TEConst.genStr(leftPath.splice(1).join('.'))], ...args.map((expr) => ['', expr] as [string, ThExpr]), ], node ); } else if (leftPath && leftPath.length === 2 && leftPath[0] === 'sys' && leftPath[1] === 'exit') { return TELibCall.create( LibCallType.explicit, [['$func', TEConst.genStr('builtins.exit')], ...args.map((expr) => ['', expr] as [string, ThExpr])], node ); } } if (left.etype === TEType.Name) { if (left.ident === 'super') { if (args.length === 1) { return TECall.create(left, [args[0], TEName.create('__self__')], node); } else { return TECall.create(left, [TEName.create('__class__'), TEName.create('__self__')], node); } } else if (left.ident === 'print') { // ignore print function return TEConst.create(TEConstType.None, undefined, left.source); } } if ( node.arguments.some( (arg) => arg.name !== undefined || arg.argumentCategory === ArgumentCategory.UnpackedDictionary || arg.argumentCategory === ArgumentCategory.UnpackedList ) ) { const kwargs: [string, ThExpr][] = []; const posArgs: [string, ThExpr][] = []; node.arguments.forEach((arg, i) => { if (arg.name) { kwargs.push([arg.name.value, args[i]]); } else if (arg.argumentCategory === ArgumentCategory.UnpackedDictionary) { kwargs.push(['$kwargs', args[i]]); } else if (arg.argumentCategory === ArgumentCategory.UnpackedList) { posArgs.push(['$varargs', args[i]]); } else { posArgs.push(['', args[i]]); } }); return TELibCall.create(LibCallType.callKV, [['$func', left], ...posArgs, ...kwargs], node); } return TECall.create(left, args, node); } visitContinue(node: ContinueNode): ThStmt { return TSContinue.create(node); } visitConstant(node: ConstantNode): ThExpr { switch (node.constType) { case KeywordType.True: return TEConst.create(TEConstType.Bool, true, node); case KeywordType.False: return TEConst.create(TEConstType.Bool, false, node); case KeywordType.None: return TEConst.create(TEConstType.None, undefined, node); default: this.fail(node); } } visitIf(node: IfNode): ThStmt { const expr = this.visitExprNode(node.testExpression); const ifStmt = this.visitArray(node.ifSuite.statements); const elseSuite = node.elseSuite; let elseStmt: ThStmt; if (elseSuite) { if (elseSuite.nodeType === ParseNodeType.If) { elseStmt = this.visitIf(elseSuite); } else { elseStmt = this.visitArray(elseSuite.statements); } } else { elseStmt = TSPass.get(); } return TSIf.create(expr, ifStmt, elseStmt, node); } visitIndex(node: IndexNode): ThExpr { // TODO: handle argumentCategory const items = node.items.map((arg) => this.visitExprNode(arg.valueExpression)); if (items.length === 0) { this.fail(node); } else if (items.length >= 2) { const tuple = TETuple.create(items, node); return TESubscr.create(this.visitExprNode(node.baseExpression), tuple, node); } else { return TESubscr.create(this.visitExprNode(node.baseExpression), items[0], node); } } visitFor(node: ForNode): ThStmt { const idx = extractIds(node.targetExpression); if (!idx) { this.fail(node); } const iter = this.visitExprNode(node.iterableExpression); let body = this.visitArray(node.forSuite.statements); let idxName: string; if (idx.length === 1) { idxName = idx[0]; } else { idxName = this._getImm(); } if (idx.length > 1) { if (node.targetExpression.nodeType === ParseNodeType.Tuple) { body = TSSeq.create( this._assignTuple(node.targetExpression, TEName.create(idxName, node.targetExpression)), body ); } else if (node.targetExpression.nodeType === ParseNodeType.List) { body = TSSeq.create( this._assignList(node.targetExpression, TEName.create(idxName, node.targetExpression)), body ); } return TSForIn.create(idxName, iter, body, node); } return TSForIn.create(idxName, iter, body, node); } visitTry(node: TryNode): ThStmt { // TODO: implement except clause /* if (node.finallySuite) { return TSSeq.create( this.visitArray(node.trySuite.statements), this.visitArray(node.finallySuite.statements), node ); } return this.visitArray(node.trySuite.statements); */ const error = TECall.create(TEName.create('RuntimeError'), []); const tryStmt = this.visitArray(node.trySuite.statements); const exceptNode: ExceptNode[] = node.exceptClauses; //const exceptStmt = [this.visitArray(exceptNode[0].exceptSuite.statements)]; const exceptStmt:ThStmt[]=[] const exceptName:ThExpr[]=[] for(let i=0;i<exceptNode.length;i++){ exceptStmt.push(this.visitArray(exceptNode[i].exceptSuite.statements)); var t= exceptNode[i].typeExpression? this.visitExprNode(exceptNode[i].typeExpression as ExpressionNode):TEName.create("exception",exceptNode[i].typeExpression); exceptName.push(t); } //const exceptStmt=exceptNode.map(this.visitExceptClSt); /* const exceptName = exceptNode[0].typeExpression? [this.visitExprNode(exceptNode[0].typeExpression)]: [TEName.create("exception", exceptNode[0].typeExpression)]; */ //const exceptName=exceptNode.map(this.visitExceptClName); const elseStmt = node.elseSuite ? this.visitArray(node.elseSuite.statements) : TSPass.get(); const finallyStmt = node.finallySuite ? this.visitArray(node.finallySuite.statements) : TSPass.get(); return TSTry.create(tryStmt, exceptName, exceptStmt, elseStmt, finallyStmt, node); } /*export interface ExceptNode extends ParseNodeBase { readonly nodeType: ParseNodeType.Except; typeExpression?: ExpressionNode | undefined; name?: NameNode | undefined; exceptSuite: SuiteNode; }*/ visitExcept(node: ExceptNode): [TEExcpt, ThStmt] { const exptSt = this.visitArray(node.exceptSuite.statements); if (node.name) { const excptname = this.visitName(node.name) as TEName; const excpt = TEExcpt.create(excptname.ident, node.name); return [excpt, exptSt]; } else { const excpt = TEExcpt.create(undefined); return [excpt, exptSt]; //const error=TECall.create(TEName.create('RuntimeError'), []); //return [TSExpr.create(TELibCall.create(LibCallType.raise, [['value', error]], node))]; } } visitFunction(node: FunctionNode): [string, string[], ThStmt] { const name = node.name.value; const params = extractIds(node.parameters); const localDef = extractLocalDef( node.suite.statements, node.parameters.map((p) => p.name?.value) ); if (!params) { this.fail(node); } const body = this.visitArray(node.suite.statements); const stmt = this._mergeLocalDef(localDef, TSSeq.create(body, TSReturn.create(TEConst.genNone()))); return [name, params, stmt]; } visitName(node: NameNode): TEName { return TEName.create(node.value, node); } visitNumber(node: NumberNode): ThExpr { if (node.isInteger) { return TEConst.create(TEConstType.Int, node.value, node); } else { return TEConst.create(TEConstType.Float, node.value, node); } } visitMemberAccess(node: MemberAccessNode): ThExpr { return TEAttr.create(this.visitExprNode(node.leftExpression), node.memberName.value, node); } visitPass(node: PassNode): ThStmt { return TSPass.get(node); } visitReturn(node: ReturnNode): ThStmt { const expr = node.returnExpression ? this.visitExprNode(node.returnExpression) : TEConst.create(TEConstType.None, undefined); return TSReturn.create(expr, node); } visitString(node: StringNode): ThExpr { return TEConst.create(TEConstType.String, node.value, node); } visitStringList(node: StringListNode): ThExpr { return TEConst.create(TEConstType.String, node.strings.map((str) => str.value).join(''), node); } visitTuple(node: TupleNode): ThExpr { return TETuple.create( node.expressions.map((e) => this.visitExprNode(e)), node ); } visitUnaryOperation(node: UnaryOperationNode): ThExpr { const uop = parseUnaryOp(node.operator); if (uop === undefined) { this.fail(node); } return TEUnaryOp.create(uop, this.visitExprNode(node.expression), node); } visitAssert(node: AssertNode): ThStmt { if (PyteaService.ignoreAssert()) { return TSPass.get(); } // if node.testExpression: pass // else: raise AssertionError(node.exceptionExpression) const error = TECall.create( TEName.create('AssertionError', node.testExpression), node.exceptionExpression ? [this.visitExprNode(node.exceptionExpression)] : [], node.testExpression ); return TSIf.create( this.visitExprNode(node.testExpression), TSPass.get(), TSExpr.create(TELibCall.create(LibCallType.raise, [['value', error]], node)), node ); } visitRaise(node: RaiseNode): ThStmt { // TODO: try / catch / raise context // if valueExpression is not set, currently, jsut raise RuntimeError // also ignores traceback const error = node.typeExpression ? this.visitExprNode(node.typeExpression) : TECall.create(TEName.create('RuntimeError'), []); return TSExpr.create(TELibCall.create(LibCallType.raise, [['value', error]], node)); /*const expr = node.typeExpression ? (this.visitExprNode(node.typeExpression) as TEExcpt) : TECall.create(TEName.create('RuntimeError'), []); return TSRaise.create(expr as TEExcpt, node);*/ } visitSlice(node: SliceNode): ThExpr { return TECall.create( TEName.create('slice'), [ node.startValue ? this.visitExprNode(node.startValue) : TEConst.create(TEConstType.None, undefined), node.endValue ? this.visitExprNode(node.endValue) : TEConst.create(TEConstType.None, undefined), node.stepValue ? this.visitExprNode(node.stepValue) : TEConst.create(TEConstType.None, undefined), ], node ); } visitEllipsis(node: EllipsisNode): ThExpr { return TEName.create('Ellipsis', node); } // move list comprehension body before the last translated statement, and alter it to function call // that makes temp list visitListComprehension(node: ListComprehensionNode): ThExpr { const tempFun = this._getImm() + '_LCFun'; const tempList = this._getImm() + '_LCList'; const tempListName = TEName.create(tempList, node); // TODO: what if not an expression? const expr = node.expression as ExpressionNode; let mainBody: ThStmt = TSExpr.create( TECall.create(TEAttr.create(tempListName, 'append', node), [this.visitExprNode(expr)], expr) ); [...node.comprehensions].reverse().forEach((comp) => { if (comp.nodeType === ParseNodeType.ListComprehensionFor) { const idx = extractIds(comp.targetExpression); if (!idx) { this.fail(node); } const iter = this.visitExprNode(comp.iterableExpression); let idxName: string; if (idx.length === 1) { idxName = idx[0]; } else { idxName = this._getImm(); } if (idx.length > 1) { if (comp.targetExpression.nodeType === ParseNodeType.Tuple) { mainBody = TSSeq.create( this._assignTuple(comp.targetExpression, TEName.create(idxName, comp.targetExpression)), mainBody ); } else if (comp.targetExpression.nodeType === ParseNodeType.List) { mainBody = TSSeq.create( this._assignList(comp.targetExpression, TEName.create(idxName, comp.targetExpression)), mainBody ); } mainBody = TSForIn.create(idxName, iter, mainBody, comp); for (const name of idx) { mainBody = TSLet.create(name, mainBody); } } else { mainBody = TSForIn.create(idxName, iter, mainBody, comp); } } else { mainBody = TSIf.create(this.visitExprNode(comp.testExpression), mainBody, TSPass.get(), comp); } }); const funBody = TSLet.create( tempList, TSSeq.create(mainBody, TSReturn.create(tempListName, node)), TELibCall.create(LibCallType.genList, [], node), node ); this._preStmtStack.push([tempFun, [], funBody]); return TECall.create(TEName.create(tempFun, node), [], node); } visitLambda(node: LambdaNode): ThExpr { const tempFun = this._getImm() + '_LMFun'; // make local temp-func stack const oldStack = this._preStmtStack; this._preStmtStack = []; let funBody: ThStmt = TSReturn.create(this.visitExprNode(node.expression), node.expression); if (this._preStmtStack.length > 0) { this._preStmtStack.reverse().forEach(([tempFunName, tempFunParams, tempFunBody]) => { funBody = TSFunDef.create(tempFunName, tempFunParams, tempFunBody, funBody); }); } const params = extractIds(node.parameters) ?? []; this._preStmtStack = oldStack; this._preStmtStack.push([tempFun, params, funBody]); return TEName.create(tempFun, node); } visitNode(node: ParseNode): ThStmt | ThExpr { switch (node.nodeType) { case ParseNodeType.Assert: case ParseNodeType.Assignment: case ParseNodeType.AugmentedAssignment: case ParseNodeType.Break: case ParseNodeType.Continue: case ParseNodeType.If: case ParseNodeType.For: case ParseNodeType.Module: case ParseNodeType.Pass: case ParseNodeType.Raise: case ParseNodeType.Return: case ParseNodeType.StatementList: case ParseNodeType.Nonlocal: case ParseNodeType.Global: case ParseNodeType.Import: case ParseNodeType.ImportAs: case ParseNodeType.ImportFrom: case ParseNodeType.Class: case ParseNodeType.With: case ParseNodeType.While: case ParseNodeType.Del: case ParseNodeType.Try: //case ParseNodeType.Except: return this.visitStmtNode(node); case ParseNodeType.BinaryOperation: case ParseNodeType.UnaryOperation: case ParseNodeType.Call: case ParseNodeType.Constant: case ParseNodeType.Index: case ParseNodeType.MemberAccess: case ParseNodeType.Name: case ParseNodeType.Number: case ParseNodeType.String: case ParseNodeType.StringList: case ParseNodeType.Tuple: case ParseNodeType.List: case ParseNodeType.Dictionary: case ParseNodeType.Slice: case ParseNodeType.Ellipsis: case ParseNodeType.Lambda: case ParseNodeType.ListComprehension: return this.visitExprNode(node as ExpressionNode); default: return TSPass.get(node); } } visitStmtNode(node: ParseNode): ThStmt { let stmt: ThStmt; switch (node.nodeType) { case ParseNodeType.Assert: stmt = this.visitAssert(node); break; case ParseNodeType.Assignment: stmt = this.visitAssignment(node); break; case ParseNodeType.AugmentedAssignment: stmt = this.visitAugmentedAssignment(node); break; case ParseNodeType.Break: stmt = this.visitBreak(node); break; case ParseNodeType.Continue: stmt = this.visitContinue(node); break; case ParseNodeType.If: stmt = this.visitIf(node); break; case ParseNodeType.For: stmt = this.visitFor(node); break; case ParseNodeType.Module: stmt = this.visitModule(node); break; case ParseNodeType.Pass: stmt = this.visitPass(node); break; case ParseNodeType.Raise: stmt = this.visitRaise(node); break; case ParseNodeType.Return: stmt = this.visitReturn(node); break; case ParseNodeType.StatementList: stmt = this.visitStatementList(node); break; case ParseNodeType.Nonlocal: stmt = this.visitNonlocal(node); break; case ParseNodeType.Global: stmt = this.visitGlobal(node); break; case ParseNodeType.Import: stmt = this.visitImport(node); break; case ParseNodeType.ImportAs: stmt = this.visitImportAs(node); break; case ParseNodeType.ImportFrom: stmt = this.visitImportFrom(node); break; case ParseNodeType.Class: stmt = this.visitClass(node); break; case ParseNodeType.With: stmt = this.visitWith(node); break; case ParseNodeType.While: stmt = this.visitWhile(node); break; case ParseNodeType.Del: stmt = this.visitDel(node); break; case ParseNodeType.Try: stmt = this.visitTry(node); break; //case ParseNodeType.Except: //stmt= this.visitExcept(node); // break; default: stmt = TSPass.get(node); break; } if (this._preStmtStack.length > 0) { this._preStmtStack.reverse().forEach(([tempFunName, tempFunParams, tempFunBody]) => { stmt = TSFunDef.create(tempFunName, tempFunParams, tempFunBody, stmt); }); this._preStmtStack = []; } return stmt; } visitExprNode(node: ExpressionNode): ThExpr { switch (node.nodeType) { case ParseNodeType.BinaryOperation: return this.visitBinaryOperation(node); case ParseNodeType.UnaryOperation: return this.visitUnaryOperation(node); case ParseNodeType.Ternary: return this.visitTernary(node); case ParseNodeType.Call: return this.visitCall(node); case ParseNodeType.Constant: return this.visitConstant(node); case ParseNodeType.Index: return this.visitIndex(node); case ParseNodeType.MemberAccess: return this.visitMemberAccess(node); case ParseNodeType.Name: return this.visitName(node); case ParseNodeType.Number: return this.visitNumber(node); case ParseNodeType.String: return this.visitString(node); case ParseNodeType.StringList: return this.visitStringList(node); case ParseNodeType.Tuple: return this.visitTuple(node); case ParseNodeType.List: return this.visitList(node); case ParseNodeType.Dictionary: return this.visitDict(node); case ParseNodeType.Slice: return this.visitSlice(node); case ParseNodeType.Ellipsis: return this.visitEllipsis(node); case ParseNodeType.ListComprehension: return this.visitListComprehension(node); case ParseNodeType.Lambda: return this.visitLambda(node); default: return this.fail(node); } } fail(node: ParseNode): never { throw 'invalid node for Python script: ' + inspect(node); } private _mergeLocalDef(localDef: string[] | Set<string>, baseStmt: ThStmt): ThStmt { let stmt = baseStmt; localDef.forEach((name: string) => { stmt = TSLet.create(name, stmt); }); return stmt; } private _mergeStmt(stmts: ThStmt[]): ThStmt { if (stmts.length === 0) { return TSPass.get(); } else { const copied = [...stmts]; let stmt = copied.pop()!; copied.reverse().forEach((s) => { stmt = TSSeq.create(s, stmt); }); return stmt; } } private _getImm(): string { return `$Imm${++this._immId}`; } }
37.138278
135
0.53296
db7312e98c1a117cdb9fde805eb8785e2dc4a132
4,232
php
PHP
src/SortedMap.php
Ocramius/Ardent
c0220485c8928a7559cdf02f0f00fd8fb428ca60
[ "MIT" ]
2
2015-11-05T15:53:29.000Z
2015-12-05T17:33:53.000Z
src/SortedMap.php
Ocramius/Ardent
c0220485c8928a7559cdf02f0f00fd8fb428ca60
[ "MIT" ]
null
null
null
src/SortedMap.php
Ocramius/Ardent
c0220485c8928a7559cdf02f0f00fd8fb428ca60
[ "MIT" ]
null
null
null
<?php namespace Collections; class SortedMap implements Map { use IteratorCollection; /** * @var SplayTree */ private $avl; /** * @var callable */ private $comparator; function __construct($comparator = null) { $this->comparator = $comparator ?: '\Collections\compare'; $this->avl = new SplayTree([$this, 'compareKeys']); } function compareKeys(Pair $a, Pair $b) { return call_user_func($this->comparator, $a->first, $b->first); } /** * @return void */ function clear() { $this->avl->clear(); } /** * @param mixed $item * @param callable $callback * * @return bool * @throws TypeException when $item is not the correct type. */ function contains($item, callable $callback = null) { if ($callback === null) { $callback = '\Collections\compare'; } foreach ($this->avl as $pair) { /** * @var Pair $pair */ if (call_user_func($callback, $pair->second, $item) === 0) { return true; } } return false; } /** * @return bool */ function isEmpty() { return $this->avl->isEmpty(); } /** * @return mixed * @throws EmptyException when the tree is empty */ function first() { return $this->avl->first(); } /** * @return mixed * @throws EmptyException when the tree is empty */ function last() { return $this->avl->last(); } /** * @link http://php.net/manual/en/arrayaccess.offsetexists.php * * @param mixed $offset * * @return bool */ function offsetExists($offset) { return $this->avl->contains(new Pair($offset, null)); } /** * @param mixed $offset * @link http://php.net/manual/en/arrayaccess.offsetget.php * @return mixed * @throws KeyException */ function offsetGet($offset) { if (!$this->offsetExists($offset)) { throw new KeyException; } return $this->get($offset); } /** * @link http://php.net/manual/en/arrayaccess.offsetset.php * * @param mixed $offset * @param mixed $value * * @return void */ function offsetSet($offset, $value) { $this->set($offset, $value); } /** * @link http://php.net/manual/en/arrayaccess.offsetunset.php * * @param mixed $offset * * @return void */ function offsetUnset($offset) { $this->remove($offset); } /** * @param $key * * @return mixed * @throws TypeException when the $key is not the correct type. * @throws KeyException when the $key is not the correct type. */ function get($key) { if (!$this->offsetExists($key)) { throw new KeyException; } /** * @var Pair $pair */ $pair = $this->avl->get(new Pair($key, null)); return $pair->second; } /** * Note that if the key is considered equal to an already existing key in * the map that it's value will be replaced with the new one. * * @param $key * @param mixed $value * * @return void * @throws TypeException when the $key or value is not the correct type. */ function set($key, $value) { $this->avl->add(new Pair($key, $value)); } /** * @param $key * * @return mixed * @throws TypeException when the $key is not the correct type. */ function remove($key) { $this->avl->remove(new Pair($key, null)); } /** * @link http://php.net/manual/en/countable.count.php * @return int */ function count() { return $this->avl->count(); } /** * @link http://php.net/manual/en/iteratoraggregate.getiterator.php * @return SortedMapIterator */ function getIterator() { return new SortedMapIterator( new InOrderIterator($this->avl->toBinaryTree(), $this->avl->count()), $this->avl->count() ); } }
20.248804
81
0.518667
25bb82dd249da2575672c066327138e311455f73
2,367
rs
Rust
src/day8.rs
stevejb71/rust-advent-of-code-2021
dab1cdd71067ba4f71ba53b823cb50030ea46829
[ "Unlicense" ]
null
null
null
src/day8.rs
stevejb71/rust-advent-of-code-2021
dab1cdd71067ba4f71ba53b823cb50030ea46829
[ "Unlicense" ]
null
null
null
src/day8.rs
stevejb71/rust-advent-of-code-2021
dab1cdd71067ba4f71ba53b823cb50030ea46829
[ "Unlicense" ]
null
null
null
use crate::common::*; pub fn run(part: u8) -> u64 { let input_lines = include_str!("../inputs/day8.txt"); run_part(part, input_lines, vec_of_str, part1, part2) } #[derive(Debug)] struct Entry { signals: Vec<String>, outputs: Vec<String>, } pub fn part1(entries: &Vec<&str>) -> u64 { let entries = entries.iter().map(|x| parse(&x)).collect::<Vec<_>>(); entries.iter() .flat_map(|e| &e.outputs) .filter(|o| o.len() == 2 || o.len() == 3 || o.len() == 4 || o.len() == 7) .count() as u64 } pub fn part2(entries: &Vec<&str>) -> u64 { let entries = entries.iter().map(|x| parse(&x)).collect::<Vec<_>>(); entries.iter().map(|entry| { let pick_one = |len| { let matches = entry.signals.iter().filter(|s| s.len() == len).collect::<Vec<_>>(); assert_eq!(1, matches.len()); matches[0] }; let one = pick_one(2); let four = pick_one(4); let digits = entry.outputs.iter().map(|output| { let count_overlaps = |d: &String| { output.chars().filter(|&co| d.contains(co)).count() }; match output.len() { 2 => 1, 4 => 4, 3 => 7, 7 => 8, 5 => { if count_overlaps(one) == 2 { 3 } else if count_overlaps(four) == 2 { 2 } else { 5 } }, 6 => { if count_overlaps(four) == 4 { 9 } else if count_overlaps(one) == 2 { 0 } else { 6 } } _ => panic!("shouldn't happen") } }).collect::<Vec<_>>(); digits[0] * 1000 + digits[1] * 100 + digits[2] * 10 + digits[3] }).sum::<u64>() } fn parse(e: &str) -> Entry { let mut split = e.split("|"); let signals = split.next().unwrap().split_ascii_whitespace().map(|x| x.to_string()).collect::<Vec<_>>(); let outputs = split.next().unwrap().split_ascii_whitespace().map(|x| x.to_string()).collect::<Vec<_>>(); Entry { signals, outputs } } #[cfg(test)] mod tests { use super::*; #[test] fn part1_finds_easy_entries() { let entries = sample(); assert_eq!(26, part1(&entries)); } #[test] fn part2_finds_all_entries() { let entries = sample(); assert_eq!(61229, part2(&entries)); } fn sample() -> Vec<&'static str> { include_str!("../test_inputs/day8.txt").lines().collect() } }
25.180851
106
0.517533
e23f3867fa3b1af2d848bc3403aa47f39bb94a4b
1,071
py
Python
baekjoon/python/order_of_matrix_multiple_11049.py
yskang/AlgorithmPractice
31b76e38b4c2f1e3e29fb029587662a745437912
[ "MIT" ]
null
null
null
baekjoon/python/order_of_matrix_multiple_11049.py
yskang/AlgorithmPractice
31b76e38b4c2f1e3e29fb029587662a745437912
[ "MIT" ]
1
2019-11-04T06:44:04.000Z
2019-11-04T06:46:55.000Z
baekjoon/python/order_of_matrix_multiple_11049.py
yskang/AlgorithmPractice
31b76e38b4c2f1e3e29fb029587662a745437912
[ "MIT" ]
null
null
null
# Title: 행렬 곱셈 순서 # Link: https://www.acmicpc.net/problem/11049 import sys sys.setrecursionlimit(10 ** 6) read_single_int = lambda: int(sys.stdin.readline().strip()) read_list_int = lambda: list(map(int, sys.stdin.readline().strip().split(' '))) def get_min_times(start: int, end: int, matrixs: list, dp: list): if dp[start][end] != -1: return dp[start][end] if end == start: dp[start][end] = 0 return 0 min_value = 999999999999999999999 for i in range(start, end): min_value = min(get_min_times(start, i, matrixs, dp) + get_min_times(i+1, end, matrixs, dp) + (matrixs[start][0] * matrixs[end][1] * matrixs[i][1]), min_value) dp[start][end] = min_value return min_value def solution(n: int, matrixs: list): dp = [[-1 for _ in range(n+1)] for _ in range(n+1)] return get_min_times(1, n, matrixs, dp) def main(): n = read_single_int() matrixs = [0] for _ in range(n): matrixs.append(read_list_int()) print(solution(n, matrixs)) if __name__ == '__main__': main()
24.340909
167
0.625584
3926fad534452c8776a5bd86f992d01970a1cc22
222
py
Python
run.py
phamvanhanh6720/Face-Recognition
cc6dd6324334e26be1dd2b024f4bb2297c313dea
[ "MIT" ]
8
2021-11-02T04:37:18.000Z
2022-02-09T03:06:50.000Z
run.py
phamvanhanh6720/Face-Recognition
cc6dd6324334e26be1dd2b024f4bb2297c313dea
[ "MIT" ]
1
2021-08-16T09:42:03.000Z
2021-08-18T12:47:29.000Z
run.py
phamvanhanh6720/Face-Recognition
cc6dd6324334e26be1dd2b024f4bb2297c313dea
[ "MIT" ]
null
null
null
from face_recognition import main import asyncio if __name__ == '__main__': futures = [main(cam_device=0, input_size=(480, 640))] loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.wait(futures))
27.75
57
0.738739
4bb42b810567dbe097568b23e35fd8026be52179
332
hpp
C++
dynamic/wrappers/cell_based/AbstractCellPopulationBoundaryCondition3_3.cppwg.hpp
jmsgrogan/PyChaste
48a9863d2c941c71e47ecb72e917b477ba5c1413
[ "FTL" ]
6
2017-02-04T16:10:53.000Z
2021-07-01T08:03:16.000Z
dynamic/wrappers/cell_based/AbstractCellPopulationBoundaryCondition3_3.cppwg.hpp
jmsgrogan/PyChaste
48a9863d2c941c71e47ecb72e917b477ba5c1413
[ "FTL" ]
6
2017-06-22T08:50:41.000Z
2019-12-15T20:17:29.000Z
dynamic/wrappers/cell_based/AbstractCellPopulationBoundaryCondition3_3.cppwg.hpp
jmsgrogan/PyChaste
48a9863d2c941c71e47ecb72e917b477ba5c1413
[ "FTL" ]
3
2017-05-15T21:33:58.000Z
2019-10-27T21:43:07.000Z
#ifndef AbstractCellPopulationBoundaryCondition3_3_hpp__pyplusplus_wrapper #define AbstractCellPopulationBoundaryCondition3_3_hpp__pyplusplus_wrapper namespace py = pybind11; void register_AbstractCellPopulationBoundaryCondition3_3_class(py::module &m); #endif // AbstractCellPopulationBoundaryCondition3_3_hpp__pyplusplus_wrapper
47.428571
78
0.915663
71ca70407b1b4903c07d5cac8c731d030e517167
12,728
rs
Rust
pyrite/src/renderer/bidirectional.rs
Ogeon/pyrite
930dea014943620e11ad932229b9917e59a44673
[ "Apache-2.0", "MIT" ]
4
2016-08-27T22:14:58.000Z
2020-07-30T09:17:16.000Z
pyrite/src/renderer/bidirectional.rs
Ogeon/pyrite
930dea014943620e11ad932229b9917e59a44673
[ "Apache-2.0", "MIT" ]
1
2020-06-07T08:36:02.000Z
2020-07-12T12:35:42.000Z
pyrite/src/renderer/bidirectional.rs
Ogeon/pyrite
930dea014943620e11ad932229b9917e59a44673
[ "Apache-2.0", "MIT" ]
1
2020-07-30T09:17:18.000Z
2020-07-30T09:17:18.000Z
use rand::{self, Rng, SeedableRng}; use rand_xorshift::XorShiftRng; use cgmath::{EuclideanSpace, InnerSpace, Point2, Vector3}; use collision::Ray3; use super::{ algorithm::{contribute, make_tiles, Tile}, LocalProgress, Progress, Renderer, TaskRunner, }; use crate::cameras::Camera; use crate::film::{Film, Sample}; use crate::lamp::{RaySample, Surface}; use crate::tracer::{trace, Bounce, BounceType}; use crate::utils::pairs; use crate::{ materials::ProbabilityInput, math::DIST_EPSILON, program::{ExecutionContext, Resources}, world::World, }; use std::{ cell::Cell, time::{Duration, Instant}, }; pub struct BidirParams { pub bounces: u32, } pub(crate) fn render<F: FnMut(Progress<'_>)>( film: &Film, task_runner: TaskRunner, mut on_status: F, renderer: &Renderer, config: &BidirParams, world: &World, camera: &Camera, resources: Resources, ) { fn gen_rng() -> XorShiftRng { XorShiftRng::from_rng(rand::thread_rng()).expect("could not generate RNG") } let tiles = make_tiles(film.width(), film.height(), renderer.tile_size, camera); let status_message = "Rendering"; on_status(Progress { progress: 0, message: &status_message, }); let mut progress: usize = 0; let num_tiles = tiles.len(); task_runner.run_tasks( tiles.into_iter().map(|f| (f, gen_rng())), |index, (tile, rng), progress| { render_tile( index, rng, tile, film, camera, world, resources, renderer, config, progress, ); }, |_, _| { progress += 1; on_status(Progress { progress: ((progress * 100) / num_tiles) as u8, message: &status_message, }); }, ); } fn render_tile<R: Rng>( index: usize, mut rng: R, tile: Tile, film: &Film, camera: &Camera, world: &World, resources: Resources, renderer: &Renderer, bidir_params: &BidirParams, progress: LocalProgress, ) { let mut lamp_path = Vec::with_capacity(bidir_params.bounces as usize + 1); let mut camera_path = Vec::with_capacity(renderer.bounces as usize); let mut additional_samples = Vec::with_capacity(renderer.spectrum_samples as usize - 1); let mut exe = ExecutionContext::new(resources); let iterations = tile.area() as u64 * renderer.pixel_samples as u64; let message = format!("Tile {}", index); let mut last_progress = Instant::now(); progress.show(&message, iterations); for i in 0..iterations { if Instant::now() - last_progress > Duration::from_millis(100) { progress.set_progress(i); last_progress = Instant::now(); } lamp_path.clear(); camera_path.clear(); additional_samples.clear(); let position = tile.sample_point(&mut rng); additional_samples.extend( film.sample_many_wavelengths(&mut rng, renderer.spectrum_samples as usize) .map(|wavelength| { ( Sample { wavelength, brightness: 0.0, weight: 1.0, }, 1.0, ) }), ); let mut main_sample = additional_samples.swap_remove(rng.gen_range(0, additional_samples.len())); let wavelength = main_sample.0.wavelength; let camera_ray = camera.ray_towards(&position, &mut rng); let lamp_sample = world .pick_lamp(&mut rng) .and_then(|(l, p)| l.sample_ray(&mut rng).map(|r| (r, p))); if let Some((lamp_sample, probability)) = lamp_sample { let RaySample { mut ray, surface, weight, } = lamp_sample; let (color, material_probability, dispersed, normal, texture) = match surface { Surface::Physical { normal, material, texture, } => { let component = material.choose_emissive(&mut rng); let input = ProbabilityInput { wavelength, wavelength_used: Cell::new(false), normal, incident: -ray.direction, texture_coordinate: texture, }; let probability = component.get_probability(&mut exe, &input); ( component.bsdf.color, probability, input.wavelength_used.get(), normal, texture, ) } Surface::Color(color) => (color, 1.0, false, ray.direction, Point2::origin()), }; ray.origin += normal * DIST_EPSILON; lamp_path.push(Bounce { ty: BounceType::Emission, dispersed, color, incident: Vector3::new(0.0, 0.0, 0.0), position: ray.origin, normal, texture, probability: weight / (probability * material_probability), direct_light: vec![], }); trace( &mut lamp_path, &mut rng, ray, wavelength, world, bidir_params.bounces, 0, &mut exe, ); pairs(&mut lamp_path, |to, from| { to.incident = -from.incident; if let BounceType::Diffuse(_, ref mut o) = from.ty { *o = from.incident } }); if lamp_path.len() > 1 { if let Some(last) = lamp_path.pop() { match last.ty { BounceType::Diffuse(_, _) | BounceType::Specular => lamp_path.push(last), BounceType::Emission => {} } } } lamp_path.reverse(); } trace( &mut camera_path, &mut rng, camera_ray, wavelength, world, renderer.bounces, renderer.light_samples, &mut exe, ); let total = (camera_path.len() * lamp_path.len()) as f32; let weight = 1.0 / total; let mut use_additional = true; for bounce in &camera_path { use_additional = !bounce.dispersed && use_additional; let additional_samples_slice = if use_additional { &mut *additional_samples } else { &mut [] }; contribute(bounce, &mut main_sample, additional_samples_slice, &mut exe); for mut contribution in connect_paths( &bounce, &main_sample, &additional_samples, &lamp_path, world, use_additional, &mut exe, ) { contribution.weight = weight; film.expose(position, contribution); } } film.expose(position, main_sample.0.clone()); if use_additional { for &(ref sample, _) in &additional_samples { film.expose(position, sample.clone()); } } let weight = 1.0 / lamp_path.len() as f32; for (i, bounce) in lamp_path.iter().enumerate() { if let BounceType::Diffuse(_, _) = bounce.ty { } else { continue; } let camera_hit = camera.is_visible(bounce.position, &world, &mut rng); if let Some((position, ray)) = camera_hit { if position.x > -1.0 && position.x < 1.0 && position.y > -1.0 && position.y < 1.0 { let sq_distance = (ray.origin - bounce.position).magnitude2(); let scale = 1.0 / (sq_distance); let brdf_in = bounce.ty.brdf(-ray.direction, bounce.normal) / bounce.ty.brdf(bounce.incident, bounce.normal); main_sample.0.brightness = 0.0; main_sample.0.weight = weight; main_sample.1 = scale; use_additional = true; for &mut (ref mut sample, ref mut reflectance) in &mut additional_samples { sample.brightness = 0.0; sample.weight = weight; *reflectance = scale; } for (i, bounce) in lamp_path[i..].iter().enumerate() { use_additional = !bounce.dispersed && use_additional; let additional_samples = if use_additional { &mut *additional_samples } else { &mut [] }; contribute(bounce, &mut main_sample, additional_samples, &mut exe); if i == 0 { main_sample.1 *= brdf_in; for (_, reflectance) in additional_samples { *reflectance *= brdf_in; } } } film.expose(position, main_sample.0.clone()); if use_additional { for &(ref sample, _) in &additional_samples { film.expose(position, sample.clone()); } } } } } } } fn connect_paths<'a>( bounce: &Bounce<'a>, main: &(Sample, f32), additional: &[(Sample, f32)], path: &[Bounce<'a>], world: &World, use_additional: bool, exe: &mut ExecutionContext<'a>, ) -> Vec<Sample> { let mut contributions = vec![]; let bounce_brdf = match bounce.ty { BounceType::Emission | BounceType::Specular => return contributions, BounceType::Diffuse(brdf, _) => brdf, }; for (i, lamp_bounce) in path.iter().enumerate() { if let BounceType::Specular = lamp_bounce.ty { continue; } let from = bounce.position; let to = lamp_bounce.position; let direction = to - from; let sq_distance = direction.magnitude2(); let distance = sq_distance.sqrt(); let ray = Ray3::new(from, direction / distance); if bounce.normal.dot(ray.direction) <= 0.0 { continue; } if lamp_bounce.normal.dot(-ray.direction) <= 0.0 { continue; } let hit = world.intersect(ray).map(|hit| hit.distance); if let Some(dist) = hit { if dist < distance - DIST_EPSILON { continue; } } let cos_out = bounce.normal.dot(ray.direction).abs(); let cos_in = lamp_bounce.normal.dot(-ray.direction).abs(); let brdf_out = bounce_brdf(bounce.incident, bounce.normal, ray.direction) / bounce.ty.brdf(bounce.incident, bounce.normal); let scale = cos_in * cos_out * brdf_out / (2.0 * std::f32::consts::PI * sq_distance); let brdf_in = lamp_bounce.ty.brdf(-ray.direction, lamp_bounce.normal) / lamp_bounce .ty .brdf(lamp_bounce.incident, lamp_bounce.normal); let mut use_additional = use_additional; let mut additional: Vec<_> = additional .iter() .cloned() .map(|(s, r)| (s, r * scale)) .collect(); let mut main = main.clone(); main.1 *= scale; for (i, bounce) in path[i..].iter().enumerate() { use_additional = !bounce.dispersed && use_additional; let additional_samples = if use_additional { &mut *additional } else { &mut [] }; contribute(bounce, &mut main, additional_samples, exe); if i == 0 { main.1 *= brdf_in; for (_, reflectance) in additional_samples { *reflectance *= brdf_in; } } } contributions.push(main.0); if use_additional { contributions.extend(additional.into_iter().map(|(s, _)| s)); } } contributions }
31.899749
99
0.489629
be6f051da7df0fe8fc9227cc9d5431209563a4ac
86
sql
SQL
db/migrations/133_migrate_pushed_value_to_project_status.up.sql
epmd-edp/admin-console
fe389bccf95f5cb48f0d5e11c50eb5f560b37311
[ "Apache-2.0" ]
3
2019-12-14T14:53:20.000Z
2021-05-06T17:25:25.000Z
db/migrations/133_migrate_pushed_value_to_project_status.up.sql
epam/edp-admin-console
33e9d7518f6a24ddea16e2df7f0fcac41a27dd17
[ "Apache-2.0" ]
null
null
null
db/migrations/133_migrate_pushed_value_to_project_status.up.sql
epam/edp-admin-console
33e9d7518f6a24ddea16e2df7f0fcac41a27dd17
[ "Apache-2.0" ]
4
2021-03-12T11:58:18.000Z
2022-02-21T11:51:29.000Z
update codebase set project_status = 'templates_pushed' where project_status = 'true';
28.666667
39
0.813953
9f01535f99fc9083ad04b17af71c602181a1eeea
483
kt
Kotlin
buildSrc/src/main/kotlin/Dependencies.kt
rickclephas/KMP-NativeCoroutines
45bb98fc6cd405e442942e5c20878896d67fb6e4
[ "MIT" ]
264
2021-06-13T20:41:13.000Z
2022-03-30T20:55:25.000Z
buildSrc/src/main/kotlin/Dependencies.kt
rickclephas/KMP-NativeCoroutines
45bb98fc6cd405e442942e5c20878896d67fb6e4
[ "MIT" ]
40
2021-06-18T14:00:35.000Z
2022-03-30T21:43:14.000Z
buildSrc/src/main/kotlin/Dependencies.kt
rickclephas/KMP-NativeCoroutines
45bb98fc6cd405e442942e5c20878896d67fb6e4
[ "MIT" ]
14
2021-07-16T23:44:20.000Z
2022-03-28T09:28:04.000Z
object Dependencies { object Kotlin { private const val version = "1.6.10" const val gradlePlugin = "org.jetbrains.kotlin:kotlin-gradle-plugin:$version" const val compiler = "org.jetbrains.kotlin:kotlin-compiler:$version" const val embeddableCompiler = "org.jetbrains.kotlin:kotlin-compiler-embeddable:$version" } object Kotlinx { const val coroutinesCore = "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.0-native-mt" } }
37.153846
98
0.693582
2cfe6152d781ead5b251bb4a0c32fc277b8a1c1b
965
cpp
C++
oli/vii2018puzzle/main.cpp
rockoanna/nirvana
81fadbe66b0a24244feec312c6f7fe5c8effccaa
[ "MIT" ]
null
null
null
oli/vii2018puzzle/main.cpp
rockoanna/nirvana
81fadbe66b0a24244feec312c6f7fe5c8effccaa
[ "MIT" ]
12
2019-09-04T10:38:24.000Z
2019-12-08T18:09:41.000Z
oli/vii2018puzzle/main.cpp
rockoanna/nirvana
81fadbe66b0a24244feec312c6f7fe5c8effccaa
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; int main() { int n; cin >> n; vector<int> pieces(n); for(int i = 0; i < n; i++) { cin >> pieces[i]; } int res = 0; for(int i = 0; i < n - 1; i++) { for(int j = i + 1; j < n; j++) { bool ok = true; int nr1 = pieces[i]; int nr2 = pieces[j]; int x = nr1 % 10 + nr2 % 10; nr1 = nr1 / 10; nr2 = nr2 / 10; while(nr1 != 0) { if(nr1 % 10 + nr2 % 10 == x) { nr1 = nr1 / 10; nr2 = nr2 / 10; } else { ok = false; break; } } if(ok == true) { res += 1; } } } cout << res << endl; return 0; }
16.929825
44
0.288083
ec89bec00a58efa62bd4b9185c089dd96be9dbd2
412
kt
Kotlin
src/main/kotlin/com/bajdcc/util/lexer/automata/dfa/DFAEdgeData.kt
bajdcc/jInterpreter
90b19af98da99b53bba5b3269ad5666df7c05e49
[ "MIT" ]
71
2015-09-29T13:12:11.000Z
2022-01-11T16:20:11.000Z
src/main/kotlin/com/bajdcc/util/lexer/automata/dfa/DFAEdgeData.kt
bajdcc/jInterpreter
90b19af98da99b53bba5b3269ad5666df7c05e49
[ "MIT" ]
1
2017-04-23T12:13:41.000Z
2017-05-09T14:37:24.000Z
src/main/kotlin/com/bajdcc/util/lexer/automata/dfa/DFAEdgeData.kt
bajdcc/jInterpreter
90b19af98da99b53bba5b3269ad5666df7c05e49
[ "MIT" ]
20
2017-03-28T18:05:20.000Z
2021-06-12T08:40:10.000Z
package com.bajdcc.util.lexer.automata.dfa import com.bajdcc.util.lexer.automata.EdgeType import com.bajdcc.util.lexer.automata.nfa.NFAEdge /** * DFA边数据 * [type] 边类型 * [param] 数据 * [nfaEdges] NFA边集合 * @author bajdcc */ data class DFAEdgeData (var type: EdgeType = EdgeType.EPSILON, var param: Int = -1, var nfaEdges: MutableList<NFAEdge> = mutableListOf())
27.466667
77
0.650485
84e7bfcd51fcb7516078279efafc5640517f60a5
3,759
cs
C#
ShoppingAgain/Controllers/UserController.cs
Moosemorals/ShoppingAgain
ed2a294fd76dc25d29443c306f94788c0bd024a8
[ "0BSD" ]
null
null
null
ShoppingAgain/Controllers/UserController.cs
Moosemorals/ShoppingAgain
ed2a294fd76dc25d29443c306f94788c0bd024a8
[ "0BSD" ]
null
null
null
ShoppingAgain/Controllers/UserController.cs
Moosemorals/ShoppingAgain
ed2a294fd76dc25d29443c306f94788c0bd024a8
[ "0BSD" ]
null
null
null
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using ShoppingAgain.Classes; using ShoppingAgain.Database; using ShoppingAgain.Models; using ShoppingAgain.ViewModels; namespace ShoppingAgain.Controllers { [Route("u"), Authorize(Roles = Names.RoleUser)] public class UserController : ShoppingBaseController { public UserController(ShoppingService Lists) : base(Lists) { } [HttpGet("", Name = Names.UserIndex)] public IActionResult Index() { return View(); } [HttpGet("Password", Name = Names.UserChangePassword)] public IActionResult ChangePassword() { return View(); } [HttpPost("Password"), ValidateAntiForgeryToken] public async Task<IActionResult> ChangePassword(ChangePasswordVM vm) { if (!ModelState.IsValid) { return View(vm); } User u = GetUser(); if (!u.Password.Validate(vm.OldPassword)) { ModelState.AddModelError(nameof(vm.OldPassword), "That wasn't your old password"); return View(vm); } // At this point we know that the old password is right, // the new password is >= 12 chars, and the new and confirm // passwords match. So, change the password await lists.ChangePassword(u, vm.NewPassword); Message("Your password has been changed"); return RedirectToRoute(Names.ListIndex, Names.ListHash); } [HttpGet("Friends", Name = Names.UserFriends)] public IActionResult Friends() { User current = GetUser(); FriendsVM vm = new FriendsVM { Friends = new List<FriendVM>(), }; foreach (User u in lists.GetUsers()) { if (u.ID == current.ID) { // Can't be friends with yourself continue; } vm.Friends.Add(new FriendVM { UserId = u.ID, UserName = u.Name, IsFriend = current.Friends.Any(uf => uf.FriendID == u.ID), }); } return View(vm); } [HttpPost("Friends"), ValidateAntiForgeryToken] public async Task<IActionResult> Friends(FriendsVM vm) { if (!ModelState.IsValid) { return View(vm); } foreach (FriendVM friendVM in vm.Friends) { User u = lists.GetUser(friendVM.UserId); if (u == null) { ModelState.AddModelError(nameof(friendVM.UserId), "UserID isn't valid"); continue; } } if (!ModelState.IsValid) { return View(vm); } User current = GetUser(); foreach (FriendVM friendVM in vm.Friends) { User u = lists.GetUser(friendVM.UserId); await lists.ManageFriend(current, u, friendVM.IsFriend); } if (current.Friends.Count > 0) { Message("You are now friends with {0}", string.Join(", ", current.Friends.Select(uf => uf.Friend.Name))); } else { Message("You have no friends"); } return RedirectToRoute(Names.UserIndex, "user-controls"); } } }
29.833333
121
0.510242
e025054105a965b8005fb35aed626b66fbc4631d
87
h
C
src/apps/PreferencesWindow/PreferencesWindow/ProfilesTableView.h
rolandwalker/Karabiner-Elements
3a537d3dd7a47100baf95bb3477e897a6e59bee8
[ "Unlicense" ]
1
2021-11-09T10:28:50.000Z
2021-11-09T10:28:50.000Z
src/apps/PreferencesWindow/PreferencesWindow/ProfilesTableView.h
rolandwalker/Karabiner-Elements
3a537d3dd7a47100baf95bb3477e897a6e59bee8
[ "Unlicense" ]
null
null
null
src/apps/PreferencesWindow/PreferencesWindow/ProfilesTableView.h
rolandwalker/Karabiner-Elements
3a537d3dd7a47100baf95bb3477e897a6e59bee8
[ "Unlicense" ]
null
null
null
// -*- Mode: objc -*- @import Cocoa; @interface ProfilesTableView : NSTableView @end
12.428571
42
0.678161
c67f08152198fef1bd8afd69e1913c284dd0a310
5,624
css
CSS
src/main/webapp/resources/backend/css/src/main.css
jianmakeji/yxyp
3d56d787ffe9926f83832954f5e718e640f59341
[ "MIT" ]
1
2019-02-14T01:18:57.000Z
2019-02-14T01:18:57.000Z
src/main/webapp/resources/backend/css/src/main.css
jianmakeji/yxyp
3d56d787ffe9926f83832954f5e718e640f59341
[ "MIT" ]
5
2020-05-15T21:06:24.000Z
2021-12-09T20:40:01.000Z
src/main/webapp/resources/backend/css/src/main.css
jianmakeji/yxyp
3d56d787ffe9926f83832954f5e718e640f59341
[ "MIT" ]
null
null
null
[v-cloak] { display: none; } ivu-modal-header-inner{ text-align: center; color: #ed3f14; } html{ height: 100%; width:100%; } body{ margin: 0px; padding:0px; height: 100%; position: relative; font-family: "Arail","Microsoft YaHei","Heiti"; background: #efefef!important; } ul{ padding:0px; margin: 0px; list-style: none; } a{ text-decoration: none!important; } label.error{ color: red; } .zyHidden{ display: none!important; } /** *复写datatable */ table.dataTable{ margin-top: 20px; width: 100%; border-bottom: #efefef solid 1px; } table.dataTable thead { background: #fff; } table.dataTable thead th{ color: #333; border: none; font-weight: bold; padding: 5px; text-align: center; line-height: 30px!important; } table.dataTable tr{ line-height: 25px!important; border-top: #efefef solid 1px; } table.dataTable tr.odd{ background:#fff; } table.dataTable tr.even{ background:#fff; } table.dataTable td { padding: 5px!important; text-align: center; } table.dataTable .thumb{ width: 100px; height: auto; } .dataTables_paginate,.dataTables_info{ margin: 15px 0 20px; height:40px; line-height: 40px; } .paging_full_numbers{ height: 40px; line-height: 1; } .paging_full_numbers a.paginate_button, .paging_full_numbers a.paginate_active{ height:40px; line-height: 40px; min-width: 40px; text-align: center; border-radius: 2px; display: inline-block; padding:0 5px; box-sizing: border-box; } .paging_full_numbers a.paginate_active{ background:#56abff; color: #fff !important; border: none; } .paging_full_numbers a.paginate_button{ background:#fff; border: #ddd 1px solid; } .paging_full_numbers a.paginate_button:hover{ background:#ddd; } /********覆写bootstrap*************/ .table>tbody>tr>td{ vertical-align: middle; } .panel{ border-radius: 0; } .input-group-btn{ z-index: 2; } .modal-header{ position: relative; } .close{ float: none; width:40px; height: 40px; border-radius: 20px; line-height: 40px; text-align: center; } .close:hover{ background:#ddd; } .modal-header .close{ position: absolute; top: 10px; right: 20px } .left{ width: 180px; } .right{ border-left: 1px solid #ddd; background: #efefef; padding:10px; position: absolute; left:180px; top:64px; bottom: 0px; right: 0px; overflow: auto; } .main{ width: 100%; margin: 0px auto 0px auto; } .main .row{ margin: 10px auto; position: relative; clear: both; } .hasRightBorder{ border-right:1px solid #ddd; } .hasLeftBorder{ border-left:1px solid #ddd; } .header{ position: relative; z-index: 99; background: #333; height: 64px; box-shadow: 0 2px 5px rgba(0,0,0,0.3); } /** *logo */ .logo{ width: 100%; height: 64px; margin: 0px; display: inline-block; color: #fff; line-height: 64px; font-size: 20px; letter-spacing: .05em; vertical-align: middle; padding-left:64px; position: relative; } .logo .icon{ font-size: 32px; display: inline-block; width:64px; height: 64px; line-height: 64px; text-align: center; position: absolute; left: 0; top: 0; background-size: cover; } /*topNav*/ .topNav{ position: absolute; top:0; right: 0; height: 64px; width:100px; } .topNav ul{ display: flex; } .topNav ul li{ flex:1; } .topNav ul li a{ display: block; width:100%; height: 100%; line-height: 64px; text-align: center; font-size: 12px; color: #efefef; } .topNav ul li a:hover{ color: #ccc; } /** *menu */ .menu{ } .menu .separate{ height: 10px; background: #fff; } .menu .item { min-height: 40px; width: 100%; border-bottom: 1px solid #ddd; line-height: 40px; position: relative; } .menu .item .glyphicon{ padding: 0px 10px; } .menu .item .rightIcon{ margin-left: 100px; } .menu .item .link{ font-size: 16px; color: #727171; border-left: 1px solid #edece3; display: inline-block; position: absolute; left:34px; top:0px; bottom: 0px; right:0px; height: 100%; padding-left: 5px; } .menu .item:hover,.menu .item.active{ background: #ffffff; } .menu .item:hover .link,.menu .item.active .link{ color: #56abff; } .menu .item:hover .subMenu{ display: block; } .menu .subMenu{ background: #ffffff; display: none; } .menu .subMenu .sItem{ height: 35px; position: relative; } .menu .subMenu .sItem .circle { width: 10px; height: 10px; border-radius: 5px; background: #edece3; font-size: 0px; display: inline-block; margin-left: 30px; margin-top: 15px; } .menu .subMenu .sItem .sLink{ font-size: 12px; color: #727171; display: inline-block; position: absolute; left:34px; top:0px; bottom: 0px; right:0px; height: 100%; padding-left: 25px; } .menu .subMenu .sItem:hover .circle { background: #56abff; } .menu .subMenu .sItem:hover .sLink{ color: #56abff; } .welcome{ color: #56abff; } .tableSearchContainer{ position: absolute; top: 0; right:0; width:50%; } /** *loading */ .zyLoading{ position: fixed; top:0px; left:0px; width: 100%; height: 100%; z-index: 9998; opacity: .5; filter: progid:DXImageTransform.Microsoft.Alpha(opacity=50); background: #000; } .zyLoading .zyText{ position: absolute; left:50%; top:50%; color:#fff; }
16.78806
79
0.614154
434dc07600dff9b1e3e5b572ee82967ad55a3d3b
416
ts
TypeScript
src/app/components/progress-bar/progress-bar.component.ts
tenuj/angular2-homework-2
65b97cd2057464fbf2708fd053058c260a65c0b4
[ "MIT" ]
null
null
null
src/app/components/progress-bar/progress-bar.component.ts
tenuj/angular2-homework-2
65b97cd2057464fbf2708fd053058c260a65c0b4
[ "MIT" ]
null
null
null
src/app/components/progress-bar/progress-bar.component.ts
tenuj/angular2-homework-2
65b97cd2057464fbf2708fd053058c260a65c0b4
[ "MIT" ]
null
null
null
/** * This code has been written by Denis Shavenzov * If you have any questions or notices you can contact me by email shavenzov@gmail.com */ import { Component, Input } from '@angular/core'; @Component({ selector: 'progress-bar', templateUrl: './progress-bar.component.html', styleUrls: ['./progress-bar.component.less'] }) export class ProgressBarComponent { @Input() public visible : boolean; }
20.8
87
0.706731
cf03a19dd3845a85a2ec4bd39c453b950b8efc5d
2,584
php
PHP
app/Http/Controllers/Store/CustomerController.php
javzero/nolita
e9357426e6d9b7691314b23b0035edc79a0fff4b
[ "MIT" ]
null
null
null
app/Http/Controllers/Store/CustomerController.php
javzero/nolita
e9357426e6d9b7691314b23b0035edc79a0fff4b
[ "MIT" ]
4
2021-01-05T04:37:42.000Z
2021-09-09T22:19:49.000Z
app/Http/Controllers/Store/CustomerController.php
javzero/nolita
e9357426e6d9b7691314b23b0035edc79a0fff4b
[ "MIT" ]
null
null
null
<?php namespace App\Http\Controllers\Store; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Customer; class CustomerController extends Controller { public function update(Request $request) { // dd($request->all()); $customer = Customer::findOrFail(auth()->guard('customer')->user()->id); if($request->cuit == null && $request->dni == null) { return redirect()->back()->withErrors('Debe ingresar su CUIT'); } if($request->cuit != null ) { $this->validate($request,[ 'cuit' => 'digits:11|unique:customers,cuit,'.$customer->id ]); } if($request->dni != null ) { $this->validate($request,[ 'dni' => 'digits:8|unique:customers,dni,'.$customer->id ]); } $this->validate($request,[ 'name' => 'required|string|max:255', 'surname' => 'required|string|max:255', 'username' => 'required|string|max:20|unique:customers,username,'.$customer->id, 'email' => 'required|string|email|max:255|unique:customers,email,'.$customer->id, 'phone' => 'required|max:255', 'address' => 'required|max:255', 'cp' => 'required|max:255', 'geoprov_id' => 'required|max:255', 'geoloc_id' => 'required|max:255', ],[ 'username.unique' => 'Ese nombre de usuario ya existe', 'phone.required' => 'Debe ingresar su número de teléfono', 'addres.required' => 'Debe ingresar su dirección', 'geoprov_id.required' => 'Debe ingresar su provincia', 'geoloc_id.required' => 'Debe ingresar su localidad', 'cp.required' => 'Debe ingresar su código postal' ]); $customer->fill($request->all()); $customer->save(); if($request->from == "checkout"){ return redirect()->route('store.checkout')->with('message','Datos actualizados'); } return redirect()->route('store.customer-account')->with('message','Datos actualizados'); } public function updatePassword(Request $request) { //dd($request->all()); $this->validate($request,[ 'password' => 'required|string|min:6|confirmed' ],[ 'password.required' => 'Debe ingresar un password', 'password.confirmed' => 'Las constraseñas no coinciden', ]); //bcrypt } }
33.128205
97
0.531347
6dd6d862e55f650038d8a74715cf3b0779ea19ea
4,837
c
C
EKF/matlab/scripts/Inertial Nav EKF/K_VELX.c
fx815/EKF
ac33a6500d6cedd441758cae2f9aa7192f0f2a87
[ "BSD-3-Clause" ]
15
2017-07-21T07:26:56.000Z
2022-01-11T17:51:02.000Z
EKF/matlab/scripts/Inertial Nav EKF/K_VELX.c
fx815/EKF
ac33a6500d6cedd441758cae2f9aa7192f0f2a87
[ "BSD-3-Clause" ]
6
2020-05-24T06:53:13.000Z
2020-11-22T15:41:04.000Z
EKF/matlab/scripts/Inertial Nav EKF/K_VELX.c
fx815/EKF
ac33a6500d6cedd441758cae2f9aa7192f0f2a87
[ "BSD-3-Clause" ]
11
2017-01-17T07:53:17.000Z
2020-01-08T04:19:24.000Z
float t2 = q0*q3*2.0f; float t3 = q1*q2*2.0f; float t4 = t2+t3; float t5 = q0*q0; float t6 = q1*q1; float t7 = q2*q2; float t8 = q3*q3; float t9 = t5+t6-t7-t8; float t10 = q0*q2*2.0f; float t25 = q1*q3*2.0f; float t11 = t10-t25; float t12 = q3*ve*2.0f; float t13 = q0*vn*2.0f; float t26 = q2*vd*2.0f; float t14 = t12+t13-t26; float t15 = q3*vd*2.0f; float t16 = q2*ve*2.0f; float t17 = q1*vn*2.0f; float t18 = t15+t16+t17; float t19 = q0*vd*2.0f; float t20 = q2*vn*2.0f; float t27 = q1*ve*2.0f; float t21 = t19+t20-t27; float t22 = q1*vd*2.0f; float t23 = q0*ve*2.0f; float t28 = q3*vn*2.0f; float t24 = t22+t23-t28; float t29 = P[0][0]*t14; float t30 = P[1][1]*t18; float t31 = P[4][5]*t9; float t32 = P[5][5]*t4; float t33 = P[0][5]*t14; float t34 = P[1][5]*t18; float t35 = P[3][5]*t24; float t79 = P[6][5]*t11; float t80 = P[2][5]*t21; float t36 = t31+t32+t33+t34+t35-t79-t80; float t37 = t4*t36; float t38 = P[4][6]*t9; float t39 = P[5][6]*t4; float t40 = P[0][6]*t14; float t41 = P[1][6]*t18; float t42 = P[3][6]*t24; float t81 = P[6][6]*t11; float t82 = P[2][6]*t21; float t43 = t38+t39+t40+t41+t42-t81-t82; float t44 = P[4][0]*t9; float t45 = P[5][0]*t4; float t46 = P[1][0]*t18; float t47 = P[3][0]*t24; float t84 = P[6][0]*t11; float t85 = P[2][0]*t21; float t48 = t29+t44+t45+t46+t47-t84-t85; float t49 = t14*t48; float t50 = P[4][1]*t9; float t51 = P[5][1]*t4; float t52 = P[0][1]*t14; float t53 = P[3][1]*t24; float t86 = P[6][1]*t11; float t87 = P[2][1]*t21; float t54 = t30+t50+t51+t52+t53-t86-t87; float t55 = t18*t54; float t56 = P[4][2]*t9; float t57 = P[5][2]*t4; float t58 = P[0][2]*t14; float t59 = P[1][2]*t18; float t60 = P[3][2]*t24; float t78 = P[2][2]*t21; float t88 = P[6][2]*t11; float t61 = t56+t57+t58+t59+t60-t78-t88; float t62 = P[4][3]*t9; float t63 = P[5][3]*t4; float t64 = P[0][3]*t14; float t65 = P[1][3]*t18; float t66 = P[3][3]*t24; float t90 = P[6][3]*t11; float t91 = P[2][3]*t21; float t67 = t62+t63+t64+t65+t66-t90-t91; float t68 = t24*t67; float t69 = P[4][4]*t9; float t70 = P[5][4]*t4; float t71 = P[0][4]*t14; float t72 = P[1][4]*t18; float t73 = P[3][4]*t24; float t92 = P[6][4]*t11; float t93 = P[2][4]*t21; float t74 = t69+t70+t71+t72+t73-t92-t93; float t75 = t9*t74; float t83 = t11*t43; float t89 = t21*t61; float t76 = R_VEL+t37+t49+t55+t68+t75-t83-t89; float t77 = 1.0f/t76; Kfusion[0] = t77*(t29+P[0][5]*t4+P[0][4]*t9-P[0][6]*t11+P[0][1]*t18-P[0][2]*t21+P[0][3]*t24); Kfusion[1] = t77*(t30+P[1][5]*t4+P[1][4]*t9+P[1][0]*t14-P[1][6]*t11-P[1][2]*t21+P[1][3]*t24); Kfusion[2] = t77*(-t78+P[2][5]*t4+P[2][4]*t9+P[2][0]*t14-P[2][6]*t11+P[2][1]*t18+P[2][3]*t24); Kfusion[3] = t77*(t66+P[3][5]*t4+P[3][4]*t9+P[3][0]*t14-P[3][6]*t11+P[3][1]*t18-P[3][2]*t21); Kfusion[4] = t77*(t69+P[4][5]*t4+P[4][0]*t14-P[4][6]*t11+P[4][1]*t18-P[4][2]*t21+P[4][3]*t24); Kfusion[5] = t77*(t32+P[5][4]*t9+P[5][0]*t14-P[5][6]*t11+P[5][1]*t18-P[5][2]*t21+P[5][3]*t24); Kfusion[6] = t77*(-t81+P[6][5]*t4+P[6][4]*t9+P[6][0]*t14+P[6][1]*t18-P[6][2]*t21+P[6][3]*t24); Kfusion[7] = t77*(P[7][5]*t4+P[7][4]*t9+P[7][0]*t14-P[7][6]*t11+P[7][1]*t18-P[7][2]*t21+P[7][3]*t24); Kfusion[8] = t77*(P[8][5]*t4+P[8][4]*t9+P[8][0]*t14-P[8][6]*t11+P[8][1]*t18-P[8][2]*t21+P[8][3]*t24); Kfusion[9] = t77*(P[9][5]*t4+P[9][4]*t9+P[9][0]*t14-P[9][6]*t11+P[9][1]*t18-P[9][2]*t21+P[9][3]*t24); Kfusion[10] = t77*(P[10][5]*t4+P[10][4]*t9+P[10][0]*t14-P[10][6]*t11+P[10][1]*t18-P[10][2]*t21+P[10][3]*t24); Kfusion[11] = t77*(P[11][5]*t4+P[11][4]*t9+P[11][0]*t14-P[11][6]*t11+P[11][1]*t18-P[11][2]*t21+P[11][3]*t24); Kfusion[12] = t77*(P[12][5]*t4+P[12][4]*t9+P[12][0]*t14-P[12][6]*t11+P[12][1]*t18-P[12][2]*t21+P[12][3]*t24); Kfusion[13] = t77*(P[13][5]*t4+P[13][4]*t9+P[13][0]*t14-P[13][6]*t11+P[13][1]*t18-P[13][2]*t21+P[13][3]*t24); Kfusion[14] = t77*(P[14][5]*t4+P[14][4]*t9+P[14][0]*t14-P[14][6]*t11+P[14][1]*t18-P[14][2]*t21+P[14][3]*t24); Kfusion[15] = t77*(P[15][5]*t4+P[15][4]*t9+P[15][0]*t14-P[15][6]*t11+P[15][1]*t18-P[15][2]*t21+P[15][3]*t24); Kfusion[16] = t77*(P[16][5]*t4+P[16][4]*t9+P[16][0]*t14-P[16][6]*t11+P[16][1]*t18-P[16][2]*t21+P[16][3]*t24); Kfusion[17] = t77*(P[17][5]*t4+P[17][4]*t9+P[17][0]*t14-P[17][6]*t11+P[17][1]*t18-P[17][2]*t21+P[17][3]*t24); Kfusion[18] = t77*(P[18][5]*t4+P[18][4]*t9+P[18][0]*t14-P[18][6]*t11+P[18][1]*t18-P[18][2]*t21+P[18][3]*t24); Kfusion[19] = t77*(P[19][5]*t4+P[19][4]*t9+P[19][0]*t14-P[19][6]*t11+P[19][1]*t18-P[19][2]*t21+P[19][3]*t24); Kfusion[20] = t77*(P[20][5]*t4+P[20][4]*t9+P[20][0]*t14-P[20][6]*t11+P[20][1]*t18-P[20][2]*t21+P[20][3]*t24); Kfusion[21] = t77*(P[21][5]*t4+P[21][4]*t9+P[21][0]*t14-P[21][6]*t11+P[21][1]*t18-P[21][2]*t21+P[21][3]*t24); Kfusion[22] = t77*(P[22][5]*t4+P[22][4]*t9+P[22][0]*t14-P[22][6]*t11+P[22][1]*t18-P[22][2]*t21+P[22][3]*t24); Kfusion[23] = t77*(P[23][5]*t4+P[23][4]*t9+P[23][0]*t14-P[23][6]*t11+P[23][1]*t18-P[23][2]*t21+P[23][3]*t24);
41.34188
109
0.563572
b088e3d6ca12d2d57e5fea723a2db90996f8cf08
474
py
Python
packages/micropython-official/v1.9.4/esp32/stubs/micropython.py
TheVinhLuong102/micropy-stubs
55ff1773008f7c4dfc3d70a403986486226eb6b3
[ "MIT" ]
18
2019-07-11T13:31:09.000Z
2022-01-27T06:38:40.000Z
packages/micropython-official/v1.9.4/esp32/stubs/micropython.py
TheVinhLuong102/micropy-stubs
55ff1773008f7c4dfc3d70a403986486226eb6b3
[ "MIT" ]
9
2019-09-01T21:44:49.000Z
2022-02-04T20:55:08.000Z
packages/micropython-official/v1.9.4/esp32/stubs/micropython.py
TheVinhLuong102/micropy-stubs
55ff1773008f7c4dfc3d70a403986486226eb6b3
[ "MIT" ]
6
2019-10-08T05:31:21.000Z
2021-04-22T10:21:01.000Z
""" Module: 'micropython' on esp32 1.9.4 """ # MCU: (sysname='esp32', nodename='esp32', release='1.9.4', version='v1.9.4 on 2018-05-11', machine='ESP32 module with ESP32') # Stubber: 1.2.0 def alloc_emergency_exception_buf(): pass def const(): pass def heap_lock(): pass def heap_unlock(): pass def kbd_intr(): pass def mem_info(): pass def opt_level(): pass def qstr_info(): pass def schedule(): pass def stack_use(): pass
13.166667
126
0.628692
ef6ed6be85b069f442e80b2eef3b56915187e77c
1,754
h
C
include/drivers/nxp/dcfg/scfg.h
Nuvoton-Israel/arm-trusted-firmware
469101d48a1b0cb6c93ea5fe3bd3b32b46bd047e
[ "MIT" ]
1,408
2015-01-26T17:15:15.000Z
2022-03-31T12:54:11.000Z
include/drivers/nxp/dcfg/scfg.h
Nuvoton-Israel/arm-trusted-firmware
469101d48a1b0cb6c93ea5fe3bd3b32b46bd047e
[ "MIT" ]
1,177
2015-01-07T12:55:46.000Z
2022-01-19T10:49:12.000Z
include/drivers/nxp/dcfg/scfg.h
Nuvoton-Israel/arm-trusted-firmware
469101d48a1b0cb6c93ea5fe3bd3b32b46bd047e
[ "MIT" ]
959
2015-01-08T09:12:45.000Z
2022-03-28T03:07:50.000Z
/* * Copyright 2020-2021 NXP * * SPDX-License-Identifier: BSD-3-Clause * */ #ifndef SCFG_H #define SCFG_H #ifdef CONFIG_CHASSIS_2 /* SCFG register offsets */ #define SCFG_CORE0_SFT_RST_OFFSET 0x0130 #define SCFG_SNPCNFGCR_OFFSET 0x01A4 #define SCFG_CORESRENCR_OFFSET 0x0204 #define SCFG_RVBAR0_0_OFFSET 0x0220 #define SCFG_RVBAR0_1_OFFSET 0x0224 #define SCFG_COREBCR_OFFSET 0x0680 #define SCFG_RETREQCR_OFFSET 0x0424 #define SCFG_COREPMCR_OFFSET 0x042C #define COREPMCR_WFIL2 0x1 #define SCFG_GIC400_ADDR_ALIGN_OFFSET 0x0188 #define SCFG_BOOTLOCPTRH_OFFSET 0x0600 #define SCFG_BOOTLOCPTRL_OFFSET 0x0604 #define SCFG_SCRATCHRW2_OFFSET 0x0608 #define SCFG_SCRATCHRW3_OFFSET 0x060C /* SCFG bit fields */ #define SCFG_SNPCNFGCR_SECRDSNP 0x80000000 #define SCFG_SNPCNFGCR_SECWRSNP 0x40000000 #endif /* CONFIG_CHASSIS_2 */ #ifndef __ASSEMBLER__ #include <endian.h> #include <lib/mmio.h> #ifdef NXP_SCFG_BE #define scfg_in32(a) bswap32(mmio_read_32((uintptr_t)(a))) #define scfg_out32(a, v) mmio_write_32((uintptr_t)(a), bswap32(v)) #define scfg_setbits32(a, v) mmio_setbits_32((uintptr_t)(a), v) #define scfg_clrbits32(a, v) mmio_clrbits_32((uintptr_t)(a), v) #define scfg_clrsetbits32(a, clear, set) \ mmio_clrsetbits_32((uintptr_t)(a), clear, set) #elif defined(NXP_SCFG_LE) #define scfg_in32(a) mmio_read_32((uintptr_t)(a)) #define scfg_out32(a, v) mmio_write_32((uintptr_t)(a), v) #define scfg_setbits32(a, v) mmio_setbits_32((uintptr_t)(a), v) #define scfg_clrbits32(a, v) mmio_clrbits_32((uintptr_t)(a), v) #define scfg_clrsetbits32(a, clear, set) \ mmio_clrsetbits_32((uintptr_t)(a), clear, set) #else #error Please define CCSR SCFG register endianness #endif #endif /* __ASSEMBLER__ */ #endif /* SCFG_H */
29.233333
66
0.775941
f4d174b6239f0f8bda8343cd1e4c3fdc2707cccd
865
ts
TypeScript
src/general/general.class.ts
HitSystems/sanPedro
5ae80bdbcc44f13e721d8dd766afca995bc59f3d
[ "MIT" ]
null
null
null
src/general/general.class.ts
HitSystems/sanPedro
5ae80bdbcc44f13e721d8dd766afca995bc59f3d
[ "MIT" ]
null
null
null
src/general/general.class.ts
HitSystems/sanPedro
5ae80bdbcc44f13e721d8dd766afca995bc59f3d
[ "MIT" ]
null
null
null
import { IResult } from 'mssql'; import { recHit } from '../conexion/mssql'; export class General { /* Transforma el codigo de licencia en el codigo de tienda. Normalmente es el mismo, pero por si acaso lo comprueba en ParamsHw */ getCodigoTiendaFromLicencia(database: string, licencia: number): Promise<boolean|number> { return recHit(database, `SELECT Valor1 as codigoCliente FROM ParamsHw WHERE Codi = ${licencia}`).then((res: IResult<any>) => { if(res) { if (res.recordset.length > 0) { return res.recordset[0].codigoCliente; } else { return false } } return false; }).catch((err) => { console.log(err); return false; }); } } export const generalInstance = new General();
36.041667
134
0.566474
440f39c8c7a7476c6895bf8540ec7700963c4bb4
1,701
py
Python
remove_worms.py
AbigailMcGovern/platelet-segmentation
46cd87b81fc44473b07a2bebed1e6134b2582348
[ "BSD-3-Clause" ]
1
2022-02-01T23:40:38.000Z
2022-02-01T23:40:38.000Z
remove_worms.py
AbigailMcGovern/platelet-segmentation
46cd87b81fc44473b07a2bebed1e6134b2582348
[ "BSD-3-Clause" ]
3
2021-03-12T02:03:15.000Z
2021-03-31T00:39:05.000Z
remove_worms.py
AbigailMcGovern/platelet-segmentation
46cd87b81fc44473b07a2bebed1e6134b2582348
[ "BSD-3-Clause" ]
1
2021-04-06T23:23:32.000Z
2021-04-06T23:23:32.000Z
# script to remove worms import numpy as np from scipy.ndimage.measurements import label from skimage.measure import regionprops_table import zarr import os from pathlib import Path from segmentation_pipeline import add_elongation import pandas as pd def get_labs_less_than(df, lab_col='label', cond_col='elongation', val=0.9): df = df[(df[cond_col] < val)] labs = df[lab_col].values return labs def only_include_labels(labels, ids): new = np.zeros_like(labels) new = new.ravel() for i, elem in enumerate(labels.ravel()): if elem in labs: # numpy where doesnt like this kind of condition unfortunately new[i] = elem new = new.reshape(labels.shape) return new def get_files(dirs, ends='.zarr'): files = [] for d in dirs: for sub in os.walk(d): if ends.endswith('.zarr'): if sub[0].endswith(ends): files.append(sub[0]) for fl in sub[2]: f = os.path.join(sub[0], fl) if f.endswith(ends): files.append(f) return files dirs = ['/home/abigail/data/plateseg-training/training_gt/Volga', '/home/abigail/data/plateseg-training/training_gt/Pia'] files = get_files(dirs, ends='_labels.zarr') props = ('label', 'centroid', 'inertia_tensor_eigvals') for f in files: labels = zarr.open(f) labels = np.array(labels) df = regionprops_table(labels, properties=props) df = pd.DataFrame(df) df = add_elongation(df) labs = get_labs_less_than(df) new = only_include_labels(labels, labs) p = Path(f) new_path = os.path.join(p.parents[0], p.stem + '_no-worms.zarr') zarr.save(new_path, new)
29.842105
121
0.646091
7ab61e4b2a91504bafded1c37b1116e72cf167f2
7,030
cs
C#
osu!stream/GameplayElements/Scoring/Score.cs
DJPopsicle/osu-stream
7dfa5bc238f0e3b88f8b076707d268a77355554e
[ "MIT" ]
146
2019-05-03T06:40:27.000Z
2022-03-26T22:57:24.000Z
osu!stream/GameplayElements/Scoring/Score.cs
DJPopsicle/osu-stream
7dfa5bc238f0e3b88f8b076707d268a77355554e
[ "MIT" ]
36
2019-05-03T08:08:24.000Z
2022-01-29T11:20:26.000Z
osu!stream/GameplayElements/Scoring/Score.cs
DJPopsicle/osu-stream
7dfa5bc238f0e3b88f8b076707d268a77355554e
[ "MIT" ]
43
2019-05-27T13:27:24.000Z
2022-02-08T13:22:54.000Z
using System; using osum.Graphics; using osum.Helpers; namespace osum.GameplayElements.Scoring { public class Score : bSerializable { public string Username; public int Id; public ushort count100; public ushort count300; public ushort count50; public ushort countMiss; public DateTime date; public ushort maxCombo; public int spinnerBonusScore; public int hitOffsetMilliseconds; public int hitOffsetCount; public int comboBonusScore; public int accuracyBonusScore { get { if (!UseAccuracyBonus) return 0; return (int)Math.Round(Math.Max(0, accuracy - 0.60) / 0.4 * ACCURACY_BONUS_AMOUNT); } } public int hitScore; public bool UseAccuracyBonus = true; public int totalScore => spinnerBonusScore + hitScore + comboBonusScore + accuracyBonusScore; public const int ACCURACY_BONUS_AMOUNT = 400000; public const int HIT_PLUS_COMBO_BONUS_AMOUNT = MAX_SCORE - ACCURACY_BONUS_AMOUNT; public const int MAX_SCORE = 1000000; public bool guest; public int OnlineRank; private Rank ranking; public Rank Ranking { get { if (ranking == Rank.N) { float acc = accuracy; if (acc == 1) ranking = Rank.SS; else if (acc > 0.9f) ranking = Rank.S; else if (acc > 0.8f) ranking = Rank.A; else if (acc > 0.7f) ranking = Rank.B; else if (acc > 0.6f) ranking = Rank.C; else if (totalScore > 0) ranking = Rank.D; } return ranking; } set => ranking = value; } public pTexture RankingTexture { get { pTexture rankLetter = null; switch (Ranking) { case Rank.SS: rankLetter = TextureManager.Load(OsuTexture.rank_x); break; case Rank.S: rankLetter = TextureManager.Load(OsuTexture.rank_s); break; case Rank.A: rankLetter = TextureManager.Load(OsuTexture.rank_a); break; case Rank.B: rankLetter = TextureManager.Load(OsuTexture.rank_b); break; case Rank.C: rankLetter = TextureManager.Load(OsuTexture.rank_c); break; case Rank.D: rankLetter = TextureManager.Load(OsuTexture.rank_d); break; } return rankLetter; } } public pTexture RankingTextureSmall { get { pTexture rankLetter = null; switch (Ranking) { case Rank.SS: rankLetter = TextureManager.Load(OsuTexture.rank_x_small); break; case Rank.S: rankLetter = TextureManager.Load(OsuTexture.rank_s_small); break; case Rank.A: rankLetter = TextureManager.Load(OsuTexture.rank_a_small); break; case Rank.B: rankLetter = TextureManager.Load(OsuTexture.rank_b_small); break; case Rank.C: rankLetter = TextureManager.Load(OsuTexture.rank_c_small); break; case Rank.D: rankLetter = TextureManager.Load(OsuTexture.rank_d_small); break; } return rankLetter; } } public pTexture RankingTextureTiny { get { pTexture rankLetter = null; switch (Ranking) { case Rank.SS: rankLetter = TextureManager.Load(OsuTexture.rank_x_tiny); break; case Rank.S: rankLetter = TextureManager.Load(OsuTexture.rank_s_tiny); break; case Rank.A: rankLetter = TextureManager.Load(OsuTexture.rank_a_tiny); break; case Rank.B: rankLetter = TextureManager.Load(OsuTexture.rank_b_tiny); break; case Rank.C: rankLetter = TextureManager.Load(OsuTexture.rank_c_tiny); break; case Rank.D: rankLetter = TextureManager.Load(OsuTexture.rank_d_tiny); break; } return rankLetter; } } internal virtual float accuracy => totalHits > 0 ? (float)(count50 * 1 + count100 * 2 + count300 * 4) / (totalHits * 4) : 0; internal virtual int totalHits => count50 + count100 + count300 + countMiss; internal virtual int totalSuccessfulHits => count50 + count100 + count300; #region bSerializable implementation public void ReadFromStream(SerializationReader sr) { count300 = sr.ReadUInt16(); count100 = sr.ReadUInt16(); count50 = sr.ReadUInt16(); countMiss = sr.ReadUInt16(); //date = sr.ReadDateTime(); maxCombo = sr.ReadUInt16(); spinnerBonusScore = sr.ReadInt32(); comboBonusScore = sr.ReadInt32(); hitScore = sr.ReadInt32(); if (BeatmapDatabase.Version > 9) ranking = (Rank)sr.ReadInt32(); } public void WriteToStream(SerializationWriter sw) { sw.Write(count300); sw.Write(count100); sw.Write(count50); sw.Write(countMiss); sw.Write(maxCombo); sw.Write(spinnerBonusScore); sw.Write(comboBonusScore); sw.Write(hitScore); sw.Write((int)Ranking); } #endregion } public enum Rank { N, D, C, B, A, S, SS } }
32.396313
133
0.444808
7c06f6e657e0027ffe8670a8e1b8e1eeb88b15c4
2,988
py
Python
tools/cmakeformat.py
TaoweiZhang/MegEngine
bd3c4a05274f69dacca6097d8cbadbb34c7cc2e4
[ "Apache-2.0" ]
1
2022-03-21T03:13:45.000Z
2022-03-21T03:13:45.000Z
tools/cmakeformat.py
TaoweiZhang/MegEngine
bd3c4a05274f69dacca6097d8cbadbb34c7cc2e4
[ "Apache-2.0" ]
null
null
null
tools/cmakeformat.py
TaoweiZhang/MegEngine
bd3c4a05274f69dacca6097d8cbadbb34c7cc2e4
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # MegEngine is Licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import argparse import os import subprocess from pathlib import Path CMAKE_FILS_DIRS = [ "test", "dnn", "tools", "sdk", "src", "imperative", "lite", "cmake", "toolchains", ] def main(): os.chdir(str(Path(__file__).resolve().parent.parent)) parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter) parser.add_argument("--check", action="store_true", help="check model") parser.add_argument( "--cmake_files", nargs="+", default=None, dest="cmake_files", help="cmake files to format, please split with space", ) args = parser.parse_args() handle_files = [] if args.cmake_files: handle_files = args.cmake_files for cmake_file in handle_files: assert os.path.isfile( cmake_file ), "error input --cmake_files, can not find file: {}".format(cmake_file) else: handle_files.append("CMakeLists.txt") for cmake_file_dir in CMAKE_FILS_DIRS: assert os.path.isdir( cmake_file_dir ), "{} is not a directory, may config error for CMAKE_FILS_DIRS".format( cmake_file_dir ) for cmake_file in [ os.path.join(root, file) for root, dirs, files in os.walk(cmake_file_dir) for file in files if file.endswith("CMakeLists.txt") or file.endswith(".cmake") ]: print("find cmake_file: {}".format(cmake_file)) assert os.path.isfile(cmake_file), "code issue happened!!" handle_files.append(cmake_file) for cmake_file in handle_files: handle_type = ["format", "--in-place"] if args.check: handle_type = ["check", "--check"] cmd = "cmake-format -c tools/cmake_format_config.json {} {}".format( handle_type[1], cmake_file ) print("try {}: {} with command: {}".format(handle_type[0], cmake_file, cmd)) try: subprocess.check_call(cmd, shell=True) except Exception as exc: print("run cmd {} failed".format(cmd)) if args.check: print( 'please run: "python3 tools/cmakeformat.py" to format cmake files' ) else: print("code issue happened!!, please FIXME!!") raise exc if __name__ == "__main__": subprocess.check_call("python3 -m pip install cmakelang==0.6.13 --user", shell=True) main()
32.835165
88
0.590027
4cf64b7b4fad45afa67724748c2d35bf98eb3d5c
231
py
Python
htsinfer/infer_read_orientation.py
dcpb0/htsinfer
426f34186917020815298999bd93ea23229d9d1b
[ "Apache-2.0" ]
null
null
null
htsinfer/infer_read_orientation.py
dcpb0/htsinfer
426f34186917020815298999bd93ea23229d9d1b
[ "Apache-2.0" ]
null
null
null
htsinfer/infer_read_orientation.py
dcpb0/htsinfer
426f34186917020815298999bd93ea23229d9d1b
[ "Apache-2.0" ]
null
null
null
"""Infer read orientation from sample data.""" def infer(): """Main function coordinating the execution of all other functions. Should be imported/called from main app and return results to it. """ # implement me
25.666667
71
0.69697
4b5291e14bb7f110080ed9c1ea979456375028cf
917
dart
Dart
lib/flutter_status_bar.dart
reimibeta/flutter_status_bar
120385c64662cdefe78b1e09faf90172e4d61f6b
[ "MIT" ]
null
null
null
lib/flutter_status_bar.dart
reimibeta/flutter_status_bar
120385c64662cdefe78b1e09faf90172e4d61f6b
[ "MIT" ]
null
null
null
lib/flutter_status_bar.dart
reimibeta/flutter_status_bar
120385c64662cdefe78b1e09faf90172e4d61f6b
[ "MIT" ]
null
null
null
library flutter_status_bar; import 'package:flutter/material.dart'; import 'dart:io' show Platform; export 'src/flutter_status_bar_color.dart' show FlutterStatusBarColor; class FlutterStatusBar extends StatelessWidget { final Color color; final Color androidColor; final Widget child; final bool top; FlutterStatusBar({Key key, this.color, this.child, this.top, this.androidColor}):super(key: key); @override Widget build(BuildContext context) { var color = this.color == null ? Colors.white : this.color; if(Platform.isAndroid){ if(androidColor == null){ color = Colors.grey; } else { color = androidColor; } } var child = this.child == null ? Container() : this.child; var top = this.top == null ? true : this.top; return Container( color: color, child: SafeArea( child: child, top: top, ), );; } }
25.472222
99
0.652126
e44e60d03a5d08cf73cdccf9044fc73b4e316ef0
823
hpp
C++
src/util/log.hpp
larsrh/associative
5e8a6c5d03e4726e85c8835df5d7458dff00f95a
[ "Apache-2.0" ]
null
null
null
src/util/log.hpp
larsrh/associative
5e8a6c5d03e4726e85c8835df5d7458dff00f95a
[ "Apache-2.0" ]
null
null
null
src/util/log.hpp
larsrh/associative
5e8a6c5d03e4726e85c8835df5d7458dff00f95a
[ "Apache-2.0" ]
null
null
null
#ifndef ASSOCIATIVE_LOG_HPP #define ASSOCIATIVE_LOG_HPP #include <log4cpp/Appender.hh> #include <log4cpp/Layout.hh> #include <log4cpp/Category.hh> #include <log4cpp/Priority.hh> #include "util.hpp" #define TRACE(LOGGER, MSG) \ LOGGER->debug() << __FILE__ << ":" << __LINE__ << " " << (MSG); namespace associative { class Logger { private: log4cpp::Appender* const appender; log4cpp::Layout* const layout; log4cpp::Category& category; public: typedef log4cpp::Priority Priority; typedef log4cpp::Priority::PriorityLevel PriorityLevel; Logger(const fs::path& file); ~Logger(); log4cpp::CategoryStream log(const PriorityLevel& level); log4cpp::CategoryStream error(); log4cpp::CategoryStream warn(); log4cpp::CategoryStream info(); log4cpp::CategoryStream debug(); }; } #endif
20.073171
64
0.712029
e96351af9621f0ea1e1130b8a1daf088f3b3aaf3
222
css
CSS
src/components/atoms/Hero/Hero.css
jamesslock/simpleasmilk
ce3b4e4dc8895df8607f7ae7c09c3389b5cf5a10
[ "BSD-3-Clause" ]
null
null
null
src/components/atoms/Hero/Hero.css
jamesslock/simpleasmilk
ce3b4e4dc8895df8607f7ae7c09c3389b5cf5a10
[ "BSD-3-Clause" ]
null
null
null
src/components/atoms/Hero/Hero.css
jamesslock/simpleasmilk
ce3b4e4dc8895df8607f7ae7c09c3389b5cf5a10
[ "BSD-3-Clause" ]
null
null
null
.root { position: relative; } .large { min-height: 640px; } .huge { min-height: 780px; } .full { height: 100vh; } .image { background-size: cover; } .primary { background-color: #eb3552; }
11.1
31
0.558559
b7a5efbecdf08718353f630eb1480152c12465a4
3,103
cpp
C++
src/SystemState.cpp
zhouyu1989/system_state
2f2e5a27b5d89ccfa0e45e35e2c55d9d5f496710
[ "Apache-2.0" ]
null
null
null
src/SystemState.cpp
zhouyu1989/system_state
2f2e5a27b5d89ccfa0e45e35e2c55d9d5f496710
[ "Apache-2.0" ]
null
null
null
src/SystemState.cpp
zhouyu1989/system_state
2f2e5a27b5d89ccfa0e45e35e2c55d9d5f496710
[ "Apache-2.0" ]
null
null
null
/************************************************************** * Copyright (c) 2018-2020,Hangzhou Rokid Tech. Co., Ltd. * All rights reserved. * * FileName: SystemState.cpp * Description: Gets information about the device's CPU, memory, and so on * * Date : 2018.09.18 * Author: zhouyu * Modification: add file * **************************************************************/ #include <iostream> #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include "SystemStatus.h" using namespace std; using namespace ROKID_SYSTEM; /******************************************************* * Function name :CSystemState * Description: econstructor function * Parameter: * @ * Return :0 success, other fail **********************************************************/ CSystemState::CSystemState() : m_fCpuUsage(0), m_u64MemUsed(0), m_u64MenUnused(0), m_u64FlashUsed(0), m_u64FlashUnused(0), m_fFlashUsage(0), m_nNetStatus(0) { } /******************************************************* * Function name :~CSystemState * Description: destructor function * Parameter: * @ * Return :0 success, other fail **********************************************************/ CSystemState::~CSystemState() { } /******************************************************* * Function name :CpuState * Description: Capture CPU utilization * Parameter: * @fCpuUsed :CPU usage * Return :0 success, other fail **********************************************************/ int CSystemState::CpuState(float &fCpuUsed) { int ret=0; ret=m_cSysinfo.GetCPUinfo(fCpuUsed); if(ret < 0) { return -1; } return 0; } /******************************************************* * Function name :Memorystate * Description: Get memory status * Parameter: * @fMemUsed :memory usage * @u64Used :Used size * @u64Unused :unUsed size * Return :0 success, other fail **********************************************************/ int CSystemState::Memorystate(float &fMemUsed, uint64_t &u64Used, uint64_t &u64Unused) { int ret=0; ret=m_cSysinfo.GetMeninfo(fMemUsed, u64Used, u64Unused); if(ret < 0) { return -1; } return 0; } /******************************************************* * Function name :FlashState * Description: Get Flash status * Parameter: * @fFlashUsed :Flash usage * @u64Used :Used size * @u64Unused :unUsed size * Return :0 success, other fail **********************************************************/ int CSystemState::FlashState(float &fFlashUsed, float &u64Used, float &u64Unused) { int ret=0; ret=m_cSysinfo.GetFlashinfo(fFlashUsed, u64Used, u64Unused); if(ret < 0) { return -1; } return 0; } /******************************************************* * Function name :NetState * Description: Get network status * Parameter: * @nNetstate :network status :network disconnect -1, Normal network 0, weak network 1 * Return :0 success, other fail **********************************************************/ int CSystemState::NetState(int &nNetstate) { int ret=0; ret=m_cSysinfo.GetNetinfo(nNetstate); if(ret < 0) { return -1; } return 0; }
23.330827
87
0.518208
3efea6a58701aba330c61a84ca5d58114d0419ea
684
js
JavaScript
lib/units/force/Imperial.js
Eldelshell/flowsnake
a5a3beca473e0c036e0c4caa5b28221cbf9122ed
[ "MIT" ]
1
2019-05-07T12:47:48.000Z
2019-05-07T12:47:48.000Z
lib/units/force/Imperial.js
Eldelshell/flowsnake
a5a3beca473e0c036e0c4caa5b28221cbf9122ed
[ "MIT" ]
9
2018-01-26T09:17:39.000Z
2018-02-08T13:51:38.000Z
lib/units/force/Imperial.js
Eldelshell/flowsnake
a5a3beca473e0c036e0c4caa5b28221cbf9122ed
[ "MIT" ]
null
null
null
import Unit from '../Unit'; import System from '../System'; const TYPE = 'Force'; const Imperial = new System('Imperial', { Metric: 4.4482, Gravitational: 453.6 }); const ForceImperial = { PoundForce: new Unit({ id: 'lbf', name: 'PoundForce', type: TYPE, system: Imperial, converter: 1 }), OunceForce: new Unit({ id: 'ozf', name: 'OunceForce', type: TYPE, system: Imperial, converter: 1/16 }), Poundal: new Unit({ id: 'pdl', name: 'Poundal', type: TYPE, system: Imperial, converter: 1/32.174 }) }; export default ForceImperial;
19
41
0.527778
1a66076c9f9aa1dab83bcde12b5c2539d8163772
9,255
py
Python
Main_Execute.py
industrial-optimization-group/offline_data_driven_moea
4e454694f444ff44f86da24dc33672eb23561bfa
[ "MIT" ]
1
2022-03-30T17:24:55.000Z
2022-03-30T17:24:55.000Z
Main_Execute.py
industrial-optimization-group/offline_data_driven_moea
4e454694f444ff44f86da24dc33672eb23561bfa
[ "MIT" ]
null
null
null
Main_Execute.py
industrial-optimization-group/offline_data_driven_moea
4e454694f444ff44f86da24dc33672eb23561bfa
[ "MIT" ]
null
null
null
from desdeo_problem.Problem import DataProblem from desdeo_problem.surrogatemodels.SurrogateModels import GaussianProcessRegressor from desdeo_problem.surrogatemodels.SurrogateKriging import SurrogateKriging from desdeo_problem.testproblems.TestProblems import test_problem_builder from pyDOE import lhs import plotly.graph_objects as go import matplotlib.pyplot as plt import numpy as np import pandas as pd from desdeo_emo.EAs.ProbRVEA import RVEA from desdeo_emo.EAs.ProbRVEA import ProbRVEA from desdeo_emo.EAs.ProbRVEA import ProbRVEA_v3 from desdeo_emo.EAs.ProbRVEA import HybRVEA from desdeo_emo.EAs.ProbRVEA import HybRVEA_v3 from desdeo_emo.EAs.ProbMOEAD import MOEA_D, ProbMOEAD_TCH, ProbMOEAD_WS from desdeo_emo.EAs.ProbMOEAD import ProbMOEAD from desdeo_emo.EAs.ProbMOEAD import ProbMOEAD_v3 from desdeo_emo.EAs.ProbMOEAD import HybMOEAD from desdeo_emo.EAs.ProbMOEAD import HybMOEAD_v3 #from pygmo import non_dominated_front_2d as nd2 #from non_domx import ndx import scipy.io from sklearn.neighbors import NearestNeighbors import time gen_per_iter_set = 10 max_func_evals = 40000 nsamples = 109 def build_surrogates(problem_testbench, problem_name, nobjs, nvars, is_data, x_data, y_data): x_names = [f'x{i}' for i in range(1,nvars+1)] y_names = [f'f{i}' for i in range(1,nobjs+1)] row_names = ['lower_bound','upper_bound'] if is_data is False: prob = test_problem_builder(problem_name, nvars, nobjs) x = lhs(nvars, nsamples) y = prob.evaluate(x) data = pd.DataFrame(np.hstack((x,y.objectives)), columns=x_names+y_names) else: data = pd.DataFrame(np.hstack((x_data,y_data)), columns=x_names+y_names) if problem_testbench == 'DDMOPP': x_low = np.ones(nvars)*-1 x_high = np.ones(nvars) elif problem_testbench == 'DTLZ': x_low = np.ones(nvars)*0 x_high = np.ones(nvars) bounds = pd.DataFrame(np.vstack((x_low,x_high)), columns=x_names, index=row_names) problem = DataProblem(data=data, variable_names=x_names, objective_names=y_names,bounds=bounds) start = time.time() problem.train(SurrogateKriging) end = time.time() time_taken = end - start return problem, time_taken def read_dataset(problem_testbench, folder_data, problem_name, nobjs, nvars, sampling, run): if problem_testbench == "DDMOPP": mat = scipy.io.loadmat(folder_data + '/Initial_Population_' + problem_testbench + '_' + sampling + '_AM_' + str(nvars) + '_109.mat') x = ((mat['Initial_Population_'+problem_testbench])[0][run])[0] mat = scipy.io.loadmat(folder_data+'/Obj_vals_DDMOPP_'+sampling+'_AM_'+problem_name+'_' + str(nobjs) + '_' + str(nvars) + '_109.mat') y = ((mat['Obj_vals_DDMOPP'])[0][run])[0] else: mat = scipy.io.loadmat(folder_data + '/Initial_Population_DTLZ_'+sampling+'_AM_' + str(nvars) + '_109.mat') prob = test_problem_builder( name=problem_name, n_of_objectives=nobjs, n_of_variables=nvars ) x = ((mat['Initial_Population_DTLZ'])[0][run])[0] y = prob.evaluate(x)[0] return x, y def optimize_surrogates_1(problem,x): print("Optimizing...") evolver_opt = RVEA(problem, use_surrogates=True, n_gen_per_iter=gen_per_iter_set, total_function_evaluations=max_func_evals) #, population_params={'design':'InitSamples','init_pop':x}, population_size=109) while evolver_opt.continue_evolution(): evolver_opt.iterate() print("FE count:",evolver_opt._function_evaluation_count) #front_true = evolver_opt.population.objectives #evolver_opt.population. #print(front_true) return evolver_opt.population def optimize_surrogates_7(problem,x): print("Optimizing...") evolver_opt = ProbRVEA(problem, use_surrogates=True, n_gen_per_iter=gen_per_iter_set, total_function_evaluations=max_func_evals) #, population_params={'design':'InitSamples','init_pop':x}, population_size=109) while evolver_opt.continue_evolution(): evolver_opt.iterate() print("FE count:",evolver_opt._function_evaluation_count) #front_true = evolver_opt.population.objectives #evolver_opt.population. #print(front_true) return evolver_opt.population def optimize_surrogates_8(problem,x): print("Optimizing...") evolver_opt = HybRVEA_v3(problem, use_surrogates=True, n_gen_per_iter=gen_per_iter_set, total_function_evaluations=max_func_evals) #, population_params={'design':'InitSamples','init_pop':x}, population_size=109) while evolver_opt.continue_evolution(): evolver_opt.iterate() print("FE count:",evolver_opt._function_evaluation_count) #front_true = evolver_opt.population.objectives #evolver_opt.population. #print(front_true) return evolver_opt.population def optimize_surrogates_12(problem,x): print("Optimizing...") evolver_opt = MOEA_D(problem, use_surrogates=True, n_gen_per_iter=gen_per_iter_set, total_function_evaluations=max_func_evals) #, population_params={'design':'InitSamples','init_pop':x}, population_size=109) while evolver_opt.continue_evolution(): evolver_opt.iterate() print("FE count:",evolver_opt._function_evaluation_count) #front_true = evolver_opt.population.objectives #evolver_opt.population. #print(front_true) return evolver_opt.population def optimize_surrogates_72(problem,x): print("Optimizing...") evolver_opt = ProbMOEAD(problem, use_surrogates=True, n_gen_per_iter=gen_per_iter_set, total_function_evaluations=max_func_evals) #, population_params={'design':'InitSamples','init_pop':x}) #, population_size=109) while evolver_opt.continue_evolution(): evolver_opt.iterate() print("FE count:",evolver_opt._function_evaluation_count) #front_true = evolver_opt.population.objectives #evolver_opt.population. #print(front_true) return evolver_opt.population def optimize_surrogates_722(problem,x): print("Optimizing...") evolver_opt = ProbMOEAD_WS(problem, SF_type='WS',use_surrogates=True, n_gen_per_iter=gen_per_iter_set, total_function_evaluations=max_func_evals) #, population_params={'design':'InitSamples','init_pop':x}) #, population_size=109) while evolver_opt.continue_evolution(): evolver_opt.iterate() print("FE count:",evolver_opt._function_evaluation_count) #front_true = evolver_opt.population.objectives #evolver_opt.population. #print(front_true) return evolver_opt.population def optimize_surrogates_723(problem,x): print("Optimizing...") evolver_opt = ProbMOEAD_TCH(problem, SF_type='TCH',use_surrogates=True, n_gen_per_iter=gen_per_iter_set, total_function_evaluations=max_func_evals) #, population_params={'design':'InitSamples','init_pop':x}) #, population_size=109) while evolver_opt.continue_evolution(): evolver_opt.iterate() print("FE count:",evolver_opt._function_evaluation_count) #front_true = evolver_opt.population.objectives #evolver_opt.population. #print(front_true) return evolver_opt.population def optimize_surrogates_82(problem,x): print("Optimizing...") evolver_opt = HybMOEAD_v3(problem, use_surrogates=True, n_gen_per_iter=gen_per_iter_set, total_function_evaluations=max_func_evals) #, population_params={'design':'InitSamples','init_pop':x}, population_size=109) while evolver_opt.continue_evolution(): evolver_opt.iterate() print("FE count:",evolver_opt._function_evaluation_count) #front_true = evolver_opt.population.objectives #evolver_opt.population. #print(front_true) return evolver_opt.population def run_optimizer(problem_testbench, folder_data, problem_name, nobjs, nvars, sampling, is_data, run, approach): if is_data is True: x, y = read_dataset(problem_testbench, folder_data, problem_name, nobjs, nvars, sampling, run) surrogate_problem, time_taken = build_surrogates(problem_testbench,problem_name, nobjs, nvars, is_data, x, y) print(time_taken) if approach == 1: population = optimize_surrogates_1(surrogate_problem,x) elif approach == 7: population = optimize_surrogates_7(surrogate_problem,x) elif approach == 8: population = optimize_surrogates_8(surrogate_problem,x) elif approach == 12: population = optimize_surrogates_12(surrogate_problem,x) elif approach == 72: population = optimize_surrogates_72(surrogate_problem,x) elif approach == 722: population = optimize_surrogates_722(surrogate_problem,x) elif approach == 723: population = optimize_surrogates_723(surrogate_problem,x) elif approach == 82: population = optimize_surrogates_82(surrogate_problem,x) results_dict = { 'individual_archive': population.individuals_archive, 'objectives_archive': population.objectives_archive, 'uncertainty_archive': population.uncertainty_archive, 'individuals_solutions': population.individuals, 'obj_solutions': population.objectives, 'uncertainty_solutions': population.uncertainity, 'time_taken': time_taken } return results_dict
46.507538
235
0.737223
b1a2bac2b14ef0ed4e2e228a610348edc6969a09
8,261
sql
SQL
schema.sql
TheBeege/mentor-me-api
4b1df998470c87c0dd765416fab4347df06a27ac
[ "MIT" ]
1
2017-03-19T19:50:11.000Z
2017-03-19T19:50:11.000Z
schema.sql
TheBeege/mentor-me-api
4b1df998470c87c0dd765416fab4347df06a27ac
[ "MIT" ]
null
null
null
schema.sql
TheBeege/mentor-me-api
4b1df998470c87c0dd765416fab4347df06a27ac
[ "MIT" ]
null
null
null
-- -- PostgreSQL database dump -- SET statement_timeout = 0; SET client_encoding = 'UTF8'; SET standard_conforming_strings = on; SET check_function_bodies = false; SET client_min_messages = warning; SET search_path = public, pg_catalog; ALTER TABLE ONLY public.mentor_topic DROP CONSTRAINT mentor_topic_user_id; ALTER TABLE ONLY public.mentor_topic DROP CONSTRAINT mentor_topic_topic_id; ALTER TABLE ONLY public.mentor_request DROP CONSTRAINT mentor_request_mentor_id; ALTER TABLE ONLY public.mentor_request DROP CONSTRAINT mentor_request_mentee_id; DROP INDEX public.fki_mentor_request_mentor_id; DROP INDEX public.fki_mentor_request_mentee_id; ALTER TABLE ONLY public."user" DROP CONSTRAINT user_unq_username; ALTER TABLE ONLY public."user" DROP CONSTRAINT user_unq_email; ALTER TABLE ONLY public."user" DROP CONSTRAINT user_pk; ALTER TABLE ONLY public.topic DROP CONSTRAINT topic_unq_name; ALTER TABLE ONLY public.topic DROP CONSTRAINT topic_id; ALTER TABLE ONLY public.mentor_topic DROP CONSTRAINT mentor_topic_id; ALTER TABLE ONLY public.mentor_request DROP CONSTRAINT mentor_request_id; ALTER TABLE public."user" ALTER COLUMN id DROP DEFAULT; ALTER TABLE public.topic ALTER COLUMN id DROP DEFAULT; ALTER TABLE public.mentor_topic ALTER COLUMN mentor_topic_id DROP DEFAULT; ALTER TABLE public.mentor_request ALTER COLUMN mentor_request_id DROP DEFAULT; DROP SEQUENCE public.user_user_id_seq; DROP TABLE public."user"; DROP SEQUENCE public.topic_id_seq; DROP TABLE public.topic; DROP SEQUENCE public.mentor_topic_mentor_topic_id_seq; DROP TABLE public.mentor_topic; DROP SEQUENCE public.mentor_request_mentor_request_id_seq; DROP TABLE public.mentor_request; DROP EXTENSION plpgsql; DROP SCHEMA public; -- -- Name: public; Type: SCHEMA; Schema: -; Owner: - -- CREATE SCHEMA public; -- -- Name: SCHEMA public; Type: COMMENT; Schema: -; Owner: - -- COMMENT ON SCHEMA public IS 'standard public schema'; -- -- Name: plpgsql; Type: EXTENSION; Schema: -; Owner: - -- CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog; -- -- Name: EXTENSION plpgsql; Type: COMMENT; Schema: -; Owner: - -- COMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language'; SET search_path = public, pg_catalog; SET default_tablespace = ''; SET default_with_oids = false; -- -- Name: mentor_request; Type: TABLE; Schema: public; Owner: -; Tablespace: -- CREATE TABLE mentor_request ( mentor_request_id integer NOT NULL, mentor_id integer NOT NULL, mentee_id integer NOT NULL, requested timestamp without time zone NOT NULL, accepted timestamp without time zone, rejected timestamp without time zone ); -- -- Name: mentor_request_mentor_request_id_seq; Type: SEQUENCE; Schema: public; Owner: - -- CREATE SEQUENCE mentor_request_mentor_request_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; -- -- Name: mentor_request_mentor_request_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - -- ALTER SEQUENCE mentor_request_mentor_request_id_seq OWNED BY mentor_request.mentor_request_id; -- -- Name: mentor_topic; Type: TABLE; Schema: public; Owner: -; Tablespace: -- CREATE TABLE mentor_topic ( mentor_topic_id integer NOT NULL, user_id integer NOT NULL, topic_id integer NOT NULL, level integer, description text ); -- -- Name: mentor_topic_mentor_topic_id_seq; Type: SEQUENCE; Schema: public; Owner: - -- CREATE SEQUENCE mentor_topic_mentor_topic_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; -- -- Name: mentor_topic_mentor_topic_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - -- ALTER SEQUENCE mentor_topic_mentor_topic_id_seq OWNED BY mentor_topic.mentor_topic_id; -- -- Name: topic; Type: TABLE; Schema: public; Owner: -; Tablespace: -- CREATE TABLE topic ( id integer NOT NULL, name text NOT NULL ); -- -- Name: topic_id_seq; Type: SEQUENCE; Schema: public; Owner: - -- CREATE SEQUENCE topic_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; -- -- Name: topic_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - -- ALTER SEQUENCE topic_id_seq OWNED BY topic.id; -- -- Name: user; Type: TABLE; Schema: public; Owner: -; Tablespace: -- CREATE TABLE "user" ( id integer NOT NULL, username text, display_name text, email text, created timestamp without time zone DEFAULT now(), last_activity timestamp without time zone DEFAULT now() NOT NULL, password text, description text, icon_url text ); -- -- Name: user_user_id_seq; Type: SEQUENCE; Schema: public; Owner: - -- CREATE SEQUENCE user_user_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; -- -- Name: user_user_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - -- ALTER SEQUENCE user_user_id_seq OWNED BY "user".id; -- -- Name: mentor_request_id; Type: DEFAULT; Schema: public; Owner: - -- ALTER TABLE ONLY mentor_request ALTER COLUMN mentor_request_id SET DEFAULT nextval('mentor_request_mentor_request_id_seq'::regclass); -- -- Name: mentor_topic_id; Type: DEFAULT; Schema: public; Owner: - -- ALTER TABLE ONLY mentor_topic ALTER COLUMN mentor_topic_id SET DEFAULT nextval('mentor_topic_mentor_topic_id_seq'::regclass); -- -- Name: id; Type: DEFAULT; Schema: public; Owner: - -- ALTER TABLE ONLY topic ALTER COLUMN id SET DEFAULT nextval('topic_id_seq'::regclass); -- -- Name: id; Type: DEFAULT; Schema: public; Owner: - -- ALTER TABLE ONLY "user" ALTER COLUMN id SET DEFAULT nextval('user_user_id_seq'::regclass); -- -- Name: mentor_request_id; Type: CONSTRAINT; Schema: public; Owner: -; Tablespace: -- ALTER TABLE ONLY mentor_request ADD CONSTRAINT mentor_request_id PRIMARY KEY (mentor_request_id); -- -- Name: mentor_topic_id; Type: CONSTRAINT; Schema: public; Owner: -; Tablespace: -- ALTER TABLE ONLY mentor_topic ADD CONSTRAINT mentor_topic_id PRIMARY KEY (mentor_topic_id); -- -- Name: topic_id; Type: CONSTRAINT; Schema: public; Owner: -; Tablespace: -- ALTER TABLE ONLY topic ADD CONSTRAINT topic_id PRIMARY KEY (id); -- -- Name: topic_unq_name; Type: CONSTRAINT; Schema: public; Owner: -; Tablespace: -- ALTER TABLE ONLY topic ADD CONSTRAINT topic_unq_name UNIQUE (name); -- -- Name: user_pk; Type: CONSTRAINT; Schema: public; Owner: -; Tablespace: -- ALTER TABLE ONLY "user" ADD CONSTRAINT user_pk PRIMARY KEY (id); -- -- Name: user_unq_email; Type: CONSTRAINT; Schema: public; Owner: -; Tablespace: -- ALTER TABLE ONLY "user" ADD CONSTRAINT user_unq_email UNIQUE (email); -- -- Name: user_unq_username; Type: CONSTRAINT; Schema: public; Owner: -; Tablespace: -- ALTER TABLE ONLY "user" ADD CONSTRAINT user_unq_username UNIQUE (username); -- -- Name: fki_mentor_request_mentee_id; Type: INDEX; Schema: public; Owner: -; Tablespace: -- CREATE INDEX fki_mentor_request_mentee_id ON mentor_request USING btree (mentee_id); -- -- Name: fki_mentor_request_mentor_id; Type: INDEX; Schema: public; Owner: -; Tablespace: -- CREATE INDEX fki_mentor_request_mentor_id ON mentor_request USING btree (mentor_id); -- -- Name: mentor_request_mentee_id; Type: FK CONSTRAINT; Schema: public; Owner: - -- ALTER TABLE ONLY mentor_request ADD CONSTRAINT mentor_request_mentee_id FOREIGN KEY (mentee_id) REFERENCES "user"(id); -- -- Name: mentor_request_mentor_id; Type: FK CONSTRAINT; Schema: public; Owner: - -- ALTER TABLE ONLY mentor_request ADD CONSTRAINT mentor_request_mentor_id FOREIGN KEY (mentor_id) REFERENCES "user"(id); -- -- Name: mentor_topic_topic_id; Type: FK CONSTRAINT; Schema: public; Owner: - -- ALTER TABLE ONLY mentor_topic ADD CONSTRAINT mentor_topic_topic_id FOREIGN KEY (topic_id) REFERENCES topic(id); -- -- Name: mentor_topic_user_id; Type: FK CONSTRAINT; Schema: public; Owner: - -- ALTER TABLE ONLY mentor_topic ADD CONSTRAINT mentor_topic_user_id FOREIGN KEY (user_id) REFERENCES "user"(id); -- -- Name: public; Type: ACL; Schema: -; Owner: - -- REVOKE ALL ON SCHEMA public FROM PUBLIC; REVOKE ALL ON SCHEMA public FROM postgres; GRANT ALL ON SCHEMA public TO postgres; GRANT ALL ON SCHEMA public TO PUBLIC; -- -- PostgreSQL database dump complete --
23.738506
133
0.745309
39442aaaf4dd7ba09d2a967f592094a150a782a4
88
py
Python
notifiers/wechat.py
AzusaChino/iris-python
92aa6bf23d5bf8f2ac4f3d2b0ee5f36e177d97d2
[ "MIT" ]
null
null
null
notifiers/wechat.py
AzusaChino/iris-python
92aa6bf23d5bf8f2ac4f3d2b0ee5f36e177d97d2
[ "MIT" ]
null
null
null
notifiers/wechat.py
AzusaChino/iris-python
92aa6bf23d5bf8f2ac4f3d2b0ee5f36e177d97d2
[ "MIT" ]
null
null
null
import notifiers class Wechat(notifiers): def __init__(self) -> None: pass
14.666667
31
0.659091
e05ec550d56013faf35391fb14bd649d8c34ae5e
9,890
c
C
owl-driver/cm160.c
gbilder/owl-netdata
85fe8de672349a084910377926f3dfdbe191f5ad
[ "MIT" ]
null
null
null
owl-driver/cm160.c
gbilder/owl-netdata
85fe8de672349a084910377926f3dfdbe191f5ad
[ "MIT" ]
null
null
null
owl-driver/cm160.c
gbilder/owl-netdata
85fe8de672349a084910377926f3dfdbe191f5ad
[ "MIT" ]
null
null
null
/* * eagle-owl application. * * Copyright (C) 2012 Philippe Cornet <phil.cornet@gmail.com> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ #include <stdio.h> #include <stdbool.h> #include <string.h> #include <usb.h> #include <pthread.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include "cm160.h" #include "usb_utils.h" #include "db.h" #include "demonize.h" static char ID_MSG[11] = { 0xA9, 0x49, 0x44, 0x54, 0x43, 0x4D, 0x56, 0x30, 0x30, 0x31, 0x01 }; static char WAIT_MSG[11] = { 0xA9, 0x49, 0x44, 0x54, 0x57, 0x41, 0x49, 0x54, 0x50, 0x43, 0x52 }; #define HISTORY_SIZE 65536 // 30 * 24 * 60 = 43200 theoric history size #define CP210X_IFC_ENABLE 0x00 #define CP210X_GET_LINE_CTL 0x04 #define CP210X_SET_MHS 0x07 #define CP210X_GET_MDMSTS 0x08 #define CP210X_GET_FLOW 0x14 #define CP210X_GET_BAUDRATE 0x1D #define CP210X_SET_BAUDRATE 0x1E /* CP210X_IFC_ENABLE */ #define UART_ENABLE 0x0001 #define UART_DISABLE 0x0000 struct cm160_device g_devices[MAX_DEVICES]; static unsigned char history[HISTORY_SIZE][11]; static void process_live_data(struct record_data *rec) { static double _watts = -1; double w = rec->watts; if(!rec->isLiveData) // special case: update only the time { if(_watts == -1) return; w = _watts; } else _watts = w; FILE *fp = fopen("/tmp/eagle-owl-live.txt", "w"); if(fp) { if(rec->hour!=255) // to avoid writing strange values (i.e. date 2255, hour 255:255) that sometimes I got fprintf(fp, "%02d\t%02d\t%04d\t%02d:%02d\t%.02f\tkW\n", rec->day, rec->month, rec->year, rec->hour, rec->min, w); fclose(fp); } } static void decode_frame(unsigned char *frame, struct record_data *rec) { int volt = 230; // TODO: use the value from energy_param table (supply_voltage) rec->addr = 0; // TODO: don't use an harcoded addr value for the device... rec->year = frame[1]+2000; rec->month = frame[2]; rec->day = frame[3]; rec->hour = frame[4]; rec->min = frame[5]; rec->cost = (frame[6]+(frame[7]<<8))/100.0; rec->amps = (frame[8]+(frame[9]<<8))*0.07; // mean intensity during one minute rec->watts = rec->amps * volt; // mean power during one minute rec->ah = rec->amps/60; // -> we must devide by 60 to convert into ah and wh rec->wh = rec->watts/60; rec->isLiveData = (frame[0] == FRAME_ID_LIVE)? true:false; } // Insert history into DB worker thread void n(void *data) { int i; int num_elems = (int)data; // For an unknown reason, the cm160 sometimes sends a value > 12 for month // -> in that case we use the last valid month received. static int last_valid_month = 0; ///printf("insert %d elems\n", num_elems); ///printf("insert into db...\n"); clock_t cStartClock = clock(); ///db_begin_transaction(); for(i=0; i<num_elems; i++) { unsigned char *frame = history[i]; struct record_data rec; decode_frame(frame, &rec); if(rec.month < 0 || rec.month > 12) rec.month = last_valid_month; else last_valid_month = rec.month; ///db_insert_hist(&rec); ///printf("\r %.1f%%", min(100, 100*((double)i/num_elems))); fflush(stdout); } ///db_update_status(); ///db_end_transaction(); ///printf("\rinsert into db... 100%%\n"); fflush(stdout); ///printf("update db in %4.2f seconds\n", /// (clock() - cStartClock) / (double)CLOCKS_PER_SEC); } bool receive_history = true; int frame_id = 0; static int process_frame(int dev_id, unsigned char *frame) { int i; unsigned char data[1]; unsigned int checksum = 0; static int last_valid_month = 0; usb_dev_handle *hdev = g_devices[dev_id].hdev; int epout = g_devices[dev_id].epout; if(strncmp((char *)frame, ID_MSG, 11) == 0) { // printf("received ID MSG\n"); data[0]=0x5A; usb_bulk_write(hdev, epout, (const char *)&data, sizeof(data), 1000); } else if(strncmp((char *)frame, WAIT_MSG, 11) == 0) { // printf("received WAIT MSG\n"); data[0]=0xA5; usb_bulk_write(hdev, epout, (const char *)&data, sizeof(data), 1000); } else { if(frame[0] != FRAME_ID_LIVE && frame[0] != FRAME_ID_DB) { printf("data error: invalid ID 0x%x\n", frame[0]); for(i=0; i<11; i++) printf("0x%02x - ", frame[i]); printf("\n"); return -1; } for(i=0; i<10; i++) checksum += frame[i]; checksum &= 0xff; if(checksum != frame[10]) { printf("data error: invalid checksum: expected 0x%x, got 0x%x\n", frame[10], checksum); return -1; } struct record_data rec; decode_frame(frame, &rec); if(rec.month < 0 || rec.month > 12) rec.month = last_valid_month; else last_valid_month = rec.month; if(frame[0]==FRAME_ID_DB) { if(receive_history && frame_id < HISTORY_SIZE) { if(frame_id == 0) printf("\rSkipping history...\n"); else if(frame_id%10 == 0) { // print progression status // rough estimation : we should received a month of history // -> 31x24x60 minute records printf("\r %.1f%%", min(100, 100*((double)frame_id/(31*24*60)))); fflush(stdout); } // cache the history in a buffer, we will insert it in the db later. ///memcpy(history[frame_id++], frame, 11); } else { ///db_insert_hist(&rec); ///db_update_status(); process_live_data(&rec); // the record is not live data, but we do that to // update the time in the .live file // (the cm160 send a DB frame when a new minute starts) } } else { if(receive_history) { // When we receive the first live data, // we know that the history is totally downloaded printf("\rSkipped history.\n"); fflush(stdout); receive_history = false; // Now, insert the history into the db ///pthread_t thread; ///pthread_create(&thread, NULL, (void *)&insert_db_history, (void *)frame_id); } process_live_data(&rec); ///printf("LIVE: %02d/%02d/%04d %02d:%02d : %f W\n", /// rec.day, rec.month, rec.year, rec.hour, rec.min, rec.watts); } } return 0; } static int io_loop(int dev_id) { int ret; usb_dev_handle *hdev = g_devices[dev_id].hdev; int epin = g_devices[dev_id].epin; unsigned char buffer[512]; unsigned char word[11]; memset(buffer, 0, sizeof(buffer)); memset(word, 0, sizeof(word)); while(1) { memset(buffer, 0, sizeof(buffer)); ret = usb_bulk_read(hdev, epin, (char*)buffer, sizeof(buffer), 10000); if(ret < 0) { printf("bulk_read returned %d (%s)\n", ret, usb_strerror()); return -1; } // printf("read %d bytes: \n", ret); unsigned char *bufptr = (unsigned char *)buffer; int nb_words = ret/11; // incomplete words are resent while(nb_words--) { memcpy(word, bufptr, 11); bufptr+=11; process_frame(dev_id, word); } } return 0; } static int handle_device(int dev_id) { int r, i; struct usb_device *dev = g_devices[dev_id].usb_dev; usb_dev_handle *hdev = g_devices[dev_id].hdev; usb_detach_kernel_driver_np(hdev, 0); if( 0 != (r = usb_set_configuration(hdev, dev->config[0].bConfigurationValue)) ) { printf("usb_set_configuration returns %d (%s)\n", r, usb_strerror()); return -1; } if((r = usb_claim_interface(hdev, 0)) < 0) { printf("Interface cannot be claimed: %d\n", r); return r; } int nep = dev->config->interface->altsetting->bNumEndpoints; for(i=0; i<nep; i++) { int ep = dev->config->interface->altsetting->endpoint[i].bEndpointAddress; if(ep&(1<<7)) g_devices[dev_id].epin = ep; else g_devices[dev_id].epout = ep; } // Set baudrate int baudrate = 250000; r = usb_control_msg(hdev, USB_TYPE_VENDOR | USB_RECIP_INTERFACE | USB_ENDPOINT_OUT, CP210X_IFC_ENABLE, UART_ENABLE, 0, NULL, 0, 500); r = usb_control_msg(hdev, USB_TYPE_VENDOR | USB_RECIP_INTERFACE | USB_ENDPOINT_OUT, CP210X_SET_BAUDRATE, 0, 0, (char *)&baudrate, sizeof(baudrate), 500); r = usb_control_msg(hdev, USB_TYPE_VENDOR | USB_RECIP_INTERFACE | USB_ENDPOINT_OUT, CP210X_IFC_ENABLE, UART_DISABLE, 0, NULL, 0, 500); // read/write main loop io_loop(dev_id); usb_release_interface(hdev, 0); return 0; } int main(int argc, char **argv) { int dev_cnt; if(argc>1 && (strcmp(argv[1], "-d")==0) ) demonize(argv[0]); while(1) { ///db_open(); dev_cnt = 0; receive_history = true; frame_id = 0; printf("Wait for cm160 device to be connected\n"); while((dev_cnt = scan_usb()) == 0) sleep(2); printf("Found %d compatible device%s\n", dev_cnt, dev_cnt>1?"s":""); // Only 1 device supported if(!(g_devices[0].hdev = usb_open(g_devices[0].usb_dev))) { fprintf(stderr, "failed to open device\n"); ///db_close(); break; } handle_device(0); usb_close(g_devices[0].hdev); ///db_close(); } return 0; }
28.41954
109
0.617695
45c3f4266f6d1555ab630fa752bf88942a2492bc
1,093
py
Python
output/models/nist_data/atomic/name/schema_instance/nistschema_sv_iv_atomic_name_enumeration_2_xsd/nistschema_sv_iv_atomic_name_enumeration_2.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
1
2021-08-14T17:59:21.000Z
2021-08-14T17:59:21.000Z
output/models/nist_data/atomic/name/schema_instance/nistschema_sv_iv_atomic_name_enumeration_2_xsd/nistschema_sv_iv_atomic_name_enumeration_2.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
4
2020-02-12T21:30:44.000Z
2020-04-15T20:06:46.000Z
output/models/nist_data/atomic/name/schema_instance/nistschema_sv_iv_atomic_name_enumeration_2_xsd/nistschema_sv_iv_atomic_name_enumeration_2.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
null
null
null
from dataclasses import dataclass, field from enum import Enum from typing import Optional __NAMESPACE__ = "NISTSchema-SV-IV-atomic-Name-enumeration-2-NS" class NistschemaSvIvAtomicNameEnumeration2Type(Enum): UOF_RETRIEVE_THE_PROVIDED_SPECIFIC_IN_SYSTEMS_ON_A_CHI = "uof.retrieve:the_provided_specific_in_systems-on-a-chi" PIS_KNOWN_OVER_ALLOW = "pis_known:over.allow." DISCOVERY_DESIGNED_GRAPHICS_PERV = "_discovery:designed_graphics_perv" JREGISTRY_INTEROPERABILITY_HAMPERED_O = "jregistry.interoperability_hampered-o" GREAT_DESK = "_great-desk" RA_THE_PARTNERS_THAT_PERVASIVE_BY_CHALLENGES_DISCOVER = "ra-the-partners-that-pervasive.by_challenges:discover" PNEXT_CREAT = "pnext:creat" YR = "yr" @dataclass class NistschemaSvIvAtomicNameEnumeration2: class Meta: name = "NISTSchema-SV-IV-atomic-Name-enumeration-2" namespace = "NISTSchema-SV-IV-atomic-Name-enumeration-2-NS" value: Optional[NistschemaSvIvAtomicNameEnumeration2Type] = field( default=None, metadata={ "required": True, } )
35.258065
117
0.763038
e24633162df779a38c44b32ecd43fd1690eca694
29
py
Python
src/amuse/community/flash/__init__.py
sibonyves/amuse
5557bf88d14df1aa02133a199b6d60c0c57dcab7
[ "Apache-2.0" ]
null
null
null
src/amuse/community/flash/__init__.py
sibonyves/amuse
5557bf88d14df1aa02133a199b6d60c0c57dcab7
[ "Apache-2.0" ]
12
2021-11-15T09:13:03.000Z
2022-02-02T14:53:04.000Z
src/amuse/community/flash/__init__.py
sibonyves/amuse
5557bf88d14df1aa02133a199b6d60c0c57dcab7
[ "Apache-2.0" ]
null
null
null
from .interface import Flash
14.5
28
0.827586
c9e377c1ea30bafc3df90f222ffda6b3e76d6243
282
tsx
TypeScript
generators/app/templates/monorepo/packages/web/src/App.tsx
vitorfreitas/generator-ts-monorepo
513c7066e6dca9ceeb3b1e4c0267e1dd97648ccd
[ "MIT" ]
19
2020-01-10T13:48:12.000Z
2022-02-08T02:13:10.000Z
packages/web/src/App.tsx
vitorfreitas/monorepo-fullstack-ts
044324200624766f1fc74c9ba8bca542b55af3e7
[ "MIT" ]
1
2021-05-11T02:07:09.000Z
2021-05-11T02:07:09.000Z
generators/app/templates/monorepo/packages/web/src/App.tsx
vitorfreitas/generator-ts-monorepo
513c7066e6dca9ceeb3b1e4c0267e1dd97648ccd
[ "MIT" ]
null
null
null
import React, { Suspense } from 'react' import PagesRouter from './pages' import GlobalStyles from './globalStyles' const App: React.FC = () => { return ( <Suspense fallback="Loading..."> <GlobalStyles /> <PagesRouter /> </Suspense> ) } export default App
18.8
41
0.634752
a30fc3d79a551fc4c4e68c5ac77aab6c18f72062
453
ts
TypeScript
src/buyer/buyer.service.spec.ts
song9797/demouserserver
69c2858667e26e20ad1d44d0fe18d86657a8d248
[ "MIT" ]
null
null
null
src/buyer/buyer.service.spec.ts
song9797/demouserserver
69c2858667e26e20ad1d44d0fe18d86657a8d248
[ "MIT" ]
3
2021-03-09T23:32:09.000Z
2022-01-22T09:51:35.000Z
src/buyer/buyer.service.spec.ts
FerLuisxd/fin-backend
fc469a9f42dadb5474ef710703f1973a27ecbc23
[ "MIT" ]
null
null
null
import { Test, TestingModule } from '@nestjs/testing'; import { BuyerService } from './buyer.service'; describe('BuyerService', () => { let service: BuyerService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [BuyerService], }).compile(); service = module.get<BuyerService>(BuyerService); }); it('should be defined', () => { expect(service).toBeDefined(); }); });
23.842105
66
0.644592
c6247ed06780c703e8e4a66e4aa43d6347b92778
139
rb
Ruby
0_code_wars/sum_arrays.rb
etdev/algorithms
25cfa4222e9add2806f0bf1e9cc1b76faefc50f2
[ "MIT" ]
5
2016-01-30T04:18:16.000Z
2021-06-11T03:06:42.000Z
0_code_wars/sum_arrays.rb
etdev/algorithms
25cfa4222e9add2806f0bf1e9cc1b76faefc50f2
[ "MIT" ]
null
null
null
0_code_wars/sum_arrays.rb
etdev/algorithms
25cfa4222e9add2806f0bf1e9cc1b76faefc50f2
[ "MIT" ]
null
null
null
# http://www.codewars.com/kata/53dc54212259ed3d4f00071c # --- iteration 1 --- # Sum Numbers def sum(numbers) numbers.reduce(0, &:+) end
17.375
55
0.690647
2006de8538e01d04a76b311d42b8458d31dda43d
2,358
py
Python
backend/api/models/containers.py
SelfhostedPro/yacht-vue
62d020dd33eca9ebdeeb14ba81825335cd63913b
[ "MIT" ]
6
2020-07-08T05:33:22.000Z
2021-08-22T20:19:54.000Z
backend/api/models/containers.py
sharmasecureservicesusa/yacht-vue
62d020dd33eca9ebdeeb14ba81825335cd63913b
[ "MIT" ]
2
2021-06-02T02:22:42.000Z
2022-02-27T07:46:10.000Z
backend/api/models/containers.py
sharmasecureservicesusa/yacht-vue
62d020dd33eca9ebdeeb14ba81825335cd63913b
[ "MIT" ]
4
2020-07-08T05:33:24.000Z
2021-09-23T15:31:25.000Z
from .. import db from datetime import datetime from werkzeug.security import check_password_hash, generate_password_hash class Template(db.Model): __tablename__ = 'templates' id = db.Column(db.Integer, primary_key=True) # alternative: DateTime(timezone=True), sqlalchemy.sql.func.now() created_at = db.Column(db.DateTime, nullable=False, unique=False, index=False, default=datetime.utcnow) updated_at = db.Column(db.DateTime, nullable=False, unique=False, index=False, default=datetime.utcnow, onupdate=datetime.utcnow) # rename to title title = db.Column(db.String(255), nullable=False, unique=True, index=True) url = db.Column(db.Text, nullable=False, unique=True, index=False) items = db.relationship('TemplateItem', backref='template', lazy='dynamic', cascade='all, delete-orphan') class TemplateItem(db.Model): __tablename__ = 'template_item' id = db.Column(db.Integer, primary_key=True) type= db.Column(db.Integer, nullable=False, unique=False, index=False) title = db.Column(db.String(255), nullable=False, unique=False, index=True) platform = db.Column(db.String(64), nullable=False, unique=False, index=False) description = db.Column(db.Text, nullable=True, unique=False, index=False) name = db.Column(db.String(255), nullable=True, unique=False, index=True) logo = db.Column(db.Text, nullable=True, unique=False, index=False) image = db.Column(db.String(128), nullable=True, unique=False, index=False) notes = db.Column(db.Text, nullable=True, unique=False, index=False) categories = db.Column(db.JSON, nullable=True, unique=False, index=False) restart_policy = db.Column(db.String(20), nullable=True, unique=False, index=False) ports = db.Column(db.JSON, nullable=True, unique=False, index=False) volumes = db.Column(db.JSON, nullable=True, unique=False, index=False) env = db.Column(db.JSON, nullable=True, unique=False, index=False) sysctls = db.Column(db.JSON, nullable=True, unique=False, index=False) cap_add = db.Column(db.JSON, nullable=True, unique=False, index=False) template_id = db.Column(db.Integer, db.ForeignKey('templates.id'))
35.727273
73
0.671756
eba320cb2c826587fb62d2148d45de47e921a634
40,203
css
CSS
pub/theme/default/frontend/css/style.css
peachyang/py_website
355ae86806b995f3105b9bf79b654aef575e37f6
[ "MIT" ]
2
2017-09-19T07:02:07.000Z
2018-06-28T03:12:38.000Z
pub/theme/default/frontend/css/style.css
peachyang/py_website
355ae86806b995f3105b9bf79b654aef575e37f6
[ "MIT" ]
null
null
null
pub/theme/default/frontend/css/style.css
peachyang/py_website
355ae86806b995f3105b9bf79b654aef575e37f6
[ "MIT" ]
null
null
null
/* Template Name: Unify - Responsive Bootstrap Template Description: Business, Corporate, Portfolio and Blog Theme. Version: 1.2 Author: Html Stream Website: http://htmlstream.com/preview/unify */ /*Import Google Fonts*/ @import url(http://fonts.googleapis.com/css?family=Monda:400,700); @import url(http://fonts.googleapis.com/css?family=Open+Sans); * { border-radius:0 !important; } body { padding:0; color:#333; font-size:13px; line-height:1.6; background:#fff; } p, a, li { color:#555; line-height:1.6; } a, a:focus, a:hover, a:active { outline:0 !important; } a:hover { color:#72c02c; text-decoration:underline; } h1, h2, h3, h4, h5 { color:#555; margin-top:5px; text-shadow:none; text-shadow:0 0 1px #f6f6f6; font-weight:normal !important; font-family:'Open Sans', sans-serif; } h1 i, h2 i, h3 i, h4 i, h5 i { margin-right:7px; } /*Block headline*/ .heading { padding:5px 20px 5px 20px; border-left:4px solid #27c5f2; } .headline { display:block; margin:10px 0 25px 0; border-bottom:1px dotted #e4e9f0; } .headline h3, .headline h4 { color:#585f69; margin:0 0 -2px 0; padding-right:10px; display:inline-block; text-shadow:0 0 1px #f6f6f6; border-bottom:2px solid #72c02c; } /*Purchase*/ .purchase { padding:30px 0 20px; box-shadow:inset 0 0 4px #eee; background:url(../img/breadcrumbs.png) repeat; } .purchase .container { padding:0 20px; } .purchase .container .span9 { margin-right:20px; } .purchase span { color:#666; display:block; font-size:32px; line-height:35px; margin-bottom:12px; } .purchase a.btn-buy { float:right; color:#fff; font-size:16px; cursor:pointer; margin-top:22px; font-weight:bold; border-radius:2px; background:#72c02c; display:inline-block; text-decoration:none; padding:12px 28px 9px; text-transform:uppercase; text-shadow:0 1px 0 #51a00b; } .purchase a.btn-buy:hover { color:#fff; background:#68af28; text-decoration:none; box-shadow:0 0 5px #c0c2c1; } /*Service*/ .service { margin-bottom:10px; padding:15px 15px 10px; } .service:hover { border-radius:2px; box-shadow:0 0 8px #ddd; background:#fcfcfc; -webkit-transition:box-shadow 0.2s ease-in-out; -moz-transition:box-shadow 0.2s ease-in-out; -o-transition:box-shadow 0.2s ease-in-out; transition:box-shadow 0.2s ease-in-out; } .service:hover i { color:#656565; } .service i { float:left; padding:10px; color:#72c02c; font-size:45px; text-align:center; -webkit-transition:all 0.4s ease-in-out; -moz-transition:all 0.4s ease-in-out; -o-transition:all 0.4s ease-in-out; transition:all 0.4s ease-in-out; } .service i.icon-cogs { font-size:37px; } .service .desc { width:75%; float:right; } .service .desc h4 { font-size:1.375em; line-height:1.5625em; } .ie7 .service .circle i { padding-bottom:45px !important; /*ie7*/ } /*Blockquote*/ blockquote:hover { border-left-color:#72c02c; -webkit-transition:all 0.4s ease-in-out; -moz-transition:all 0.4s ease-in-out; -o-transition:all 0.4s ease-in-out; transition:all 0.4s ease-in-out; } .hero { padding:18px; margin:20px 0; color:#566c8a; font-size:16px; background:#fcfcfc; border-left:4px solid #94c564; font-family:'Open Sans', sans-serif; } .hero h1, .hero p { text-shadow:1px 1px 0 #fff; } .hero-unify p { font-size:13px; line-height:20px; } /* Recent Work */ .recent-work a { text-align:center; background:#fcfcfc; display:inline-block; } .recent-work a:hover { text-decoration:none; } .recent-work a:hover strong { color:#555; } .recent-work em.overflow-hidden { display:block; } .recent-work a span { display:block; padding:10px; border-bottom:solid 2px #eee; } .recent-work a strong { color:#555; display:block; } .recent-work a i { color:#777; } .recent-work a img { -webkit-transition: all 0.8s ease-in-out; -moz-transition: all 0.8s ease-in-out; -o-transition: all 0.8s ease-in-out; -ms-transition: all 0.8s ease-in-out; transition: all 0.8s ease-in-out; } .recent-work a:hover img { opacity:0.8; -webkit-transform: scale(1.2) rotate(3deg); -moz-transform: scale(1.2) rotate(3deg); -o-transform: scale(1.0) rotate(3deg); -ms-transform: scale(1.2) rotate(3deg); transform: scale(1.2) rotate(3deg); } .recent-work a:hover span { border-bottom:solid 2px #72c02c; -webkit-transition:all 0.2s ease-in-out; -moz-transition:all 0.3s ease-in-out; -o-transition:all 0.2s ease-in-out; transition:all 0.3s ease-in-out; } /* Work */ .work { margin-top:6px; } .work .details { padding:10px; } .work .caption { display:block; padding-top:5px; color:#585f69 !important; font-size:18px !important; } .work .caption:hover { cursor:pointer; color:#444 !important; text-decoration:underline; } /* Testimonials */ .testimonial-body { padding:10px; margin-top:5px; background:#fcfcfc; border:1px solid #f5f5f5; } .testimonial-author{ padding-top:15px; padding-left:20px; } .testimonial-author .arrow { width:0; height:0; position:absolute; margin-top:-16px; margin-left:20px; border-top:15px solid #fcfcfc; border-bottom:15px solid transparent; border-right:15px solid transparent; } .testimonial-author .name { color:#585f69; font-weight:bold; } .testimonal-arrow a { margin:0; top:-22px; float:right; color:#72c02c; font-size:25px; position:relative; display:inline-block; text-decoration: none; padding:0 9px !important; } .testimonal-arrow a:hover { color:#fff; text-decoration:none; background:#72c02c !important; } /*Carousel Arrow */ .carousel-caption { padding:10px 15px; } .carousel-arrow a.carousel-control { font-size:40px; height:inherit; } .carousel-arrow a.left { left:0; } .carousel-arrow a.right { right:0; } /*Clients (Flexslider)*/ .clients { box-shadow:none !important; margin-bottom:0 !important; } .clients li { float:left; overflow:hidden; margin-left:1px; position:relative; background:#fafafa; } .clients li:hover { background:#f6f6f6; } .clients li img.color-img { top:0; left:0; display:none; position:absolute; } .clients li:hover img.color-img { display:block; } .clients li img { filter:gray; /* IE6-9 */ float:none !important; margin:0 auto !important; } .clients li img:hover { filter:none; } .clients, .flexslider.home { border:0px; overflow:hidden; margin-top:10px; margin-bottom:30px; border-radius:0; -moz-border-radius:0; -webkit-border-radius:0; } .flexslider { margin-top:10px !important; } .flexslider .flex-direction-nav a { margin-top:-10px !important; } /*Pegination*/ .pagination ul { box-shadow:none; } .pagination li a { color:#777; padding:5px 15px; border-radius:0 !important; } /*Footer*/ .footer { margin-top:40px; padding:20px 10px 0px; background:#272727; color:#dadada; } .footer h1, .footer h2, .footer h3, .footer h4, .footer h5 { text-shadow:none; font-weight:normal !important; } .footer p, .footer a { font-size:14px; } .footer p { color:#dadada; } .footer a { color:#72c02c; } .footer a:hover { color:#a8f85f; -webkit-transition:all 0.4s ease-in-out; -moz-transition:all 0.4s ease-in-out; -o-transition:all 0.4s ease-in-out; transition:all 0.4s ease-in-out; } .footer h4, .footer h3 { color:#e4e4e4; background:none; text-shadow:none; } .footer li{ list-style:none; } /*Blog Posts*/ .footer .posts { /* padding:0 15px;*/ } .footer .blog-list { margin:0; padding:0; color:#dadada; list-style:none; } .footer .blog-list li { padding:0 0; margin-bottom:7px; } .footer .list-inline>li{ display:inline-block; width:auto; padding:auto 5px; } .footer .blog-list li span { color:#818488; } .footer .dl-horizontal, .footer .dl-horizontal:hover { border:none !important; background:none !important; } .footer .dl-horizontal a { color:#dadada; } .footer .dl-horizontal a:hover { color:#a8f85f !important; } .footer .dl-horizontal img { border-color:#888 !important; } .footer .posts .latest-list a{ color:#ffffff; } .footer .posts .latest-list a:hover { color:#72c02c; } .footer .posts .latest-list small { color: #999; display: block; } .footer ul{ margin:0; } .footer-v1 .link-list li { border-top:none; border-bottom:solid 1px #353535; line-height:30px; } /*Copyright*/ .copyright { font-size:12px; padding:5px 10px; background:#272727; border-top:solid 1px #777; } .copyright p { color:#dadada; } .copyright a { margin:0 5px; color:#72c02c; } .copyright a:hover { color:#a8f85f; -webkit-transition:all 0.4s ease-in-out; -moz-transition:all 0.4s ease-in-out; -o-transition:all 0.4s ease-in-out; transition:all 0.4s ease-in-out; } .copyright .span8 { padding-top:15px; } .copyright .span4 { padding-top:10px; } /*Home Page "Main page" (Default) ------------------------------------*/ /*Thumbnail*/ .thumbnail-style { padding:5px; border-radius:2px; overflow: hidden; } .thumbnail-style:hover { box-shadow:0 0 8px #ddd; -webkit-transition:box-shadow 0.2s ease-in-out; -moz-transition:box-shadow 0.2s ease-in-out; -o-transition:box-shadow 0.2s ease-in-out; transition:box-shadow 0.2s ease-in-out; } .grid .thumbnail-style .thumbnail-img { height: auto; max-height: 180px; text-align: center; } .list .thumbnail-style .thumbnail-img { float: left; margin-right: 15px; max-height: 168px; height: auto; } .list .thumbnail-style h3 { display: inline-block; } .thumbnail-style h3 { margin:5px 0 0 0; } .thumbnail-style h3 a { font-size:20px; } .thumbnail-style h3 a:hover { color:#72c02c; text-decoration:none; } .thumbnail-style .thumbnail-img { position:relative; max-height: 232px; overflow: hidden } .thumbnail-style .star-vote{ display: block; width: auto; } .thumbnail-style .star-vote li{ display: inline-block } .thumbnail-style a.btn-more { right:-10px; bottom:10px; color:#fff; padding:1px 6px; position:absolute; background:#72c02c; display:inline-block; } .thumbnail-style a.btn-more:hover { text-decoration:none; box-shadow:0 0 0 2px #377500; } .thumbnail-style:hover a.btn-more { right:10px; } .thumbnail-kenburn img { left:10px; margin-left:-10px; position:relative; -webkit-transition: all 0.8s ease-in-out; -moz-transition: all 0.8s ease-in-out; -o-transition: all 0.8s ease-in-out; -ms-transition: all 0.8s ease-in-out; transition: all 0.8s ease-in-out; } .thumbnail-kenburn:hover img { -webkit-transform: scale(1.2) rotate(2deg); -moz-transform: scale(1.2) rotate(2deg); -o-transform: scale(1.2) rotate(2deg); -ms-transform: scale(1.2) rotate(2deg); transform: scale(1.2) rotate(2deg); } /*Welcome Block*/ .servive-block .span4 { padding:20px 30px; text-align:center; margin-bottom:20px; background:#fafafa; border-radius:2px; -webkit-transition:all 0.3s ease-in-out; -moz-transition:all 0.3s ease-in-out; -o-transition:all 0.3s ease-in-out; transition:all 0.3s ease-in-out; } .servive-block .span4:hover { border-radius:2px; box-shadow:0 0 8px #ddd; } .servive-block .span4 h4 a:hover { color:#72c02c; text-decoration:none; } .servive-block .span4:hover h4, .servive-block .span4:hover i { color:#72c02c; } .servive-block .span4 i { color:#565656; font-size:40px; -webkit-transition:all 0.4s ease-in-out; -moz-transition:all 0.4s ease-in-out; -o-transition:all 0.4s ease-in-out; transition:all 0.4s ease-in-out; } .servive-block-in .span4 i { color:#72c02c; } .servive-block-in .span4:hover i { color:#565656; } /*Breadcrumbs*/ .breadcrumbs { padding:10px 0 6px; box-shadow:inset 0 0 4px #eee; background:url(../img/breadcrumbs.png) repeat; } .breadcrumbs h1 { color:#686868; font-size:30px; text-shadow:0 1px 0 #f1efef; } .breadcrumbs .container { padding:0 15px; } .breadcrumb { top:9px; padding-right:0; background:none; position:relative; } .breadcrumb a { color:#777; } .breadcrumb li.active, .breadcrumb li a:hover { color:#72c02c; text-decoration:none; } .breadcrumb li+li:before{ padding: 0 5px; color: #ccc; content: "/\00a0"; } /*Home Page "Options" ------------------------------------*/ /*Accardion*/ .acc-home a.accordion-toggle { color:#686868; font-size:18px; background:none; padding:5px 15px; background:#fafafa; border-bottom:solid 1px #eee; text-decoration:none !important; } .acc-home a.active, .acc-home a.accordion-toggle:hover { color:#92d556; text-decoration:none !important; } .acc-home .accordion-group { border:none; margin:0 !important; } .acc-home .accordion-heading, .acc-home .accordion-inner { border:none; } .acc-home .accordion-inner { border:none; padding-top:3px; } .acc-home .collapse.in { margin-top:-1px; margin-bottom:20px; background:#fdfdfd; border-bottom:solid 1px #72c02c; } /*Posts*/ .posts .dl-horizontal { margin-bottom:0; padding:3px; background:#fdfdfd; border-right:solid 2px #eee; } .posts .dl-horizontal:hover { border-right:solid 2px #72c02c; -webkit-transition:all 0.4s ease-in-out; -moz-transition:all 0.4s ease-in-out; -o-transition:all 0.4s ease-in-out; transition:all 0.4s ease-in-out; } .posts .dl-horizontal dt { width:56px; float:left; } .posts .dl-horizontal dt img { width:50px; height:50px; border:solid 3px #eee; } .posts .dl-horizontal dd { margin-left:66px; } .posts .dl-horizontal dd p { margin:0; } .posts .dl-horizontal a { font-size:15px; line-height:14px !important; } .posts .dl-horizontal a:hover { color:#72c02c; text-decoration:none; } .posts .dl-horizontal:hover dt img, .posts .dl-horizontal:hover dd a { color:#72c02c; border-color:#72c02c !important; -webkit-transition:all 0.4s ease-in-out; -moz-transition:all 0.4s ease-in-out; -o-transition:all 0.4s ease-in-out; transition:all 0.4s ease-in-out; } /*Home Page "Options" ------------------------------------*/ /*Slider*/ .slider-inner .da-slider { box-shadow:none; border-bottom:2px solid #ddd; } /*Carousel*/ .row-fluid .carousel .carousel-control { font-size: 40px; } .carousel-control { color:#fff; border:none; margin-top:0; border-radius:2px; } .carousel-control:hover { opacity:1; color:#72c02c; } /*Tabs*/ .nav-tabs { background:none !important; } .nav-tabs a { font-size:14px; padding:5px 15px !important; } .nav-tabs li.active a, .nav-tabs li.active a:hover, .nav-tabs > .active > a, .nav-tabs > .active > a:hover, .nav-tabs > .active > a:focus { color:#fff; border:none; background:#72c02c; } .nav-tabs > li > a { border:none; border-radius:0; } .nav-tabs > li > a:hover { color:#fff; background:#72c02c; } .tab-content { padding:7px 10px; border-top:solid 2px #72c02c; } /*Home Page "Options" ------------------------------------*/ /*Right Sidebar*/ .who li { margin-bottom:6px; } .who li i { color:#72c02c; position:relative; top:2px; margin-right:7px; font-size:18px; } .who li:hover i, .who li:hover a { color:#777; } .who li:hover a:hover { text-decoration:none; } /*Home Page "Options" ------------------------------------*/ /*Service Blocks*/ .service-alternative .service:hover { background:#76ca2c; -webkit-transition:all 0.4s ease-in-out; -moz-transition:all 0.4s ease-in-out; -o-transition:all 0.4s ease-in-out; transition:all 0.4s ease-in-out; } .service-alternative .service:hover i, .service-alternative .service:hover p, .service-alternative .service:hover h4 { color:#fff; } /*About Page ------------------------------------*/ .team ul { text-align:right; } .team ul li { padding:0 !important; margin:0 !important; } .team ul li a, .team ul li a:hover { text-decoration:none; } .team ul li i { color:#aaa; font-size:20px; padding:4px; background:#f7f7f7; } .team ul li i:hover { color:#fff; background:#72c02c; -webkit-transition:all 0.2s ease-in-out; -moz-transition:all 0.2s ease-in-out; -o-transition:all 0.2s ease-in-out; transition:all 0.2s ease-in-out; } .team .thumbnail-style { padding:12px; } .team .thumbnail-style small { display:block; font-size:12px; } .team .thumbnail-style h3 { margin-bottom:10px; } .team .thumbnail-style:hover h3 a { color:#72c02c !important; } /*Icons Page ------------------------------------*/ .icon-page li { color:#555; margin:5px 0; font-size:14px; font-family:Arial; } .icon-page li i { font-size:14px; margin-right:5px; } .icon-page li:hover { color:#72c02c; } /*Pricing Page ------------------------------------*/ /*Pricing Head*/ .pricing { position:relative; border-radius:3px; margin-bottom:15px; box-shadow:0 0 5px #eee; } .pricing:hover { box-shadow:0 0 15px #b5b5b5; } .pricing:hover h4 { color:#55c931; } .pricing-head { text-align:center; } .pricing-head h3, .pricing-head h4 { margin:0; line-height:normal; font-weight:bold !important; } .pricing-head h3 span, .pricing-head h4 span { display:block; margin-top:5px; font-size:12px; font-style:italic; } .pricing-head h3 { color:#fafafa; padding:12px 0; font-size:35px; font-family:Arial; background:#55c931; border-radius:3px 3px 0 0; text-shadow:0 1px 0 #32a20f; border-bottom:solid 1px #41b91c; } .pricing-head h4 { color:#bac39f; padding:5px 0; font-size:70px; font-family:Arial; background:#fbfef2; text-shadow:0 1px 0 #fff; border-bottom:solid 1px #f5f9e7; } .pricing-head h4 i { top:-8px; font-size:28px; font-style:normal; position:relative; } .pricing-head h4 span { top:-10px; font-size:14px; font-style:normal; position:relative; } /*Pricing Content*/ .pricing-content li { color:#888; font-size:12px; padding:7px 15px; border-bottom:solid 1px #f5f9e7; } .pricing-content li i { top:2px; color:#72c02c; font-size:16px; margin-right:5px; position:relative; } /*Pricing Footer*/ .pricing-footer { color:#777; font-size:11px; line-height:17px; text-align:center; padding:0 20px 19px; border-radius:0 0 3px 3px; } .pricing-footer a, .pricing-footer button { color:#fff; border:none; margin-top:5px; font-size:16px; padding:6px 15px; text-align:center; border-radius:2px; background:#55c931; display:inline-block; text-transform:uppercase; text-shadow:0 1px 0 #38b312; border-bottom:solid 2px #41b91c; } .pricing-footer a:hover, .pricing-footer button:hover { cursor:pointer; background:#40ba1a; text-decoration:none; box-shadow:0 0 3px #999; } /*Priceing Active*/ .price-active, .pricing:hover { z-index:9; margin-top:-15px; box-shadow:0 0 15px #b5b5b5; } .price-active h4 { color:#55c931; } .no-space-pricing .pricing:hover { -webkit-transition:box-shadow 0.3s ease-in-out; -moz-transition:box-shadow 0.3s ease-in-out; -o-transition:box-shadow 0.3s ease-in-out; transition:box-shadow 0.2s ease-in-out; } .no-space-pricing .price-active .pricing-head h4, .no-space-pricing .pricing:hover .pricing-head h4 { color:#55c931; padding:15px 0; font-size:80px; -webkit-transition:color 0.5s ease-in-out; -moz-transition:color 0.5s ease-in-out; -o-transition:color 0.5s ease-in-out; transition:color 0.5s ease-in-out; } /*Gallery Page ------------------------------------*/ .gallery .thumbnail, .gallery .thumbnail:hover { padding:0; border:none; box-shadow:none; } .gallery .thumbnails { margin-bottom:6px; } /*Registration and Login Page ------------------------------------*/ .reg-page, .login-page { overflow:hidden; margin:0 auto; background:#fcfcfc; border:solid 1px #eee; box-shadow:0 0 7px #eee; } /*Registration*/ .reg-page { min-width:30%; max-width:30%; padding:30px 50px 30px; } .reg-page h3 { margin-bottom:25px; } /*Login*/ .login-page { min-width:25%; max-width:25%; padding:35px 30px 30px; } .login-page h3 { margin:0 0 25px 0; } .login-page input.login-inputs { width:86%; } .login-page .checkbox { margin-top:7px; } .login-page .checkbox input { margin-right:6px !important; } .login-page button { margin:0 0 5px 0; } /*Login Page v1.1*/ .log-page { width: 310px; padding: 20px; margin: 0 auto; background:#fcfcfc; border:solid 1px #eee; box-shadow:0 0 7px #eee; } /*404 Page ------------------------------------*/ .page-404 p { top:70px; color:#777; font-size:300px; line-height:180px; text-align:center; position:relative; } .page-404 p i { font-style:normal; text-shadow:0 0 3px; } .page-404 p span { display:block; font-size:32px; position:relative; } /*Clients Page ------------------------------------*/ .clients-page { overflow:hidden; } .clients-page p { overflow:auto; } .clients-page p a { overflow:auto; text-decoration:underline; } .clients-page a.img-hover { display:block; position:relative; } .clients-page img { float:left; margin-right:20px; background:#fafafa; border:solid 1px #eee; width:120px; height:120px; } .clients-page img.img-colorful { display:none; } .clients-page a:hover img.img-colorful, .clients-page:hover img.img-colorful { top:0; left:0; display:block; position:absolute; } /*Privacy Page ------------------------------------*/ .privacy {} .privacy a { text-decoration:underline; } .privacy a:hover { color:#72c02c; text-decoration:none; } /*Portfolio Page ------------------------------------*/ .portfolio-columns .span3 { margin-bottom:1.8%; } .portfolio-columns .span4 { margin-bottom:2.3%; } .portfolio-columns .span6 { margin-bottom:2.2%; } /*Portfolio Item Page ------------------------------------*/ .portfolio-item h3 { margin-top:0; } .portfolio-item li { padding:3px 0; } .portfolio-item p a { text-decoration:underline; } .portfolio-item p a:hover { text-decoration:none; } /*Blog Page ------------------------------------*/ .blog-page ul, .blog-page li { margin:0 !important; padding:0 !important; } .blog h3 { color:#72c02c; text-align:center; } .blog-page .blog h3.text-left { text-align:left; } .blog ul { color:#555; font-size:12px; } .blog li { margin-right:7px !important; } .blog li i { color:#666; } .blog li a:hover { color:#72c02c; text-decoration:none; } .blog ul.blog-info { border-top:solid 1px #eee; } .blog .blog-img { margin:10px 0; } /*Blog Tags*/ ul.blog-tags a { font-size:13px; padding:2px 5px; background:#f7f7f7; margin:0 2px 5px 0; display:inline-block; text-shadow:0 1px 0 #fff; } ul.blog-tags a:hover, ul.blog-tags a:hover i { color:#72c02c; text-decoration:none; -webkit-transition:all 0.3s ease-in-out; -moz-transition:all 0.3s ease-in-out; -o-transition:all 0.3s ease-in-out; transition:all 0.3s ease-in-out; } ul.blog-tags a i { color:#777; } .blog ul.blog-tags,.blog ul.blog-twitter { border-bottom:solid 1px #eee; padding-bottom:4px !important; } .blog ul.blog-tags a { font-size:10px; display:inline; padding:2px 3px; margin-right:2px; background:#f4f4f4; } /*Blog Ads*/ .blog-ads li { display:inline; } .blog-ads li img { opacity:0.6; width:60px; height:60px; margin:0 2px 8px; } .blog-ads li img:hover { opacity:1; box-shadow:0 0 0 4px #72c02c; } /*Blog Latest Tweets*/ .blog-twitter p { } .blog-twitter p span { color:#777; display:block; font-size:11px; } .blog-twitter p a { color:#72c02c; text-decoration:none; } .blog-twitter p a:hover { text-decoration:underline; } /*Blog Item Page ------------------------------------*/ .blog-item .media img { top:3px; width:54px; height:54px; position:relative; } .blog-item h4.media-heading { position:relative; } .blog-item h4.media-heading span { top:3px; right:0; color:#777; font-size:12px; position:absolute; } .blog-item h4.media-heading span a { color:#72c02c; } /*Contact Page ------------------------------------*/ .map { width:100%; height:350px; border-top:solid 1px #eee; border-bottom:solid 1px #eee; } .map-box { height: 250px; } .map-box-space { margin-top: 25px; } /*Coming Soon Page ------------------------------------*/ .coming-soon-page { background: #585f69; } .coming-soon-border { border-top: solid 3px #72c02c; } .coming-soon-logo { margin-top: 10px; padding-top: 15px; border-top: solid 1px #4c5159; } .coming-soon-logo a { display: block; text-align: center; } .coming-soon, .coming-soon-plugin { padding: 20px; text-align: center; margin-top: 20px; } .coming-soon-plugin { min-height: 260px; } .coming-soon h1, .coming-soon p { color: #fff; } .coming-soon h1 { font-size: 50px; line-height: 50px; margin-bottom: 15px; text-shadow: none; } .coming-soon p { font-size: 16px; line-height: 22px; } .coming-soon input { box-shadow: none; -moz-box-shadow: none; -webkit-box-shadow: none; } .coming-soon-copyright { padding: 5px 0; } .coming-soon-copyright p { color: #fff; text-align: right; } /*One Page ------------------------------------*/ .one-page { padding-left: 0; padding-right: 0; } .one-page h1, .one-page h2 { color: #fff; font-size: 30px; text-shadow: none; margin-bottom: 20px; } .one-page p { color: #fff; } .one-page .one-default p, .one-page .one-default h1, .one-page .one-default h2, .one-page .one-grey p, .one-page .one-grey h1, .one-page .one-grey h2 { color: #555; } .one-page .one-page-inner { padding: 30px 20px; min-height: 300px; } .one-page .one-page-btn { font-size: 20px !important; padding-left: 30px !important; padding-right: 30px !important; margin-bottom: 15px; } .one-page .btn-u { margin-bottom: 15px; } .one-page .one-default { background: #fff; } .one-page .one-grey { background: #fafafa; } .one-page .one-blue { background: #3498db; } .one-page .one-red { background: #e74c3c; } .one-page .one-orange { background: #e67e22; } .one-page .one-green { background: #2ecc71; } /*Search Page ------------------------------------*/ .search-page h2 { font-size: 28px; margin-bottom: 20px; } .booking-blocks { overflow: hidden; padding: 15px 20px; margin-bottom: 25px; background: #fafafa; -webkit-transition:all 0.3s ease-in-out; -moz-transition:all 0.3s ease-in-out; -o-transition:all 0.3s ease-in-out; transition:all 0.3s ease-in-out; } .booking-blocks:hover { border-radius:2px; background: #fafafa; box-shadow:0 0 8px #ddd; } .booking-blocks p a { color: #72c02c; } .booking-blocks .booking-img { width: 140px; margin-right: 10px; } .booking-blocks .booking-img li { color: #777; } .booking-blocks .booking-img li i { color: #78ccf8; font-size: 12px; margin-right: 5px; } .booking-blocks .booking-img img { float: left; width: 140px; height: auto; margin: 5px 10px 10px 0; } .booking-blocks h2 { margin-top: 0; font-size: 20px; line-height: 20px; } .booking-blocks ul.inline li { padding: 0; } .booking-blocks ul.inline li i { color: #f8be2c; cursor: pointer; font-size: 16px; } .booking-blocks ul.inline li i:hover { color: #f8be2c; } /*Others (Global classes) ------------------------------------*/ .color-red { color:#c00;} .color-green { color:#72c02c;} .color-blue { color:#3498db;} .pull-lft { text-align:left;} .pull-rgt { text-align:right;} .rgt-img-margin { margin:4px 0 5px 8px;} .lft-img-margin { margin:5px 20px 5px 0;} .overflow-hidden { overflow:hidden;} .padding-left-5 { padding-left:5px;} .img-width-200 { width:200px;} /*Image Border*/ .img-border { border:solid 3px #fff; } /*Background light-style*/ .bg-light { padding:10px 15px; border-radius:3px; margin-bottom:10px; background:#fcfcfc; } .bg-light:hover { padding:9px 14px; border:solid 1px #e5e5e5; } /*Link read-more*/ a.read-more { font-weight:bold; text-decoration:none; } a.read-more:hover { color:#72c02c; text-decoration:none; } /*Link color-green-style*/ .linked:hover { color:#72c02c; text-decoration:none; } /*CSS3 Hover Effects*/ .hover-effect { -webkit-transition:all 0.4s ease-in-out; -moz-transition:all 0.4s ease-in-out; -o-transition:all 0.4s ease-in-out; transition:all 0.4s ease-in-out; } .hover-effect-kenburn { left:10px; margin-left:-10px; position:relative; -webkit-transition: all 0.8s ease-in-out; -moz-transition: all 0.8s ease-in-out; -o-transition: all 0.8s ease-in-out; -ms-transition: all 0.8s ease-in-out; transition: all 0.8s ease-in-out; } .hover-effect-kenburn:hover { -webkit-transform: scale(2) rotate(5deg); -moz-transform: scale(2) rotate(5deg); -o-transform: scale(2) rotate(5deg); -ms-transform: scale(2) rotate(5deg); transform: scale(2) rotate(5deg); } /*Spaces*/ .margin-bottom-5, .margin-bottom-10, .margin-bottom-20, .margin-bottom-20, .margin-bottom-25, .margin-bottom-40, .margin-bottom-50, .margin-bottom-60 { clear:both; } .margin-bottom-5 { margin-bottom:5px; } .margin-bottom-10 { margin-bottom:10px; } .margin-bottom-20 { margin-bottom:20px; } .margin-bottom-25 { margin-bottom:25px; } .margin-bottom-30 { margin-bottom:30px; } .margin-bottom-40 { margin-bottom:40px; } .margin-bottom-50 { margin-bottom:50px; } .margin-bottom-60 { margin-bottom:60px; } .top-2 { top:2px; } /*Button Style*/ .btn { box-shadow: none; } .btn-u { border:0; font-size:14px; cursor:pointer; padding:5px 13px; position:relative; background:#72c02c; display:inline-block; color:#fff !important; text-decoration:none !important; } .btn-u:hover { color:#fff; background:#5fb611; text-decoration:none; -webkit-transition:all 0.4s ease-in-out; -moz-transition:all 0.4s ease-in-out; -o-transition:all 0.4s ease-in-out; transition:all 0.4s ease-in-out; } .btn-u-small { padding:3px 12px; } .btn-u-large { font-size:18px; padding:10px 25px; } a.btn-u { padding:4px 13px; vertical-align:middle; } a.btn-u-small { padding:2px 12px; } a.btn-u-large { font-size:18px; padding:6px 25px; } /*Buttons Color*/ .btn-u-blue { background: #3498db !important; } .btn-u-blue:hover { background: #2980b9 !important; } .btn-u-red { background: #e74c3c !important; } .btn-u-red:hover { background: #c0392b !important; } .btn-u-orange { background: #e67e22 !important; } .btn-u-orange:hover { background: #d35400 !important; } .btn-u-sea { background: #1abc9c !important; } .btn-u-sea:hover { background: #16a085 !important; } .btn-u-green { background: #2ecc71 !important; } .btn-u-green:hover { background: #27ae60 !important; } .btn-u-yellow { background: #F1C40F !important; } .btn-u-yellow:hover { background: #F39C12 !important; } /*Social Icons*/ .social-icons { margin:0; } .social-icons li { float:left; display:inline; list-style:none; margin-right:5px; margin-bottom:5px; text-indent:-9999px; } .social-icons li a, a.social-icon { width:28px; height:28px; display:block; background-position:0 0; background-repeat:no-repeat; transition: all 0.3s ease-in-out; -o-transition: all 0.3s ease-in-out; -ms-transition: all 0.3s ease-in-out; -moz-transition: all 0.3s ease-in-out; -webkit-transition: all 0.3s ease-in-out; } .social-icons li:hover a { background-position:0 -38px; } .social_amazon {background: url(../img/icons/social/amazon.png) no-repeat;} .social_behance {background: url(../img/icons/social/behance.png) no-repeat;} .social_blogger {background: url(../img/icons/social/blogger.png) no-repeat;} .social_deviantart {background: url(../img/icons/social/deviantart.png) no-repeat;} .social_dribbble {background: url(../img/icons/social/dribbble.png) no-repeat;} .social_dropbox {background: url(../img/icons/social/dropbox.png) no-repeat;} .social_evernote {background: url(../img/icons/social/evernote.png) no-repeat;} .social_facebook {background: url(../img/icons/social/facebook.png) no-repeat;} .social_forrst {background: url(../img/icons/social/forrst.png) no-repeat;} .social_github {background: url(../img/icons/social/github.png) no-repeat;} .social_googleplus {background: url(../img/icons/social/googleplus.png) no-repeat;} .social_jolicloud {background: url(../img/icons/social/jolicloud.png) no-repeat;} .social_last-fm {background: url(../img/icons/social/last-fm.png) no-repeat;} .social_linkedin {background: url(../img/icons/social/linkedin.png) no-repeat;} .social_picasa {background: url(../img/icons/social/picasa.png) no-repeat;} .social_pintrest {background: url(../img/icons/social/pintrest.png) no-repeat;} .social_rss {background: url(../img/icons/social/rss.png) no-repeat;} .social_skype {background: url(../img/icons/social/skype.png) no-repeat;} .social_spotify {background: url(../img/icons/social/spotify.png) no-repeat;} .social_stumbleupon {background: url(../img/icons/social/stumbleupon.png) no-repeat;} .social_tumblr {background: url(../img/icons/social/tumblr.png) no-repeat;} .social_twitter {background: url(../img/icons/social/twitter.png) no-repeat;} .social_vimeo {background: url(../img/icons/social/vimeo.png) no-repeat;} .social_wordpress {background: url(../img/icons/social/wordpress.png) no-repeat;} .social_xing {background: url(../img/icons/social/xing.png) no-repeat;} .social_yahoo {background: url(../img/icons/social/yahoo.png) no-repeat;} .social_youtube {background: url(../img/icons/social/youtube.png) no-repeat;} /*Glyphicons*/ .glyphicons-demo { text-align: ; } .glyphicons-demo .glyphicons { color: #999999; display: inline-block; font-size: 14px; line-height: 48px; margin-right: 20px; text-align: left; width: 150px; } .glyphicons-demo .glyphicons i:before { color: #666666; line-height: 55px !important; } .glyphicons-demo a:hover { color: #72c02c; text-decoration: none; } /*Style Switcher*/ i.style-switcher-btn { right: 0; top: 37px; color: #fff; font-size: 18px; cursor: pointer; z-index: 555555; position: fixed; padding: 7px 9px; background: #585f69; } i.style-switcher-btn:hover { background:#707985; } i.style-switcher-btn-option { top: 38px; background: #9097a0; } i.style-switcher-btn-option:hover { background: #707985; } .style-switcher { right: 0; top: 37px; display: none; z-index: 555555; position: fixed; background: #585f69; padding: 15px 15px 15px 20px; } .style-switcher-inner { background: #9097a0; } .style-switcher .theme-close { top: 10px; right: 6px; position: absolute; } .style-switcher .theme-close i { color: #fff; cursor: pointer; font-size: 16px; padding: 5px 7px; background: #464e5b; } .style-switcher .theme-close i:hover { color: #464e5b; background: #fff; } .style-switcher .theme-heading { color: #fff; font-size: 14px; margin-bottom: 10px; text-transform: uppercase; } .style-switcher ul { margin-bottom: 0; } .style-switcher li { width: 20px; height: 20px; cursor: pointer; background: #c00; margin-right: 5px; display: inline-block; border: solid 1px #70747a; } .style-switcher li:hover, .style-switcher li.theme-active { margin-right: 3px; border: solid 2px #fff; } .style-switcher li.theme-default { background: #72c02c; } .style-switcher li.theme-blue { background: #3498db; } .style-switcher li.theme-orange { background: #e67e22; } .style-switcher li.theme-red { background: #e74c3c; } .style-switcher li.theme-light { background: #ecf0f1; } /*Revolution Slider*/ .bg-black-opacity { background: url(../img/sliders/revolution/bg-text.png) repeat; padding: 7px; text-shadow: none !important; } /*peach add-------index lis-group*/ .list-group>li{line-height:40px} .row-fluid .carousel .carousel-indicators{ top:85%; margin-left:40%; margin-right:47%; } @media(min-width:414px){ .row-fluid .carousel .carousel-indicators{ top:80%; margin-left:38%; margin-right:38%; } } /*插件样式*/ /* .poster-main{position: relative;width: 900px;height: 270px} .poster-main a,.poster-main img{display:block;} .poster-main .poster-list{width: 900px;height: 270px;margin:0} .poster-main .poster-list .poster-item{position: absolute;left: 0px;top: 0px} .poster-main .poster-btn{position: absolute;height: 100%;width:100px;top: 0px;z-index: 10;opacity: 0.3;} .poster-main .poster-prev-btn{left: 0px;background: url("images/img/carousel/btn_l.png") no-repeat center center; } .poster-main .poster-next-btn{right: 0px;background: url("images/img/carousel/btn_r.png") no-repeat center center;} */
20.616923
116
0.599309
c6b25dc2f61f06fb3348a1ba99464e08a3d476a4
56
py
Python
cotidia/stripe/__init__.py
guillaumepiot/cotidia-stripe
f23329e8363c3d8577acf9633966d6af61c090eb
[ "BSD-3-Clause" ]
null
null
null
cotidia/stripe/__init__.py
guillaumepiot/cotidia-stripe
f23329e8363c3d8577acf9633966d6af61c090eb
[ "BSD-3-Clause" ]
null
null
null
cotidia/stripe/__init__.py
guillaumepiot/cotidia-stripe
f23329e8363c3d8577acf9633966d6af61c090eb
[ "BSD-3-Clause" ]
null
null
null
default_app_config = 'cotidia.stripe.apps.StripeConfig'
28
55
0.839286
b0e4c0a581ab78e0cacf0e6c26f3b1787787c271
952
py
Python
cdApi/task.py
renqiukai/cd_api
4f1f641adaf031252b097db03249a2581268cc11
[ "MIT" ]
null
null
null
cdApi/task.py
renqiukai/cd_api
4f1f641adaf031252b097db03249a2581268cc11
[ "MIT" ]
null
null
null
cdApi/task.py
renqiukai/cd_api
4f1f641adaf031252b097db03249a2581268cc11
[ "MIT" ]
null
null
null
''' @说明 :任务接口。 @时间 :2020/3/19 下午4:51:48 @作者 :任秋锴 @版本 :1.0 ''' from .base import base class task(base): def __init__(self, token): super().__init__(token) def list(self, pageNum=1, pageSize=10): api_name = "manager/task/list" data = { "pageNum": pageNum, "pageSize": pageSize, } return self.request(api_name, data) def create(self, data): api_name = "manager/task/add" return self.request(api_name, data, method="POST") def read(self, _id): api_name = "manager/task/info" data = { "id": _id, } response = self.request(api_name, data, method="GET") return self.response(response) def update(self, data): api_name = "manager/task/update" response = self.request(api_name, data, method="POST") return self.response(response) def delete(self): pass
22.666667
62
0.557773
d8e00ef4903152bb60a1e30cb39030037160fb7b
515
rb
Ruby
public/www/app.rb
doudizhu/activity
00eda1489d205215a5d7caee7b994c228a55a4f8
[ "Apache-2.0" ]
1
2020-05-26T01:55:26.000Z
2020-05-26T01:55:26.000Z
public/www/app.rb
doudizhu/activity
00eda1489d205215a5d7caee7b994c228a55a4f8
[ "Apache-2.0" ]
null
null
null
public/www/app.rb
doudizhu/activity
00eda1489d205215a5d7caee7b994c228a55a4f8
[ "Apache-2.0" ]
null
null
null
ENV['RACK_ENV'] ||= "development" require 'sinatra' require 'haml' require 'moode-haml-toolkit/component_helper' require 'jt-partial' if File.exist? "component/custom.rb" load "component/custom.rb" end require 'moode-haml-toolkit/component_generator' require 'moode-haml-component-angular' configure do set :views, File.join(File.dirname(__FILE__), 'hamls') set :public_folder, File.dirname(__FILE__) end get "/" do haml :index end get "/pages/:name.html" do haml "pages/#{params[:name]}".to_sym end
19.807692
56
0.737864
da38577ee2d6238f680c0501056389e361ebdc5b
961
php
PHP
application/models/m_book.php
yanuaraditia/cip
99127fab7ff19d22e8ead9ab261316e65ce7b2e1
[ "Apache-2.0" ]
1
2021-03-25T06:43:10.000Z
2021-03-25T06:43:10.000Z
application/models/m_book.php
yanuaraditia/cip
99127fab7ff19d22e8ead9ab261316e65ce7b2e1
[ "Apache-2.0" ]
null
null
null
application/models/m_book.php
yanuaraditia/cip
99127fab7ff19d22e8ead9ab261316e65ce7b2e1
[ "Apache-2.0" ]
null
null
null
<?php class M_book extends CI_Model{ function list_lantai(){ $id = base64_decode($this->input->get('id')); $lantai=$this->db->get_where('lantai',array('kd_lokasi'=>$id)); return $lantai; } function detail_lokasi() { $id = base64_decode($this->input->get('id')); $detail = $this->db->get_where('lokasi',array('kd_lokasi'=>$id)); return $detail; } function book_confirm($data) { $this->db->insert('booking',$data); } function show_slot($kd_lantai) { return $this->db->get_where('slot',array('kd_lantai' => $kd_lantai)); } function book_check($id_user) { $this->db->select('id_user'); $this->db->from('booking'); $this->db->where(array( 'status != ' => 2, 'id_user' => $id_user )); return $this->db->get(); } }
33.137931
81
0.490114
79b27fdabe0c72ca5a6d42a540e3d0d3803734d4
753
rb
Ruby
spec/spec_helper.rb
lokalportal/json-schema_dsl
edec20f4416a7569b753d34d6c6db3b2f468462b
[ "MIT" ]
1
2019-11-13T20:48:36.000Z
2019-11-13T20:48:36.000Z
spec/spec_helper.rb
lokalportal/json-schema_dsl
edec20f4416a7569b753d34d6c6db3b2f468462b
[ "MIT" ]
null
null
null
spec/spec_helper.rb
lokalportal/json-schema_dsl
edec20f4416a7569b753d34d6c6db3b2f468462b
[ "MIT" ]
null
null
null
# frozen_string_literal: true require 'bundler/setup' require 'pry' require 'json/schema_dsl' module DummyRender class Dummy include JSON::SchemaDsl def self.parse(&block) new.object(&block) end def self.render(&block) parse(&block).as_json end end def parsed(&block) Dummy.parse(&block) end def rendered(&block) Dummy.render(&block) end end RSpec.configure do |config| # Enable flags like --only-failures and --next-failure config.example_status_persistence_file_path = '.rspec_status' # Disable RSpec exposing methods globally on `Module` and `main` # config.disable_monkey_patching! config.include DummyRender config.expect_with :rspec do |c| c.syntax = :expect end end
17.928571
66
0.705179
c6979248d7452afe98ee6daf4eddfca4be84c67f
4,209
py
Python
djangoerp/menus/tests/test_signals.py
xarala221/django-erp
f84ee8ab193b3b06ee4522ac3c888ed47396e795
[ "MIT" ]
345
2015-02-16T17:36:32.000Z
2022-01-13T11:04:35.000Z
djangoerp/menus/tests/test_signals.py
xarala221/django-erp
f84ee8ab193b3b06ee4522ac3c888ed47396e795
[ "MIT" ]
22
2015-09-11T13:29:00.000Z
2021-11-27T18:47:38.000Z
djangoerp/menus/tests/test_signals.py
xarala221/django-erp
f84ee8ab193b3b06ee4522ac3c888ed47396e795
[ "MIT" ]
243
2015-03-31T12:08:30.000Z
2022-01-29T08:23:53.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals """This file is part of the django ERP project. 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. """ __author__ = 'Emanuele Bertoldi <emanuele.bertoldi@gmail.com>' __copyright__ = 'Copyright (c) 2013-2015, django ERP Team' __version__ = '0.0.5' from django.test import TestCase from django.contrib.auth import get_user_model from . import * from ..models import * from ..utils import * from ..signals import * class SignalTestCase(TestCase): def test_bookmarks_auto_creation_for_users(self): """Tests a bookmarks list must be auto-created for new users. """ self.assertEqual(Menu.objects.filter(slug="user_1_bookmarks").count(), 0) u1 = get_user_model().objects.create(username="u1") self.assertEqual(Menu.objects.filter(slug="user_1_bookmarks").count(), 1) def test_bookmarks_stop_auto_creation(self): """Tests disabling bookmarks list auto-creation. """ user_model = get_user_model() self.assertEqual(Menu.objects.filter(slug="user_2_bookmarks").count(), 0) manage_bookmarks(user_model, False) # Disable auto-creation. u2 = user_model.objects.create(username="u2") self.assertEqual(Menu.objects.filter(slug="user_2_bookmarks").count(), 0) manage_bookmarks(user_model) # Enable auto-creation. def test_manage_author_permissions_on_bookmarks(self): """Tests that "manage_author_permissions" auto-generate perms for author. """ u1, n = get_user_model().objects.get_or_create(username="u1") bookmarks = get_bookmarks_for(u1.username) self.assertTrue(ob.has_perm(u1, "menus.view_menu", bookmarks)) self.assertTrue(ob.has_perm(u1, "menus.change_menu", bookmarks)) self.assertTrue(ob.has_perm(u1, "menus.delete_menu", bookmarks)) def test_manage_author_permissions_on_bookmark(self): """Tests that "manage_author_permissions" auto-generate perms for author. """ user_model = get_user_model() u2, n = user_model.objects.get_or_create(username="u2") u3, n = user_model.objects.get_or_create(username="u3") prev_user = logged_cache.user # The current author ("logged" user) is now u2. logged_cache.user = u2 b1, n = Bookmark.objects.get_or_create(menu=get_bookmarks_for(u2.username), title="b1", url="/") self.assertTrue(ob.has_perm(u2, "menus.view_link", b1)) self.assertTrue(ob.has_perm(u2, "menus.change_link", b1)) self.assertTrue(ob.has_perm(u2, "menus.delete_link", b1)) self.assertFalse(ob.has_perm(u3, "menus.view_link", b1)) self.assertFalse(ob.has_perm(u3, "menus.change_link", b1)) self.assertFalse(ob.has_perm(u3, "menus.delete_link", b1)) # Restores previous cached user. logged_cache.user = prev_user def test_bookmarks_auto_deletion(self): """Tests automatic deletion of bookmarks when their owners are deleted. """ d = None try: d = get_bookmarks_for("u4") except: pass self.assertEqual(d, None) u4, n = get_user_model().objects.get_or_create(username="u4") try: d = get_bookmarks_for("u4") except: pass self.assertNotEqual(d, None) u4.delete() try: d = get_bookmarks_for("u4") except: d = None self.assertEqual(d, None)
35.974359
104
0.633405
14481789019b5e581cc16cd5b1ea2766f530ab4b
57
ts
TypeScript
src/configs/envTXT.ts
zalddeve/aocrunner
eb197ce4bce606643fe6968ab0f59d0c2e1e5d8d
[ "ISC" ]
57
2021-11-18T03:42:41.000Z
2022-01-15T11:55:31.000Z
src/configs/envTXT.ts
zalddeve/aocrunner
eb197ce4bce606643fe6968ab0f59d0c2e1e5d8d
[ "ISC" ]
9
2021-12-01T09:11:27.000Z
2022-01-11T14:29:41.000Z
src/configs/envTXT.ts
zalddeve/aocrunner
eb197ce4bce606643fe6968ab0f59d0c2e1e5d8d
[ "ISC" ]
9
2021-11-22T14:14:22.000Z
2021-12-31T14:58:05.000Z
const envTXT = "AOC_SESSION_KEY=" export default envTXT
14.25
33
0.789474
1a549560261a63320b9227e19aa83105f1786024
107
py
Python
exercises/ex014.py
mouraa0/python-exercises
78ecf1cb0d1dfd7dfbdd05574cce5cd6a5cba0f1
[ "MIT" ]
null
null
null
exercises/ex014.py
mouraa0/python-exercises
78ecf1cb0d1dfd7dfbdd05574cce5cd6a5cba0f1
[ "MIT" ]
null
null
null
exercises/ex014.py
mouraa0/python-exercises
78ecf1cb0d1dfd7dfbdd05574cce5cd6a5cba0f1
[ "MIT" ]
null
null
null
c = float(input('Temperatura em °C: ')) f = (((c*9)/5)+32) print('{:.1f}°C é igual a {:.1f}°F'.format(c,f))
35.666667
48
0.53271
e44ac6f64287891a0628c46a769e49425b55a688
414
sql
SQL
resources/migrations/20200722-01-add-structured-address-to-polling-location.up.sql
votinginfoproject/data-processor
1aaf2e030e8e4d2645bde9f1002f331b0c036d11
[ "BSD-3-Clause" ]
10
2016-11-02T04:37:58.000Z
2020-09-18T10:14:58.000Z
resources/migrations/20200722-01-add-structured-address-to-polling-location.up.sql
votinginfoproject/data-processor
1aaf2e030e8e4d2645bde9f1002f331b0c036d11
[ "BSD-3-Clause" ]
225
2015-02-03T20:34:01.000Z
2021-08-30T19:33:14.000Z
resources/migrations/20200722-01-add-structured-address-to-polling-location.up.sql
votinginfoproject/data-processor
1aaf2e030e8e4d2645bde9f1002f331b0c036d11
[ "BSD-3-Clause" ]
4
2015-11-07T17:37:08.000Z
2018-10-17T19:29:47.000Z
ALTER TABLE v5_2_polling_locations ADD COLUMN structured_line_1 text; ALTER TABLE v5_2_polling_locations ADD COLUMN structured_line_2 text; ALTER TABLE v5_2_polling_locations ADD COLUMN structured_line_3 text; ALTER TABLE v5_2_polling_locations ADD COLUMN structured_city text; ALTER TABLE v5_2_polling_locations ADD COLUMN structured_state text; ALTER TABLE v5_2_polling_locations ADD COLUMN structured_zip text;
59.142857
69
0.884058
c3ca53868aa63bcf3040b5226c89487f1fb23cd0
5,847
cs
C#
src/DSharp.Mscorlib/NonStandard/Array.cs
strofimo/dsharp
871714a11bebe5dbf90b14c17694489fc35a19c8
[ "Apache-2.0" ]
null
null
null
src/DSharp.Mscorlib/NonStandard/Array.cs
strofimo/dsharp
871714a11bebe5dbf90b14c17694489fc35a19c8
[ "Apache-2.0" ]
null
null
null
src/DSharp.Mscorlib/NonStandard/Array.cs
strofimo/dsharp
871714a11bebe5dbf90b14c17694489fc35a19c8
[ "Apache-2.0" ]
null
null
null
using System.Collections; using System.Runtime.CompilerServices; using NonStandard; namespace System { public partial class Array { private Array() { } [ScriptName("push")] [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] public extern void AddRange(params object[] items); [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] public extern Array Concat(params object[] objects); [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] public extern bool Every(ArrayFilterCallback filterCallback); [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] public extern bool Every(ArrayItemFilterCallback itemFilterCallback); [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] public extern Array Filter(ArrayFilterCallback filterCallback); [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] public extern Array Filter(ArrayItemFilterCallback itemFilterCallback); [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] public extern void ForEach(ArrayCallback callback); [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] public extern void ForEach(ArrayItemCallback itemCallback); [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] public extern int IndexOf(object item, int startIndex); [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] public extern string Join(); [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] public extern string Join(string delimiter); [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] public extern int LastIndexOf(object item); [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] public extern int LastIndexOf(object item, int fromIndex); [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] [DSharpScriptMemberName("array")] public extern static Array ToArray(object o); [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] public extern Array Map(ArrayMapCallback mapCallback); [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] public extern Array Map(ArrayItemMapCallback mapItemCallback); [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] public extern static Array Parse(string s); [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] public extern object Reduce(ArrayReduceCallback callback); [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] public extern object Reduce(ArrayReduceCallback callback, object initialValue); [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] public extern object Reduce(ArrayItemReduceCallback callback); [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] public extern object Reduce(ArrayItemReduceCallback callback, object initialValue); [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] public extern object ReduceRight(ArrayReduceCallback callback); [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] public extern object ReduceRight(ArrayReduceCallback callback, object initialValue); [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] public extern object ReduceRight(ArrayItemReduceCallback callback); [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] public extern object ReduceRight(ArrayItemReduceCallback callback, object initialValue); [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] public extern void Reverse(); [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] public extern object Shift(); [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] public extern Array Slice(int start); [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] public extern Array Slice(int start, int end); [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] public extern bool Some(ArrayFilterCallback filterCallback); [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] public extern bool Some(ArrayItemFilterCallback itemFilterCallback); [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] public extern void Sort(); [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] public extern void Sort(CompareCallback compareCallback); [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] public extern void Splice(int start, int deleteCount); [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] public extern void Splice(int start, int deleteCount, params object[] itemsToInsert); [Obsolete(ObsoleteConsts.MESSAGE_ON_OBSOLETE, ObsoleteConsts.ERROR_ON_OBSOLETE)] public extern void Unshift(params object[] items); } }
47.92623
96
0.769112
c07669541a3be40d41d4a0f5d806e76f9374f29e
1,928
lua
Lua
Data/Scripts/LootPickup.lua
Core-Team-META/CC-Cosmetic-Store
7e8631b4329b393eea0235b1761f94504b5f97bc
[ "Apache-2.0" ]
null
null
null
Data/Scripts/LootPickup.lua
Core-Team-META/CC-Cosmetic-Store
7e8631b4329b393eea0235b1761f94504b5f97bc
[ "Apache-2.0" ]
null
null
null
Data/Scripts/LootPickup.lua
Core-Team-META/CC-Cosmetic-Store
7e8631b4329b393eea0235b1761f94504b5f97bc
[ "Apache-2.0" ]
null
null
null
--[[ Copyright 2020 Manticore Games, Inc. 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. --]] local root = script.parent local RESOURCE_NAME = root:GetCustomProperty("ResourceName") local RESOURCE_AMOUNT_MIN = root:GetCustomProperty("ResourceMin") local RESOURCE_AMOUNT_MAX = root:GetCustomProperty("ResourceMax") local TRIGGER = root:GetCustomProperty("Trigger"):WaitForObject() local PICKUP_FX_TEMPLATE = root:GetCustomProperty("PickupFX") local VFX_POS = script:GetWorldPosition() function SpawnPickupVFX() if PICKUP_FX_TEMPLATE then World.SpawnAsset(PICKUP_FX_TEMPLATE, {position = VFX_POS}) end end function AddRewards(player) local amount = math.random(RESOURCE_AMOUNT_MIN, RESOURCE_AMOUNT_MAX) player:AddResource(RESOURCE_NAME, amount) end function OnBeginOverlap(trigger, other) if other:IsA("Player") then SpawnPickupVFX() AddRewards(other) script.parent:Destroy() end end TRIGGER.beginOverlapEvent:Connect(OnBeginOverlap)
41.913043
118
0.806017
dcf64ca35af7fb18ef3e759348a90a237ac6d3a3
134
rb
Ruby
lib/equitrac_utilities.rb
LAS-IT/equitrac_utilities
f2fe45471d3c75b35f211006c2e507566bb9a5e1
[ "MIT" ]
null
null
null
lib/equitrac_utilities.rb
LAS-IT/equitrac_utilities
f2fe45471d3c75b35f211006c2e507566bb9a5e1
[ "MIT" ]
1
2020-03-03T15:07:13.000Z
2020-03-03T15:07:13.000Z
lib/equitrac_utilities.rb
LAS-IT/equitrac_utilities
f2fe45471d3c75b35f211006c2e507566bb9a5e1
[ "MIT" ]
null
null
null
require "equitrac_utilities/version" require "equitrac_utilities/connection" module EquitracUtilities # Your code goes here... end
19.142857
39
0.813433
e24971ff980f7ec446e598a55149376c52a4c864
133
py
Python
python/testData/optimizeImports/orderByType.after.py
truthiswill/intellij-community
fff88cfb0dc168eea18ecb745d3e5b93f57b0b95
[ "Apache-2.0" ]
2
2019-04-28T07:48:50.000Z
2020-12-11T14:18:08.000Z
python/testData/optimizeImports/orderByType.after.py
truthiswill/intellij-community
fff88cfb0dc168eea18ecb745d3e5b93f57b0b95
[ "Apache-2.0" ]
173
2018-07-05T13:59:39.000Z
2018-08-09T01:12:03.000Z
python/testData/optimizeImports/orderByType.after.py
truthiswill/intellij-community
fff88cfb0dc168eea18ecb745d3e5b93f57b0b95
[ "Apache-2.0" ]
2
2020-03-15T08:57:37.000Z
2020-04-07T04:48:14.000Z
from __future__ import with_statement import datetime import sys import foo from bar import * sys.path datetime.datetime foo.bar()
12.090909
37
0.81203
134784d1137e7e596acc64800ec15345c83b1838
27,299
c
C
minimal-examples-lowlevel/api-tests/api-test-cose/keys.c
horchi/libwebsockets
e1a73c42096a9f94617a25440501d7adc4abbd9f
[ "Apache-2.0" ]
3,539
2015-01-02T18:31:36.000Z
2022-03-30T09:56:47.000Z
minimal-examples-lowlevel/api-tests/api-test-cose/keys.c
horchi/libwebsockets
e1a73c42096a9f94617a25440501d7adc4abbd9f
[ "Apache-2.0" ]
2,393
2015-01-06T08:43:52.000Z
2022-03-31T14:09:09.000Z
minimal-examples-lowlevel/api-tests/api-test-cose/keys.c
horchi/libwebsockets
e1a73c42096a9f94617a25440501d7adc4abbd9f
[ "Apache-2.0" ]
1,483
2015-01-04T11:33:23.000Z
2022-03-30T17:45:00.000Z
/* * lws-api-test-jose - RFC8152 cose_key tests * * Written in 2010-2021 by Andy Green <andy@warmcat.com> * * This file is made available under the Creative Commons CC0 1.0 * Universal Public Domain Dedication. * * Raw key CBOR created from descriptions at * * https://github.com/cose-wg/Examples/blob/master/KeySet.txt */ #include <libwebsockets.h> #include <stdlib.h> #include <fcntl.h> static int key_import_cb(struct lws_cose_key *s, void *user) { lwsl_notice("%s: key type %lld\n", __func__, (long long)s->kty); return 0; } static const uint8_t cose_key1[] = { 0xa6, 0x01, 0x02, 0x02, 0x62, 0x31, 0x31, 0x20, 0x01, 0x21, 0x58, 0x20, 0xba, 0xc5, 0xb1, 0x1c, 0xad, 0x8f, 0x99, 0xf9, 0xc7, 0x2b, 0x05, 0xcf, 0x4b, 0x9e, 0x26, 0xd2, 0x44, 0xdc, 0x18, 0x9f, 0x74, 0x52, 0x28, 0x25, 0x5a, 0x21, 0x9a, 0x86, 0xd6, 0xa0, 0x9e, 0xff, 0x22, 0x58, 0x20, 0x20, 0x13, 0x8b, 0xf8, 0x2d, 0xc1, 0xb6, 0xd5, 0x62, 0xbe, 0x0f, 0xa5, 0x4a, 0xb7, 0x80, 0x4a, 0x3a, 0x64, 0xb6, 0xd7, 0x2c, 0xcf, 0xed, 0x6b, 0x6f, 0xb6, 0xed, 0x28, 0xbb, 0xfc, 0x11, 0x7e, 0x23, 0x58, 0x20, 0x57, 0xc9, 0x20, 0x77, 0x66, 0x41, 0x46, 0xe8, 0x76, 0x76, 0x0c, 0x95, 0x20, 0xd0, 0x54, 0xaa, 0x93, 0xc3, 0xaf, 0xb0, 0x4e, 0x30, 0x67, 0x05, 0xdb, 0x60, 0x90, 0x30, 0x85, 0x07, 0xb4, 0xd3 }, cose_key2[] = { 0xa6, 0x01, 0x02, 0x02, 0x78, 0x24, 0x6d, 0x65, 0x72, 0x69, 0x61, 0x64, 0x6f, 0x63, 0x2e, 0x62, 0x72, 0x61, 0x6e, 0x64, 0x79, 0x62, 0x75, 0x63, 0x6b, 0x40, 0x62, 0x75, 0x63, 0x6b, 0x6c, 0x61, 0x6e, 0x64, 0x2e, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x20, 0x01, 0x21, 0x58, 0x20, 0x65, 0xed, 0xa5, 0xa1, 0x25, 0x77, 0xc2, 0xba, 0xe8, 0x29, 0x43, 0x7f, 0xe3, 0x38, 0x70, 0x1a, 0x10, 0xaa, 0xa3, 0x75, 0xe1, 0xbb, 0x5b, 0x5d, 0xe1, 0x08, 0xde, 0x43, 0x9c, 0x08, 0x55, 0x1d, 0x22, 0x58, 0x20, 0x1e, 0x52, 0xed, 0x75, 0x70, 0x11, 0x63, 0xf7, 0xf9, 0xe4, 0x0d, 0xdf, 0x9f, 0x34, 0x1b, 0x3d, 0xc9, 0xba, 0x86, 0x0a, 0xf7, 0xe0, 0xca, 0x7c, 0xa7, 0xe9, 0xee, 0xcd, 0x00, 0x84, 0xd1, 0x9c, 0x23, 0x58, 0x20, 0xaf, 0xf9, 0x07, 0xc9, 0x9f, 0x9a, 0xd3, 0xaa, 0xe6, 0xc4, 0xcd, 0xf2, 0x11, 0x22, 0xbc, 0xe2, 0xbd, 0x68, 0xb5, 0x28, 0x3e, 0x69, 0x07, 0x15, 0x4a, 0xd9, 0x11, 0x84, 0x0f, 0xa2, 0x08, 0xcf }, cose_key3[] = { 0xa3, 0x01, 0x04, 0x02, 0x6a, 0x6f, 0x75, 0x72, 0x2d, 0x73, 0x65, 0x63, 0x72, 0x65, 0x74, 0x20, 0x58, 0x20, 0x84, 0x9b, 0x57, 0x21, 0x9d, 0xae, 0x48, 0xde, 0x64, 0x6d, 0x07, 0xdb, 0xb5, 0x33, 0x56, 0x6e, 0x97, 0x66, 0x86, 0x45, 0x7c, 0x14, 0x91, 0xbe, 0x3a, 0x76, 0xdc, 0xea, 0x6c, 0x42, 0x71, 0x88 }, cose_key4[] = { 0xa6, 0x01, 0x02, 0x02, 0x78, 0x1e, 0x62, 0x69, 0x6c, 0x62, 0x6f, 0x2e, 0x62, 0x61, 0x67, 0x67, 0x69, 0x6e, 0x73, 0x40, 0x68, 0x6f, 0x62, 0x62, 0x69, 0x74, 0x6f, 0x6e, 0x2e, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x20, 0x03, 0x21, 0x58, 0x42, 0x00, 0x72, 0x99, 0x2c, 0xb3, 0xac, 0x08, 0xec, 0xf3, 0xe5, 0xc6, 0x3d, 0xed, 0xec, 0x0d, 0x51, 0xa8, 0xc1, 0xf7, 0x9e, 0xf2, 0xf8, 0x2f, 0x94, 0xf3, 0xc7, 0x37, 0xbf, 0x5d, 0xe7, 0x98, 0x66, 0x71, 0xea, 0xc6, 0x25, 0xfe, 0x82, 0x57, 0xbb, 0xd0, 0x39, 0x46, 0x44, 0xca, 0xaa, 0x3a, 0xaf, 0x8f, 0x27, 0xa4, 0x58, 0x5f, 0xbb, 0xca, 0xd0, 0xf2, 0x45, 0x76, 0x20, 0x08, 0x5e, 0x5c, 0x8f, 0x42, 0xad, 0x22, 0x58, 0x42, 0x01, 0xdc, 0xa6, 0x94, 0x7b, 0xce, 0x88, 0xbc, 0x57, 0x90, 0x48, 0x5a, 0xc9, 0x74, 0x27, 0x34, 0x2b, 0xc3, 0x5f, 0x88, 0x7d, 0x86, 0xd6, 0x5a, 0x08, 0x93, 0x77, 0xe2, 0x47, 0xe6, 0x0b, 0xaa, 0x55, 0xe4, 0xe8, 0x50, 0x1e, 0x2a, 0xda, 0x57, 0x24, 0xac, 0x51, 0xd6, 0x90, 0x90, 0x08, 0x03, 0x3e, 0xbc, 0x10, 0xac, 0x99, 0x9b, 0x9d, 0x7f, 0x5c, 0xc2, 0x51, 0x9f, 0x3f, 0xe1, 0xea, 0x1d, 0x94, 0x75, 0x23, 0x58, 0x42, 0x00, 0x08, 0x51, 0x38, 0xdd, 0xab, 0xf5, 0xca, 0x97, 0x5f, 0x58, 0x60, 0xf9, 0x1a, 0x08, 0xe9, 0x1d, 0x6d, 0x5f, 0x9a, 0x76, 0xad, 0x40, 0x18, 0x76, 0x6a, 0x47, 0x66, 0x80, 0xb5, 0x5c, 0xd3, 0x39, 0xe8, 0xab, 0x6c, 0x72, 0xb5, 0xfa, 0xcd, 0xb2, 0xa2, 0xa5, 0x0a, 0xc2, 0x5b, 0xd0, 0x86, 0x64, 0x7d, 0xd3, 0xe2, 0xe6, 0xe9, 0x9e, 0x84, 0xca, 0x2c, 0x36, 0x09, 0xfd, 0xf1, 0x77, 0xfe, 0xb2, 0x6d }, cose_key5[] = { 0xa3, 0x01, 0x04, 0x02, 0x6b, 0x6f, 0x75, 0x72, 0x2d, 0x73, 0x65, 0x63, 0x72, 0x65, 0x74, 0x32, 0x20, 0x50, 0x84, 0x9b, 0x57, 0x86, 0x45, 0x7c, 0x14, 0x91, 0xbe, 0x3a, 0x76, 0xdc, 0xea, 0x6c, 0x42, 0x71 }, cose_key6[] = { 0xa6, 0x01, 0x02, 0x02, 0x78, 0x21, 0x70, 0x65, 0x72, 0x65, 0x67, 0x72, 0x69, 0x6e, 0x2e, 0x74, 0x6f, 0x6f, 0x6b, 0x40, 0x74, 0x75, 0x63, 0x6b, 0x62, 0x6f, 0x72, 0x6f, 0x75, 0x67, 0x68, 0x2e, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x20, 0x01, 0x21, 0x58, 0x20, 0x98, 0xf5, 0x0a, 0x4f, 0xf6, 0xc0, 0x58, 0x61, 0xc8, 0x86, 0x0d, 0x13, 0xa6, 0x38, 0xea, 0x56, 0xc3, 0xf5, 0xad, 0x75, 0x90, 0xbb, 0xfb, 0xf0, 0x54, 0xe1, 0xc7, 0xb4, 0xd9, 0x1d, 0x62, 0x80, 0x22, 0x58, 0x20, 0xf0, 0x14, 0x00, 0xb0, 0x89, 0x86, 0x78, 0x04, 0xb8, 0xe9, 0xfc, 0x96, 0xc3, 0x93, 0x21, 0x61, 0xf1, 0x93, 0x4f, 0x42, 0x23, 0x06, 0x91, 0x70, 0xd9, 0x24, 0xb7, 0xe0, 0x3b, 0xf8, 0x22, 0xbb, 0x23, 0x58, 0x20, 0x02, 0xd1, 0xf7, 0xe6, 0xf2, 0x6c, 0x43, 0xd4, 0x86, 0x8d, 0x87, 0xce, 0xb2, 0x35, 0x31, 0x61, 0x74, 0x0a, 0xac, 0xf1, 0xf7, 0x16, 0x36, 0x47, 0x98, 0x4b, 0x52, 0x2a, 0x84, 0x8d, 0xf1, 0xc3 }, cose_key7[] = { 0xa3, 0x01, 0x04, 0x02, 0x58, 0x24, 0x30, 0x31, 0x38, 0x63, 0x30, 0x61, 0x65, 0x35, 0x2d, 0x34, 0x64, 0x39, 0x62, 0x2d, 0x34, 0x37, 0x31, 0x62, 0x2d, 0x62, 0x66, 0x64, 0x36, 0x2d, 0x65, 0x65, 0x66, 0x33, 0x31, 0x34, 0x62, 0x63, 0x37, 0x30, 0x33, 0x37, 0x20, 0x58, 0x20, 0x84, 0x9b, 0x57, 0x21, 0x9d, 0xae, 0x48, 0xde, 0x64, 0x6d, 0x07, 0xdb, 0xb5, 0x33, 0x56, 0x6e, 0x97, 0x66, 0x86, 0x45, 0x7c, 0x14, 0x91, 0xbe, 0x3a, 0x76, 0xdc, 0xea, 0x6c, 0x42, 0x71, 0x88 }, cose_key8[] = { /* kid "sec-48" for hmac 384 */ 0xa3, 0x01, 0x04, 0x02, 0x66, 0x73, 0x65, 0x63, 0x2d, 0x34, 0x38, 0x20, 0x58, 0x30, 0x84, 0x9b, 0x57, 0x21, 0x9d, 0xae, 0x48, 0xde, 0x64, 0x6d, 0x07, 0xdb, 0xb5, 0x33, 0x56, 0x6e, 0x97, 0x66, 0x86, 0x45, 0x7c, 0x14, 0x91, 0xbe, 0x3a, 0x76, 0xdc, 0xea, 0x6c, 0x42, 0x71, 0x88, 0x00, 0x11, 0x22, 0x33, 0x77, 0x88, 0x99, 0xaa, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28 }, cose_key9[] = { /* kid "sec-64" for hmac 512 */ 0xa3, 0x01, 0x04, 0x02, 0x46, 0x73, 0x65, 0x63, 0x2d, 0x36, 0x34, 0x20, 0x58, 0x40, 0x84, 0x9b, 0x57, 0x21, 0x9d, 0xae, 0x48, 0xde, 0x64, 0x6d, 0x07, 0xdb, 0xb5, 0x33, 0x56, 0x6e, 0x97, 0x66, 0x86, 0x45, 0x7c, 0x14, 0x91, 0xbe, 0x3a, 0x76, 0xdc, 0xea, 0x6c, 0x42, 0x71, 0x88, 0x00, 0x11, 0x22, 0x33, 0x77, 0x88, 0x99, 0xaa, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xa0, 0xb1, 0xb2, 0xb3, 0xb4, }, cose_key10[] = { /* kid "11" (again) ed22519 OKP key */ 0xa5, 0x01, 0x01, 0x02, 0x42, 0x31, 0x31, 0x20, 0x06, 0x21, 0x58, 0x20, 0xd7, 0x5a, 0x98, 0x01, 0x82, 0xb1, 0x0a, 0xb7, 0xd5, 0x4b, 0xfe, 0xd3, 0xc9, 0x64, 0x07, 0x3a, 0x0e, 0xe1, 0x72, 0xf3, 0xda, 0xa6, 0x23, 0x25, 0xaf, 0x02, 0x1a, 0x68, 0xf7, 0x07, 0x51, 0x1a, 0x23, 0x58, 0x20, 0x9d, 0x61, 0xb1, 0x9d, 0xef, 0xfd, 0x5a, 0x60, 0xba, 0x84, 0x4a, 0xf4, 0x92, 0xec, 0x2c, 0xc4, 0x44, 0x49, 0xc5, 0x69, 0x7b, 0x32, 0x69, 0x19, 0x70, 0x3b, 0xac, 0x03, 0x1c, 0xae, 0x7f, 0x60 }, cose_key_set1[] = { 0x89, 0xa6, 0x01, 0x02, 0x02, 0x42, 0x31, 0x31, 0x20, 0x01, 0x21, 0x58, 0x20, 0xba, 0xc5, 0xb1, 0x1c, 0xad, 0x8f, 0x99, 0xf9, 0xc7, 0x2b, 0x05, 0xcf, 0x4b, 0x9e, 0x26, 0xd2, 0x44, 0xdc, 0x18, 0x9f, 0x74, 0x52, 0x28, 0x25, 0x5a, 0x21, 0x9a, 0x86, 0xd6, 0xa0, 0x9e, 0xff, 0x22, 0x58, 0x20, 0x20, 0x13, 0x8b, 0xf8, 0x2d, 0xc1, 0xb6, 0xd5, 0x62, 0xbe, 0x0f, 0xa5, 0x4a, 0xb7, 0x80, 0x4a, 0x3a, 0x64, 0xb6, 0xd7, 0x2c, 0xcf, 0xed, 0x6b, 0x6f, 0xb6, 0xed, 0x28, 0xbb, 0xfc, 0x11, 0x7e, 0x23, 0x58, 0x20, 0x57, 0xc9, 0x20, 0x77, 0x66, 0x41, 0x46, 0xe8, 0x76, 0x76, 0x0c, 0x95, 0x20, 0xd0, 0x54, 0xaa, 0x93, 0xc3, 0xaf, 0xb0, 0x4e, 0x30, 0x67, 0x05, 0xdb, 0x60, 0x90, 0x30, 0x85, 0x07, 0xb4, 0xd3, 0xa6, 0x01, 0x02, 0x02, 0x58, 0x24, 0x6d, 0x65, 0x72, 0x69, 0x61, 0x64, 0x6f, 0x63, 0x2e, 0x62, 0x72, 0x61, 0x6e, 0x64, 0x79, 0x62, 0x75, 0x63, 0x6b, 0x40, 0x62, 0x75, 0x63, 0x6b, 0x6c, 0x61, 0x6e, 0x64, 0x2e, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x20, 0x01, 0x21, 0x58, 0x20, 0x65, 0xed, 0xa5, 0xa1, 0x25, 0x77, 0xc2, 0xba, 0xe8, 0x29, 0x43, 0x7f, 0xe3, 0x38, 0x70, 0x1a, 0x10, 0xaa, 0xa3, 0x75, 0xe1, 0xbb, 0x5b, 0x5d, 0xe1, 0x08, 0xde, 0x43, 0x9c, 0x08, 0x55, 0x1d, 0x22, 0x58, 0x20, 0x1e, 0x52, 0xed, 0x75, 0x70, 0x11, 0x63, 0xf7, 0xf9, 0xe4, 0x0d, 0xdf, 0x9f, 0x34, 0x1b, 0x3d, 0xc9, 0xba, 0x86, 0x0a, 0xf7, 0xe0, 0xca, 0x7c, 0xa7, 0xe9, 0xee, 0xcd, 0x00, 0x84, 0xd1, 0x9c, 0x23, 0x58, 0x20, 0xaf, 0xf9, 0x07, 0xc9, 0x9f, 0x9a, 0xd3, 0xaa, 0xe6, 0xc4, 0xcd, 0xf2, 0x11, 0x22, 0xbc, 0xe2, 0xbd, 0x68, 0xb5, 0x28, 0x3e, 0x69, 0x07, 0x15, 0x4a, 0xd9, 0x11, 0x84, 0x0f, 0xa2, 0x08, 0xcf, 0xa3, 0x01, 0x04, 0x02, 0x4a, 0x6f, 0x75, 0x72, 0x2d, 0x73, 0x65, 0x63, 0x72, 0x65, 0x74, 0x20, 0x58, 0x20, 0x84, 0x9b, 0x57, 0x21, 0x9d, 0xae, 0x48, 0xde, 0x64, 0x6d, 0x07, 0xdb, 0xb5, 0x33, 0x56, 0x6e, 0x97, 0x66, 0x86, 0x45, 0x7c, 0x14, 0x91, 0xbe, 0x3a, 0x76, 0xdc, 0xea, 0x6c, 0x42, 0x71, 0x88, 0xa6, 0x01, 0x02, 0x02, 0x58, 0x1e, 0x62, 0x69, 0x6c, 0x62, 0x6f, 0x2e, 0x62, 0x61, 0x67, 0x67, 0x69, 0x6e, 0x73, 0x40, 0x68, 0x6f, 0x62, 0x62, 0x69, 0x74, 0x6f, 0x6e, 0x2e, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x20, 0x03, 0x21, 0x58, 0x42, 0x00, 0x72, 0x99, 0x2c, 0xb3, 0xac, 0x08, 0xec, 0xf3, 0xe5, 0xc6, 0x3d, 0xed, 0xec, 0x0d, 0x51, 0xa8, 0xc1, 0xf7, 0x9e, 0xf2, 0xf8, 0x2f, 0x94, 0xf3, 0xc7, 0x37, 0xbf, 0x5d, 0xe7, 0x98, 0x66, 0x71, 0xea, 0xc6, 0x25, 0xfe, 0x82, 0x57, 0xbb, 0xd0, 0x39, 0x46, 0x44, 0xca, 0xaa, 0x3a, 0xaf, 0x8f, 0x27, 0xa4, 0x58, 0x5f, 0xbb, 0xca, 0xd0, 0xf2, 0x45, 0x76, 0x20, 0x08, 0x5e, 0x5c, 0x8f, 0x42, 0xad, 0x22, 0x58, 0x42, 0x01, 0xdc, 0xa6, 0x94, 0x7b, 0xce, 0x88, 0xbc, 0x57, 0x90, 0x48, 0x5a, 0xc9, 0x74, 0x27, 0x34, 0x2b, 0xc3, 0x5f, 0x88, 0x7d, 0x86, 0xd6, 0x5a, 0x08, 0x93, 0x77, 0xe2, 0x47, 0xe6, 0x0b, 0xaa, 0x55, 0xe4, 0xe8, 0x50, 0x1e, 0x2a, 0xda, 0x57, 0x24, 0xac, 0x51, 0xd6, 0x90, 0x90, 0x08, 0x03, 0x3e, 0xbc, 0x10, 0xac, 0x99, 0x9b, 0x9d, 0x7f, 0x5c, 0xc2, 0x51, 0x9f, 0x3f, 0xe1, 0xea, 0x1d, 0x94, 0x75, 0x23, 0x58, 0x42, 0x00, 0x08, 0x51, 0x38, 0xdd, 0xab, 0xf5, 0xca, 0x97, 0x5f, 0x58, 0x60, 0xf9, 0x1a, 0x08, 0xe9, 0x1d, 0x6d, 0x5f, 0x9a, 0x76, 0xad, 0x40, 0x18, 0x76, 0x6a, 0x47, 0x66, 0x80, 0xb5, 0x5c, 0xd3, 0x39, 0xe8, 0xab, 0x6c, 0x72, 0xb5, 0xfa, 0xcd, 0xb2, 0xa2, 0xa5, 0x0a, 0xc2, 0x5b, 0xd0, 0x86, 0x64, 0x7d, 0xd3, 0xe2, 0xe6, 0xe9, 0x9e, 0x84, 0xca, 0x2c, 0x36, 0x09, 0xfd, 0xf1, 0x77, 0xfe, 0xb2, 0x6d, 0xa3, 0x01, 0x04, 0x02, 0x4b, 0x6f, 0x75, 0x72, 0x2d, 0x73, 0x65, 0x63, 0x72, 0x65, 0x74, 0x32, 0x20, 0x50, 0x84, 0x9b, 0x57, 0x86, 0x45, 0x7c, 0x14, 0x91, 0xbe, 0x3a, 0x76, 0xdc, 0xea, 0x6c, 0x42, 0x71, 0xa6, 0x01, 0x02, 0x02, 0x58, 0x21, 0x70, 0x65, 0x72, 0x65, 0x67, 0x72, 0x69, 0x6e, 0x2e, 0x74, 0x6f, 0x6f, 0x6b, 0x40, 0x74, 0x75, 0x63, 0x6b, 0x62, 0x6f, 0x72, 0x6f, 0x75, 0x67, 0x68, 0x2e, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x20, 0x01, 0x21, 0x58, 0x20, 0x98, 0xf5, 0x0a, 0x4f, 0xf6, 0xc0, 0x58, 0x61, 0xc8, 0x86, 0x0d, 0x13, 0xa6, 0x38, 0xea, 0x56, 0xc3, 0xf5, 0xad, 0x75, 0x90, 0xbb, 0xfb, 0xf0, 0x54, 0xe1, 0xc7, 0xb4, 0xd9, 0x1d, 0x62, 0x80, 0x22, 0x58, 0x20, 0xf0, 0x14, 0x00, 0xb0, 0x89, 0x86, 0x78, 0x04, 0xb8, 0xe9, 0xfc, 0x96, 0xc3, 0x93, 0x21, 0x61, 0xf1, 0x93, 0x4f, 0x42, 0x23, 0x06, 0x91, 0x70, 0xd9, 0x24, 0xb7, 0xe0, 0x3b, 0xf8, 0x22, 0xbb, 0x23, 0x58, 0x20, 0x02, 0xd1, 0xf7, 0xe6, 0xf2, 0x6c, 0x43, 0xd4, 0x86, 0x8d, 0x87, 0xce, 0xb2, 0x35, 0x31, 0x61, 0x74, 0x0a, 0xac, 0xf1, 0xf7, 0x16, 0x36, 0x47, 0x98, 0x4b, 0x52, 0x2a, 0x84, 0x8d, 0xf1, 0xc3, 0xa3, 0x01, 0x04, 0x02, 0x58, 0x24, 0x30, 0x31, 0x38, 0x63, 0x30, 0x61, 0x65, 0x35, 0x2d, 0x34, 0x64, 0x39, 0x62, 0x2d, 0x34, 0x37, 0x31, 0x62, 0x2d, 0x62, 0x66, 0x64, 0x36, 0x2d, 0x65, 0x65, 0x66, 0x33, 0x31, 0x34, 0x62, 0x63, 0x37, 0x30, 0x33, 0x37, 0x04, 0x58, 0x20, 0x84, 0x9b, 0x57, 0x21, 0x9d, 0xae, 0x48, 0xde, 0x64, 0x6d, 0x07, 0xdb, 0xb5, 0x33, 0x56, 0x6e, 0x97, 0x66, 0x86, 0x45, 0x7c, 0x14, 0x91, 0xbe, 0x3a, 0x76, 0xdc, 0xea, 0x6c, 0x42, 0x71, 0x88, /* kid "sec-48" for hmac 384 */ 0xa3, 0x01, 0x04, 0x02, 0x46, 0x73, 0x65, 0x63, 0x2d, 0x34, 0x38, 0x20, 0x58, 0x30, 0x84, 0x9b, 0x57, 0x21, 0x9d, 0xae, 0x48, 0xde, 0x64, 0x6d, 0x07, 0xdb, 0xb5, 0x33, 0x56, 0x6e, 0x97, 0x66, 0x86, 0x45, 0x7c, 0x14, 0x91, 0xbe, 0x3a, 0x76, 0xdc, 0xea, 0x6c, 0x42, 0x71, 0x88, 0x00, 0x11, 0x22, 0x33, 0x77, 0x88, 0x99, 0xaa, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, /* kid "sec-64" for hmac 512 */ 0xa3, 0x01, 0x04, 0x02, 0x46, 0x73, 0x65, 0x63, 0x2d, 0x36, 0x34, 0x20, 0x58, 0x40, 0x84, 0x9b, 0x57, 0x21, 0x9d, 0xae, 0x48, 0xde, 0x64, 0x6d, 0x07, 0xdb, 0xb5, 0x33, 0x56, 0x6e, 0x97, 0x66, 0x86, 0x45, 0x7c, 0x14, 0x91, 0xbe, 0x3a, 0x76, 0xdc, 0xea, 0x6c, 0x42, 0x71, 0x88, 0x00, 0x11, 0x22, 0x33, 0x77, 0x88, 0x99, 0xaa, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xa0, 0xb1, 0xb2, 0xb3, 0xb4, } ; struct keyinfo { const uint8_t *set; size_t len; }; struct keyinfo keyset1 = { cose_key_set1, sizeof(cose_key_set1) }, key3 = { cose_key3, sizeof(cose_key3) }, key8 = { cose_key8, sizeof(cose_key8) }, key9 = { cose_key9, sizeof(cose_key9) }, key10 = { cose_key10, sizeof(cose_key10) } ; /* key pieces */ static const uint8_t key1_x[] = { 0xba, 0xc5, 0xb1, 0x1c, 0xad, 0x8f, 0x99, 0xf9, 0xc7, 0x2b, 0x05, 0xcf, 0x4b, 0x9e, 0x26, 0xd2, 0x44, 0xdc, 0x18, 0x9f, 0x74, 0x52, 0x28, 0x25, 0x5a, 0x21, 0x9a, 0x86, 0xd6, 0xa0, 0x9e, 0xff }, key1_y[] = { 0x20, 0x13, 0x8b, 0xf8, 0x2d, 0xc1, 0xb6, 0xd5, 0x62, 0xbe, 0x0f, 0xa5, 0x4a, 0xb7, 0x80, 0x4a, 0x3a, 0x64, 0xb6, 0xd7, 0x2c, 0xcf, 0xed, 0x6b, 0x6f, 0xb6, 0xed, 0x28, 0xbb, 0xfc, 0x11, 0x7e }, key1_d[] = { 0x57, 0xc9, 0x20, 0x77, 0x66, 0x41, 0x46, 0xe8, 0x76, 0x76, 0x0c, 0x95, 0x20, 0xd0, 0x54, 0xaa, 0x93, 0xc3, 0xaf, 0xb0, 0x4e, 0x30, 0x67, 0x05, 0xdb, 0x60, 0x90, 0x30, 0x85, 0x07, 0xb4, 0xd3 }, key2_x[] = { 0x65, 0xed, 0xa5, 0xa1, 0x25, 0x77, 0xc2, 0xba, 0xe8, 0x29, 0x43, 0x7f, 0xe3, 0x38, 0x70, 0x1a, 0x10, 0xaa, 0xa3, 0x75, 0xe1, 0xbb, 0x5b, 0x5d, 0xe1, 0x08, 0xde, 0x43, 0x9c, 0x08, 0x55, 0x1d }, key2_y[] = { 0x1e, 0x52, 0xed, 0x75, 0x70, 0x11, 0x63, 0xf7, 0xf9, 0xe4, 0x0d, 0xdf, 0x9f, 0x34, 0x1b, 0x3d, 0xc9, 0xba, 0x86, 0x0a, 0xf7, 0xe0, 0xca, 0x7c, 0xa7, 0xe9, 0xee, 0xcd, 0x00, 0x84, 0xd1, 0x9c }, key2_d[] = { 0xaf, 0xf9, 0x07, 0xc9, 0x9f, 0x9a, 0xd3, 0xaa, 0xe6, 0xc4, 0xcd, 0xf2, 0x11, 0x22, 0xbc, 0xe2, 0xbd, 0x68, 0xb5, 0x28, 0x3e, 0x69, 0x07, 0x15, 0x4a, 0xd9, 0x11, 0x84, 0x0f, 0xa2, 0x08, 0xcf }, key3_k[] = { 0x84, 0x9b, 0x57, 0x21, 0x9d, 0xae, 0x48, 0xde, 0x64, 0x6d, 0x07, 0xdb, 0xb5, 0x33, 0x56, 0x6e, 0x97, 0x66, 0x86, 0x45, 0x7c, 0x14, 0x91, 0xbe, 0x3a, 0x76, 0xdc, 0xea, 0x6c, 0x42, 0x71, 0x88 }, key4_x[] = { 0x00, 0x72, 0x99, 0x2c, 0xb3, 0xac, 0x08, 0xec, 0xf3, 0xe5, 0xc6, 0x3d, 0xed, 0xec, 0x0d, 0x51, 0xa8, 0xc1, 0xf7, 0x9e, 0xf2, 0xf8, 0x2f, 0x94, 0xf3, 0xc7, 0x37, 0xbf, 0x5d, 0xe7, 0x98, 0x66, 0x71, 0xea, 0xc6, 0x25, 0xfe, 0x82, 0x57, 0xbb, 0xd0, 0x39, 0x46, 0x44, 0xca, 0xaa, 0x3a, 0xaf, 0x8f, 0x27, 0xa4, 0x58, 0x5f, 0xbb, 0xca, 0xd0, 0xf2, 0x45, 0x76, 0x20, 0x08, 0x5e, 0x5c, 0x8f, 0x42, 0xad }, key4_y[] = { 0x01, 0xdc, 0xa6, 0x94, 0x7b, 0xce, 0x88, 0xbc, 0x57, 0x90, 0x48, 0x5a, 0xc9, 0x74, 0x27, 0x34, 0x2b, 0xc3, 0x5f, 0x88, 0x7d, 0x86, 0xd6, 0x5a, 0x08, 0x93, 0x77, 0xe2, 0x47, 0xe6, 0x0b, 0xaa, 0x55, 0xe4, 0xe8, 0x50, 0x1e, 0x2a, 0xda, 0x57, 0x24, 0xac, 0x51, 0xd6, 0x90, 0x90, 0x08, 0x03, 0x3e, 0xbc, 0x10, 0xac, 0x99, 0x9b, 0x9d, 0x7f, 0x5c, 0xc2, 0x51, 0x9f, 0x3f, 0xe1, 0xea, 0x1d, 0x94, 0x75 }, key4_d[] = { 0x00, 0x08, 0x51, 0x38, 0xdd, 0xab, 0xf5, 0xca, 0x97, 0x5f, 0x58, 0x60, 0xf9, 0x1a, 0x08, 0xe9, 0x1d, 0x6d, 0x5f, 0x9a, 0x76, 0xad, 0x40, 0x18, 0x76, 0x6a, 0x47, 0x66, 0x80, 0xb5, 0x5c, 0xd3, 0x39, 0xe8, 0xab, 0x6c, 0x72, 0xb5, 0xfa, 0xcd, 0xb2, 0xa2, 0xa5, 0x0a, 0xc2, 0x5b, 0xd0, 0x86, 0x64, 0x7d, 0xd3, 0xe2, 0xe6, 0xe9, 0x9e, 0x84, 0xca, 0x2c, 0x36, 0x09, 0xfd, 0xf1, 0x77, 0xfe, 0xb2, 0x6d }, key5_k[] = { 0x84, 0x9b, 0x57, 0x86, 0x45, 0x7c, 0x14, 0x91, 0xbe, 0x3a, 0x76, 0xdc, 0xea, 0x6c, 0x42, 0x71 }, key6_x[] = { 0x98, 0xf5, 0x0a, 0x4f, 0xf6, 0xc0, 0x58, 0x61, 0xc8, 0x86, 0x0d, 0x13, 0xa6, 0x38, 0xea, 0x56, 0xc3, 0xf5, 0xad, 0x75, 0x90, 0xbb, 0xfb, 0xf0, 0x54, 0xe1, 0xc7, 0xb4, 0xd9, 0x1d, 0x62, 0x80 }, key6_y[] = { 0xf0, 0x14, 0x00, 0xb0, 0x89, 0x86, 0x78, 0x04, 0xb8, 0xe9, 0xfc, 0x96, 0xc3, 0x93, 0x21, 0x61, 0xf1, 0x93, 0x4f, 0x42, 0x23, 0x06, 0x91, 0x70, 0xd9, 0x24, 0xb7, 0xe0, 0x3b, 0xf8, 0x22, 0xbb }, key6_d[] = { 0x02, 0xd1, 0xf7, 0xe6, 0xf2, 0x6c, 0x43, 0xd4, 0x86, 0x8d, 0x87, 0xce, 0xb2, 0x35, 0x31, 0x61, 0x74, 0x0a, 0xac, 0xf1, 0xf7, 0x16, 0x36, 0x47, 0x98, 0x4b, 0x52, 0x2a, 0x84, 0x8d, 0xf1, 0xc3 }, key7_k[] = { 0x84, 0x9b, 0x57, 0x21, 0x9d, 0xae, 0x48, 0xde, 0x64, 0x6d, 0x07, 0xdb, 0xb5, 0x33, 0x56, 0x6e, 0x97, 0x66, 0x86, 0x45, 0x7c, 0x14, 0x91, 0xbe, 0x3a, 0x76, 0xdc, 0xea, 0x6c, 0x42, 0x71, 0x88 }, key8_k[] = { 0x84, 0x9b, 0x57, 0x21, 0x9d, 0xae, 0x48, 0xde, 0x64, 0x6d, 0x07, 0xdb, 0xb5, 0x33, 0x56, 0x6e, 0x97, 0x66, 0x86, 0x45, 0x7c, 0x14, 0x91, 0xbe, 0x3a, 0x76, 0xdc, 0xea, 0x6c, 0x42, 0x71, 0x88, 0x00, 0x11, 0x22, 0x33, 0x77, 0x88, 0x99, 0xaa, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28 }, key9_k[] = { 0x84, 0x9b, 0x57, 0x21, 0x9d, 0xae, 0x48, 0xde, 0x64, 0x6d, 0x07, 0xdb, 0xb5, 0x33, 0x56, 0x6e, 0x97, 0x66, 0x86, 0x45, 0x7c, 0x14, 0x91, 0xbe, 0x3a, 0x76, 0xdc, 0xea, 0x6c, 0x42, 0x71, 0x88, 0x00, 0x11, 0x22, 0x33, 0x77, 0x88, 0x99, 0xaa, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xa0, 0xb1, 0xb2, 0xb3, 0xb4 } #if 0 , key10_x[] = { 0xd7, 0x5a, 0x98, 0x01, 0x82, 0xb1, 0x0a, 0xb7, 0xd5, 0x4b, 0xfe, 0xd3, 0xc9, 0x64, 0x07, 0x3a, 0x0e, 0xe1, 0x72, 0xf3, 0xda, 0xa6, 0x23, 0x25, 0xaf, 0x02, 0x1a, 0x68, 0xf7, 0x07, 0x51, 0x1a }, key10_d[] = { 0x9d, 0x61, 0xb1, 0x9d, 0xef, 0xfd, 0x5a, 0x60, 0xba, 0x84, 0x4a, 0xf4, 0x92, 0xec, 0x2c, 0xc4, 0x44, 0x49, 0xc5, 0x69, 0x7b, 0x32, 0x69, 0x19, 0x70, 0x3b, 0xac, 0x03, 0x1c, 0xae, 0x7f, 0x60 } #endif ; int test_cose_keys(struct lws_context *context) { struct lws_cose_key *ck; lws_dll2_owner_t set; lws_lec_pctx_t wc; uint8_t buf[4096]; int n; #if 0 { int fd = open("set1.cks", LWS_O_CREAT | LWS_O_TRUNC | LWS_O_WRONLY, 0600); if (fd >= 0) { write(fd, cose_key_set1, sizeof(cose_key_set1)); close(fd); } } #endif #if 0 lws_lec_pctx_t wx; uint8_t dump[8192]; lws_lec_init(&wx, buf, sizeof(buf)); if (lws_lec_printf(&wx, "{%d:%d, %d:%.*b, %d:%d, %d:%.*b, %d:%.*b}", LWSCOSE_WKK_KTY, LWSCOSE_WKKTV_OKP, LWSCOSE_WKK_KID, 2, "11", LWSCOSE_WKOKP_CRV, LWSCOSE_WKEC_ED25519, LWSCOSE_WKECKP_X, (int)sizeof(key10_x), key10_x, // LWSCOSE_WKECKP_Y, (int)sizeof(key6_y), key6_y, LWSCOSE_WKECKP_D, (int)sizeof(key10_d), key10_d) != LWS_LECPCTX_RET_FINISHED) return 1; lws_hex_from_byte_array(buf, wx.used, (char *)dump, sizeof(dump)); puts((const char *)dump); #endif #if 0 lws_lec_pctx_t wx; uint8_t dump[8192]; lws_lec_init(&wx, buf, sizeof(buf)); if (lws_lec_printf(&wx, "{%d:%d, %d:%.*b, %d:%.*b}", LWSCOSE_WKK_KTY, LWSCOSE_WKKTV_SYMMETRIC, LWSCOSE_WKK_KID, 6, "sec-64", -1, (int)sizeof(key9_k), key9_k) != LWS_LECPCTX_RET_FINISHED) return 1; lws_hex_from_byte_array(buf, wx.used, (char *)dump, sizeof(dump)); puts((const char *)dump); #endif /* key1 import */ lwsl_user("%s: key 1 import\n", __func__); ck = lws_cose_key_import(NULL, key_import_cb, NULL, cose_key1, sizeof(cose_key1)); if (!ck) return 1; if (ck->kty != LWSCOSE_WKKTV_EC2 || ck->gencrypto_kty != LWS_GENCRYPTO_KTY_EC || ck->e[LWS_GENCRYPTO_EC_KEYEL_X].len != sizeof(key1_x) || ck->e[LWS_GENCRYPTO_EC_KEYEL_Y].len != sizeof(key1_y) || ck->e[LWS_GENCRYPTO_EC_KEYEL_D].len != sizeof(key1_d) || memcmp(ck->e[LWS_GENCRYPTO_EC_KEYEL_X].buf, key1_x, sizeof(key1_x)) || memcmp(ck->e[LWS_GENCRYPTO_EC_KEYEL_Y].buf, key1_y, sizeof(key1_y)) || memcmp(ck->e[LWS_GENCRYPTO_EC_KEYEL_D].buf, key1_d, sizeof(key1_d))) goto bail; // lws_cose_key_dump(ck); /* key 1 export */ lwsl_user("%s: key 1 export\n", __func__); lws_lec_init(&wc, buf, sizeof(buf)); n = (int)lws_cose_key_export(ck, &wc, LWSJWKF_EXPORT_PRIVATE); lws_cose_key_destroy(&ck); if (n != LWS_LECPCTX_RET_FINISHED) goto bail; // lwsl_hexdump_notice(buf, wc.used); /* key2 import */ lwsl_user("%s: key 2 import\n", __func__); ck = lws_cose_key_import(NULL, NULL, NULL, cose_key2, sizeof(cose_key2)); if (!ck) return 1; if (ck->kty != LWSCOSE_WKKTV_EC2 || ck->gencrypto_kty != LWS_GENCRYPTO_KTY_EC || ck->e[LWS_GENCRYPTO_EC_KEYEL_X].len != sizeof(key2_x) || ck->e[LWS_GENCRYPTO_EC_KEYEL_Y].len != sizeof(key2_y) || ck->e[LWS_GENCRYPTO_EC_KEYEL_D].len != sizeof(key2_d) || memcmp(ck->e[LWS_GENCRYPTO_EC_KEYEL_X].buf, key2_x, sizeof(key2_x)) || memcmp(ck->e[LWS_GENCRYPTO_EC_KEYEL_Y].buf, key2_y, sizeof(key2_y)) || memcmp(ck->e[LWS_GENCRYPTO_EC_KEYEL_D].buf, key2_d, sizeof(key2_d))) goto bail; lws_cose_key_destroy(&ck); /* key3 import */ lwsl_user("%s: key 3 import\n", __func__); ck = lws_cose_key_import(NULL, NULL, NULL, cose_key3, sizeof(cose_key3)); if (!ck) { lwsl_err("%s: key 3 import failed\n", __func__); goto bail; } if (ck->kty != LWSCOSE_WKKTV_SYMMETRIC || ck->gencrypto_kty != LWS_GENCRYPTO_KTY_OCT || ck->e[LWS_GENCRYPTO_OCT_KEYEL_K].len != sizeof(key3_k) || memcmp(ck->e[LWS_GENCRYPTO_OCT_KEYEL_K].buf, key3_k, sizeof(key3_k))) { lwsl_err("%s: key 3 checks failed %d %d %d\n", __func__, (int)ck->kty, (int)ck->gencrypto_kty, (int)ck->e[LWS_GENCRYPTO_OCT_KEYEL_K].len); goto bail; } lws_cose_key_destroy(&ck); /* key4 import */ lwsl_user("%s: key 4 import\n", __func__); ck = lws_cose_key_import(NULL, NULL, NULL, cose_key4, sizeof(cose_key4)); if (!ck) return 1; if (ck->kty != LWSCOSE_WKKTV_EC2 || ck->gencrypto_kty != LWS_GENCRYPTO_KTY_EC || ck->e[LWS_GENCRYPTO_EC_KEYEL_X].len != sizeof(key4_x) || ck->e[LWS_GENCRYPTO_EC_KEYEL_Y].len != sizeof(key4_y) || ck->e[LWS_GENCRYPTO_EC_KEYEL_D].len != sizeof(key4_d) || memcmp(ck->e[LWS_GENCRYPTO_EC_KEYEL_X].buf, key4_x, sizeof(key4_x)) || memcmp(ck->e[LWS_GENCRYPTO_EC_KEYEL_Y].buf, key4_y, sizeof(key4_y)) || memcmp(ck->e[LWS_GENCRYPTO_EC_KEYEL_D].buf, key4_d, sizeof(key4_d))) goto bail; lws_cose_key_destroy(&ck); /* key5 import */ lwsl_user("%s: key 5 import\n", __func__); ck = lws_cose_key_import(NULL, NULL, NULL, cose_key5, sizeof(cose_key5)); if (!ck) return 1; if (ck->kty != LWSCOSE_WKKTV_SYMMETRIC || ck->gencrypto_kty != LWS_GENCRYPTO_KTY_OCT || ck->e[LWS_GENCRYPTO_OCT_KEYEL_K].len != sizeof(key5_k) || memcmp(ck->e[LWS_GENCRYPTO_OCT_KEYEL_K].buf, key5_k, sizeof(key5_k))) goto bail; lws_cose_key_destroy(&ck); /* key6 import */ lwsl_user("%s: key 6 import\n", __func__); ck = lws_cose_key_import(NULL, NULL, NULL, cose_key6, sizeof(cose_key6)); if (!ck) return 1; if (ck->kty != LWSCOSE_WKKTV_EC2 || ck->gencrypto_kty != LWS_GENCRYPTO_KTY_EC || ck->e[LWS_GENCRYPTO_EC_KEYEL_X].len != sizeof(key6_x) || ck->e[LWS_GENCRYPTO_EC_KEYEL_Y].len != sizeof(key6_y) || ck->e[LWS_GENCRYPTO_EC_KEYEL_D].len != sizeof(key6_d) || memcmp(ck->e[LWS_GENCRYPTO_EC_KEYEL_X].buf, key6_x, sizeof(key6_x)) || memcmp(ck->e[LWS_GENCRYPTO_EC_KEYEL_Y].buf, key6_y, sizeof(key6_y)) || memcmp(ck->e[LWS_GENCRYPTO_EC_KEYEL_D].buf, key6_d, sizeof(key6_d))) goto bail; lws_cose_key_destroy(&ck); /* key7 import */ lwsl_user("%s: key 7 import\n", __func__); ck = lws_cose_key_import(NULL, NULL, NULL, cose_key7, sizeof(cose_key7)); if (!ck) return 1; if (ck->kty != LWSCOSE_WKKTV_SYMMETRIC || ck->gencrypto_kty != LWS_GENCRYPTO_KTY_OCT || ck->e[LWS_GENCRYPTO_OCT_KEYEL_K].len != sizeof(key7_k) || memcmp(ck->e[LWS_GENCRYPTO_OCT_KEYEL_K].buf, key7_k, sizeof(key7_k))) goto bail; lws_cose_key_destroy(&ck); /* key8 import */ lwsl_user("%s: key 8 import\n", __func__); ck = lws_cose_key_import(NULL, NULL, NULL, cose_key8, sizeof(cose_key8)); if (!ck) return 1; if (ck->kty != LWSCOSE_WKKTV_SYMMETRIC || ck->gencrypto_kty != LWS_GENCRYPTO_KTY_OCT || ck->e[LWS_GENCRYPTO_OCT_KEYEL_K].len != sizeof(key8_k) || memcmp(ck->e[LWS_GENCRYPTO_OCT_KEYEL_K].buf, key8_k, sizeof(key8_k))) goto bail; lws_cose_key_destroy(&ck); /* key9 import */ lwsl_user("%s: key 9 import\n", __func__); ck = lws_cose_key_import(NULL, NULL, NULL, cose_key9, sizeof(cose_key9)); if (!ck) { lwsl_err("%s: cose9 import fail\n", __func__); goto bail; } if (ck->kty != LWSCOSE_WKKTV_SYMMETRIC || ck->gencrypto_kty != LWS_GENCRYPTO_KTY_OCT || ck->e[LWS_GENCRYPTO_OCT_KEYEL_K].len != sizeof(key9_k) || memcmp(ck->e[LWS_GENCRYPTO_OCT_KEYEL_K].buf, key9_k, sizeof(key9_k))) { lwsl_notice("%s: key9 check fails\n", __func__); goto bail; } lws_cose_key_destroy(&ck); /* key set 1 */ lwsl_user("%s: key_set1\n", __func__); lws_dll2_owner_clear(&set); ck = lws_cose_key_import(&set, NULL, NULL, cose_key_set1, sizeof(cose_key_set1)); if (!ck) return 1; lws_cose_key_set_destroy(&set); /* generate */ ck = lws_cose_key_generate(context, LWSCOSE_WKKTV_EC2, (1 << LWSCOSE_WKKO_SIGN) | (1 << LWSCOSE_WKKO_VERIFY) | (1 << LWSCOSE_WKKO_ENCRYPT) | (1 << LWSCOSE_WKKO_DECRYPT), 0, "P-256", (const uint8_t *)"the-keyid", 9); if (!ck) return 1; // lws_cose_key_dump(ck); lws_cose_key_destroy(&ck); return 0; bail: lwsl_err("%s: selftest failed ++++++++++++++++++++\n", __func__); return 1; }
29.290773
83
0.624345
dbff296aa1343d09efd08ae029def7b2e0d69130
3,463
c
C
src/problemB/problem1081.c
kbpoyo/ForgotCLearning
17daa0898a916b77fa66b9de3365c7e68b1f9321
[ "Apache-2.0" ]
28
2019-09-07T02:36:54.000Z
2022-02-09T14:11:55.000Z
src/problemB/problem1081.c
kbpoyo/ForgotCLearning
17daa0898a916b77fa66b9de3365c7e68b1f9321
[ "Apache-2.0" ]
null
null
null
src/problemB/problem1081.c
kbpoyo/ForgotCLearning
17daa0898a916b77fa66b9de3365c7e68b1f9321
[ "Apache-2.0" ]
16
2020-02-03T07:42:19.000Z
2021-09-26T13:46:33.000Z
// // Created by forgot on 2019-08-04. // //1081 检查密码 (15 point(s)) /*本题要求你帮助某网站的用户注册模块写一个密码合法性检查的小功能。该网站要求用户设置的密码必须由不少于6个字符组成,并且只能有英文字母、数字和小数点 * .,还必须既有字母也有数字。 输入格式: 输入第一行给出一个正整数 N(≤ 100),随后 N 行,每行给出一个用户设置的密码,为不超过 80 个字符的非空字符串,以回车结束。 输出格式: 对每个用户的密码,在一行中输出系统反馈信息,分以下5种: 如果密码合法,输出Your password is wan mei.; 如果密码太短,不论合法与否,都输出Your password is tai duan le.; 如果密码长度合法,但存在不合法字符,则输出Your password is tai luan le.; 如果密码长度合法,但只有字母没有数字,则输出Your password needs shu zi.; 如果密码长度合法,但只有数字没有字母,则输出Your password needs zi mu.。 输入样例: 5 123s zheshi.wodepw 1234.5678 WanMei23333 pass*word.6 输出样例: Your password is tai duan le. Your password needs shu zi. Your password needs zi mu. Your password is wan mei. Your password is tai luan le.*/ ////如果只有小数点会怎样?好像文中没有说啊, 那首先判断没有数字,就输出 Your password needs shu zi. //// 题目没说密码不能有空格,所以要注意处理空格输入,不然会错第三个用例 //#include "stdio.h" //#include "string.h" // //int main() { // int N; // scanf("%d", &N); // getchar(); // for (int i = 0; i < N; ++i) { // char pwd[81]; // gets(pwd); // int illegal = 0; // int hasChar = 0; // int hasNum = 0; // int hasDot = 0; // if (strlen(pwd) < 6) { // printf("Your password is tai duan le."); // } else { // for (int j = 0; j < strlen(pwd); ++j) { // if (pwd[j] >= '0' && pwd[j] <= '9') { // hasNum = 1; // } else if ((pwd[j] >= 'a' && pwd[j] <= 'z') || (pwd[j] >= 'A' && pwd[j] <= 'Z')) { // hasChar = 1; // } else if (pwd[j] == '.') { // hasDot = 1; // } else { // illegal = 1; // } // } // // if (illegal) { // printf("Your password is tai luan le."); // } else if (!hasNum) { // printf("Your password needs shu zi."); // } else if (!hasChar) { // printf("Your password needs zi mu."); // } else { // printf("Your password is wan mei."); // } // } // // if (i != N - 1) { // printf("\n"); // } // // } // // return 0; //} //#include "stdio.h" //#include "string.h" //错了一个用例 //int main() { // int N; // scanf("%d", &N); // for (int i = 0; i < N; ++i) { // char pwd[81]; // scanf("%s",pwd); // int illegal = 0; // int hasChar = 0; // int hasNum = 0; // if (strlen(pwd) < 6) { // printf("Your password is tai duan le."); // if (i!=N-1){ // printf("\n"); // } // continue; // } // // for (int j = 0; j < strlen(pwd); ++j) { // if (pwd[j] >= '0' && pwd[j] <= '9') { // hasNum = 1; // } else if ((pwd[j] >= 'a' && pwd[j] <= 'z') || (pwd[j] >= 'A' && pwd[j] <= 'Z')) { // hasChar = 1; // } else if (pwd[j] != '.') { // illegal = 1; // } // } // // if (illegal){ // printf("Your password is tai luan le."); // }else if (hasChar&&!hasNum){ // printf("Your password needs shu zi."); // }else if (hasNum&&!hasChar){ // printf("Your password needs zi mu."); // }else{ // printf("Your password is wan mei."); // } // // if (i!=N-1){ // printf("\n"); // } // // } // // return 0; //}
25.843284
100
0.439215
f44aab5c50306dd93d8d21db441e3d367906251a
787
ts
TypeScript
src/socketio.response.ts
toniton/angular2-sails-socketio
c1acf622fba1c1ea18b8400bb1eff6e2c3f91edd
[ "MIT" ]
null
null
null
src/socketio.response.ts
toniton/angular2-sails-socketio
c1acf622fba1c1ea18b8400bb1eff6e2c3f91edd
[ "MIT" ]
2
2017-04-20T07:57:07.000Z
2017-12-21T04:04:03.000Z
src/socketio.response.ts
toniton/angular2-sails-socketio
c1acf622fba1c1ea18b8400bb1eff6e2c3f91edd
[ "MIT" ]
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author Tunde */ export class SocketIOResponse { private code: string; private data: any; private message: string; constructor(raw: any) { if (raw["code"]) { this.code = raw["code"]; } if (raw["data"]) { this.data = raw["data"]; } if (raw["message"]) { this.message = raw["message"]; } } public getCode(): string { return this.code; } public getData(): any{ return this.data; } public getMessage(): string { return this.message; } }
19.195122
79
0.541296
1f4627cb14652e7a4cf1bcd3b61df984444f7a84
22,708
cs
C#
Server/Form1.cs
suarezoscar/logoquizz
f6695a4cf096600b87adebd7d4dd66cf6b6d53c7
[ "MIT" ]
null
null
null
Server/Form1.cs
suarezoscar/logoquizz
f6695a4cf096600b87adebd7d4dd66cf6b6d53c7
[ "MIT" ]
null
null
null
Server/Form1.cs
suarezoscar/logoquizz
f6695a4cf096600b87adebd7d4dd66cf6b6d53c7
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace Server { public partial class Form1 : Form { public Form1() { InitializeComponent(); CheckForIllegalCrossThreadCalls = false; // desactiva la deteccion de llamadas no seguras a controles WindowsForms } #region Declaraciones Globales //configuracion del juego int jugadoresMax; int puertoEscucha = 3000; private static object key = new object(); List<Jugador> Jugadores = new List<Jugador>(); delegate void DelegadoInstruccion(int numInstruccion, string mensaje); delegate void DelegadoEscribirLista(); delegate void DelegadoRespuesta(); DelegadoEscribirLista del; TimeSpan horaConexion; TcpListener newsock; Partida p = new Partida(); Jugador j; Thread t; #endregion private void RecibirClientes() { try { newsock = new TcpListener(IPAddress.Any, Convert.ToInt32(numericUpDown_puertoEscucha.Value)); newsock.Start(); Console.WriteLine("Esperando por clientes"); while (true) { TcpClient cliente = newsock.AcceptTcpClient(); //linea bloqueante Thread t = new Thread(() => this.ManejarCliente(cliente)); t.Start(); } } catch (Exception er) { Console.WriteLine(er.ToString()); } } private void ManejarCliente(TcpClient cli) { string data; NetworkStream ns = cli.GetStream(); StreamReader sr = new StreamReader(ns); StreamWriter sw = new StreamWriter(ns); string ip = cli.Client.RemoteEndPoint.ToString().Split(':')[0]; //confirmacion de conexion sw.WriteLine("OK"); sw.Flush(); while (true) { try { //Manejo del cliente //instrucciones del juego AQUI data = sr.ReadLine(); Console.WriteLine("data: " + data); //para depurar en el server String[] subdatos = data.Split('#'); #region comINSCRIBIR if (subdatos[1] == "INSCRIBIR") { if (!p.PartidaIniciada) { if (Jugadores.Count < jugadoresMax) { if (!Jugadores.Any(c => c.Nick.Equals(subdatos[2]))) { puertoEscucha++; sw.WriteLine("#OK#" + puertoEscucha + "#"); sw.Flush(); EnviarInstruccion(8, subdatos[2] + " ENTRÓ EN LA SALA" + "#"); //Aviso a todos los jugadores que el cliente entró en la sala Jugadores.Add(new Jugador(cli, subdatos[2], cli.Client.RemoteEndPoint.ToString().Split(':')[0], puertoEscucha)); del = new DelegadoEscribirLista(escribirListaClientes); del.Invoke(); } else { sw.WriteLine("#NOK#el nick ya existe, elige otro"); sw.Flush(); } } else { sw.WriteLine("#NOK#Límite máximo de " + jugadoresMax + " jugadores alcanzado#"); sw.Flush(); } } else { sw.WriteLine("#NOK#Ya hay una partida en curso#"); sw.Flush(); } } #endregion #region com LISTOPARAJUGAR if (subdatos[1] == "LISTOPARAJUGAR") { lock (key) { try { Jugador j = Jugadores.Find(c => c.Cliente.Equals(cli)); Console.WriteLine(subdatos[1]); //El jugador esta listo para jugar la partida j.Listoparajugar = true; sw.WriteLine("#OK#" + numericUpDown_tiempoRonda.Value + "#"); sw.Flush(); EnviarInstruccion(8, j.Nick.ToUpper() + " ESTÁ LISTO!" + "#"); // SI TODOS LOS JUGADORES ESTÁN LISTOS INICIA NUEVA PARTIDA if (Jugadores.All(c => c.Listoparajugar) == true) { Console.WriteLine("Todos los jugadores estan listos para jugar"); p.PartidaIniciada = true; p.MaxPuntos = Convert.ToInt32(numericUpDown_maxPuntos.Value); p.MaxRondas = Convert.ToInt32(numericUpDown_maxRondas.Value); //Envia instruccion de nueva partida con la primera imagen de la pila EnviarInstruccion(3); } } catch (Exception error) { sw.WriteLine("#NOK#" + error); sw.Flush(); } } } #endregion #region com JUGADA if (subdatos[1] == "JUGADA") { lock (key) { if (p.Respuesta == subdatos[2]) //respuesta acertada { j = Jugadores.Find(c => c.Cliente == cli); j.RespuestaAdivinada = true; sw.WriteLine("#OK#correcto"); sw.Flush(); EnviarInstruccion(8, j.Nick.ToUpper() + " ACERTÓ!"); } else { sw.WriteLine("#OK#incorrecto"); sw.Flush(); } } } #endregion #region com PUNTUACION if (subdatos[1] == "PUNTUACION") { try { j = Jugadores.Find(c => c.Cliente == cli); j.Puntuacion += Convert.ToInt32(subdatos[2]); sw.WriteLine("#OK#"); sw.Flush(); } catch (Exception er) { sw.WriteLine("#NOK#" + er); sw.Flush(); } } #endregion #region com FIN DE RONDA if (subdatos[1] == "FINDERONDA") { lock (key) { j = Jugadores.Find(c => c.Cliente == cli); j.PartidaFinalizada = true; sw.WriteLine("#OK#faltan " + Jugadores.Where(c => c.PartidaFinalizada == false).ToList().Count + " jugadores#"); sw.Flush(); EnviarInstruccion(7); } } #endregion #region com CHAT if (subdatos[1] == "MSGCHAT") { EnviarInstruccion(8, subdatos[2]); } #endregion #region comDESCONEXION if (subdatos[1] == "DESCONEXION") { lock (key) { j = Jugadores.Find(c => c.Cliente.Equals(cli)); Jugadores.Remove(j); del = new DelegadoEscribirLista(escribirListaClientes); EnviarInstruccion(8, j.Nick.ToUpper() + " SE DESCONECTÓ"); del.Invoke(); cli.Close(); } } #endregion } catch (Exception error) { Console.WriteLine("Errro: {0}", error.ToString()); break; } } } private void buttonStartServer_Click(object sender, EventArgs e) { CargarImagenes(); jugadoresMax = Convert.ToInt32(numericUpDown_maxPlayers.Value); horaConexion = DateTime.Now.TimeOfDay; timer_uptime.Start(); SwitchStartStopButtons(); label_connectedPlayers.Text = "Esperando jugadores..."; //thread de repción continua de clientes; t = new Thread(this.RecibirClientes); t.Start(); } private void escribirListaClientes() { listbox_connectedPlayers.Items.Clear(); foreach (var j in Jugadores) { string player = j.Nick + " - Ip:" + j.Ip + " Puerto: " + j.PuertoEscucha; listbox_connectedPlayers.Items.Add(player); } label_connectedPlayers.Text = "Jugadores conectados (" + Jugadores.Count + ")"; } private void button_StopServer_Click(object sender, EventArgs e) { EnviarInstruccion(11); try { label_connectedPlayers.Text = "Inicia el servidor"; label_ServerState.Text = "Estado del servidor: APAGADO"; timer_uptime.Stop(); Jugadores.Clear(); listbox_connectedPlayers.Items.Clear(); newsock.Stop(); t.Abort(); SwitchStartStopButtons(); progressBar_imagenes.Value = 0; p.ListaImg.Clear(); } catch (Exception er) { Console.WriteLine(er); } } private void timer_uptime_Tick(object sender, EventArgs e) { TimeSpan horaActual = DateTime.Now.TimeOfDay; label_ServerState.Text = "Estado del servidor: ACTIVO " + (horaActual - horaConexion).ToString().Split('.')[0]; } public void SwitchStartStopButtons() { button_StopServer.Enabled = !button_StopServer.Enabled; button_StopServer.Visible = !button_StopServer.Visible; buttonStartServer.Enabled = !buttonStartServer.Enabled; buttonStartServer.Visible = !buttonStartServer.Visible; button_kickPlayer.Enabled = !button_kickPlayer.Enabled; numericUpDown_puertoEscucha.Enabled = !numericUpDown_puertoEscucha.Enabled; numericUpDown_maxPuntos.Enabled = !numericUpDown_maxPuntos.Enabled; numericUpDown_maxPlayers.Enabled = !numericUpDown_maxPlayers.Enabled; numericUpDown_maxRondas.Enabled = !numericUpDown_maxRondas.Enabled; numericUpDown_tiempoRonda.Enabled = !numericUpDown_tiempoRonda.Enabled; p.PartidaIniciada = false; } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { button_StopServer_Click(sender, e); } private void EnviarInstruccion(int numInstruccion, string mensaje = "") { lock (key) { Thread.Sleep(100); TcpClient cliente; NetworkStream ns; StreamReader sr; StreamWriter sw; #region Instruccion Nueva Partida - 3 if (numInstruccion == 3) //ENVIO INSTRUCCION DE NUEVA PARTIDA { p.RondaActual++; foreach (Jugador j in Jugadores) { j.PartidaFinalizada = false; j.RespuestaAdivinada = false; cliente = new TcpClient(j.Ip, j.PuertoEscucha); ns = cliente.GetStream(); sr = new StreamReader(ns); sw = new StreamWriter(ns); sw.WriteLine("#INICIARNUEVAPARTIDA#"); sw.Flush(); string dato = sr.ReadLine(); //recibe respuesta del cliente if (dato.Split('#')[1].Equals("OK")) { try { //Enviar Imagen Bitmap tImage = p.NewImg(); sw.WriteLine("#PISTA#" + p.Respuesta + "#"); sw.Flush(); ImageConverter imageConverter = new ImageConverter(); byte[] bStream = (byte[])imageConverter.ConvertTo(tImage, typeof(byte[])); //convierte imagen a array de byte ns.Write(bStream, 0, bStream.Length); } catch (SocketException er) { Console.WriteLine("Error Envio: " + er); } } else { Console.WriteLine("No se pudo iniciar la partida"); } cliente.Close(); } } #endregion #region Enviar Resultado total - 7 if (numInstruccion == 7) //ENVIAR RESULTADO TOTAL { if (Jugadores.All(c => c.PartidaFinalizada == true)) { string resultados = "#RESULTADOTOTAL#"; int cont = 0; foreach (Jugador j in Jugadores.OrderByDescending(c => c.Puntuacion)) { cont++; resultados += cont + ") " + j.Nick + " - " + j.Puntuacion + "#"; } foreach (Jugador j in Jugadores) { //Envio resultados a todos los clientes cliente = new TcpClient(j.Ip, j.PuertoEscucha); ns = cliente.GetStream(); sr = new StreamReader(ns); sw = new StreamWriter(ns); sw.WriteLine(resultados); sw.Flush(); } Console.WriteLine("ronda: " + p.RondaActual); //COMPRUEBA SI SE ALCANZÓ EL NUMERO MAX DE RONDAS, //TODO NUMERO MAX DE PUNTOS if (p.RondaActual < numericUpDown_maxRondas.Value) { EnviarInstruccion(3); } else { //FIN DE LA PARTIDA EnviarInstruccion(9); } } } #endregion #region Enviar Mensaje - 8 if (numInstruccion == 8) //ENVIO DE MENSAJE DE CHAT { foreach (Jugador j in Jugadores) { //envio info al primer cliente cliente = new TcpClient(j.Ip, j.PuertoEscucha); ns = cliente.GetStream(); sr = new StreamReader(ns); sw = new StreamWriter(ns); Console.WriteLine(j.Nick + ":" + mensaje); sw.WriteLine("#MSGCHAT#" + mensaje); sw.Flush(); } } #endregion #region EnviarDesconexion - 11 if (numInstruccion == 11 && mensaje == "") { foreach (Jugador j in Jugadores) { cliente = new TcpClient(j.Ip, j.PuertoEscucha); ns = cliente.GetStream(); sr = new StreamReader(ns); sw = new StreamWriter(ns); sw.WriteLine("#DESCONEXION#"); sw.Flush(); string dato = sr.ReadLine(); //recibe respuesta del cliente if (dato.Split('#')[1] == "OK") { j.Cliente.Close(); j.Cliente.Dispose(); } } } if (numInstruccion == 11 && mensaje != "") { if (listbox_connectedPlayers.SelectedIndex > -1) { try { string value = listbox_connectedPlayers.Text; string ip = value.Split(':')[1].Split(' ')[0].Trim(); int puerto = Convert.ToInt32(value.Split(':')[2].Trim()); cliente = new TcpClient(ip, puerto); ns = cliente.GetStream(); sr = new StreamReader(ns); sw = new StreamWriter(ns); sw.WriteLine("#DESCONEXION#"); sw.Flush(); string dato = sr.ReadLine(); //recibe respuesta del cliente if (dato.Split('#')[1] == "OK") { listbox_connectedPlayers.Items.RemoveAt(listbox_connectedPlayers.SelectedIndex); Jugadores.Remove(Jugadores.Where(c => c.PuertoEscucha.Equals(puerto)).First()); label_connectedPlayers.Text = "Jugadores conectados (" + Jugadores.Count + ")"; cliente.Close(); } } catch (Exception er) { Console.WriteLine(er); } } } #endregion #region FIN DE PARTIDA if (numInstruccion == 9) // FIN DE PARTIDA { p.PartidaIniciada = false; p.RondaActual = 0; p.ListaImg = p.Barajar(p.ListaImg); //recuento de puntos y podio List<Jugador> podio = new List<Jugador>(); podio = Jugadores.Where(c => c.Puntuacion.Equals(Jugadores.Max(x => x.Puntuacion))).ToList(); string clasificacion = "#"; if (podio.Count > 1) { clasificacion += "HAY " + podio.Count + " GANADORES EMPATADOS:#"; } else { clasificacion += "GANADOR:#"; } foreach (Jugador x in podio) { clasificacion += x.Nick.ToUpper() + " - " + x.Puntuacion + "PUNTOS#"; } foreach (Jugador j in Jugadores) { cliente = new TcpClient(j.Ip, j.PuertoEscucha); ns = cliente.GetStream(); sr = new StreamReader(ns); sw = new StreamWriter(ns); Console.WriteLine("ENTRO AQUI " + j.Nick + "pts: " + j.Puntuacion); j.Listoparajugar = false; j.PartidaFinalizada = false; j.Puntuacion = 0; j.RespuestaAdivinada = false; Console.WriteLine("SALIO AQUI " + j.Nick + "pts: " + j.Puntuacion); sw.WriteLine("#FINDEPARTIDA#=====FIN DE LA PARTIDA=====" + clasificacion); sw.Flush(); Console.WriteLine(sr.ReadLine()); } } #endregion } } private void CargarImagenes() { progressBar_imagenes.Maximum = Directory.GetFiles(Environment.CurrentDirectory + "/imagenes/").Count(); //Carga de imagenes en la lista string[] imagenes = Directory.GetFiles(Environment.CurrentDirectory + "/imagenes/"); foreach (string item in imagenes) { Bitmap img = new Bitmap(item); img.Tag = Path.GetFileName(item).Split('.')[0].Replace('_', ' ').ToLower().Trim(); p.ListaImg.Add(img); progressBar_imagenes.Value = p.ListaImg.Count(); } listbox_connectedPlayers.Items.Add(p.ListaImg.Count + " Imagenes cargadas"); p.ListaImg = p.Barajar(p.ListaImg); } private void button_kickPlayer_Click(object sender, EventArgs e) { EnviarInstruccion(11, "kickPlayer"); } } }
40.049383
160
0.406773
0bbe79eceec26074fa83f8e9b407653759ccf612
9,706
kt
Kotlin
glance/glance/src/test/kotlin/androidx/glance/layout/PaddingTest.kt
DSteve595/androidx
004096c49c04048ae493b9fa9c7e19ad7474e79d
[ "Apache-2.0" ]
null
null
null
glance/glance/src/test/kotlin/androidx/glance/layout/PaddingTest.kt
DSteve595/androidx
004096c49c04048ae493b9fa9c7e19ad7474e79d
[ "Apache-2.0" ]
null
null
null
glance/glance/src/test/kotlin/androidx/glance/layout/PaddingTest.kt
DSteve595/androidx
004096c49c04048ae493b9fa9c7e19ad7474e79d
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2021 The Android Open Source Project * * 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 androidx.glance.layout import android.content.res.Resources import android.util.DisplayMetrics import androidx.glance.GlanceModifier import androidx.glance.findModifier import androidx.compose.ui.unit.dp import com.google.common.truth.Truth.assertThat import com.nhaarman.mockitokotlin2.doReturn import com.nhaarman.mockitokotlin2.mock import org.junit.Test class PaddingTest { private val mockDisplayMetrics = DisplayMetrics().also { it.density = density } private val mockResources = mock<Resources>() { on { displayMetrics } doReturn mockDisplayMetrics on { getDimension(dimensionRes1) } doReturn dimension1InDp * density on { getDimension(dimensionRes2) } doReturn dimension2InDp * density } @Test fun buildPadding() { val modifiers = GlanceModifier.padding( start = 1.dp, top = 2.dp, end = 3.dp, bottom = 4.dp ) // Find the padding modifier... val paddingModifier = checkNotNull(modifiers.findModifier<PaddingModifier>()) assertThat(paddingModifier).isEqualTo( PaddingModifier( start = PaddingDimension(1.dp), top = PaddingDimension(2.dp), end = PaddingDimension(3.dp), bottom = PaddingDimension(4.dp), ) ) } @Test fun buildVerticalHorizontalPadding() { val modifiers = GlanceModifier.padding(vertical = 2.dp, horizontal = 4.dp) val paddingModifier = checkNotNull(modifiers.findModifier<PaddingModifier>()) assertThat(paddingModifier).isEqualTo( PaddingModifier( start = PaddingDimension(4.dp), top = PaddingDimension(2.dp), end = PaddingDimension(4.dp), bottom = PaddingDimension(2.dp), ) ) } @Test fun buildAllPadding() { val modifiers = GlanceModifier.padding(all = 5.dp) val paddingModifier = checkNotNull(modifiers.findModifier<PaddingModifier>()) assertThat(paddingModifier).isEqualTo( PaddingModifier( start = PaddingDimension(5.dp), top = PaddingDimension(5.dp), end = PaddingDimension(5.dp), bottom = PaddingDimension(5.dp), ) ) } @Test fun buildAbsolutePadding() { val modifiers = GlanceModifier.absolutePadding( left = 1.dp, top = 2.dp, right = 3.dp, bottom = 4.dp, ) val paddingModifier = checkNotNull(modifiers.findModifier<PaddingModifier>()) assertThat(paddingModifier).isEqualTo( PaddingModifier( left = PaddingDimension(1.dp), top = PaddingDimension(2.dp), right = PaddingDimension(3.dp), bottom = PaddingDimension(4.dp), ) ) } @Test fun extractPadding_shouldReturnNull() { val modifiers = GlanceModifier.then(object : GlanceModifier.Element {}) assertThat(modifiers.collectPadding()).isNull() assertThat(modifiers.collectPaddingInDp(mockResources)).isNull() } @Test fun mergePadding_noOrientation() { val modifiers = GlanceModifier.padding(horizontal = 15.dp).padding(vertical = dimensionRes1) val paddingModifier = checkNotNull(modifiers.collectPadding()) assertThat(paddingModifier).isEqualTo( PaddingModifier( start = PaddingDimension(15.dp), end = PaddingDimension(15.dp), top = PaddingDimension(dimensionRes1), bottom = PaddingDimension(dimensionRes1), ) ) val paddingInDp = checkNotNull(modifiers.collectPaddingInDp(mockResources)) assertThat(paddingInDp).isEqualTo( PaddingInDp( start = 15.dp, end = 15.dp, top = dimension1InDp.dp, bottom = dimension1InDp.dp, ) ) } @Test fun mergePadding_resetWithAll() { val modifiers = GlanceModifier.padding(horizontal = 12.dp).padding(all = dimensionRes2) val paddingModifier = checkNotNull(modifiers.collectPadding()) assertThat(paddingModifier).isEqualTo( PaddingModifier( start = PaddingDimension(dp = 12.dp, resources = listOf(dimensionRes2)), end = PaddingDimension(dp = 12.dp, resources = listOf(dimensionRes2)), top = PaddingDimension(dimensionRes2), bottom = PaddingDimension(dimensionRes2), ) ) val paddingInDp = checkNotNull(modifiers.collectPaddingInDp(mockResources)) assertThat(paddingInDp).isEqualTo( PaddingInDp( start = (12 + dimension2InDp).dp, end = (12 + dimension2InDp).dp, top = dimension2InDp.dp, bottom = dimension2InDp.dp, ) ) } @Test fun mergePadding_withRelativeOrientation() { val modifiers = GlanceModifier.padding(start = 15.dp, end = 12.dp, top = 20.dp) .padding(end = dimensionRes1) val paddingModifier = checkNotNull(modifiers.collectPadding()) assertThat(paddingModifier).isEqualTo( PaddingModifier( start = PaddingDimension(15.dp), end = PaddingDimension(dp = 12.dp, resources = listOf(dimensionRes1)), top = PaddingDimension(20.dp), ) ) } @Test fun mergePadding_withAbsoluteOrientation() { val modifiers = GlanceModifier.absolutePadding(left = 15.dp, right = 12.dp) .absolutePadding(left = dimensionRes1, bottom = dimensionRes2) val paddingModifier = checkNotNull(modifiers.collectPadding()) assertThat(paddingModifier).isEqualTo( PaddingModifier( left = PaddingDimension(dp = 15.dp, resources = listOf(dimensionRes1)), right = PaddingDimension(12.dp), bottom = PaddingDimension(dimensionRes2), ) ) } @Test fun mergePadding_setOrientationToRelative() { val modifiers = GlanceModifier.absolutePadding(left = 10.dp, right = 10.dp) .padding(start = dimensionRes1, end = dimensionRes2) val paddingModifier = checkNotNull(modifiers.collectPadding()) assertThat(paddingModifier).isEqualTo( PaddingModifier( start = PaddingDimension(dimensionRes1), end = PaddingDimension(dimensionRes2), left = PaddingDimension(10.dp), right = PaddingDimension(10.dp), ) ) } @Test fun mergePadding_setOrientationToAbsolute() { val modifiers = GlanceModifier.padding(start = dimensionRes1, end = dimensionRes2) .absolutePadding(left = 10.dp, right = 12.dp) val paddingModifier = checkNotNull(modifiers.collectPadding()) assertThat(paddingModifier).isEqualTo( PaddingModifier( left = PaddingDimension(10.dp), right = PaddingDimension(12.dp), start = PaddingDimension(dimensionRes1), end = PaddingDimension(dimensionRes2),) ) } @Test fun toRelative() { val paddingInDp = PaddingInDp( left = 1.dp, right = 2.dp, start = 10.dp, end = 20.dp, top = 50.dp, bottom = 100.dp, ) assertThat(paddingInDp.toRelative(isRtl = true)).isEqualTo( PaddingInDp( start = 12.dp, end = 21.dp, top = 50.dp, bottom = 100.dp, ) ) assertThat(paddingInDp.toRelative(isRtl = false)).isEqualTo( PaddingInDp( start = 11.dp, end = 22.dp, top = 50.dp, bottom = 100.dp, ) ) } @Test fun toAbsolute() { val paddingInDp = PaddingInDp( left = 1.dp, right = 2.dp, start = 10.dp, end = 20.dp, top = 50.dp, bottom = 100.dp, ) assertThat(paddingInDp.toAbsolute(isRtl = true)).isEqualTo( PaddingInDp( left = 21.dp, right = 12.dp, top = 50.dp, bottom = 100.dp, ) ) assertThat(paddingInDp.toAbsolute(isRtl = false)).isEqualTo( PaddingInDp( left = 11.dp, right = 22.dp, top = 50.dp, bottom = 100.dp, ) ) } private companion object { const val dimensionRes1 = 123 const val dimensionRes2 = 321 const val density = 2f const val dimension1InDp = 100f const val dimension2InDp = 200f } }
31.108974
100
0.576448
af7db0103645a1926e46acb65be4224b274784b2
1,486
py
Python
content/wagtail_hooks.py
bikramtuladhar/covid-19-procurement-explorer-admin
9bba473c8b83c8651e3178b6fba01af74d8b27dc
[ "BSD-3-Clause" ]
null
null
null
content/wagtail_hooks.py
bikramtuladhar/covid-19-procurement-explorer-admin
9bba473c8b83c8651e3178b6fba01af74d8b27dc
[ "BSD-3-Clause" ]
null
null
null
content/wagtail_hooks.py
bikramtuladhar/covid-19-procurement-explorer-admin
9bba473c8b83c8651e3178b6fba01af74d8b27dc
[ "BSD-3-Clause" ]
null
null
null
from wagtail.core import hooks @hooks.register("construct_main_menu") def hide_reports_menu_item(request, menu_items): menu_items[:] = [item for item in menu_items if item.name != "reports"] @hooks.register("construct_main_menu") def hide_settings_menu_item(request, menu_items): menu_items[:] = [item for item in menu_items if item.name != "settings"] @hooks.register("construct_main_menu") def hide_explorer_menu_item(request, menu_items): menu_items[:] = [item for item in menu_items if item.name != "explorer"] @hooks.register("construct_page_action_menu") def remove_submit_to_moderator_option(menu_items, request, context): menu_items[:] = [item for item in menu_items if item.name != "action-submit"] @hooks.register("construct_page_action_menu") def remove_delete_option(menu_items, request, context): menu_items[:] = [item for item in menu_items if item.name != "action-delete"] @hooks.register("construct_page_action_menu") def remove_lock_option(menu_items, request, context): menu_items[:] = [item for item in menu_items if item.name != "action-lock"] @hooks.register("construct_page_action_menu") def remove_unpublish_option(menu_items, request, context): menu_items[:] = [item for item in menu_items if item.name != "action-unpublish"] @hooks.register("construct_page_action_menu") def remove_save_draft_option(menu_items, request, context): menu_items[:] = [item for item in menu_items if item.name != "action-save-draft"]
35.380952
85
0.759758
2186c65af8b889931bc44f329140fea9186ffff1
480
lua
Lua
gamemode/sh_playermeta.lua
BlackVoid/deathrun
62d049f4e46a0f7a585eac4c2a4a3f6fd2a2b398
[ "MIT" ]
2
2016-01-06T01:57:24.000Z
2019-03-04T09:36:00.000Z
gamemode/sh_playermeta.lua
BlackVoid/deathrun
62d049f4e46a0f7a585eac4c2a4a3f6fd2a2b398
[ "MIT" ]
3
2015-03-10T22:32:14.000Z
2020-01-16T19:26:13.000Z
gamemode/sh_playermeta.lua
BlackVoid/deathrun
62d049f4e46a0f7a585eac4c2a4a3f6fd2a2b398
[ "MIT" ]
2
2015-01-12T23:38:32.000Z
2017-03-06T11:38:36.000Z
local meta = FindMetaTable( "Player" ) function meta:IsObserver() return ( self:Team() == TEAM_SPECTATOR or self:GetObserverMode() > OBS_MODE_NONE ); end if CLIENT then return end function meta:DeathrunSync() net.Start("DeathRun_GameState") net.WriteInt(GAMEMODE:GetGameState(), 4) net.Send(self) net.Start("DeathRun_Round") net.WriteInt(GAMEMODE:GetRound(), 8) net.Send(self) net.Start("DeathRun_LastWinner") net.WriteInt(GAMEMODE.LastWinner, 4) net.Send(self) end
22.857143
84
0.752083
a9e41deddc5bb79dfcac996cbd94103181fccee5
879
php
PHP
database/migrations/2018_10_04_184403_alter_clientes_table.php
ale395/proyecto_ferreteria
adaf55c20e94f2b646a1f16cd241bef093e31681
[ "MIT" ]
null
null
null
database/migrations/2018_10_04_184403_alter_clientes_table.php
ale395/proyecto_ferreteria
adaf55c20e94f2b646a1f16cd241bef093e31681
[ "MIT" ]
13
2018-05-03T13:10:57.000Z
2018-10-24T12:30:21.000Z
database/migrations/2018_10_04_184403_alter_clientes_table.php
ale395/proyecto_ferreteria
adaf55c20e94f2b646a1f16cd241bef093e31681
[ "MIT" ]
null
null
null
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AlterClientesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('clientes', function (Blueprint $table) { $table->decimal('limite_credito', 14, 2)->default(0); $table->integer('lista_precio_id')->nullable(); $table->foreign('lista_precio_id')->references('id')->on('lista_precios_cabecera'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('clientes', function (Blueprint $table) { $table->dropColumn('limite_credito'); $table->dropColumn('lista_precio_id'); }); } }
23.756757
95
0.588168
a40f3918d2d2178dae0e808cc6fc8ffa70868599
5,381
php
PHP
resources/views/pages/kontak.blade.php
ersadishla/SIYAP
e837736dd5fee4c068a999ca0fae558c3dfa38b0
[ "MIT" ]
null
null
null
resources/views/pages/kontak.blade.php
ersadishla/SIYAP
e837736dd5fee4c068a999ca0fae558c3dfa38b0
[ "MIT" ]
null
null
null
resources/views/pages/kontak.blade.php
ersadishla/SIYAP
e837736dd5fee4c068a999ca0fae558c3dfa38b0
[ "MIT" ]
null
null
null
<!doctype html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head> @include('layouts.header') </head> <body> <div id="page-container" class="sidebar-inverse side-scroll page-header-fixed main-content-boxed"> <header id="page-header"> @include('layouts.navbar') </header> <main id="main-container"> <div class="content"> <div class="col-xl-2"></div> <div class="col-xl-8"> <div class="block-content"> <h3 class="h2 block-title">Kritik dan Saran</h3> </div> <div class="block-content"> <p> Untuk Informasi & Layanan, silahkan menghubungi kami di kontak berikut, Kirimkan pesan, saran dan komentar kepada kami : </p> </div> <!-- Material (floating) Contact --> <div class="block block-themed"> <div class="block-options float-right"> <button type="button" class="btn-block-option" data-toggle="block-option" data-action="state_toggle" data-action-mode="demo"> <i class="si si-refresh"></i> </button> </div> <div class="block-content"> <form class="js-validation-material" action="#" method="post" onsubmit="return false;" novalidate="novalidate"> <div class="form-group row"> <div class="col-12"> <div class="form-material floating"> <input type="text" class="form-control" id="contact3-firstname" name="contact3-firstname"> <label for="contact3-firstname">Nama</label> </div> </div> </div> <div class="form-group row"> <div class="col-12"> <div class="form-material floating input-group"> <input type="email" class="form-control" id="contact3-email" name="contact3-email"> <label for="contact3-email">Email</label> <div class="input-group-append"> <span class="input-group-text"> <i class="fa fa-envelope-o"></i> </span> </div> </div> </div> </div> <div class="form-group row"> <div class="col-12"> <div class="form-material floating"> <input type="text" class="form-control" id="contact3-firstname" name="contact3-firstname"> <label for="contact3-firstname">Judul</label> </div> </div> </div> <div class="form-group row"> <div class="col-12"> <div class="form-material floating"> <textarea class="form-control" id="contact3-msg" name="contact3-msg" rows="7"></textarea> <label for="contact3-msg">Pesan</label> </div> </div> </div> <div class="form-group row"> <div class="col-12"> <button type="submit" class="btn btn-alt-info"> <i class="fa fa-send mr-5"></i> Send Message </button> </div> </div> </form> </div> </div> <!-- END Material (floating) Contact --> <div class="col-xl-2"></div> </div> </div> </main> <!-- Footer --> <footer id="page-footer" class="opacity-0 bg-light"> @include('layouts.footer') </footer> <!-- END Footer --> </div> </body> </html>
54.353535
157
0.328192
2d4ae0b9419417ceea63bf2030c839a5962da1e4
82
sql
SQL
src/test/resources/sql/alter_user/8c9cd152.sql
Shuttl-Tech/antlr_psql
fcf83192300abe723f3fd3709aff5b0c8118ad12
[ "MIT" ]
66
2018-06-15T11:34:03.000Z
2022-03-16T09:24:49.000Z
src/test/resources/sql/alter_user/8c9cd152.sql
Shuttl-Tech/antlr_psql
fcf83192300abe723f3fd3709aff5b0c8118ad12
[ "MIT" ]
13
2019-03-19T11:56:28.000Z
2020-08-05T04:20:50.000Z
src/test/resources/sql/alter_user/8c9cd152.sql
Shuttl-Tech/antlr_psql
fcf83192300abe723f3fd3709aff5b0c8118ad12
[ "MIT" ]
28
2019-01-05T19:59:02.000Z
2022-03-24T11:55:50.000Z
-- file:rolenames.sql ln:110 expect:true ALTER USER SESSION_USER WITH REPLICATION
27.333333
40
0.817073
a49b496d88b074e9e76f0528a9102ab17af93e7f
22,454
php
PHP
interfaces/intMP3toSQL.php
oyosoftware/oyomusic
3b01ae91c3773c6fa142372f9aec4ae9b4de375b
[ "MIT" ]
null
null
null
interfaces/intMP3toSQL.php
oyosoftware/oyomusic
3b01ae91c3773c6fa142372f9aec4ae9b4de375b
[ "MIT" ]
null
null
null
interfaces/intMP3toSQL.php
oyosoftware/oyomusic
3b01ae91c3773c6fa142372f9aec4ae9b4de375b
[ "MIT" ]
null
null
null
<?php error_reporting(22519); require_once('../settings.inc'); require_once('../plugins/getid3/getid3.php'); require_once('../helpers/functions.php'); function getLetter($name) { $letter = strunacc(mb_substr($name, 0, 1)); switch (true) { case preg_match("/[a-z]/", $letter): $letter = strtoupper($letter); break; case preg_match("/[A-Z]/", $letter): break; case preg_match("/[0-9]/", $letter): $letter = "#"; break; case $letter == "(": $letter = "&"; break; case!preg_match("/[A-Z]/", $letter): $letter = "$"; break; } return $letter; } function read_files($dir) { global $getID3, $link, $symaudiosource, $counter, $log, $encoders; $iter = new DirectoryIterator($dir); $itercounter = 0; $discnoprev = 0; $logged = false; $albumartistlogged = false; $albumtitlelogged = false; foreach ($iter as $item) { if ($item != '.' && $item != '..') { if ($item->isDir()) { read_files("$dir/$item"); } else { $ext = $item->getExtension(); if ($ext == 'mp3' or $ext == 'wav' or $ext == 'flac' or $ext == 'ogg') { $counter++; if (($counter % 10000) == 0) { echo "counter: " . $counter . " " . date('H:i:s') . "\r\n\r\n"; } $pos = mb_strlen($symaudiosource); $folder = mb_substr($item->getPath(), $pos); $filename = $item->getFilename(); $lastmodified = date("Ymd"); // fetch tags $itercounter++; $pathname = $item->getPathname(); $tag = $getID3->analyze($pathname); if ($ext == 'mp3' or $ext == 'wav') { $albumartist = $tag["tags"]["id3v2"]["band"][0]; $albumartistletter = getLetter($albumartist); $genre = $tag["tags"]["id3v2"]["genre"][0]; $released = $tag["tags"]["id3v2"]["year"][0]; $albumtitle = $tag["tags"]["id3v2"]["album"][0]; $discno = $tag["tags"]["id3v2"]["part_of_a_set"][0]; if (!$discno) { $discno = 1; } $artist = $tag["tags"]["id3v2"]["artist"][0]; $artistletter = getLetter($artist); $track = $tag["tags"]["id3v2"]["track_number"][0]; $tracktitle = $tag["tags"]["id3v2"]["title"][0]; } else { $albumartist = $tag["tags"]["vorbiscomment"]["albumartist"][0]; $albumartistletter = getLetter($albumartist); $genre = $tag["tags"]["vorbiscomment"]["genre"][0]; $released = $tag["tags"]["vorbiscomment"]["date"][0]; $albumtitle = $tag["tags"]["vorbiscomment"]["album"][0]; $discno = $tag["tags"]["vorbiscomment"]["discnumber"][0]; if (!$discno) { $discno = 1; } $artist = $tag["tags"]["vorbiscomment"]["artist"][0]; $artistletter = getLetter($artist); $track = $tag["tags"]["vorbiscomment"]["tracknumber"][0]; $tracktitle = $tag["tags"]["vorbiscomment"]["title"][0]; } $format = strtoupper($tag["audio"]["dataformat"]); $playingtime = round($tag["playtime_seconds"]); $bitrate = floor($tag["audio"]["bitrate"] / 1000); $bitratemode = mb_strtoupper($tag["audio"]["bitrate_mode"]); $id3warnings = $tag["warning"]; if ($id3warnings != null) { $tracklogged = false; foreach ($id3warnings as $value) { if ($value and strpos($value, "ID3v1") == false) { if ($tracklogged == false and $logged == false) { fwrite($log, "warning: file may be corrupt " . $folder . "/" . $filename . "\r\n"); } if ($logged == false) { fwrite($log, $value . "\r\n"); } $logged = true; $tracklogged = true; } } } // logging $error = false; $warning = false; if ($albumartist == "") { $error = true; if (!$albumartistlogged) { fwrite($log, "error: albumartist is empty for album $folder\r\n"); $logged = true; $albumartistlogged = true; } } if ($genre == "") { $warning = true; fwrite($log, "warning: genre is empty for track " . $folder . "/" . $filename . "\r\n"); $logged = true; } if (!is_numeric($released)) { $error = true; fwrite($log, "error: released is not numeric for track " . $folder . "/" . $filename . "\r\n"); $logged = true; } if ($albumtitle == "") { $error = true; if (!$albumtitlelogged) { fwrite($log, "error: albumtitle is empty for album $folder\r\n"); $logged = true; $albumtitlelogged = true; } } if (!is_numeric($discno)) { $error = true; fwrite($log, "error: discno is not numeric for track " . $folder . "/" . $filename . "\r\n"); $logged = true; } if ($artist == "") { $warning = true; fwrite($log, "warning: artist is empty for track " . $folder . "/" . $filename . "\r\n"); $logged = true; } //$track = $tag["tags"]["id3v2"]["track_number"][0]; if (!is_numeric($track)) { $warning = true; fwrite($log, "warning: track " . $track . " is not (completely) numeric for track " . $folder . "/" . $filename . "\r\n"); $pos = mb_strpos($track, "/"); $track = mb_substr($track, 0, $pos); if (!is_numeric($track)) { $error = true; fwrite($log, "error: track is still not numeric for track " . $folder . "/" . $filename . "\r\n"); } $logged = true; } if ($tracktitle == "") { $warning = true; fwrite($log, "warning: tracktitle is empty for track " . $folder . "/" . $filename . "\r\n"); $logged = true; } if ($error) { $itercounter--; continue; } // album artists if ($itercounter == 1) { $escalbumartist = mysqli_real_escape_string($link, $albumartist); $escalbumartistletter = mysqli_real_escape_string($link, $albumartistletter); $sql = "select * from artists where name = '$escalbumartist'"; $result = mysqli_query($link, $sql); if (mysqli_affected_rows($link) == 0) { $sqli = "insert into artists (name, letter, countryid) values ('$escalbumartist', '$escalbumartistletter', -1)"; mysqli_query($link, $sqli); $albumartistid = mysqli_insert_id($link); echo "insert " . $albumartist . "\r\n"; } else { $row = mysqli_fetch_assoc($result); $albumartistid = $row["Id"]; if ($row["Name"] != $albumartist or $row["Letter"] != $albumartistletter) { $sqlu = "update artists set name = '$escalbumartist', letter = '$escalbumartistletter' where id = $albumartistid"; mysqli_query($link, $sqlu); echo "update " . $albumartist . "\r\n"; } if ($row["Name"] != $albumartist) { fwrite($log, "warning: albumartist for album $folder has changed to $albumartist\r\n"); $logged = true; echo "warning: albumartist for album $folder has changed to $albumartist\r\n"; } } } // formats if ($itercounter == 1) { $sql = "select * from formats where format = '$format'"; $result = mysqli_query($link, $sql); if (mysqli_affected_rows($link) == 0) { $sqli = "insert into formats (format) values ('$format')"; mysqli_query($link, $sqli); $formatid = mysqli_insert_id($link); } else { $formatid = mysqli_fetch_assoc($result)["Id"]; } } // genres if ($itercounter == 1) { $escgenre = mysqli_real_escape_string($link, $genre); if ($escgenre <> '') { $sql = "select * from genres where genre = '$escgenre'"; $result = mysqli_query($link, $sql); if (mysqli_affected_rows($link) == 0) { $sqli = "insert into genres (genre) values ('$escgenre')"; mysqli_query($link, $sqli); $genreid = mysqli_insert_id($link); } else { $genreid = mysqli_fetch_assoc($result)["Id"]; } } else { $genreid = -1; } } // albums if ($itercounter == 1) { $escalbumtitle = mysqli_real_escape_string($link, $albumtitle); $escfolder = mysqli_real_escape_string($link, $folder); $symbols = array("\\", "/", ":", "*", "?", "\"", "<", ">", "|"); $falbumartist = str_replace($symbols, "_", $albumartist); $lastfolder = substr(strrchr($folder, '/'), 1); $imagefilename = $falbumartist . " - " . $lastfolder . ".jpg"; $escimagefilename = mysqli_real_escape_string($link, $imagefilename); $sql = "select * from albums where folder = '$escfolder'"; $result = mysqli_query($link, $sql); if (mysqli_affected_rows($link) == 0) { $sqli = "insert into albums (artistid, released, title, formatid, genreid, folder, imagefilename, lastmodified) values ($albumartistid, $released, '$escalbumtitle', $formatid, $genreid, '$escfolder', '$escimagefilename', $lastmodified)"; mysqli_query($link, $sqli); $albumid = mysqli_insert_id($link); echo "insert " . $albumartist . " - " . $released . " - " . $albumtitle . "\r\n"; } else { $row = mysqli_fetch_assoc($result); $albumid = $row["Id"]; if ($row["ArtistId"] != $albumartistid or $row["Released"] != $released or $row["Title"] != $albumtitle or $row["GenreId"] != $genreid) { $sqlu = "update albums set artistid = $albumartistid, released = $released, title = '$escalbumtitle', genreid = $genreid, lastmodified = $lastmodified where id = $albumid"; mysqli_query($link, $sqlu); echo "update " . $albumartist . " - " . $released . " - " . $albumtitle . "\r\n"; } if ($row["Folder"] != $folder or $row["ImageFileName"] != $imagefilename) { $sqlu = "update albums set folder = '$escfolder', imagefilename = '$escimagefilename', lastmodified = $lastmodified where id = $albumid"; mysqli_query($link, $sqlu); echo "update folder " . $albumartist . " - " . $released . " - " . $albumtitle . "\r\n"; } if ($row["Title"] != $albumtitle) { fwrite($log, "warning: albumtitle for album $folder has changed to $albumtitle\r\n"); $logged = true; echo "warning: albumtitle for album $folder has changed to $albumtitle\r\n"; } } } // discs if ($discno != $discnoprev) { $sql = "select * from discs where albumid = $albumid and discno = $discno"; $result = mysqli_query($link, $sql); if (mysqli_affected_rows($link) == 0) { $sqli = "insert into discs (albumid, discno) values ($albumid, $discno)"; mysqli_query($link, $sqli); } } // artists $escartist = mysqli_real_escape_string($link, $artist); $escartistletter = mysqli_real_escape_string($link, $artistletter); if ($artist <> '') { $sql = "select * from artists where name = '$escartist'"; $result = mysqli_query($link, $sql); if (mysqli_affected_rows($link) == 0) { $sqli = "insert into artists (name, letter, countryid) values ('$escartist', '$escartistletter', -1)"; mysqli_query($link, $sqli); $artistid = mysqli_insert_id($link); } else { $row = mysqli_fetch_assoc($result); $artistid = $row["Id"]; if ($row["Letter"] != $artistletter) { $sqlu = "update artists set letter = '$escartistletter' where id = $artistid"; mysqli_query($link, $sqlu); echo "update " . $artist . "\r\n"; } } } else { $artistid = -1; } // tracks $esctracktitle = mysqli_real_escape_string($link, $tracktitle); $escfolder = mysqli_real_escape_string($link, $folder); $escfilename = mysqli_real_escape_string($link, $filename); $sql = "select * from albums inner join tracks on id = albumid where folder = '$escfolder' and filename = '$escfilename'"; $result = mysqli_query($link, $sql); $affectedrows = mysqli_affected_rows($link); if ($affectedrows == 0) { $sql = "select * from tracks where albumid = $albumid and discno = $discno and track = $track"; $result = mysqli_query($link, $sql); if (mysqli_affected_rows($link) > 0) { $sqld = "delete from tracks where albumid = $albumid and discno = $discno and track = $track"; mysqli_query($link, $sqld); fwrite($log, "warning: key already exists for track and will be changed to " . $folder . "/" . $filename . "\r\n"); $logged = true; } } else { $row = mysqli_fetch_assoc($result); if ($row["AlbumId"] != $albumid or $row["DiscNo"] != $discno or $row["Track"] != $track) { $sql = "select * from tracks where albumid = $albumid and discno = $discno and track = $track"; $result = mysqli_query($link, $sql); if (mysqli_affected_rows($link) > 0) { $sqld = "delete from tracks where albumid = $albumid and discno = $discno and track = $track"; mysqli_query($link, $sqld); fwrite($log, "warning: key already exists for track and will be changed to:" . $folder . "/" . $filename . "\r\n"); $logged = true; } } } if ($affectedrows == 0) { $sqli = "insert into tracks (albumid, discno, track, title, artistid, playingtime, audiobitrate, audiobitratemode, filename, lastmodified) values ($albumid, $discno, $track, '$esctracktitle', $artistid, $playingtime, $bitrate, '$bitratemode', '$escfilename', $lastmodified)"; mysqli_query($link, $sqli); } else { $oldalbumid = $row["AlbumId"]; $olddiscno = $row["DiscNo"]; $oldtrack = $row["Track"]; if ($row["AlbumId"] != $albumid or $row["DiscNo"] != $discno or $row["Track"] != $track or $row["Title"] != $tracktitle or $row["ArtistId"] != $artistid or $row["PlayingTime"] != $playingtime or $row["AudioBitrate"] != $bitrate or $row["AudioBitrateMode"] != $bitratemode) { $sqlu = "update tracks set albumid = $albumid, discno = $discno, track = $track, title = '$esctracktitle', artistid = $artistid, playingtime = $playingtime, audiobitrate = $bitrate, audiobitratemode = '$bitratemode', lastmodified = $lastmodified where albumid = $oldalbumid and discno = $olddiscno and track = $oldtrack"; mysqli_query($link, $sqlu); } if ($row["FileName"] != $filename) { $sqlu = "update tracks set filename = '$escfilename, lastmodified = $lastmodified where albumid = $albumid and discno = $discno and track = $track"; mysqli_query($link, $sqlu); echo "update file " . $albumartist . " - " . $released . " - " . $albumtitle . " - " . $discno . "-" . $track . " - " . $tracktitle . "\r\n"; } if ($row["Title"] != $tracktitle) { fwrite($log, "warning: tracktitle for track $folder/$filename has changed to $tracktitle\r\n"); $logged = true; echo "warning: tracktitle for track $folder/$filename has changed to $tracktitle\r\n"; } } $discnoprev = $discno; } // endif ext mp3 } // end else not dir } // endif ./.. } // end items in dir if ($logged) { fwrite($log, "\r\n"); echo "\r\n"; } } $log = fopen("error.log", "w"); $link = mysqli_connect($server, $username, $password, $database); $getID3 = new getID3; $base = ""; //$base = "/World/123"; $path = $audiosource . $base; if (file_exists($path)) { $symaudiosource = "/#u"; if (file_exists($symaudiosource)) { rmdir($symaudiosource); } symlink($audiosource, $symaudiosource); $path = realpath($path); $path = str_ireplace("\\", "/", $path); $pos = mb_strlen($path) - mb_strlen($base); $base = mb_substr($path, $pos); $root = $symaudiosource . $base; echo "\r\njob begins for audiosource " . $audiosource . $base . " " . date('H:i:s') . "\r\n\r\n"; read_files($root); rmdir($symaudiosource); echo "counter: " . $counter . " " . date('H:i:s') . "\r\n\r\n"; echo "job is ready " . "\r\n"; } else { echo "\r\nError: path " . $path . " doesn't exist\r\n"; } mysqli_close($link); fclose($log); ?>
52.462617
170
0.398993
c4fe06d0e89af85642f74102c029023403bba445
917
hpp
C++
src/Jogo/Resources/TexturesHolder.hpp
MatheusKunnen/Jogo-TecProg
66f4320e51e42d12da74e487cc8552377ce865bb
[ "MIT" ]
null
null
null
src/Jogo/Resources/TexturesHolder.hpp
MatheusKunnen/Jogo-TecProg
66f4320e51e42d12da74e487cc8552377ce865bb
[ "MIT" ]
null
null
null
src/Jogo/Resources/TexturesHolder.hpp
MatheusKunnen/Jogo-TecProg
66f4320e51e42d12da74e487cc8552377ce865bb
[ "MIT" ]
null
null
null
// // TexturesHolder.hpp // Jogo-SFML // // Created by Matheus Kunnen Ledesma on 10/6/19. // Copyright © 2019 Matheus Kunnen Ledesma. All rights reserved. // #ifndef TexturesHolder_hpp #define TexturesHolder_hpp #include "../base_includes.hpp" #include "ResourcesHolder.hpp" namespace Game { namespace Resources{ namespace Textures { enum ID {bg_menu, bg_config, bg_ranking, bg_fase, bg_game, bg_pause, jogador_a, jogador_b, narcotraficante, desmatador, narcotraficante_desmatador, planta_venenosa, pedra, espinhos, projetil}; } class TextureHolder : public ResourceHolder<sf::Texture, Textures::ID>{ private: // Attributes static map<Textures::ID, string> default_filenames; // Const static const string DEFAULT_NOT_FILE; public: TextureHolder(); ~TextureHolder(); // Methods static const string& getFilename(Textures::ID id); }; };}; #endif /* TexturesHolder_hpp */
26.2
196
0.730643
1ab200b6e36a04dd14450670b70e4b47f73fbf71
20,089
py
Python
gitHubSpider.py
chroblert/sourceCodeCheck
5330bc40733ac7867bfe2fae8fa219633ac7ae82
[ "MIT" ]
6
2019-08-19T05:55:39.000Z
2021-02-02T07:21:23.000Z
gitHubSpider.py
chroblert/sourceCodeCheck
5330bc40733ac7867bfe2fae8fa219633ac7ae82
[ "MIT" ]
2
2021-03-31T19:09:04.000Z
2021-06-02T00:19:22.000Z
gitHubSpider.py
chroblert/sourceCodeCheck
5330bc40733ac7867bfe2fae8fa219633ac7ae82
[ "MIT" ]
11
2019-11-13T01:07:14.000Z
2021-05-10T01:25:27.000Z
# @Author: JC import requests import json from lxml import etree from tool import read_json_file_to_object from tool import get_html from tool import save_object_to_json_file from tool import save_html_response_to_html_file from tool import read_txt_file_to_list from tool import Logger from login import get_cookie_from_github from copy import deepcopy import re import os import sys import time import hashlib import shutil def get_html_with_keyword(keyword,cookie,pageNum = 1): ''' 抓取包含关键词的某一页的user/project ''' url = 'https://github.com/search?o=desc&q="'+ keyword + '"&s=indexed&type=Code&p='+ str(pageNum) html = get_html(url,cookie = cookie) if html != 'Fail': dom_tree = etree.HTML(html) # xpath匹配 userProjects = dom_tree.xpath('//*[@id="code_search_results"]/div[1]/div/div[1]/div/a[1]/text()') for userProject in userProjects: print(userProject) bottomTab = dom_tree.xpath('//*[@id="code_search_results"]/div[2]/div/a/text()') isEnd = True for tab in bottomTab: # print(tab) if tab == "Next": isEnd = False if not isEnd: print("第%d页结束,继续下一页"%pageNum) else: print("整体结束") else: isEnd = False userProjects = [] return isEnd,userProjects def get_all_user_project_with_keyword(keyword = 'chroblert',cookie={}): ''' 抓取包含关键词的所有页的user/project ''' print("抓取所有包含%s关键词的user和project"%keyword) pageNum = 0 #isEnd,allUserProjectList = get_html_with_keyword(keyword = keyword,cookie = cookie,pageNum = pageNum) isEnd = False allUserProjectList = [] while(not isEnd): pageNum = pageNum + 1 isEnd,userProjectList = get_html_with_keyword(keyword = keyword,cookie = cookie,pageNum = pageNum) if len(userProjectList) == 0: #pageNum = pageNum -1 print('没有获取到%d页的内容,继续抓取第%d页'%(pageNum-1,pageNum)) else: allUserProjectList.extend(userProjectList) print(userProjectList) return allUserProjectList def save_List_to_file(dataList,fileName = 'allUserProjectList.txt'): with open(fileName,'w') as f: for i in dataList: f.write(i) f.write('\n') # print("保存成功") def file_data_process(uri): ''' 该函数用于处理初始的格式为user/project的字符串,整理成一个字典,并存储为json文件 :uri 包含字符串的文件 ''' userProjectDict = {} with open(uri,'r') as f: lineList = f.readlines() print(len(lineList)) for i in lineList: user,project = i.split('/') project = project.replace('\n','') print(user) if user not in userProjectDict.keys(): userProjectDict[user] = [] if project not in userProjectDict[user]: userProjectDict[user].append(project) #print(userProjectDict) return userProjectDict def get_all_fileLink_one_user_one_project(userName,projectName,cookie = {}): url = 'https://github.com/' + userName + '/' + projectName return deepcopy(get_fileLink_use_recursive(url = url,cookie = cookie)) def get_fileLink_use_recursive(url,cookie = {}): ''' 递归实现抓取文件链接 ''' # 1. 结束条件:当访问目录url获得的内容里只有文件名,没有目录名(理想情况);特殊情况(无法访问目标url),同样结束 html = get_html(url = url ,cookie = cookie) fileLinkList = [] # 第一个递归结束条件 print("递归查找 %s 目录下的文件"%url) if html == 'Fail' : # print('html = Fail,结束递归: ' + url) return [] else: dom_tree = etree.HTML(html) fileAndDirLinkList = dom_tree.xpath('//tr[@class="js-navigation-item" or @class="js-navigation-item navigation-focus"]//td[@class="content"]//a/@href') fileLinkCount = 0 for fileOrDirLink in fileAndDirLinkList: # 为链接前加上https://github.com fileOrDirLink = 'https://github.com' + fileOrDirLink # if fileOrDirLink.split('/')[3] == 'blob': if fileOrDirLink.split('/')[5] == 'blob': # 代表是文件 # fileLink的个数。 fileLinkCount = fileLinkCount + 1 # add:只有在文件后缀格式不为可读文件的情况下,才添加进fileLinkList中 if fileOrDirLink.split('.')[len(fileOrDirLink.split('.')) - 1] in ['jpg','png','gif','ico','svg','zip','rar','exe','bin','jar','mp3','mp4','class','pdf']: print('不记录不可读文件链接') pass else: fileLinkList.append(fileOrDirLink) else: # 说明是目录 searchResult = get_fileLink_use_recursive(fileOrDirLink) # print("查找结束,返回查找到的fileLinkList") # print(searchResult) fileLinkList.extend(searchResult) # 第二个递归结束条件:若fileLink的个数为fileOrDirLink列表中元素的个数,则结束递归 if fileLinkCount == len(fileAndDirLinkList): # print('该目录下全部为文件链接,结束递归:' + url) # 返回查找得到的fileLinkList return fileLinkList # 递归返回结果 return fileLinkList class userItem: ''' 一个用于存储用户、权重、项目列表、文件链接列表的结构 ''' def __init__(self): self.userName = '' # 名称 self.weight = 0 # 权重 self.projectList = [] # 包含关键词的项目的list self.fileLinkDict = {} # 包含关键词的文件链接的dict 格式为 {"project1":["fileLink1","fileLink2","fileLink3"],"project2":["fileLink1","fileLink2","fileLink3"]} def get_all_fileLink(dataDict,cookie = {}): ''' 根据dataDict得到所有的文件链接 :dataDict 是上面定义的结构 ''' userItemList = [] for user in dataDict.keys(): print("user:" + user) uItem = userItem() uItem.userName = user uItem.projectList.extend(dataDict[user]) fileLinkDict = {} for project in dataDict[user]: #print(project) allFileLinkList = get_all_fileLink_one_user_one_project(userName = user,projectName = project,cookie = cookie) fileLinkDict[project] = [] fileLinkDict[project].extend(allFileLinkList) print("%s 用户 %s 项目内包含敏感信息的文件链接:=======================") print(allFileLinkList) uItem.fileLinkDict.update(fileLinkDict) userItemList.append(uItem) #print(userItemList) return userItemList def read_json_file_to_userItemList(fileName): ''' 从json格式的文件中读取数据并返回一饿userItemList :fileName 存储json数据的文件名 ''' allUserItemList = read_json_file_to_object(fileName) # print(allUserItemList) allUItemList = [] for uItem in allUserItemList: usItem = userItem() usItem.userName = uItem['userName'] usItem.weight = uItem['weight'] usItem.projectList.extend(deepcopy(uItem['projectList'])) usItem.fileLinkDict= deepcopy(uItem['fileLinkDict']) allUItemList.append(usItem) return allUItemList def save_userItemList_to_json_file(userItemList,fileName = 'userItemList.json'): ''' 该函数将从json文件中读取数据并将其转换为userItem类型,存储在一个list中 ''' tempList = [] tempDict = {} for userItem in userItemList: tempDict['userName'] = userItem.userName tempDict['weight'] = userItem.weight tempDict['projectList'] = userItem.projectList tempDict['fileLinkDict'] = userItem.fileLinkDict tempList.append(deepcopy(tempDict)) save_object_to_json_file(tempList,fileName) def search_all_sensitive_data_in_one_file(fileLink,cookie = {}): ''' 从给定的fileLink中去查找一些关键信息,并进行匹配返回 :fileLink 文件链接 :cookie 维持登录状态的cookie值 :return fileWeight,fileHtml,list(set(retIPList)),list(set(retDomainList)),list(set(havedSensitiveKeywordList)) ''' companyIPList = read_txt_file_to_list(uri = companyIPListUri) companyDomainList = read_txt_file_to_list(companyDomainListUri) sensitiveKeywordList = read_txt_file_to_list(sensitiveKeywordListUri) fileWeight = 0 # 用来表示该文件包含敏感信息源码的程度,若为0,则表明为正常文件 # 1. 获取到该文件中的内容 html = get_html(url = fileLink,cookie=cookie) htmlFileName = str(fileLink.split('/')[len(fileLink.split('/'))-1]) + ".html" if html != "Fail": dom_tree = etree.HTML(html) # print(html) dom_tree_xpath_result_list = dom_tree.xpath('/html/body/div[4]/div/main//div[@itemprop="text" or@ id="readme"]') fileHtml = '' if len(dom_tree_xpath_result_list) != 0: fileHtml = (etree.tostring(dom_tree_xpath_result_list[0])).decode('utf-8') else: save_html_response_to_html_file(html,'ttttt.html') print("没有匹配到文本中的内容") # 2. 提取出响应内容中的所有IP allIPList = list(set(re.findall(r'\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b',fileHtml))) # print("该文件内包含的IP如下:") # print(allIPList) save_List_to_file(allIPList,'allIPList.txt') # 求出companyIPList与allIPList的交集 # retIPList = list(set(allIPList).intersection(set(companyIPList))) retIPList = [i for i in allIPList if i in list(set(companyIPList)) ] # 通过交集IPlist的len() 来判断该文件内容中是否有公司的服务器IP isHaveCompanyIP = True if len(retIPList) == 0: isHaveCompanyIP = False print("该文件内不包含公司服务器的IP地址") else: fileWeight = fileWeight + len(retIPList) print("包含的公司IP如下:") print(list(set(retIPList))) # print(allIP) # 3. 提取出响应内容的所有域名url # allDomainUrlList = list(set(re.findall(r'\b(https?:\/\/.*\.?com|cn|org|edu)\b',fileHtml))) # allDomainUrlList = list(set(re.findall(r'(http|https)://(\w+\.){1,3}\w+',fileHtml))) allDomainUrlList = re.findall(r'\b((?:http|https)://(?:[\w|-]+\.){1,}\w+)\b',fileHtml) # print("该文件内包含的域名如下:") # print(allDomainUrlList) save_List_to_file(list(set(allDomainUrlList)),'allDomainUrlList.txt') # 求出allDomainUrlList中的url包含company关键字的url的list retDomainList = [i for i in allDomainUrlList if company in i] # 通过交集domainList的len()来判断该文件内容中是否有公司的domain isHaveCompanyDomain = True if len(retDomainList) == 0: isHaveCompanyDomain = False print("该文件内不包含公司服务器的域名") else: fileWeight = fileWeight + len(retDomainList) print("包含的公司域名如下:") print(list(set(retDomainList))) # 4. 检索该文件内是否有一些敏感信息词汇 isHaveSensitiveKeyword = True havedSensitiveKeywordList = [] for sensitiveKeyword in sensitiveKeywordList: regPattern = re.compile(r'' + sensitiveKeyword + '') result = regPattern.findall(fileHtml) havedSensitiveKeywordList.extend(result) if len(havedSensitiveKeywordList) == 0: isHaveSensitiveKeyword = False print("不包含一些敏感信息词汇") else: fileWeight = fileWeight + len(havedSensitiveKeywordList) print("包含的敏感词汇如下:") print(list(set(havedSensitiveKeywordList))) else: print("在GitHub上读取 %s 文件失败"%fileLink) fileWeight = 0 fileHtml = '' retIPList = [] retDomainList = [] havedSensitiveKeywordList = [] return fileWeight,fileHtml,list(set(retIPList)),list(set(retDomainList)),list(set(havedSensitiveKeywordList)) # 4. 响应内容中是否包含普通敏感关键词 def get_sensitive_info_for_one_file(fullDir,fileLink,cookie = {}): ''' 对于给定的文件链接,调用search_all_sensitive_data_in_one_file()函数,去得到一些关键信息。 若文件内包含敏感信息,则fileWeight为相应的权重,returnInfo包含文件存储名,文件权重,文件敏感词list,domainlist,IPList :fullDir是为某用户某项目创建的目录 :fileLink是某用户某项目内的一个文件的链接 :cookie是去访问链接时需要用到的cookie :return fileWeight,returnInfo ''' fileWeight,fileHtml,retIPList,retDomainList,havedSensitiveKeywordList = search_all_sensitive_data_in_one_file(fileLink = fileLink,cookie = cookie) if fileWeight != 0: toStoreFileNameB = str(fileLink.split('/')[len(fileLink.split('/'))-1]) # 此处对要保存的文件名做处理,因为字符个数限制,否则可能会报错 # 格式为 :url编码后的源文件名-MD5(除了用户和项目名之外的url编码后的文件名).html fileNameUsedToComputeMD5Hash = '-'.join(fileLink.split('/')[5:]) + ".html" fileNameMD5Hash = str(hashlib.md5(fileNameUsedToComputeMD5Hash.encode('utf-8')).hexdigest()) toStoreFileNameA = toStoreFileNameB + '-' + fileNameMD5Hash + '.html' toStoreFileName = fullDir + '/' + toStoreFileNameA # 将包含敏感信息的文件的具体内容下载到本地 print("将包含敏感信息的文件的具体内容下载到本地") save_html_response_to_html_file(responseData = fileHtml,htmlFileName=toStoreFileName) # toStoreInfo = userName + '|#|' + projectName + '|#|' + toStoreFileNameA + '|#|' + str(fileWeight) + '|#|' + ' , '.join(havedSensitiveKeywordList) + '|#|' + ' , '.join(retDomainList) + '|#|' + ' , '.join(retIPList) returnInfo = toStoreFileNameA + '|#|' + str(fileWeight) + '|#|' + ' , '.join(havedSensitiveKeywordList) + '|#|' + ' , '.join(retDomainList) + '|#|' + ' , '.join(retIPList) else: returnInfo = '' return fileWeight,returnInfo def get_sensitive_info_for_one_userProject(scanResultDir,userName,projectName,userItemDict,cookie = {}): ''' 获取用户某个项目带有敏感信息的情况 ''' # fullUserProjectDir是针对于某个用户的某个项目的目录 fullUserProjectDir = scanResultDir + '/' + userName + '/' + projectName if not os.path.exists(fullUserProjectDir): os.makedirs(fullUserProjectDir) userProjectWeight = 0 with open(fullUserProjectDir + '/result.txt','w',encoding = 'utf-8') as f: f.write('userName|#|projectName|#|fileLinkUrl|#|toStoreFileName|#|fileWeight|#|havedSensitiveKeywordList|#|retDomainList|#|retIPList') f.write('\n') fileLinkUrlList = userItemDict.fileLinkDict[projectName] for fileLinkUrl in fileLinkUrlList: print("|||||======%s--->%s--->%s ======|||||"%(userName,projectName,fileLinkUrl)) fileWeight,fileInfo = get_sensitive_info_for_one_file(fullDir = fullUserProjectDir,fileLink = fileLinkUrl,cookie = cookie) if fileWeight != 0: toStoreFileInfoWithUserProjectName = userName + '|#|' + projectName + '|#|' + fileLinkUrl + '|#|' + fileInfo with open( fullUserProjectDir + '/result.txt','a',encoding = 'utf-8') as f: f.write(toStoreFileInfoWithUserProjectName) f.write('\n') userProjectWeight = userProjectWeight + fileWeight else: pass return userProjectWeight def get_sensitive_info_for_one_user(scanResultDir,userName,userItemDict,cookie = {}): ''' 获取一个用户带有敏感信息的情况 ''' projectNameList = userItemDict.projectList userWeight = 0 os.makedirs(scanResultDir + '/' + userName) with open(scanResultDir + '/' + userName + '/result.txt','w',encoding = 'utf-8') as f: f.write('userName|#|projectName|#|userProjectWeight') f.write('\n') for projectName in projectNameList: print("|||||======%s--->%s ======|||||"%(userName,projectName)) userProjectWeight = get_sensitive_info_for_one_userProject(scanResultDir = scanResultDir,userName = userName,projectName = projectName,userItemDict = userItemDict,cookie = cookie) if userProjectWeight != 0 : toStoreUserProjectInfo = userName + '|#|' + projectName + '|#|' + str(userProjectWeight) with open(scanResultDir + '/' + userName + '/result.txt','a',encoding = 'utf-8') as f: f.write(toStoreUserProjectInfo) f.write('\n') userWeight = userWeight + userProjectWeight else: pass return userWeight def get_sensitive_info_for_github(scanResultDir,userItemList,cookie = {}): ''' 获取GitHub上关于敏感信息的情况 ''' # userNameList = ['qiumingzhao'] with open(scanResultDir + '/result.txt','w',encoding = 'utf-8') as f: f.write('userName|#|userWeight') f.write('\n') for userItemDict in userItemList: # print(type(userItemDict)) userName = userItemDict.userName print("|||||======%s======|||||"%userName) userWeight = get_sensitive_info_for_one_user(scanResultDir = scanResultDir,userName = userName,userItemDict = userItemDict,cookie = cookie) if userWeight != 0: toStoreUserInfo = userName + '|#|' + str(userWeight) with open(scanResultDir + '/result.txt','a',encoding = 'utf-8') as f: f.write(toStoreUserInfo) f.write('\n') else: # 删除为该用户创建的目录 pathToBeDelete = scanResultDir + '/' + userName try: shutil.rmtree(pathToBeDelete) except OSError as e: print(e) else: print("The directory is deleted successfully") print('在Github上的源码扫描结束') def get_all_user_project_with_all_keyword(uri = 'companyKeywords.txt',cookie = {}): ''' 获取所有带有关键词的所有的用户名和项目名 ''' allUserProjectList = [] companyKeywordList = read_txt_file_to_list(uri = uri) for companyKeyword in companyKeywordList: # 将list转为set再转为list是为了去掉初始list中的重复数据 allUserProjectList.extend(list(set(get_all_user_project_with_keyword(keyword = companyKeyword,cookie = cookie)))) return deepcopy(list(set(allUserProjectList))) def show_search_result(scanResultDirUri): ''' 将最后所有的结果收集起来,并存储进show-result.txt文件中 ''' userResultTxtUri = scanResultDirUri + '/result.txt' userList = read_txt_file_to_list(userResultTxtUri) userList = deepcopy(userList[1:]) allUserProjectFileList = [] for user in userList: userProjectResultTxtUri = scanResultDirUri + '/' + user.split('|#|')[0] + '/result.txt' userProjectList = read_txt_file_to_list(userProjectResultTxtUri) userProjectList = deepcopy(userProjectList[1:]) for userProject in userProjectList: userProjectFileResultTxtUri = scanResultDirUri + '/' + user.split('|#|')[0] + '/' + userProject.split('|#|')[1] + '/result.txt' userProjectFileList = read_txt_file_to_list(userProjectFileResultTxtUri) allUserProjectFileList.extend(deepcopy(userProjectFileList[1:])) save_List_to_file(allUserProjectFileList,scanResultDirUri + '/show-result.txt') if __name__ == '__main__': scanTimeAsDir = time.strftime('%Y%m%d%H%M',time.localtime(time.time())) scanResultDir = 'scanResult/' + scanTimeAsDir if not os.path.exists(scanResultDir): os.makedirs(scanResultDir) overallScanResultUri = scanResultDir + '/' + 'scanResult.txt' logPath = scanResultDir + '/Logs' if not os.path.exists(logPath): os.makedirs(logPath) sys.stdout = Logger(logPath + '/info.log',sys.stdout) sys.stderr = Logger(logPath + '/error.log',sys.stderr) sys.stderr = Logger(logPath + '/error.log',sys.stderr) # 一些重要文件 company='chroblert' #公司的一个标志信息 companyKeywordListUri = './config/companyKeywords.txt' companyIPListUri = './config/companyIP.txt' companyDomainListUri = './config/companyDomain.txt' sensitiveKeywordListUri = './config/sensitiveKeywords.txt' # 1. 拿到用于保持登录状态的cookie cookie = get_cookie_from_github(refreshCookie=False) print(cookie) # 2. 拿到包含所有关键词的所有用户名/项目名 allUserProjectList = get_all_user_project_with_all_keyword(uri = companyKeywordListUri,cookie = cookie) save_List_to_file(allUserProjectList,fileName = 'allUserProjectList.txt') # print(allUserProjectList) # 3. 将格式为用户名/项目名的字符串进行处理,存储为字典格式,并保存到json文件中 allUserProjectListUri = "allUserProjectList.txt" userProjectDict = file_data_process(allUserProjectListUri) save_object_to_json_file(userProjectDict,'allUserProjectDict.json') # # 4. 在某用户的某个仓库中搜索关键词,得到仓库中所有包含该关键词的文件链接,并将结果保存到json文件中 allUserProjectDictUri = 'allUserProjectDict.json' allUserProjectDict = read_json_file_to_object(allUserProjectDictUri) allUserItemList = get_all_fileLink(allUserProjectDict,cookie = cookie) # print("保存成文件") save_userItemList_to_json_file(allUserItemList,fileName = 'allUserItemList.json') allUserItemListUri = 'allUserItemList.json' # 5. 读取文件中的数据 allUserItemList = read_json_file_to_userItemList(allUserItemListUri) # print(allUserItemList) get_sensitive_info_for_github(scanResultDir = scanResultDir,userItemList = allUserItemList,cookie=cookie) # 6. 搜集所有的数据并存放进一个文件中 show_search_result(scanResultDir)
42.203782
225
0.650057
b349145897d9a1a95fac6e2faebd41ba8edd3362
2,379
py
Python
p2ner/components/produceroverlay/centralproducerclient/centralproducerclient/core.py
schristakidis/p2ner
46694a41e8c1ebdc28f520b58c126da8785f3eed
[ "Apache-2.0" ]
2
2015-06-01T22:04:34.000Z
2017-07-06T09:35:00.000Z
p2ner/components/produceroverlay/centralproducerclient/centralproducerclient/core.py
schristakidis/p2ner
46694a41e8c1ebdc28f520b58c126da8785f3eed
[ "Apache-2.0" ]
null
null
null
p2ner/components/produceroverlay/centralproducerclient/centralproducerclient/core.py
schristakidis/p2ner
46694a41e8c1ebdc28f520b58c126da8785f3eed
[ "Apache-2.0" ]
1
2019-11-26T10:22:35.000Z
2019-11-26T10:22:35.000Z
# -*- coding: utf-8 -*- # Copyright 2012 Loris Corazza, Sakis Christakidis # # 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. from p2ner.abstract.overlay import Overlay from messages.peerlistmessage import AddProducerMessage from messages.peerremovemessage import ClientStoppedMessage,ClientDied from twisted.internet import reactor class CentralClient(Overlay): def registerMessages(self): self.messages = [] self.messages.append(AddProducerMessage()) self.messages.append(ClientStoppedMessage()) self.messages.append(ClientDied()) def initOverlay(self): self.log.info('initing producer overlay') self.sanityCheck(["stream", "control", "controlPipe"]) self.registerMessages() self.neighbours = [] def getNeighbours(self): return self.neighbours[:] def addNeighbour(self, peer): if not self.isNeighbour(peer): if self.netChecker.nat and peer.ip==self.netChecker.externalIp: peer.useLocalIp=True self.neighbours.append(peer) self.log.info('adding %s to neighborhood',peer) if self.scheduler.loopingCall.running: reactor.callLater(0.1, self.scheduler.sendLPB, peer) else: self.log.error("%s yet in overlay" ,peer) raise ValueError("%s peer yet in overlay" % str(peer)) def removeNeighbour(self, peer): try: self.neighbours.remove(peer) self.log.info('removing %s from neighborhood',peer) print 'removing from producer neighborhood ',peer except: self.log.error('%s is not a neighbor',peer) def isNeighbour(self, peer): return peer in self.neighbours def stop(self): self.log.info('stopping overlay') if __name__ == "__main__": a = CentralClient()
34.478261
76
0.668768
25bd735f0deb5efb24206de80862d5da843725c9
1,174
cs
C#
GigHub/GigHub/Controllers/HomeController.cs
ivannk0900/GigHub
297ddc9a39f7bda48cbcafb6a57ca3b9416c97a2
[ "MIT" ]
null
null
null
GigHub/GigHub/Controllers/HomeController.cs
ivannk0900/GigHub
297ddc9a39f7bda48cbcafb6a57ca3b9416c97a2
[ "MIT" ]
null
null
null
GigHub/GigHub/Controllers/HomeController.cs
ivannk0900/GigHub
297ddc9a39f7bda48cbcafb6a57ca3b9416c97a2
[ "MIT" ]
null
null
null
using GigHub.Models; using System.Web.Mvc; using System.Data.Entity; using System.Linq; using System; using GigHub.ViewModels; namespace GigHub.Controllers { public class HomeController : Controller { private ApplicationDbContext context; public HomeController() { this.context = new ApplicationDbContext(); } public ActionResult Index() { var upcomingGigs = this.context.Gigs .Include(g => g.Artist) .Include(g => g.Genre) .Where(g => g.DateTime > DateTime.Now); var viewModel = new GigsViewModel { UpcomingGigs = upcomingGigs, ShowActions = User.Identity.IsAuthenticated, Heading = "Upcoming Gigs" }; return View("Gigs", viewModel); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } } }
23.48
67
0.53833
e9acfcbf1e8d63ec725b5eedd7cc7aac7ef464fe
1,671
rs
Rust
arwa/src/storage.rs
RSSchermer/ARWA
5f20dd338d0086505d1c8ac7f47e260d3cb1dd8e
[ "MIT" ]
null
null
null
arwa/src/storage.rs
RSSchermer/ARWA
5f20dd338d0086505d1c8ac7f47e260d3cb1dd8e
[ "MIT" ]
null
null
null
arwa/src/storage.rs
RSSchermer/ARWA
5f20dd338d0086505d1c8ac7f47e260d3cb1dd8e
[ "MIT" ]
null
null
null
use wasm_bindgen::{throw_val, JsCast, UnwrapThrowExt}; use crate::collection::Collection; use crate::dom_exception_wrapper; use crate::impl_common_wrapper_traits; dom_exception_wrapper!(StorageQuotaExceeded); #[derive(Clone)] pub struct Storage { inner: web_sys::Storage, } impl Storage { pub fn key_at(&self, index: u32) -> Option<String> { self.inner.key(index).unwrap_throw() } pub fn get(&self, key: &str) -> Option<String> { // No indication in the spec that this can fail, unwrap for now. self.inner.get_item(key).unwrap_throw() } pub fn set(&self, key: &str, value: &str) { if let Err(err) = self.inner.set_item(key, value) { throw_val(err) } } pub fn try_set(&self, key: &str, value: &str) -> Result<(), StorageQuotaExceeded> { self.inner .set_item(key, value) .map_err(|err| StorageQuotaExceeded::new(err.unchecked_into())) } pub fn remove(&self, key: &str) { // No indication in the spec that this can fail, unwrap for now. self.inner.remove_item(key).unwrap_throw(); } pub fn clear(&self) { // No indication in the spec that this can fail, unwrap for now. self.inner.clear().unwrap_throw(); } } impl Collection for Storage { fn len(&self) -> u32 { self.inner.length().unwrap_throw() } } impl From<web_sys::Storage> for Storage { fn from(inner: web_sys::Storage) -> Self { Storage { inner } } } impl AsRef<web_sys::Storage> for Storage { fn as_ref(&self) -> &web_sys::Storage { &self.inner } } impl_common_wrapper_traits!(Storage);
25.318182
87
0.62298
a87e22e9c89fda6fd3f01cec5a534147f19f6e5c
4,473
swift
Swift
LibraryComponents/Classes/AndesDropdown/AndesDropdown.swift
oesierra/fury_andesui-ios
ea26f816ac1f4346c590613f766d4d07b3a0bd03
[ "MIT" ]
1
2021-04-03T23:10:21.000Z
2021-04-03T23:10:21.000Z
LibraryComponents/Classes/AndesDropdown/AndesDropdown.swift
oesierra/fury_andesui-ios
ea26f816ac1f4346c590613f766d4d07b3a0bd03
[ "MIT" ]
null
null
null
LibraryComponents/Classes/AndesDropdown/AndesDropdown.swift
oesierra/fury_andesui-ios
ea26f816ac1f4346c590613f766d4d07b3a0bd03
[ "MIT" ]
null
null
null
// // AndesDropdown.swift // AndesUI // // Created by Jonathan Alonso Pinto on 13/11/20. // import Foundation @objc public class AndesDropdown: UIView { private var contentView: AndesDropdownView! private var didSelect: Bool = false { didSet { self.updateView() didSelect.toggle() } } /// Set the trigger type, default is formDropdown @objc public var triggerType: AndesDropdownTrigger { didSet { self.updateContentView() self.setContentView() } } /// Set the menu type, default is bottomsheet @objc public var menuType: AndesDropdownMenu { didSet { self.setContentView() } } /// Set the delegate @objc public weak var delegate: AndesDropdownDelegate? private let rootViewController = UIApplication.shared.keyWindow?.rootViewController @objc public init() { self.triggerType = AndesDropdownTrigger() self.menuType = AndesDropdownMenu(rows: []) super.init(frame: .zero) setup() } required init?(coder: NSCoder) { self.triggerType = AndesDropdownTrigger() self.menuType = AndesDropdownMenu(rows: []) super.init(coder: coder) setup() } private func setup() { translatesAutoresizingMaskIntoConstraints = false self.backgroundColor = .clear drawContentView(with: provideView()) } private func getConfig() -> AndesDropdownViewConfig { return AndesDropdownViewConfigFactory.provide(from: self, isSelected: didSelect) } private func provideView() -> AndesDropdownView { switch self.triggerType.type { case .formDropdown: return AndesDropdownFormViewDefault(withConfig: getConfig()) case .standalone: return AndesDropdownStandaloneView(withConfig: getConfig()) } } private func drawContentView(with newView: AndesDropdownView) { self.contentView = newView self.contentView.delegate = self addSubview(contentView) contentView.pinToSuperview() } private func updateView() { contentView.update(withConfig: getConfig()) } private func updateContentView() { self.contentView.removeFromSuperview() drawContentView(with: provideView()) contentView.update(withConfig: getConfig()) } private func setContentView() { guard menuType.rows.count != 0 else { return } switch self.triggerType.type { case .standalone: contentView.text = menuType.rows[0].title case .formDropdown: contentView.text = "" } } } extension AndesDropdown: AndesDropdownViewDelegate { func didSelectTrigger() { didSelect.toggle() openMenuType() } func openMenuType() { switch self.menuType.type { case .bottomSheet: self.openSheet() case .floatingMenu: break } } } extension AndesDropdown { private func openSheet() { guard let viewController = configViewController() else { return } let sheet = AndesBottomSheetViewController(rootViewController: viewController) rootViewController?.present(sheet, animated: true) } func configViewController() -> UIViewController? { guard let menuType = self.menuType as? DropdownBottomSheetMenu else { return nil } let viewController = AndesDropdownBottomSheetViewController(nibName: "AndesDropdownBottomSheetViewController", bundle: AndesDropdownBundle.bundle()) viewController.delegate = self viewController.configController(menuCellType: menuType.rows, numberOfLines: self.menuType.numberOfLines, separatorStyle: menuType.separatorStyle, selectionStyle: menuType.selectionStyle) return viewController } } extension AndesDropdown: AndesDropdownBottomSheetViewDelegate { func didSelectRowAt(indexPath: IndexPath) { rootViewController?.dismiss(animated: true) self.contentView.text = menuType.rows[indexPath.row].title delegate?.didSelectRowAt(indexPath: indexPath) } func dismiss() { self.updateView() } }
29.045455
118
0.623966
93e9a07b88e583d3ee33472c4827fc544a7fddc5
595
cs
C#
Vostok.ClusterClient/Transforms/IRequestTransform.cs
vostok-archives/clusterclient.prototype
6bed632fa1e938bef54db0e6cb316790657d48e6
[ "MIT" ]
null
null
null
Vostok.ClusterClient/Transforms/IRequestTransform.cs
vostok-archives/clusterclient.prototype
6bed632fa1e938bef54db0e6cb316790657d48e6
[ "MIT" ]
null
null
null
Vostok.ClusterClient/Transforms/IRequestTransform.cs
vostok-archives/clusterclient.prototype
6bed632fa1e938bef54db0e6cb316790657d48e6
[ "MIT" ]
null
null
null
using JetBrains.Annotations; using Vostok.Clusterclient.Model; namespace Vostok.Clusterclient.Transforms { /// <summary> /// <para>Represents a transform used to modify request before it gets sent.</para> /// <para>Requests transforms form a chain where each transform works with a result of previous one.</para> /// </summary> public interface IRequestTransform { /// <summary> /// Implementations of this method MUST BE thread-safe. /// </summary> [Pure] [NotNull] Request Transform([NotNull] Request request); } }
29.75
111
0.653782
93b3cd6b5d6bb9d25991d08d08aa452cc8d136ea
1,262
cs
C#
III. Introduction to OOP/Pokemon Trainer/StartUp.cs
FullscreenSauna/IT-Career
e6fe31ae4b18c75ae2362364c3090c1457250319
[ "MIT" ]
null
null
null
III. Introduction to OOP/Pokemon Trainer/StartUp.cs
FullscreenSauna/IT-Career
e6fe31ae4b18c75ae2362364c3090c1457250319
[ "MIT" ]
null
null
null
III. Introduction to OOP/Pokemon Trainer/StartUp.cs
FullscreenSauna/IT-Career
e6fe31ae4b18c75ae2362364c3090c1457250319
[ "MIT" ]
2
2019-07-01T14:19:31.000Z
2019-07-04T09:51:27.000Z
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Pokemon_Trainer { class StartUp { static void Main(string[] args) { string command; var trainers = new Dictionary<string, Trainer>(); while ((command = Console.ReadLine()) != "Tournament") { var info = command.Split().ToArray(); string trainerName = info[0]; string pokemonName = info[1]; string type = info[2]; int health = int.Parse(info[3]); if (!trainers.ContainsKey(trainerName)) { trainers.Add(trainerName, new Trainer(trainerName)); } trainers[trainerName].Pokemons.Add(new Pokemon(pokemonName, type, health)); } while ((command = Console.ReadLine()) != "End") { foreach (var trainer in trainers) { trainer.Value.Battle(command); } } trainers.Values.OrderByDescending(t => t.Badges).ToList().ForEach(t => Console.WriteLine(t)); } } }
26.851064
105
0.504754
63eaf677d134b52573535dfc948ab397813990fe
2,577
ps1
PowerShell
SCCM/Invoke-DGASoftwareUpdateMaintenance/Plugins/Disabled/Decline-ByConfigMgrFolder_To Decline.ps1
ennnbeee/mem-scripts
98bd5c49a44de1cf63ad3de12f3010b33f406967
[ "MIT" ]
null
null
null
SCCM/Invoke-DGASoftwareUpdateMaintenance/Plugins/Disabled/Decline-ByConfigMgrFolder_To Decline.ps1
ennnbeee/mem-scripts
98bd5c49a44de1cf63ad3de12f3010b33f406967
[ "MIT" ]
null
null
null
SCCM/Invoke-DGASoftwareUpdateMaintenance/Plugins/Disabled/Decline-ByConfigMgrFolder_To Decline.ps1
ennnbeee/mem-scripts
98bd5c49a44de1cf63ad3de12f3010b33f406967
[ "MIT" ]
null
null
null
<# This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. #> ################################################################################ #.SYNOPSIS # Decline-ByConfigMgrFolder_To Decline.ps1 # A helper script function to identify Software Updates in ConfigMgr/SCCM # moved to a folder named "To Decline" # for declining in WSUS and expiring in ConfigMgr/SCCM #.LINK # Reference Invoke-DGASoftwareUpdateMaintenance.ps1 #.NOTES # This script is invoked by Invoke-DGASoftwareUpdateMaintenance.ps1 and not run independently # # ========== Keywords ========== # Keywords: WSUS SUP SCCM ConfigMgr Decline Expire Update Maintenance Superseded # ========== Change Log History ========== # - 2020/08/13 by Chad.Simmons@CatapultSystems.com - Created # - 2020/08/13 by Chad@ChadsTech.net - Created # === To Do / Proposed Changes === # - TODO: None ################################################################################ Function Invoke-SelectUpdatesPlugin{ $PluginName = 'Decline-ByConfigMgrFolder' $FolderPath = 'To Decline' $DeclineUpdates = @{} Add-TextToCMLog $LogFile "Discovering Updates in ConfigMgr" $PluginName 1 $ConfigMgrUpdatesInFolder = @(Get-CMSoftwareUpdate -Fast -IsExpired $false | Where-Object { $_.ObjectPath -eq "/$FolderPath" } | Select-Object CI_UniqueID).CI_UniqueID #-IsDeployed $false Add-TextToCMLog $LogFile "$($ConfigMgrUpdatesInFolder.count) Updates discovered in ConfigMgr in the folder [$FolderPath]" $PluginName 1 $UpdatesMatchingConfigMgr = $ActiveUpdates | Where-Object { $_.Id.UpdateId -in $ConfigMgrUpdatesInFolder } Add-TextToCMLog $LogFile "$($UpdatesMatchingConfigMgr.count) Updates in WSUS match an Update in ConfigMgr in the folder [$FolderPath]" $PluginName 1 #Loop through the updates and decline any that match the version. ForEach ($Update in $UpdatesMatchingConfigMgr) { $DeclineUpdates.Set_Item($Update.Id.UpdateId, "ConfigMgr Folder of [$FolderPath]") } Return $DeclineUpdates }
51.54
191
0.696158
6973c2e06e85dfc88714b49d252da76085a1833c
355
kt
Kotlin
SingleModuleApp/app/src/main/java/com/github/yamamotoj/singlemoduleapp/package53/Foo05317.kt
yamamotoj/android_multi_module_experiment
2a771697dfebca9201f6df5ef8441578b5102641
[ "Apache-2.0" ]
9
2019-02-08T06:51:52.000Z
2021-04-28T03:45:59.000Z
SingleModuleApp/app/src/main/java/com/github/yamamotoj/singlemoduleapp/package53/Foo05317.kt
yamamotoj/android_multi_module_experiment
2a771697dfebca9201f6df5ef8441578b5102641
[ "Apache-2.0" ]
null
null
null
SingleModuleApp/app/src/main/java/com/github/yamamotoj/singlemoduleapp/package53/Foo05317.kt
yamamotoj/android_multi_module_experiment
2a771697dfebca9201f6df5ef8441578b5102641
[ "Apache-2.0" ]
null
null
null
package com.github.yamamotoj.singlemoduleapp.package53 class Foo05317 { fun method0() { Foo05316().method5() } fun method1() { method0() } fun method2() { method1() } fun method3() { method2() } fun method4() { method3() } fun method5() { method4() } }
12.678571
54
0.484507
79b91ff293fbbeec616a810f55b75d371dcf62ad
522
php
PHP
src/AdapterInterface.php
metarush/log-once
3342cd13856ad7dc28719d5b7215682b491c989d
[ "MIT" ]
1
2021-02-13T19:45:27.000Z
2021-02-13T19:45:27.000Z
src/AdapterInterface.php
metarush/log-once
3342cd13856ad7dc28719d5b7215682b491c989d
[ "MIT" ]
null
null
null
src/AdapterInterface.php
metarush/log-once
3342cd13856ad7dc28719d5b7215682b491c989d
[ "MIT" ]
null
null
null
<?php declare(strict_types=1); namespace MetaRush\LogOnce; interface AdapterInterface { /** * Logs the message * * @param string $hash * @param string $message * @param string $timeZone * @return void */ public function log(string $hash, string $message, string $timeZone): void; /** * Check if a log hash exists and not yet marked as read * * @param string $hash * @return bool */ public function logExistAndNotYetRead(string $hash): bool; }
20.076923
79
0.616858
90a3e5a5ee2a94a3946d0986932a4203f1d423b4
2,958
rb
Ruby
spec/lib/config/base_spec.rb
test-classroom-for-github/test-a1
0ef7b494f39773c90d2cdf0b044b2368a5625431
[ "MIT" ]
null
null
null
spec/lib/config/base_spec.rb
test-classroom-for-github/test-a1
0ef7b494f39773c90d2cdf0b044b2368a5625431
[ "MIT" ]
null
null
null
spec/lib/config/base_spec.rb
test-classroom-for-github/test-a1
0ef7b494f39773c90d2cdf0b044b2368a5625431
[ "MIT" ]
null
null
null
require 'gitomator/classroom' require 'gitomator/classroom/config/base' require 'securerandom' require 'tmpdir' describe Gitomator::Classroom::Config::Base do it "should set the config attribute, when instantiating from hash" do expected = { 'a' + SecureRandom.hex => SecureRandom.hex, 'a' + SecureRandom.hex => 42, 'a' + SecureRandom.hex => Time.now } actual = Gitomator::Classroom::Config::Base.from_hash(expected).config expect(expected).to eq(actual) end describe 'Subclasses' do it "should have attr_reader when declaring a property" do class SubClass1 < Gitomator::Classroom::Config::Base property :name end foo = SubClass1.from_hash({ 'name' => 'Alice' }) expect(foo.name).to eq('Alice') end it "should not have attr_reader without declaring a property" do class SubClass2 < Gitomator::Classroom::Config::Base # No properties decalred end foo = SubClass2.from_hash({ 'name' => 'Alice' }) expect(foo).to_not respond_to(:name) end it "should raise an error, if a required property is missing" do class SubClass3 < Gitomator::Classroom::Config::Base property :name, { :required => true } end expect do SubClass3.from_hash({ 'age' => 27 }) end.to raise_error(Gitomator::Classroom::Exception::InvalidConfig) end it "should not raise an error, when a required property is present" do class SubClass4 < Gitomator::Classroom::Config::Base property :name, { :required => true } end SubClass4.from_hash({ 'name' => 'Alice' }) end it "should use the default property value, if the value is missing" do class SubClass5 < Gitomator::Classroom::Config::Base property :name, { :default => 'John Doe' } end expect(SubClass5.from_hash({}).name).to eq('John Doe') end it "should not use the default property value, if the value is specified" do class SubClass6 < Gitomator::Classroom::Config::Base property :name, { :default => 'John Doe' } end expect(SubClass6.from_hash({'name' => 'Alice'}).name).to eq('Alice') end it "should raise an error, if a directory property does not exist" do class SubClass7 < Gitomator::Classroom::Config::Base property :home, { :is_dir => true } end # Let's come up with a path that (most likely) doesn't exist path = "/#{SecureRandom.hex}/#{SecureRandom.hex}/#{SecureRandom.hex}" expect do SubClass7.from_hash({ 'home' => path }) end.to raise_error(Gitomator::Classroom::Exception::InvalidConfig) end it "should not raise an error, if a directory property exists" do class SubClass8 < Gitomator::Classroom::Config::Base property :home, { :is_dir => true } end Dir.mktmpdir { |path| SubClass8.from_hash({ 'home' => path }) } end end end
27.137615
80
0.640636
0d6807e7c0aa2d1f9a946fd9a834c222f050ee2d
234
cs
C#
ShoppingList/Controllers/ShoppingEventPageController.cs
Benivere/ShoppingList
89326cc9cdb0dadb317a4dcfea7f2c5a74bda7c5
[ "Apache-2.0" ]
null
null
null
ShoppingList/Controllers/ShoppingEventPageController.cs
Benivere/ShoppingList
89326cc9cdb0dadb317a4dcfea7f2c5a74bda7c5
[ "Apache-2.0" ]
null
null
null
ShoppingList/Controllers/ShoppingEventPageController.cs
Benivere/ShoppingList
89326cc9cdb0dadb317a4dcfea7f2c5a74bda7c5
[ "Apache-2.0" ]
null
null
null
using System.Web.Mvc; namespace ShoppingList.Controllers { public class ShoppingEventPageController : Controller { public ActionResult Index() { return View("ShoppingEventPage"); } } }
19.5
57
0.628205
c334a0c67df2c862da189ff2797ef5e0db54f49b
593
kt
Kotlin
app/src/main/java/com/XD/fitgain/views/fragments/Config1.kt
fabriciohernandez/fitgain_aca
e2f0046e6bd6e178169bf314a8742c20b4ad4168
[ "MIT" ]
null
null
null
app/src/main/java/com/XD/fitgain/views/fragments/Config1.kt
fabriciohernandez/fitgain_aca
e2f0046e6bd6e178169bf314a8742c20b4ad4168
[ "MIT" ]
7
2021-07-08T02:43:00.000Z
2021-07-10T04:59:42.000Z
app/src/main/java/com/XD/fitgain/views/fragments/Config1.kt
fabriciohernandez/fitgain_aca
e2f0046e6bd6e178169bf314a8742c20b4ad4168
[ "MIT" ]
1
2021-09-29T23:49:37.000Z
2021-09-29T23:49:37.000Z
package com.XD.fitgain.views.fragments import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.XD.fitgain.databinding.FragmentConfig1Binding class Config1 : Fragment() { private lateinit var binding: FragmentConfig1Binding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentConfig1Binding.inflate(inflater, container, false) return binding.root } }
24.708333
76
0.757167
dbca8b0751ce42afd18d3bc0215b959c868f6725
446
php
PHP
application/back/validate/ArticleValidate.php
zygals/weilaitp
274a711fcd2086ad585a2dd88d9546f7eac72e7e
[ "Apache-2.0" ]
null
null
null
application/back/validate/ArticleValidate.php
zygals/weilaitp
274a711fcd2086ad585a2dd88d9546f7eac72e7e
[ "Apache-2.0" ]
null
null
null
application/back/validate/ArticleValidate.php
zygals/weilaitp
274a711fcd2086ad585a2dd88d9546f7eac72e7e
[ "Apache-2.0" ]
null
null
null
<?php namespace app\back\validate; use think\Validate; class ArticleValidate extends Validate{ protected $rule = [ 'name' => 'require', 'cate' => 'require|number', 'cont' => 'require', 'sort' => 'number', 'index_show' => 'boolean', ]; protected $message = [ 'name.require' => '名称必须', 'cate.require' => '分类必须', 'cont.require' => '内容必须', ]; protected $scene = [ //'goodnew' => ['name','cate_id'], ]; }
15.928571
39
0.560538
07716af3f8b14aca3ee0a30f115e1da40c35c9ea
250
sql
SQL
MySQL/May-2019/Subqueries_and_Joins/Exercise/02.Addresses_with_Towns.sql
IvayloIV/Java
862785b40c68ee4ddcf3b4ff9989467b95eb1780
[ "MIT" ]
null
null
null
MySQL/May-2019/Subqueries_and_Joins/Exercise/02.Addresses_with_Towns.sql
IvayloIV/Java
862785b40c68ee4ddcf3b4ff9989467b95eb1780
[ "MIT" ]
24
2020-01-17T20:44:40.000Z
2022-01-21T23:49:06.000Z
MySQL/May-2019/Subqueries_and_Joins/Exercise/02.Addresses_with_Towns.sql
IvayloIV/Java
862785b40c68ee4ddcf3b4ff9989467b95eb1780
[ "MIT" ]
null
null
null
SELECT e.first_name, e.last_name, t.name AS 'town', a.address_text FROM employees AS e JOIN addresses AS a ON e.address_id = a.address_id JOIN towns AS t ON a.town_id = t.town_id ORDER BY e.first_name ASC, e.last_name ASC LIMIT 5;
17.857143
30
0.708
5807d2dcb4ea9e162bf428d27a483efe4985e701
321
lua
Lua
Assets/LuaScripts/Modulus/ECS/LComponent/Factory/LPositionComp.lua
nizhenchao/ECS_XLua
aa60d66754f18faea66f6b2e0a9a02a7cfefc15d
[ "Apache-2.0" ]
2
2018-12-21T05:53:56.000Z
2019-03-18T05:08:32.000Z
Assets/LuaScripts/Modulus/ECS/LComponent/Factory/LPositionComp.lua
woxinfeixiang2012/ECS_XLua
cb54750c78783a4ead78b578d4c97ea973429d1e
[ "Apache-2.0" ]
null
null
null
Assets/LuaScripts/Modulus/ECS/LComponent/Factory/LPositionComp.lua
woxinfeixiang2012/ECS_XLua
cb54750c78783a4ead78b578d4c97ea973429d1e
[ "Apache-2.0" ]
1
2018-10-11T06:16:42.000Z
2018-10-11T06:16:42.000Z
LPositionComp = SimpleClass(LComponent) function LPositionComp:__init(type,uid,args) self.pos = Vector3(args[1],args[2],args[3]) self.isArrive = false end function LPositionComp:isNeedUpdate() return not self.isArrive end function LPositionComp:update(pos) self.pos = pos self.isArrive = false end
21.4
47
0.741433
3f55823cade6989a797a207cc7f9367d5126d79c
1,199
sql
SQL
migrations/1610908266000_create_mentor_proposals_table/up.sql
rcos/rcos-ap
5ea4072f0593fe034a90fdc44baae22ae94863e6
[ "MIT" ]
2
2021-01-16T13:21:06.000Z
2021-01-18T01:51:57.000Z
migrations/1610908266000_create_mentor_proposals_table/up.sql
rcos/rcos-ap
5ea4072f0593fe034a90fdc44baae22ae94863e6
[ "MIT" ]
23
2021-01-12T03:38:45.000Z
2022-02-02T20:11:14.000Z
migrations/1610908266000_create_mentor_proposals_table/up.sql
rcos/rcos-ap
5ea4072f0593fe034a90fdc44baae22ae94863e6
[ "MIT" ]
1
2021-01-17T17:04:38.000Z
2021-01-17T17:04:38.000Z
CREATE TABLE mentor_proposals ( semester_id VARCHAR, username VARCHAR, reason TEXT NOT NULL, skillset TEXT NOT NULL, reviewer_username VARCHAR, reviewer_comments TEXT, is_approved boolean DEFAULT false, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), PRIMARY KEY (semester_id, username), FOREIGN KEY (semester_id, username) REFERENCES enrollments (semester_id, username), FOREIGN KEY (semester_id, reviewer_username) REFERENCES enrollments (semester_id, username) ); COMMENT ON TABLE mentor_proposals IS 'Users Interested in mentoring each semester must submit a proposal and be approved'; COMMENT ON COLUMN mentor_proposals.username IS 'Username of mentor to-be'; COMMENT ON COLUMN mentor_proposals.reason IS 'The reason the user would like to mentor'; COMMENT ON COLUMN mentor_proposals.skillset IS 'Short details of technologies user can mentor for'; COMMENT ON COLUMN mentor_proposals.reviewer_username IS 'Username of coordinator/faculty who reviewed proposal'; COMMENT ON COLUMN mentor_proposals.reviewer_comments IS 'Optional comments left by reviewer'; COMMENT ON COLUMN mentor_proposals.is_approved IS 'True if user was approved to become a mentor for the semester';
44.407407
93
0.812344
38db55392c5b60800bb8007107c15cdc2d537b3f
6,299
php
PHP
resources/views/admin/site/formulario.blade.php
hugopascoal2570/ProjetoBolsa
492788d9ca05dfc86167d6d025edb71e5e63e301
[ "MIT" ]
null
null
null
resources/views/admin/site/formulario.blade.php
hugopascoal2570/ProjetoBolsa
492788d9ca05dfc86167d6d025edb71e5e63e301
[ "MIT" ]
null
null
null
resources/views/admin/site/formulario.blade.php
hugopascoal2570/ProjetoBolsa
492788d9ca05dfc86167d6d025edb71e5e63e301
[ "MIT" ]
null
null
null
@extends('layouts.app') @extends('site.layout') @extends('site.style.form') @section('title', 'Informe seus dados') @section('script') <script> jQuery(document).ready(function() { $('.phone').mask.mask('(00) 00000-0000'); $('.cpf').mask('000.000.000-00', { reverse: true }); $('#date').mask('00/00/0000'); }); </script> @endsection @section('content') <!-- bradcam_area --> <div class="bradcam_area bradcam_bg_1"> <div class="container"> <div class="row"> <div class="col-xl-12"> <div class="bradcam_text"> <h3></h3> </div> </div> </div> </div> </div> <form action="{{ route('cadastroEtapa2') }}" method="POST" id="regForm" enctype="multipart/form-data"> @csrf @include('site.includes.alerts') <h1>Conclua seu cadastro</h1> <div class="tab">Nome: <p><input type="text" name="name" placeholder="Nome" oninput="this.className = ''"></p> <label>Data de Nascimento</label> <p><input type="date" name="birthdate" oninput="this.className = ''"></p> </div> @foreach ($dados as $dado) <input type="hidden" name="id" value="{{ $dado->id }}"> @endforeach <div class="tab">CPF: <p><input type="text" name="cpf" placeholder="000.000.000-00" data-mask="000.000.000-00" oninput="this.className = ''"></p> <label>Telefone</label> <p><input type="text" name="phone" placeholder="(00) 00000-0000" data-mask="(00) 00000-0000" oninput="this.className = ''"></p> <label>Nacionalidade</label> <select class="form-control" name="nacionalidade" required> <option value="Brasileiro">Brasileiro(a)</option> <option value="Estrangeiro">Estrangeiro(a)</option> </select> </div> <div class="tab">Foto: <input type="file" id="image" name="image" class="from-control-file" oninput="this.className = ''"> </div> <div style="overflow:auto;"> <div style="float:right;"> <button type="button" class="btn btn-info float-left" id="prevBtn" class="previus btn btn-info float-left" onclick="nextPrev(-1)">Anterior</button> <button type="button" class="next btn btn-info float-right" id="nextBtn" style="padding-left: 2.5rem; padding-right: 2.5rem;" onclick="nextPrev(1)">Próximo</button> </div> </div> <!-- Circles which indicates the steps of the form: --> <div style="text-align:center;margin-top:40px;"> <span class="step"></span> <span class="step"></span> <span class="step"></span> <span class="step"></span> </div> </form> <script> var currentTab = 0; // Current tab is set to be the first tab (0) showTab(currentTab); // Display the current tab function showTab(n) { // This function will display the specified tab of the form ... var x = document.getElementsByClassName("tab"); x[n].style.display = "block"; // ... and fix the Previous/Next buttons: if (n == 0) { document.getElementById("prevBtn").style.display = "none"; } else { document.getElementById("prevBtn").style.display = "inline"; } if (n == (x.length - 1)) { document.getElementById("nextBtn").innerHTML = "Enviar"; } else { document.getElementById("nextBtn").innerHTML = "Próximo"; } // ... and run a function that displays the correct step indicator: fixStepIndicator(n) } function nextPrev(n) { // This function will figure out which tab to display var x = document.getElementsByClassName("tab"); // Exit the function if any field in the current tab is invalid: if (n == 1 && !validateForm()) return false; // Hide the current tab: x[currentTab].style.display = "none"; // Increase or decrease the current tab by 1: currentTab = currentTab + n; // if you have reached the end of the form... : if (currentTab >= x.length) { //...the form gets submitted: document.getElementById("regForm").submit(); return false; } // Otherwise, display the correct tab: showTab(currentTab); } function validateForm() { // This function deals with validation of the form fields var x, y, i, valid = true; x = document.getElementsByClassName("tab"); y = x[currentTab].getElementsByTagName("input"); // A loop that checks every input field in the current tab: for (i = 0; i < y.length; i++) { // If a field is empty... if (y[i].value == "") { // add an "invalid" class to the field: y[i].className += " invalid"; // and set the current valid status to false: valid = false; } } // If the valid status is true, mark the step as finished and valid: if (valid) { document.getElementsByClassName("step")[currentTab].className += " finish"; } return valid; // return the valid status } function fixStepIndicator(n) { // This function removes the "active" class of all steps... var i, x = document.getElementsByClassName("step"); for (i = 0; i < x.length; i++) { x[i].className = x[i].className.replace(" active", ""); } //... and adds the "active" class to the current step: x[n].className += " active"; } </script>
37.494048
122
0.505001
e741efee87feb59af95bc941781bc12a08d08fcb
828
php
PHP
database/seeds/ParametroSeeder.php
Fed3x/citymarket_comercial
1f7f4ddb4f9e70524ac87e1966f6ab1ce8cfe2ca
[ "MIT" ]
null
null
null
database/seeds/ParametroSeeder.php
Fed3x/citymarket_comercial
1f7f4ddb4f9e70524ac87e1966f6ab1ce8cfe2ca
[ "MIT" ]
5
2020-10-28T18:18:26.000Z
2022-02-19T00:58:48.000Z
database/seeds/ParametroSeeder.php
Fed3x/citymarket_comercial
1f7f4ddb4f9e70524ac87e1966f6ab1ce8cfe2ca
[ "MIT" ]
null
null
null
<?php use Illuminate\Database\Seeder; use App\Parametro; use Carbon\Carbon; class ParametroSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $parametros = [ [ 'descripcion' => 'FECHAS', 'created_at' => Carbon::now(), 'estado' => true ], [ 'descripcion' => 'PRODUCTOS', 'created_at' => Carbon::now(), 'estado' => true ], [ 'descripcion' => 'SUCURSALES', 'created_at' => Carbon::now(), 'estado' => true ] ]; foreach($parametros as $parametro){ Parametro::create($parametro); } } }
21.789474
46
0.417874
491c819596ac4942f9bad13c18b7e1d324d6f71e
17,270
py
Python
models/netmodel.py
ISCAS007/pix2pix
50d61e0db7e49e3a5e7595ac1a469055df74b939
[ "BSD-3-Clause" ]
null
null
null
models/netmodel.py
ISCAS007/pix2pix
50d61e0db7e49e3a5e7595ac1a469055df74b939
[ "BSD-3-Clause" ]
null
null
null
models/netmodel.py
ISCAS007/pix2pix
50d61e0db7e49e3a5e7595ac1a469055df74b939
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*- # @Time : 2019/9/13 15:36 # @Author : liufang # @File : model.py import os import sys import cv2 import numpy as np import torch import torch.nn as nn from torch.nn import init import torch.optim as optim import torch.nn.functional as F import functools from models.seg_model import get_segmentation_network nclass=11 def init_weights(net, init_type='normal', init_gain=0.02): """Initialize network weights. Parameters: net (network) -- network to be initialized init_type (str) -- the name of an initialization method: normal | xavier | kaiming | orthogonal init_gain (float) -- scaling factor for normal, xavier and orthogonal. We use 'normal' in the original pix2pix and CycleGAN paper. But xavier and kaiming might work better for some applications. Feel free to try yourself. """ def init_func(m): # define the initialization function classname = m.__class__.__name__ if hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1): if init_type == 'normal': init.normal_(m.weight.data, 0.0, init_gain) elif init_type == 'xavier': init.xavier_normal_(m.weight.data, gain=init_gain) elif init_type == 'kaiming': init.kaiming_normal_(m.weight.data, a=0, mode='fan_in') elif init_type == 'orthogonal': init.orthogonal_(m.weight.data, gain=init_gain) else: raise NotImplementedError('initialization method [%s] is not implemented' % init_type) if hasattr(m, 'bias') and m.bias is not None: init.constant_(m.bias.data, 0.0) elif classname.find('BatchNorm2d') != -1: # BatchNorm Layer's weight is not a matrix; only normal distribution applies. init.normal_(m.weight.data, 1.0, init_gain) init.constant_(m.bias.data, 0.0) print('initialize network with %s' % init_type) net.apply(init_func) # apply the initialization function <init_func> def init_net(net, init_type='normal', init_gain=0.02, gpu_ids=[]): """Initialize a network: 1. register CPU/GPU device (with multi-GPU support); 2. initialize the network weights Parameters: net (network) -- the network to be initialized init_type (str) -- the name of an initialization method: normal | xavier | kaiming | orthogonal gain (float) -- scaling factor for normal, xavier and orthogonal. gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2 Return an initialized network. """ if len(gpu_ids) > 0: assert(torch.cuda.is_available()) net.to(gpu_ids[0]) net = torch.nn.DataParallel(net, gpu_ids) # multi-GPUs init_weights(net, init_type, init_gain=init_gain) return net class UnetSkipConnectionBlock(nn.Module): """Defines the Unet submodule with skip connection. X -------------------identity---------------------- |-- downsampling -- |submodule| -- upsampling --| """ def __init__(self, outer_nc, inner_nc, input_nc=None, submodule=None, outermost=False, innermost=False, norm_layer=nn.BatchNorm2d, use_dropout=False): """Construct a Unet submodule with skip connections. Parameters: outer_nc (int) -- the number of filters in the outer conv layer inner_nc (int) -- the number of filters in the inner conv layer input_nc (int) -- the number of channels in input images/features submodule (UnetSkipConnectionBlock) -- previously defined submodules outermost (bool) -- if this module is the outermost module innermost (bool) -- if this module is the innermost module norm_layer -- normalization layer user_dropout (bool) -- if use dropout layers. """ super(UnetSkipConnectionBlock, self).__init__() self.outermost = outermost if type(norm_layer) == functools.partial: use_bias = norm_layer.func == nn.InstanceNorm2d else: use_bias = norm_layer == nn.InstanceNorm2d if input_nc is None: input_nc = outer_nc kernel_size=4 downconv = nn.Conv2d(input_nc, inner_nc, kernel_size=kernel_size, stride=2, padding=1, bias=use_bias) downrelu = nn.LeakyReLU(0.2, True) downnorm = norm_layer(inner_nc) uprelu = nn.ReLU(True) upnorm = norm_layer(outer_nc) if outermost: upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc, kernel_size=kernel_size, stride=2, padding=1) down = [downconv] up = [uprelu, upconv, nn.Tanh()] model = down + [submodule] + up elif innermost: upconv = nn.ConvTranspose2d(inner_nc, outer_nc, kernel_size=kernel_size, stride=2, padding=1, bias=use_bias) down = [downrelu, downconv] up = [uprelu, upconv, upnorm] model = down + up else: upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc, kernel_size=kernel_size, stride=2, padding=1, bias=use_bias) down = [downrelu, downconv, downnorm] up = [uprelu, upconv, upnorm] if use_dropout: model = down + [submodule] + up + [nn.Dropout(0.5)] else: model = down + [submodule] + up self.model = nn.Sequential(*model) def forward(self, x): if self.outermost: return self.model(x) else: # add skip connections return torch.cat([x, self.model(x)], 1) class NetG(nn.Module): """Create a Unet-based generator""" def __init__(self, input_nc, output_nc, num_downs, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False): """Construct a Unet generator Parameters: input_nc (int) -- the number of channels in input images output_nc (int) -- the number of channels in output images num_downs (int) -- the number of downsamplings in UNet. For example, # if |num_downs| == 7, image of size 128x128 will become of size 1x1 # at the bottleneck ngf (int) -- the number of filters in the last conv layer norm_layer -- normalization layer We construct the U-Net from the innermost layer to the outermost layer. It is a recursive process. """ super(NetG, self).__init__() # construct unet structure self.conv1 = nn.Conv2d(9, 3, 3,1,1) self.BatchNorm1=nn.BatchNorm2d(3) self.LeakyReLU1 = nn.LeakyReLU(0.2, True) self.conv2 = nn.Conv2d(3, 3, 3,1,1) self.BatchNorm2 = nn.BatchNorm2d(3) self.LeakyReLU2 = nn.LeakyReLU(0.2, True) self.tanh = nn.Tanh() unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer, innermost=True) # add the innermost layer for i in range(num_downs - 5): # add intermediate layers with ngf * 8 filters unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer, use_dropout=use_dropout) # gradually reduce the number of filters from ngf * 8 to ngf unet_block = UnetSkipConnectionBlock(ngf * 4, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer) unet_block = UnetSkipConnectionBlock(ngf * 2, ngf * 4, input_nc=None, submodule=unet_block, norm_layer=norm_layer) unet_block = UnetSkipConnectionBlock(ngf, ngf * 2, input_nc=None, submodule=unet_block, norm_layer=norm_layer) self.model = UnetSkipConnectionBlock(3, ngf, input_nc=3, submodule=unet_block, outermost=True, norm_layer=norm_layer) # add the outermost layer def forward(self, input): """Standard forward""" x=self.conv1(input) # print(x.shape) x=self.BatchNorm1(x) x = self.LeakyReLU1(x) x = self.conv2(x) x = self.BatchNorm2(x) x = self.LeakyReLU2(x) x = self.model(x) output=self.tanh(x) return output #TODO modify this network to segmentation network class NetC(nn.Module): def __init__(self,input_nc,output_nc): super(NetC, self).__init__() self.net = get_segmentation_network(output_nc) def forward(self, x): x = self.net(x) return x class NetD(nn.Module): def __init__(self, input_nc,output_nc, ndf=64, norm_layer=nn.BatchNorm2d): super(NetD, self).__init__() # size: 3 * 36 * 120 self.conv1 =nn.Conv2d(input_nc, ndf, kernel_size=3, stride=2, padding=1) self.LeakyReLU1 =nn.LeakyReLU(0.2, True) kernel_size=3 padding=1 self.localNet = [ nn.Conv2d(ndf, ndf * 2, kernel_size=kernel_size, stride=2, padding=padding), norm_layer(ndf * 2), nn.LeakyReLU(0.2, True), nn.Conv2d(ndf * 2, ndf * 4, kernel_size=kernel_size, stride=2, padding=padding), norm_layer(ndf * 4), nn.LeakyReLU(0.2, True), nn.Conv2d(ndf * 4, ndf * 8, kernel_size=kernel_size, stride=2, padding=padding), norm_layer(ndf * 8), nn.LeakyReLU(0.2, True), nn.Conv2d(ndf * 8, ndf * 8, kernel_size=kernel_size, stride=2, padding=padding), norm_layer(ndf * 8), nn.LeakyReLU(0.2, True), # nn.Conv2d(ndf * 8, ndf * 8, kernel_size=4, stride=2, padding=0), # norm_layer(ndf * 8), # nn.LeakyReLU(0.2, True), ] self.localNet = nn.Sequential(*self.localNet) self.globalNet = [ nn.Conv2d(ndf, ndf * 2, kernel_size=kernel_size, stride=2, padding=padding), norm_layer(ndf * 2), nn.LeakyReLU(0.2, True), nn.Conv2d(ndf * 2, ndf * 4, kernel_size=kernel_size, stride=2, padding=padding), norm_layer(ndf * 4), nn.LeakyReLU(0.2, True), nn.Conv2d(ndf * 4, ndf * 8, kernel_size=kernel_size, stride=2, padding=padding), norm_layer(ndf * 8), nn.LeakyReLU(0.2, True), nn.Conv2d(ndf * 8, ndf * 8, kernel_size=kernel_size, stride=2, padding=padding), norm_layer(ndf * 8), nn.LeakyReLU(0.2, True), nn.Conv2d(ndf * 8, ndf * 8, kernel_size=kernel_size, stride=2, padding=padding), norm_layer(ndf * 8), nn.LeakyReLU(0.2, True) ] self.globalNet = nn.Sequential(*self.globalNet) self.fc1 = nn.Linear(8 * 8 * 512, 1024) self.drop1 = nn.Dropout(0.5) self.fc2 = nn.Linear(4 * 4 * 512, 1024) self.drop2 = nn.Dropout(0.5) self.fc3 = nn.Linear(2048, output_nc) self.drop3 = nn.Dropout(0.5) self.tanh = nn.Tanh() def forward(self, input): x=self.LeakyReLU1(self.conv1(input)) localx = self.localNet(x) localx = localx.view(-1, 8 * 8 * 512) localx = self.drop1(F.relu(self.fc1(localx))) globalx = self.globalNet(x) globalx = globalx.view(-1, 4 * 4 * 512) globalx = self.drop2(F.relu(self.fc2(globalx))) combinex=torch.cat([localx,globalx],-1) combinex = self.drop3(F.relu(self.fc3(combinex))) output=self.tanh(combinex) return output def get_norm_layer(norm_type='instance'): """Return a normalization layer Parameters: norm_type (str) -- the name of the normalization layer: batch | instance | none For BatchNorm, we use learnable affine parameters and track running statistics (mean/stddev). For InstanceNorm, we do not use learnable affine parameters. We do not track running statistics. """ if norm_type == 'batch': norm_layer = functools.partial(nn.BatchNorm2d, affine=True, track_running_stats=True) elif norm_type == 'instance': norm_layer = functools.partial(nn.InstanceNorm2d, affine=False, track_running_stats=False) else: raise NotImplementedError('normalization layer [%s] is not found' % norm_type) return norm_layer def define_Net(input_nc, output_nc, ngf, netType, norm='batch', use_dropout=False, init_type='normal', init_gain=0.02, gpu_ids=[], class_number=7): """Create a generator Parameters: input_nc (int) -- the number of channels in input images output_nc (int) -- the number of channels in output images ngf (int) -- the number of filters in the last conv layer netG (str) -- the architecture's name: resnet_9blocks | resnet_6blocks | unet_256 | unet_128 norm (str) -- the name of normalization layers used in the network: batch | instance | none use_dropout (bool) -- if use dropout layers. init_type (str) -- the name of our initialization method. init_gain (float) -- scaling factor for normal, xavier and orthogonal. gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2 Returns a generator Our current implementation provides two types of generators: U-Net: [unet_128] (for 128x128 input images) and [unet_256] (for 256x256 input images) The original U-Net paper: https://arxiv.org/abs/1505.04597 Resnet-based generator: [resnet_6blocks] (with 6 Resnet blocks) and [resnet_9blocks] (with 9 Resnet blocks) Resnet-based generator consists of several Resnet blocks between a few downsampling/upsampling operations. We adapt Torch code from Justin Johnson's neural style transfer project (https://github.com/jcjohnson/fast-neural-style). The generator has been initialized by <init_net>. It uses RELU for non-linearity. """ net = None norm_layer = get_norm_layer(norm_type=norm) if netType == 'NetG': net = NetG(input_nc, output_nc, 5, ngf, norm_layer=norm_layer, use_dropout=use_dropout) elif netType == 'NetC': net = NetC(input_nc, class_number) elif netType == 'NetD': net = NetD(input_nc, 1, ngf, norm_layer=norm_layer) else: raise NotImplementedError('Generator model name [%s] is not recognized' % netType) return init_net(net, init_type, init_gain, gpu_ids) class GANLoss(nn.Module): """Define different GAN objectives. The GANLoss class abstracts away the need to create the target label tensor that has the same size as the input. """ def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0): """ Initialize the GANLoss class. Parameters: gan_mode (str) - - the type of GAN objective. It currently supports vanilla, lsgan, and wgangp. target_real_label (bool) - - label for a real image target_fake_label (bool) - - label of a fake image Note: Do not use sigmoid as the last layer of Discriminator. LSGAN needs no sigmoid. vanilla GANs will handle it with BCEWithLogitsLoss. """ super(GANLoss, self).__init__() self.register_buffer('real_label', torch.tensor(target_real_label)) self.register_buffer('fake_label', torch.tensor(target_fake_label)) self.gan_mode = gan_mode if gan_mode == 'lsgan': self.loss = nn.MSELoss() elif gan_mode == 'vanilla': self.loss = nn.BCEWithLogitsLoss() elif gan_mode in ['wgangp']: self.loss = None else: raise NotImplementedError('gan mode %s not implemented' % gan_mode) def get_target_tensor(self, prediction, target_is_real): """Create label tensors with the same size as the input. Parameters: prediction (tensor) - - tpyically the prediction from a discriminator target_is_real (bool) - - if the ground truth label is for real images or fake images Returns: A label tensor filled with ground truth label, and with the size of the input """ if target_is_real: target_tensor = self.real_label else: target_tensor = self.fake_label return target_tensor.expand_as(prediction) def __call__(self, prediction, target_is_real): """Calculate loss given Discriminator's output and grount truth labels. Parameters: prediction (tensor) - - tpyically the prediction output from a discriminator target_is_real (bool) - - if the ground truth label is for real images or fake images Returns: the calculated loss. """ if self.gan_mode in ['lsgan', 'vanilla']: target_tensor = self.get_target_tensor(prediction, target_is_real) loss = self.loss(prediction, target_tensor) elif self.gan_mode == 'wgangp': if target_is_real: loss = -prediction.mean() else: loss = prediction.mean() return loss
42.641975
159
0.618471
a199c6f5e6ba28712f8f068ba4fa4f0e3bf3c9fe
2,216
ts
TypeScript
Distributed-eStore.UI/src/ClientApp/src/state/user/userActions.ts
KrishnaVadlamudi44/Distributed-eStore
c8442caa62f882e9bfac210c1ab4555a681cafcc
[ "MIT" ]
104
2021-02-03T07:14:37.000Z
2022-03-15T21:25:07.000Z
Distributed-eStore.UI/src/ClientApp/src/state/user/userActions.ts
KrishnaVadlamudi44/Distributed-eStore
c8442caa62f882e9bfac210c1ab4555a681cafcc
[ "MIT" ]
3
2021-04-27T16:25:51.000Z
2022-03-15T08:27:27.000Z
Distributed-eStore.UI/src/ClientApp/src/state/user/userActions.ts
KrishnaVadlamudi44/Distributed-eStore
c8442caa62f882e9bfac210c1ab4555a681cafcc
[ "MIT" ]
21
2021-04-16T21:48:14.000Z
2022-03-14T22:00:56.000Z
import { IUser, UserActionTypes } from "."; import { IAppThunkAction, ReduxAction } from ".."; import { register, login, logout } from "../../services/auth"; export type UserRegistrationData = { firstName: string, lastName: string, email: string, password: string, // technical debt role: string } const userKey = "user"; /* eslint-disable */ export const userActionCreators = { register: (userData: UserRegistrationData): IAppThunkAction<ReduxAction> => async (dispatch, getState) => { try { const { firstName, lastName, email, password, role } = userData; await register(firstName, lastName, email, password, role); dispatch({ type: UserActionTypes.REGISTRATION_SUCCESS, }); await userActionCreators.login(email, password)(dispatch, getState); } catch (error) { const message: string = (error.response && error.response.data && error.response.data.message) || error.message || error.toString(); dispatch({ type: UserActionTypes.REGISTRATION_FAILED, }); // technical debt alert(`Registration failed - ${message}`); } }, login: (email: string, password: string): IAppThunkAction<ReduxAction> => async (dispatch, getState) => { try { const user: IUser = (await login(email, password)).data; localStorage.setItem(userKey, JSON.stringify(user)); dispatch({ type: UserActionTypes.LOGIN_SUCCESS, payload: { user } }); } catch (error) { const message: string = (error.response && error.response.data && error.response.data.message) || error.message || error.toString(); dispatch({ type: UserActionTypes.LOGIN_FAIL }); // technical debt alert(`Login failed - ${message}`); } }, logout: (): IAppThunkAction<ReduxAction> => (dispatch, getState) => { logout(); dispatch({ type: UserActionTypes.LOGOUT, }); } };
31.657143
111
0.556859
033ba66a91f4c18ba8a55b27266db4bb89d5e1c7
371
rb
Ruby
lib/autoparts/packages/mercurial.rb
adamreid/boxparts
ab986b71374c41d4f7bdbadaf11b898510978696
[ "BSD-2-Clause" ]
16
2015-02-12T20:18:36.000Z
2018-09-21T02:45:25.000Z
lib/autoparts/packages/mercurial.rb
adamreid/boxparts
ab986b71374c41d4f7bdbadaf11b898510978696
[ "BSD-2-Clause" ]
47
2015-01-07T02:26:37.000Z
2017-05-31T18:13:37.000Z
lib/autoparts/packages/mercurial.rb
adamreid/boxparts
ab986b71374c41d4f7bdbadaf11b898510978696
[ "BSD-2-Clause" ]
34
2015-01-05T22:37:53.000Z
2016-11-05T00:49:14.000Z
module Autoparts module Packages class Mercurial < Package name 'mercurial' version '2.0.2' source_url '' description 'Mercurial : source control management' category Category::DEVELOPMENT_TOOLS def tips <<-EOS.unindent Mercurial 2.0.2 is preinstalled on all Codio Boxes. EOS end end end end
20.611111
59
0.628032
c4b2d8f5c876e3bd9d217324d626ee92a3ffb01e
3,911
lua
Lua
lua/xdbot/serversidecode/xdbot_hooks_sv.lua
xDShot/xdbot
a12c23f09fcc89de04120f7178b47492e45b89d7
[ "MIT" ]
1
2021-01-08T23:19:00.000Z
2021-01-08T23:19:00.000Z
lua/xdbot/serversidecode/xdbot_hooks_sv.lua
xDShot/xdbot
a12c23f09fcc89de04120f7178b47492e45b89d7
[ "MIT" ]
1
2019-12-03T11:37:05.000Z
2019-12-03T11:37:05.000Z
lua/xdbot/serversidecode/xdbot_hooks_sv.lua
xDShot/xdbot
a12c23f09fcc89de04120f7178b47492e45b89d7
[ "MIT" ]
1
2021-08-15T18:53:19.000Z
2021-08-15T18:53:19.000Z
local list = list local hook = hook hook.Add( "StartCommand", "HookXDBotControlSV", function( ply, cmd ) if ply:GetNWBool( "isXDBot" ) then if ply:IsPlayer() and not ply:IsBot() then --remove controller if player pressed buttons and give back control to player, so he's no more bot. if SERVER and cmd:GetButtons() > 0 then -- @TODO: ignore if ESC, tab, microphone or chat buttons pressed ply.ControllerEnt:ReceivedPlyInput() return end -- clear mouse cmd:SetMouseX(0) cmd:SetMouseY(0) end cmd:ClearMovement() cmd:ClearButtons() local cmdbuttons = ply:IsBot() and ply.ControllerEnt.CmdButtons or ply:GetNWInt( "xDBotButtons" ) -- ply.ControllerEnt.CmdButtons cmd:SetButtons( cmdbuttons ) local movevector = ply:IsBot() and ply.ControllerEnt.CmdMove or ply:GetNWVector( "xDBotMove" ) -- ply.ControllerEnt.CmdMove cmd:SetForwardMove( movevector.x ) cmd:SetSideMove( movevector.y ) cmd:SetUpMove( movevector.z ) local eyeangle = ply:IsBot() and ply.ControllerEnt.CmdCurAngle or ply:GetNWAngle( "xDBotAngles" )--ply.ControllerEnt.CmdCurAngle cmd:SetViewAngles( eyeangle ) ply:SetEyeAngles( eyeangle ) if ply:IsBot() then ply:SetEyeAngles( eyeangle ) end end -- if ply.isXDBot end ) -- function( ply, cmd ) hook.Add( "PlayerDisconnected", "HookXDBotDisconnected", function( ply ) if ply:GetNWBool( "isXDBot" ) and ply.ControllerEnt then ply.ControllerEnt:Remove() end end ) hook.Add( "EntityTakeDamage", "HookXDBotMakeControllerInvincible", function( target, dmg ) if target.IsXDBotController then print("yup that's him") dmg:ScaleDamage(0.00) return true end end ) -- @TODO this hook doesn't work for bots hook.Add( "PlayerDeathThink", "HookXDBotPlayerRespawn", function( ply ) if ply:GetNWBool( "isXDBot" ) and ply.ControllerEnt then ply.ControllerEnt:PlayerRespawn() end end ) hook.Add( "Initialize", "HookXDBotInitWeapprefs", function() --@TODO: Maybe another hook? Some of weps could be missed... local weapprefs = list.GetForEdit( "XDBot_Weapprefs" ) -- So it's editable local function GetKnownPref( swepname ) -- Recursively go through parent weapons and grab values from known base or base of base or base of base of base or... -- @TODO there is a bug when it tries to access to non-existent base, like fa:s base local returntable = {} local sweptable = weapons.Get( swepname ) if weapprefs[ sweptable.ClassName ] then table.Merge( returntable, weapprefs[ sweptable.ClassName ] ) elseif sweptable.XDBot_Weapprefs then table.Merge( returntable, sweptable.XDBot_Weapprefs ) elseif sweptable.Base then returntable = GetKnownPref( sweptable.Base ) end return returntable end -- Try to add prefs for other non-listed weapons local sweps = weapons.GetList() for k, v in pairs(sweps) do if not weapprefs[ v.ClassName ] then -- If already exist in list, skip it local tmptable = {} -- @TODO: Info from TFA, CW and other bases if v.XDBot_Weapprefs then -- There's Weappref stored inside of SWEP. Grab it. table.Merge( tmptable, v.XDBot_Weapprefs ) else -- Recursively go through parent weapons and grab values from known base or base of base or base of base of base or... tmptable = GetKnownPref( v.ClassName ) end weapprefs[ v.ClassName ] = {} table.Merge( weapprefs[ v.ClassName ], tmptable ) end end -- Add all default values that don't exist in table for k, v in pairs(weapprefs) do local tmptable = {} table.Merge( tmptable, XDBOT_GLOBALS.DefaulWeappref ) table.Merge( tmptable, v ) table.Merge( v, tmptable ) end end )
34.307018
134
0.66786
a30019990421cb540a2aca0e12d30bfe1684466b
7,993
h
C
src/core/web_page_base.h
webosose/wam
5d3eb5d50a176fb82c1fa5564655277181c9235a
[ "Apache-2.0" ]
12
2018-03-22T18:51:21.000Z
2020-07-18T03:57:53.000Z
src/core/web_page_base.h
webosose/wam
5d3eb5d50a176fb82c1fa5564655277181c9235a
[ "Apache-2.0" ]
24
2018-10-30T10:33:03.000Z
2020-06-02T19:59:29.000Z
src/core/web_page_base.h
webosose/wam
5d3eb5d50a176fb82c1fa5564655277181c9235a
[ "Apache-2.0" ]
17
2018-03-22T18:51:24.000Z
2021-11-19T13:03:43.000Z
// Copyright (c) 2013-2021 LG Electronics, Inc. // // 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. // // SPDX-License-Identifier: Apache-2.0 #ifndef CORE_WEB_PAGE_BASE_H_ #define CORE_WEB_PAGE_BASE_H_ #include <memory> #include <string> #include "webos/webview_base.h" #include "observer_list.h" #include "util/url.h" class ApplicationDescription; class WebAppBase; class WebAppManagerConfig; class WebPageObserver; class WebProcessManager; /** * Common base class for UI independent * web page functionality */ class WebPageBase { public: // Originally, webview_base.h, WebPageVisibilityState.h, PageVisibilityState.h // we can use enum of webview_base.h directly but this is WebPageBase in core // shouldn't depend on web engine enum WebPageVisibilityState { kWebPageVisibilityStateVisible, kWebPageVisibilityStateHidden, kWebPageVisibilityStateLaunching, kWebPageVisibilityStatePrerender, kWebPageVisibilityStateLast = kWebPageVisibilityStatePrerender }; WebPageBase(); WebPageBase(const wam::Url& url, std::shared_ptr<ApplicationDescription> desc, const std::string& params); virtual ~WebPageBase(); // WebPageBase virtual void Init() = 0; virtual void* GetWebContents() = 0; virtual void SetLaunchParams(const std::string& params); virtual void NotifyMemoryPressure( webos::WebViewBase::MemoryPressureLevel level) {} virtual std::string GetIdentifier() const; virtual wam::Url Url() const = 0; virtual wam::Url DefaultUrl() const { return default_url_; } virtual void SetDefaultUrl(const wam::Url& url) { default_url_ = url; } virtual void LoadUrl(const std::string& url) = 0; virtual int Progress() const = 0; virtual bool HasBeenShown() const = 0; virtual void SetPageProperties() = 0; virtual void SetPreferredLanguages(const std::string& language) = 0; virtual std::string DefaultFont(); virtual void SetDefaultFont(const std::string& font) = 0; virtual void CleanResources(); virtual void ReloadDefaultPage() = 0; virtual void Reload() = 0; virtual void SetVisibilityState(WebPageVisibilityState visibility_state) = 0; virtual void SetFocus(bool focus) = 0; virtual std::string Title() = 0; virtual bool CanGoBack() = 0; virtual void CloseVkb() = 0; virtual void KeyboardVisibilityChanged(bool visible) {} virtual void HandleDeviceInfoChanged(const std::string& device_info) = 0; virtual bool Relaunch(const std::string& args, const std::string& launching_app_id); virtual void EvaluateJavaScript(const std::string& jsCode) = 0; virtual void EvaluateJavaScriptInAllFrames(const std::string& js_code, const char* method = {}) = 0; virtual uint32_t GetWebProcessProxyID() = 0; virtual uint32_t GetWebProcessPID() const = 0; virtual void CreatePalmSystem(WebAppBase* app) = 0; virtual void SetUseLaunchOptimization(bool enabled, int delay_ms = {}) {} virtual void SetUseSystemAppOptimization(bool enabled) {} virtual void SetUseAccessibility(bool enabled) {} virtual void SetAppPreloadHint(bool is_preload) {} virtual void SuspendWebPageAll() = 0; virtual void ResumeWebPageAll() = 0; virtual void SuspendWebPageMedia() = 0; virtual void ResumeWebPageMedia() = 0; virtual void ResumeWebPagePaintingAndJSExecution() = 0; virtual bool IsRegisteredCloseCallback() { return false; } virtual void ExecuteCloseCallback(bool forced) {} virtual void ReloadExtensionData() {} virtual bool IsLoadErrorPageFinish() { return is_load_error_page_finish_; } virtual bool IsLoadErrorPageStart() { return is_load_error_page_start_; } virtual void UpdateIsLoadErrorPageFinish(); virtual void UpdateDatabaseIdentifier() {} virtual void DeleteWebStorages(const std::string& identifier) {} virtual void SetInspectorEnable() {} virtual void SetKeepAliveWebApp(bool keep_alive) {} virtual void SetContentsScale() {} virtual void SetCustomUserScript(); virtual void ForwardEvent(void* event) = 0; virtual void SetAudioGuidanceOn(bool on) {} virtual bool IsInputMethodActive() const { return false; } std::string LaunchParams() const; void SetApplicationDescription(std::shared_ptr<ApplicationDescription> desc); void Load(); void SetEnableBackgroundRun(bool enable) { enable_background_run_ = enable; } void SendLocaleChangeEvent(const std::string& language); void SetCleaningResources(bool cleaning_resources) { cleaning_resources_ = cleaning_resources; } bool CleaningResources() const { return cleaning_resources_; } bool DoHostedWebAppRelaunch(const std::string& launch_params); void SendRelaunchEvent(); void SetAppId(const std::string& app_id) { app_id_ = app_id; } const std::string& AppId() const { return app_id_; } void SetInstanceId(const std::string& instance_id) { instance_id_ = instance_id; } const std::string& InstanceId() const { return instance_id_; } ApplicationDescription* GetAppDescription() { return app_desc_.get(); } void SetClosing(bool status) { is_closing_ = status; } bool IsClosing() { return is_closing_; } void SetIsPreload(bool is_preload) { is_preload_ = is_preload; } bool IsPreload() const { return is_preload_; } void AddObserver(WebPageObserver* observer); void RemoveObserver(WebPageObserver* observer); virtual std::string GetIdentifierForSecurityOrigin() const; virtual void ActivateRendererCompositor() {} virtual void DeactivateRendererCompositor() {} virtual void SuspendWebPagePaintingAndJSExecution() = 0; protected: // WebPageBase virtual void CleanResourcesFinished(); virtual void HandleForceDeleteWebPage(); virtual void LoadDefaultUrl() = 0; virtual void AddUserScript(const std::string& script) = 0; virtual void AddUserScriptUrl(const wam::Url& url) = 0; virtual int SuspendDelay(); virtual bool HasLoadErrorPolicy(bool is_http_response_error, int error_code); virtual void LoadErrorPage(int error_code) = 0; virtual void RecreateWebView() = 0; virtual void SetVisible(bool visible) {} virtual bool DoDeeplinking(const std::string& launch_params); void HandleLoadStarted(); void HandleLoadFinished(); void HandleLoadFailed(int error_code); bool GetDeviceInfo(const std::string& name, std::string& value); bool GetSystemLanguage(std::string& value); int CurrentUiWidth(); int CurrentUiHeight(); WebProcessManager* GetWebProcessManager(); WebAppManagerConfig* GetWebAppManagerConfig(); bool ProcessCrashed(); virtual int MaxCustomSuspendDelay(); std::string TelluriumNubPath(); void ApplyPolicyForUrlResponse(bool is_main_frame, const std::string& url, int status_code); void PostRunningAppList(); void PostWebProcessCreated(uint32_t pid); bool IsAccessibilityEnabled() const; std::shared_ptr<ApplicationDescription> app_desc_; std::string app_id_; std::string instance_id_; bool suspend_at_load_; bool is_closing_; bool is_load_error_page_finish_; bool is_load_error_page_start_; bool did_error_page_loaded_from_net_error_helper_; bool enable_background_run_; wam::Url default_url_; std::string launch_params_; std::string load_error_policy_; ObserverList<WebPageObserver> observers_; private: void SetBackgroundColorOfBody(const std::string& color); void SetupLaunchEvent(); bool cleaning_resources_; bool is_preload_; }; #endif // CORE_WEB_PAGE_BASE_H_
37.70283
80
0.74853
df648307303da0dc660c3e9ba27fe916d75e30e3
680
rb
Ruby
lib/cfn-nag/custom_rules/LambdaPermissionWildcardPrincipalRule.rb
djonesshargani1-godaddy/cfn_nag
6eaefddba07e131e13b2220e6106d42e0adbd52d
[ "MIT" ]
1,024
2016-03-02T21:24:55.000Z
2022-03-30T16:36:43.000Z
lib/cfn-nag/custom_rules/LambdaPermissionWildcardPrincipalRule.rb
djonesshargani1-godaddy/cfn_nag
6eaefddba07e131e13b2220e6106d42e0adbd52d
[ "MIT" ]
425
2016-02-25T15:42:37.000Z
2022-03-25T11:08:31.000Z
lib/cfn-nag/custom_rules/LambdaPermissionWildcardPrincipalRule.rb
djonesshargani1-godaddy/cfn_nag
6eaefddba07e131e13b2220e6106d42e0adbd52d
[ "MIT" ]
223
2016-11-01T22:34:17.000Z
2022-03-31T16:22:51.000Z
# frozen_string_literal: true require 'cfn-nag/violation' require 'cfn-model/model/lambda_principal' require_relative 'base' class LambdaPermissionWildcardPrincipalRule < BaseRule def rule_text 'Lambda permission principal should not be wildcard' end def rule_type Violation::FAILING_VIOLATION end def rule_id 'F13' end def audit_impl(cfn_model) lambda_permissions = cfn_model.resources_by_type('AWS::Lambda::Permission') violating_lambda_permissions = lambda_permissions.select do |lambda_permission| LambdaPrincipal.wildcard? lambda_permission.principal end violating_lambda_permissions.map(&:logical_resource_id) end end
23.448276
83
0.783824