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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
da3e967a3e4b474291234d16ece0eca0eff4459f
| 2,404
|
php
|
PHP
|
elc.php
|
swarangi203/CGPA-calculator
|
f26c76bda5540013b2cade83024a9bc8e67dc152
|
[
"Apache-2.0"
] | null | null | null |
elc.php
|
swarangi203/CGPA-calculator
|
f26c76bda5540013b2cade83024a9bc8e67dc152
|
[
"Apache-2.0"
] | null | null | null |
elc.php
|
swarangi203/CGPA-calculator
|
f26c76bda5540013b2cade83024a9bc8e67dc152
|
[
"Apache-2.0"
] | null | null | null |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Swarangi's Website</title>
<link rel="stylesheet" href="css.css">
<script src="https://kit.fontawesome.com/a076d05399.js"></script>
</head>
<body>
<nav>
<ul>
<li><a style="color=white" href="php.php">Home</a></li>
<li><a style="color=white" href="About.php">About</a></li>
<li><a style="color=white" href="Contact.php">Contact</a></li>
</ul><br>
</nav>
<form action="elcp.php" method="post" autocomplete="off" target="_blank">
<div id="grade">
<div class="row">
<div class="column">
<h2>Enter grade for theory marks</h2>
<p>Enter in all caps(ex. AB)</p>
<label for="PS" style="margin-left:50px">Probability and Statistics</label><br>
<input type="text" name="PS" style="margin-left:50px"><br>
<label for="DC" style="margin-left:50px">DC machines and Transformers</label><br>
<input type="text" name="DC" style="margin-left:50px"><br>
<label for="EC" style="margin-left:50px">Electrical Circuits</label><br>
<input type="text" name="EC" style="margin-left:50px"><br>
<label for="AD" style="margin-left:50px">Analog and Digital Circuits</label><br>
<input type="text" name="AD" style="margin-left:50px"><br>
<label for="EM" style="margin-left:50px">Electrical Measurements</label><br>
<input type="text" name="EM" style="margin-left:50px"><br>
<label for="I"style="margin-left:50px">Istrumentation</label><br>
<input type="text" name="I" style="margin-left:50px"> <br>
</div>
<div class="column">
<h2>Enter grade for Practical marks</h2>
<p>Enter in all caps(ex. AB)</p>
<label for="DCP" style="margin-left:50px">DC machines and Transformers</label><br>
<input type="text" name="DCP" style="margin-left:50px"><br>
<label for="EMP" style="margin-left:50px">Electrical Circuits and Measurements</label><br>
<input type="text" name="EMP" style="margin-left:50px"><br>
<label for="ADP"style="margin-left:50px">Analog and Digital Circuits</label><br>
<input type="text" name="ADP" style="margin-left:50px"> <br>
<input type="submit" name="submit" style="margin-left:140px; margin-top:20px;"><br>
</div>
</div>
</div>
</form>
</body>
</html>
| 40.066667
| 96
| 0.604825
|
570fb43dd86a4bc35a1c6e108be6566ffa85d5e8
| 87
|
js
|
JavaScript
|
flutter_demo1/lib/flutter_node_server/router/config.js
|
Unrealplace/flutterapp
|
adde64cf3791ba4775ed49dda997ad35ea1ea07c
|
[
"MIT"
] | null | null | null |
flutter_demo1/lib/flutter_node_server/router/config.js
|
Unrealplace/flutterapp
|
adde64cf3791ba4775ed49dda997ad35ea1ea07c
|
[
"MIT"
] | null | null | null |
flutter_demo1/lib/flutter_node_server/router/config.js
|
Unrealplace/flutterapp
|
adde64cf3791ba4775ed49dda997ad35ea1ea07c
|
[
"MIT"
] | null | null | null |
const config = {
IP: '192.168.1.103',
PORT:'3000',
};
module.exports = config;
| 14.5
| 24
| 0.574713
|
661dae858c1cb2660f91e159e8c4de39caebf99f
| 370
|
py
|
Python
|
app/models.py
|
seethadixit/InsightProject
|
662b74ebef13aac8292080081a78f963ba61e884
|
[
"Apache-2.0"
] | 1
|
2018-11-13T03:10:56.000Z
|
2018-11-13T03:10:56.000Z
|
app/models.py
|
seethavenkatadri/InsightProject
|
662b74ebef13aac8292080081a78f963ba61e884
|
[
"Apache-2.0"
] | null | null | null |
app/models.py
|
seethavenkatadri/InsightProject
|
662b74ebef13aac8292080081a78f963ba61e884
|
[
"Apache-2.0"
] | null | null | null |
import db
from sqlalchemy import Column,Integer,String
class BaseModel(db.Model):
__abstract__ = True
# define here __repr__ and json methods or any common method
# that you need for all your models
class TestModel(BaseModel):
__tablename__ = 'test_table'
# define your model
id = Column(Integer, primary_key=True)
name = Column(String(256))
| 30.833333
| 64
| 0.72973
|
43e8b42114bb1b06041199bf9601c81c1929dd86
| 1,071
|
ts
|
TypeScript
|
src/lib/content/model/ContentLifecycle.ts
|
LukeT-Amplience/dc-delivery-sdk-js
|
37012f3d01b9d4b5345cc7eb7643a1ca0e788104
|
[
"Apache-2.0"
] | 57
|
2019-03-13T17:41:33.000Z
|
2021-06-15T16:46:27.000Z
|
src/lib/content/model/ContentLifecycle.ts
|
LukeT-Amplience/dc-delivery-sdk-js
|
37012f3d01b9d4b5345cc7eb7643a1ca0e788104
|
[
"Apache-2.0"
] | 45
|
2020-02-10T14:19:51.000Z
|
2022-03-02T07:37:27.000Z
|
src/lib/content/model/ContentLifecycle.ts
|
LukeT-Amplience/dc-delivery-sdk-js
|
37012f3d01b9d4b5345cc7eb7643a1ca0e788104
|
[
"Apache-2.0"
] | 10
|
2019-06-26T13:34:04.000Z
|
2022-01-05T14:08:10.000Z
|
/**
* Class representing the lifecycle status of a Content Item with helper functions.
*/
export class ContentLifecycle {
/**
* Date the content should expire in ISO 8601 format.
* The content will not become unpublished at this time but this value may be used
* by applications to choose not to show this content.
*/
expiryTime: string;
/**
* Creates a new ContentLifecycle instance.
* @param data JSON representation of the ContentLifecycle model
*/
constructor(data?: any) {
if (data) {
Object.assign(this, data);
}
}
/**
* Returns a boolean to indicate if the content should no longer be displayed by your application.
* @param currentTime Optional date to override the current time.
*/
isExpired(currentTime?: Date) {
currentTime = currentTime || new Date();
return (
this.expiryTime !== undefined &&
new Date(this.expiryTime).getTime() < currentTime.getTime()
);
}
/**
* Export to JSON
*/
toJSON(): any {
return {
expiryTime: this.expiryTime,
};
}
}
| 24.906977
| 100
| 0.654528
|
a319d80bb8479730fa6aa4bd3d2790eee3039bd7
| 220
|
ts
|
TypeScript
|
src/server/src/ts/api/v1.0/task/index.ts
|
strisys/web-application-quickstart-node
|
2b028368df8dd61e645ad4234e8f76fa8e1a77db
|
[
"MIT"
] | null | null | null |
src/server/src/ts/api/v1.0/task/index.ts
|
strisys/web-application-quickstart-node
|
2b028368df8dd61e645ad4234e8f76fa8e1a77db
|
[
"MIT"
] | null | null | null |
src/server/src/ts/api/v1.0/task/index.ts
|
strisys/web-application-quickstart-node
|
2b028368df8dd61e645ad4234e8f76fa8e1a77db
|
[
"MIT"
] | null | null | null |
import { Router } from 'express';
import { Controller } from './controller';
export const router = Router();
const controller = new Controller();
router.get(`/`, controller.get);
router.get(`/:id`, controller.getOne);
| 24.444444
| 42
| 0.695455
|
f8d9f80aed99ed433a7070608458b1fb23c19518
| 2,814
|
dart
|
Dart
|
lib/main.dart
|
ankit2001/MyExpenses
|
2ffc1b95795111a016f5b086835ebc193a3f4627
|
[
"MIT"
] | null | null | null |
lib/main.dart
|
ankit2001/MyExpenses
|
2ffc1b95795111a016f5b086835ebc193a3f4627
|
[
"MIT"
] | null | null | null |
lib/main.dart
|
ankit2001/MyExpenses
|
2ffc1b95795111a016f5b086835ebc193a3f4627
|
[
"MIT"
] | null | null | null |
import 'package:flutter/cupertino.dart';
import './widgets/addTransactions.dart';
import './widgets/transactionList.dart';
import 'package:flutter/material.dart';
import './models/transaction.dart';
import './widgets/chart.dart';
class MyExpenses extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'MyExpenses',
home: MyHomepage(),
theme: ThemeData(
primarySwatch: Colors.red,
fontFamily: 'QuickSand',
textTheme: ThemeData.light().textTheme.copyWith(
headline6: TextStyle(
fontFamily: 'QuickSand',
fontWeight: FontWeight.bold,
fontSize: 18,
color: Colors.red,
),
),
appBarTheme: AppBarTheme(
textTheme: ThemeData.light().textTheme.copyWith(
headline6: TextStyle(
fontFamily: 'QuickSand',
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
),
);
}
}
class MyHomepage extends StatefulWidget {
@override
_MyHomepageState createState() => _MyHomepageState();
}
class _MyHomepageState extends State<MyHomepage> {
final List<Transaction> _transaction = [];
List<Transaction> get _recentTx {
return _transaction.where((tx) {
return tx.date.isAfter(
DateTime.now().subtract(
Duration(days: 7),
),
);
}).toList();
}
void _addTransaction(String textTx, double amountTx) {
final newTx = Transaction(
text: textTx,
amount: amountTx,
id: DateTime.now().toString(),
date: DateTime.now(),
);
setState(() {
_transaction.add(newTx);
});
}
void _addNewTransaction(BuildContext ctx) {
showModalBottomSheet(
context: ctx,
builder: (_) {
return GestureDetector(
onTap: () => {},
child: AddTransaction(_addTransaction),
behavior: HitTestBehavior.opaque,
);
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('My Expenses'),
actions: <Widget>[
IconButton(
icon: Icon(Icons.add),
onPressed: () => _addNewTransaction(context),
),
],
),
body: Column(
children: <Widget>[
Chart(_recentTx),
TransactionList(_transaction),
],
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () => _addNewTransaction(context),
elevation: 10,
),
);
}
}
void main() => runApp(MyExpenses());
| 25.351351
| 78
| 0.574271
|
45d5eb13d0c3e2309ab95b5f04fccd479efaa70b
| 97
|
lua
|
Lua
|
bundle-example-areas/areas/limbo/manifest.lua
|
Gowa2017/skynetmudbundles
|
ca6e2221b5167b59442cdd09851ddda37567325b
|
[
"MIT"
] | null | null | null |
bundle-example-areas/areas/limbo/manifest.lua
|
Gowa2017/skynetmudbundles
|
ca6e2221b5167b59442cdd09851ddda37567325b
|
[
"MIT"
] | null | null | null |
bundle-example-areas/areas/limbo/manifest.lua
|
Gowa2017/skynetmudbundles
|
ca6e2221b5167b59442cdd09851ddda37567325b
|
[
"MIT"
] | null | null | null |
return {
behaviors = { ["progressive-respawn"] = { interval = 20 } },
title = "Limbo",
}
| 19.4
| 62
| 0.546392
|
05c210ae6e34e957b1e8991733d00bcb9b33baf2
| 1,359
|
kt
|
Kotlin
|
fints4k/src/commonMain/kotlin/net/dankito/banking/fints/messages/HbciCharset.kt
|
codinux-gmbh/fints4k.BAK
|
b4232dffd35346883ad02b220d420c46af83e815
|
[
"RSA-MD"
] | null | null | null |
fints4k/src/commonMain/kotlin/net/dankito/banking/fints/messages/HbciCharset.kt
|
codinux-gmbh/fints4k.BAK
|
b4232dffd35346883ad02b220d420c46af83e815
|
[
"RSA-MD"
] | null | null | null |
fints4k/src/commonMain/kotlin/net/dankito/banking/fints/messages/HbciCharset.kt
|
codinux-gmbh/fints4k.BAK
|
b4232dffd35346883ad02b220d420c46af83e815
|
[
"RSA-MD"
] | null | null | null |
package net.dankito.banking.fints.messages
import io.ktor.utils.io.charsets.Charsets
/**
* Der HBCI-Basiszeichensatz baut auf dem international normierten Zeichensatz ISO 8859 auf.
* Im DE „Unterstützte Sprachen“ in die Bankparameterdaten (s. Kap. D.2) stellt das Kreditinstitut
* das jeweiligen Codeset des ISO 8859 ein. Ferner wird in die BPD das sprachen-spezifische Subset
* des ISO 8859 eingestellt. Codeset und Subset definieren gemeinsam den FinTS-Basiszeichensatz.
* Dieser gilt grundsätzlich für sämtliche nicht-binären Datenelemente. Sofern hiervon aufgrund
* von Verarbeitungsrestriktionen abgewichen wird, ist dies bei der jeweiligen Formatbeschreibung
* vermerkt. Für transparente Daten gilt der jeweilige Zeichensatz des Fremdformats.
*
* Kreditinstitutsseitig ist jeweils der vollständige erlaubte Zeichensatz zu unterstützen.
* FinTS-Syntaxzeichen (s. Kap. H.1.1) bleiben von den Zeichensatzvorgaben unberührt (d. h.
* sind stets erforderlich und mit fester Codierung vorgegeben).
*
* Wird ein Auftrag an ein Kreditinstitut übermittelt, der hinsichtlich Zeichensatz und Codierung
* nicht den Richtlinien entspricht, so ist dieser abzuweisen. Eine kreditinstitutsseitige Korrektur
* der Auftragsdaten erfolgt nicht.
*/
open class HbciCharset {
companion object {
val DefaultCharset = Charsets.ISO_8859_1
}
}
| 46.862069
| 100
| 0.796909
|
f451c8553b799954eb79c266d753224fad61bb46
| 677
|
ts
|
TypeScript
|
src/utils/connect-database.ts
|
PiotrBlachnio/MoviesAPI
|
c33a260e81acf0f5f609ef19b741ec71480c7901
|
[
"MIT"
] | null | null | null |
src/utils/connect-database.ts
|
PiotrBlachnio/MoviesAPI
|
c33a260e81acf0f5f609ef19b741ec71480c7901
|
[
"MIT"
] | null | null | null |
src/utils/connect-database.ts
|
PiotrBlachnio/MoviesAPI
|
c33a260e81acf0f5f609ef19b741ec71480c7901
|
[
"MIT"
] | null | null | null |
import { createConnection, Connection } from 'typeorm';
import logger from './logger';
export let connection: Connection;
export default async (retries = 5) => {
while(retries) {
try {
connection = await createConnection();
await logger.log({ type: 'info', message: 'Connected to the database successfully', place: 'Connect database function' });
break;
} catch(error) {
console.log(error)
await logger.log({ type: 'error', message: error.message, place: 'Connect database function' });
retries -=1;
await new Promise(res => setTimeout(res, 5000));
};
};
};
| 32.238095
| 134
| 0.590842
|
0d2eb0bfc8cd7aac4eb3ec0fe39dab85767f5891
| 124
|
rb
|
Ruby
|
app/exceptions/transaction_error.rb
|
katakeynii/meppay
|
7ea69af76f6a46c939803fde403035402fb55b01
|
[
"MIT"
] | null | null | null |
app/exceptions/transaction_error.rb
|
katakeynii/meppay
|
7ea69af76f6a46c939803fde403035402fb55b01
|
[
"MIT"
] | null | null | null |
app/exceptions/transaction_error.rb
|
katakeynii/meppay
|
7ea69af76f6a46c939803fde403035402fb55b01
|
[
"MIT"
] | null | null | null |
class TransactionError < StandardError
def message
"Le montant doit etre egal au total des recettes"
end
end
| 24.8
| 57
| 0.717742
|
389102f652752fa0be34fe66fe36c1666ff799f7
| 5,946
|
php
|
PHP
|
application/views/rmekanik/downtime_breakdown.php
|
diananggit/gi-production
|
dc70788134175569ac8779676716a2b0c5a989e2
|
[
"MIT"
] | null | null | null |
application/views/rmekanik/downtime_breakdown.php
|
diananggit/gi-production
|
dc70788134175569ac8779676716a2b0c5a989e2
|
[
"MIT"
] | null | null | null |
application/views/rmekanik/downtime_breakdown.php
|
diananggit/gi-production
|
dc70788134175569ac8779676716a2b0c5a989e2
|
[
"MIT"
] | null | null | null |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Production Report | Dashboard</title>
<!-- Tell the browser to be responsive to screen width -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Font Awesome -->
<?php $this->load->view('_partials/css.php'); ?>
</head>
<body class="hold-transition sidebar-mini">
<div class="wrapper">
<!-- Navbar -->
<?php $this->load->view('_partials/navbar.php'); ?>
<!-- /.navbar -->
<!-- Main Sidebar Container -->
<?php $this->load->view('_partials/sidebar.php'); ?>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<div class="content-header">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
</div><!-- /.col -->
</div><!-- /.row -->
</div><!-- /.container-fluid -->
</div>
<!-- /.content-header -->
<!-- Main content -->
<section class="content">
<div class="container-fluid">
<h2 style="text-align: center; color: grey"><b>Globalindo Intimates - Sewing Line Report</b></h2>
<div class="form-group mx-sm-4 mb-3 mt-3">
<label><input type="text" id="month" style="text-align: center;" class="form-control" disabled></label>
</div>
<div class="card-body mt-1">
<hr />
<div class="row">
<div class="col-md-6">
<div class="card card-srcondary">
<div class="card-header">
<h3 class="card-title">Downtime Machine Chart</h3>
</div>
<div class="card-body">
<canvas id="barSewingDayChart"></canvas>
</div>
</div>
</div>
<!-- <div class="card-tools">
<button type="button" id="linkDowntimeChart" class="btn btn-danger"><i class="fa fa-bar-chart"></i>Downtime</button>
</div> -->
</div>
</div><!-- /.container-fluid -->
</section>
</div>
<?php $this->load->view('_partials/footer.php'); ?>
<!-- Control Sidebar -->
<aside class="control-sidebar control-sidebar-dark">
</aside>
</div>
<!-- jQuery -->
<?php $this->load->view('_partials/js.php'); ?>
<script type="text/javascript">
var table;
var chartSewingChart;
var month;
$(document).ready(function() {
var monthArr = localStorage.getItem('monthChart');
console.log('monthArr: ', monthArr);
var monthSplit = monthArr.split(",");
month = monthSplit[0];
showMechanicBreakdown();
function showMechanicBreakdown() {
$.ajax({
url: '<?php echo site_url('downtime_mechanic/ReportDowntimeBreakdown/get_data_machine_breakdown'); ?>',
type: 'POST',
data: {
'month': month
},
dataType: 'json',
}).done(function(data) {
// console.log(data);
var chartDowntimeCanvas = $('#barDowntimeBreakdown').get(0).getContext('2d');
var chartReportDowntimeLabels = [];
var chartDowntimeValues = [];
$.each(data, function(i, item) {
var hms = item.respon_d;
var a = hms.split(':');
console.log('hms', hms);
var respon = (+a[0]) * 60 + (+a[1]);
console.log('respon', respon);
var times = item.repair_d;
var b = times.split(':');
var repair = (+b[0]) * 60 + (+b[1]);
var total = respon + repair
chartDowntimeValues.push(total);
chartReportDowntimeLabels.push(item.line);
});
var arrColor = [];
for (x = 0; x <= chartDowntimeValues.length; x++) {
arrColor.push(
randomColor2()
);
}
if(window.bar != undefined)
window.bar.destroy();
window.bar = new Chart(chartDowntimeCanvas, {
type: 'bar',
data: {
labels: chartReportDowntimeLabels,
datasets: [{
borderColor: "#ff3333",
label: 'Downtime',
data: chartDowntimeValues,
backgroundColor :arrColor ,
fill: false
},
]
},
options: {
responsive: true,
tooltips: {
mode: 'label'
},
element: {
line: {
fill: false
}
},
scales: {
xAxes: [{
display: false,
barPercentage: 1.3,
ticks: {
max: 3,
}
}, {
display: true,
ticks: {
autoSkip: false,
max: 4,
}
}],
yAxes: [{
ticks: {
min:0
},
}]
},
},
});
})
}
// $('#linkDowntimeChart').click(function(){
// localStorage.setItem('monthChart', month);
// window.open('</?php echo site_url("LineDailyChart/ajax_get_by_line"); ?>/' + line, "_self");
// })
$('#month').val(month);
})
</script>
</body>
</html>
| 30.030303
| 133
| 0.434746
|
af9ee821eb1ae294fbb00483c520610bd079e51b
| 809
|
py
|
Python
|
api/utils.py
|
RonakRoy/spotidata
|
632163d937c5640e465431ecab8d5fd904054fcb
|
[
"MIT"
] | null | null | null |
api/utils.py
|
RonakRoy/spotidata
|
632163d937c5640e465431ecab8d5fd904054fcb
|
[
"MIT"
] | 5
|
2021-03-19T00:44:59.000Z
|
2021-06-10T18:38:09.000Z
|
api/utils.py
|
RonakRoy/tunelyze
|
632163d937c5640e465431ecab8d5fd904054fcb
|
[
"MIT"
] | null | null | null |
key_mapping = ['C', 'C#/D♭', 'D', 'D#/E♭', 'E', 'F', 'F#/G♭', 'G', 'G#/A♭', 'A', 'A#/B♭', 'B']
def get_dict_list(l):
return [e.to_dict() for e in l]
def get_english_list(l):
length = len(l)
if length == 0:
return "none"
elif length == 1:
return l[0]
elif length == 2:
return "{} and {}".format(l[0], l[1])
else:
output = ""
for i in range(length - 1):
output += "{}, ".format(l[i])
output += "and {}".format(l[length-1])
return output
def get_delimited_list(l, delimiter):
output = ""
length = len(l)
for i in range(length - 1):
output += "{}{}".format(l[i], delimiter)
output += "{}".format(l[length-1])
return output
def get_alpha_key(int_key):
return key_mapping[int_key]
| 21.864865
| 94
| 0.504326
|
f4e97880eca5a4e9416273945c832ef39b400ba3
| 921
|
tsx
|
TypeScript
|
packages/popover/src/styles.tsx
|
wygkzqa/reactour
|
af9de30a59f1aed7cfaf3b0f1546fae88a0fe096
|
[
"MIT"
] | 2,936
|
2017-03-31T10:55:35.000Z
|
2022-03-31T09:33:09.000Z
|
packages/popover/src/styles.tsx
|
wygkzqa/reactour
|
af9de30a59f1aed7cfaf3b0f1546fae88a0fe096
|
[
"MIT"
] | 413
|
2017-03-31T16:14:42.000Z
|
2022-03-30T07:58:39.000Z
|
packages/popover/src/styles.tsx
|
wygkzqa/reactour
|
af9de30a59f1aed7cfaf3b0f1546fae88a0fe096
|
[
"MIT"
] | 334
|
2017-03-31T16:02:15.000Z
|
2022-03-31T15:40:34.000Z
|
export type StylesKeys = 'popover'
export type StylesObj = {
[key in StylesKeys]?: StyleFn
}
export type StyleFn = (
props: { [key: string]: any },
state?: { [key: string]: any }
) => React.CSSProperties
export type Styles = {
popover: StyleFn
}
export type StyleKey = keyof Styles
export const defaultStyles: Styles = {
popover: () => ({
position: 'fixed',
maxWidth: 353,
// minWidth: 150,
backgroundColor: '#fff',
padding: '24px 30px',
boxShadow: '0 0.5em 3em rgba(0, 0, 0, 0.3)',
color: 'inherit',
zIndex: 100000,
transition: 'transform 0.3s',
top: 0,
left: 0,
}),
}
export type getStylesType = (key: StylesKeys, extra?: any) => {}
export function stylesMatcher(styles: StylesObj) {
return (key: StyleKey, state: {}): {} => {
const base = defaultStyles[key](state)
const custom = styles[key]
return custom ? custom(base, state) : base
}
}
| 21.418605
| 64
| 0.619978
|
d1aeb20a5297a274be72233ce1c4b857d55db573
| 1,133
|
rs
|
Rust
|
frontend/src/pages/mod.rs
|
r0m4n27/help_me
|
66c3cdfef6dcfc9f88ff66649805e92e7d64abf5
|
[
"MIT"
] | null | null | null |
frontend/src/pages/mod.rs
|
r0m4n27/help_me
|
66c3cdfef6dcfc9f88ff66649805e92e7d64abf5
|
[
"MIT"
] | null | null | null |
frontend/src/pages/mod.rs
|
r0m4n27/help_me
|
66c3cdfef6dcfc9f88ff66649805e92e7d64abf5
|
[
"MIT"
] | null | null | null |
use seed::prelude::*;
use crate::{
model::{user::User, Model},
msg::Msg,
views::nav_bar_view,
};
use self::{
admin::admin_view, guest::guest_view, requested_guest::requested_guest_view, tutor::tutor_view,
};
mod admin;
mod guest;
mod requested_guest;
mod tutor;
pub fn page_view(model: &Model) -> Node<Msg> {
match &model.user {
User::Guest(data) => guest_view(&data.0, model),
User::RequestedGuest(data) => requested_guest_view(&data.task, &data.page, model),
User::Admin(data) => admin_view(data, model),
User::Tutor(data) => tutor_view(data, model),
}
}
fn hero_view(content: Node<Msg>, model: &Model) -> Node<Msg> {
section![
C!["hero", "is-info", "is-fullheight"],
div![C!["hero-head"], nav_bar_view(model)],
div![
C!["hero-body", "section"],
div![C!["container"], content, error_message_view(model)]
]
]
}
fn error_message_view(model: &Model) -> Node<Msg> {
match model.user.page().error_message() {
Some(err) => div![C!["notification", "is-danger"], err],
None => div![],
}
}
| 25.75
| 99
| 0.590468
|
da1097414e1400ea8205f984f9586741dbf59675
| 11,353
|
php
|
PHP
|
pm.php
|
gaomy007/matchmaker
|
db60ad21a5abc84ebd8b26c70ef41f57f5c68f5d
|
[
"Unlicense"
] | 1
|
2016-03-05T11:30:55.000Z
|
2016-03-05T11:30:55.000Z
|
pm.php
|
gaomy007/matchmaker
|
db60ad21a5abc84ebd8b26c70ef41f57f5c68f5d
|
[
"Unlicense"
] | null | null | null |
pm.php
|
gaomy007/matchmaker
|
db60ad21a5abc84ebd8b26c70ef41f57f5c68f5d
|
[
"Unlicense"
] | null | null | null |
<?php
require_once("models/config.php");
if (!securePage($_SERVER['PHP_SELF'])) {
die();
}
if (!isUserLoggedIn()) {
header("Location: index.php");
die();
}
// Set the userid to 2 for testing purposes... you should have your own usersystem, so this should contain the userid
$loggedInUser = $_SESSION["userCakeUser"];
$userid=$loggedInUser->user_id;
// initiate a new pm class
$pm = new cpm($userid);
// check if a new message had been send
if(isset($_POST['newmessage'])) {
// check if there is an error while sending the message (beware, the input hasn't been checked, you should never trust users input!)
if($pm->sendmessage($_POST['to'],$_POST['subject'],$_POST['message'])) {
// Tell the user it was successful
echo "Message successfully sent!";
} else {
// Tell user something went wrong it the return was false
echo "Error, couldn't send PM. Maybe wrong user.";
}
}
// check if a message had been deleted
if(isset($_POST['delete'])) {
// check if there is an error during deletion of the message
if($pm->deleted($_POST['did'])) {
echo "Message successfully deleted!";
} else {
echo "Error, couldn't delete PM!";
}
}
require_once("models/header.php");
?>
<body>
<header class="intro-header" style="background-image: url('img/home-bg.jpg')">
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<div class="site-heading">
<h1>See the person matching you!</h1>
<hr class="small">
<span class="subheading"></span>
</div>
</div>
</div>
</div>
</header>
<div class="container">
<div class="row">
<div class="col-sm-3 col-md-2 sidebar">
<?php include("left-nav.php"); ?>
</div>
<div class="col-lg-9">
<?php
// In this switch we check what page has to be loaded, this way we just load the messages we want using numbers from 0 to 3 (0 is standart, so we don't need to type this)
if(isset($_GET['p'])) {
switch($_GET['p']) {
// get all new / unread messages
case 'new': $pm->getmessages(); break;
// get all send messages
case 'send': $pm->getmessages(2); break;
// get all read messages
case 'read': $pm->getmessages(1); break;
// get all deleted messages
case 'deleted': $pm->getmessages(3); break;
// get a specific message
case 'view': $pm->getmessage($_GET['mid']); break;
// get all new / unread messages
default: $pm->getmessages(); break;
}
} else {
// get all new / unread messages
$pm->getmessages();
}
// Standard links
?>
<div class="btn-group">
<a class="btn btn-success" href='<?php echo $_SERVER['PHP_SELF']; ?>?p=new'>New Messages</a>
<a class="btn btn-primary" href='<?php echo $_SERVER['PHP_SELF']; ?>?p=read'>All Messages</a>
<a class="btn btn-info" href='<?php echo $_SERVER['PHP_SELF']; ?>?p=send'>Sent Messages</a>
<a class="btn btn-warning" href='<?php echo $_SERVER['PHP_SELF']; ?>?p=deleted'>Deleted Messages</a>
</div>
<br>
<br>
<br>
<?php
// if it's the standart startpage or the page new, then show all new messages
if(!isset($_POST['reply'])&&(!isset($_GET['p']) || $_GET['p'] == 'new')) {
?>
<table class="table" >
<thead>
<tr>
<th>From</th>
<th>Title</th>
<th>Date</th>
</tr>
</thead>
<?php
// If there are messages, show them
if(count($pm->messages)) {
// message loop
for($i=0;$i<count($pm->messages);$i++) {
?>
<tr>
<td><?php echo $pm->messages[$i]['from']; ?></td>
<td><a href='<?php echo $_SERVER['PHP_SELF']; ?>?p=view&mid=<?php echo $pm->messages[$i]['id']; ?>'><?php echo $pm->messages[$i]['title'] ?></a></td>
<td><?php echo $pm->messages[$i]['created']; ?></td>
</tr>
<?php
}
} else {
// else... tell the user that there are no new messages
echo "<tr><td colspan='3'><strong>No new messages found</strong></td></tr>";
}
?>
</table>
<?php
// check if the user wants send messages
} elseif(!isset($_POST['reply'])&&$_GET['p'] == 'send') {
?>
<table class="table">
<thead>
<tr>
<th>To</th>
<th>Title</th>
<th>Status</th>
<th>Date</th>
</tr>
</thead>
<?php
// if there are messages, show them
if(count($pm->messages)) {
// message loop
for($i=0;$i<count($pm->messages);$i++) {
?>
<tr>
<td><?php echo $pm->messages[$i]['to']; ?></td>
<td><a href='<?php echo $_SERVER['PHP_SELF']; ?>?p=view&mid=<?php echo $pm->messages[$i]['id']; ?>'><?php echo $pm->messages[$i]['title'] ?></a></td>
<td>
<?php
// If a message is deleted and not viewed
if($pm->messages[$i]['to_deleted'] && !$pm->messages[$i]['to_viewed']) {
echo "Deleted without reading";
// if a message got deleted AND viewed
} elseif($pm->messages[$i]['to_deleted'] && $pm->messages[$i]['to_viewed']) {
echo "Deleted after reading";
// if a message got not deleted but viewed
} elseif(!$pm->messages[$i]['to_deleted'] && $pm->messages[$i]['to_viewed']) {
echo "Read";
} else {
// not viewed and not deleted
echo "Not read yet";
}
?>
</td>
<td><?php echo $pm->messages[$i]['created']; ?></td>
</tr>
<?php
}
} else {
// else... tell the user that there are no new messages
echo "<tr><td colspan='4'><strong>No send messages found</strong></td></tr>";
}
?>
</table>
<?php
// check if the user wants the read messages
} elseif($_GET['p'] == 'read') {
?>
<table class='table'>
<thead>
<tr>
<th>From</th>
<th>Title</th>
<th>Date</th>
</tr>
</thead>
<?php
// if there are messages, show them
if(count($pm->messages)) {
// message loop
for($i=0;$i<count($pm->messages);$i++) {
?>
<tr>
<td><?php echo $pm->messages[$i]['from']; ?></td>
<td><a href='<?php echo $_SERVER['PHP_SELF']; ?>?p=view&mid=<?php echo $pm->messages[$i]['id']; ?>'><?php echo $pm->messages[$i]['title'] ?></a></td>
<td><?php echo $pm->messages[$i]['to_vdate']; ?></td>
</tr>
<?php
}
} else {
// else... tell the user that there are no new messages
echo "<tr><td colspan='4'><strong>No read messages found</strong></td></tr>";
}
?>
</table>
<?php
// check if the user wants the deleted messages
} elseif($_GET['p'] == 'deleted') {
?>
<table class='table'>
<thead>
<tr>
<th>From</th>
<th>Title</th>
<th>Date</th>
</tr>
</thead>
<?php
// if there are messages, show them
if(count($pm->messages)) {
// message loop
for($i=0;$i<count($pm->messages);$i++) {
?>
<tr>
<td><?php echo $pm->messages[$i]['from']; ?></td>
<td><a href='<?php echo $_SERVER['PHP_SELF']; ?>?p=view&mid=<?php echo $pm->messages[$i]['id']; ?>'><?php echo $pm->messages[$i]['title'] ?></a></td>
<td><?php echo $pm->messages[$i]['to_ddate']; ?></td>
</tr>
<?php
}
} else {
// else... tell the user that there are no new messages
echo "<tr><td colspan='4'><strong>No deleted messages found</strong></td></tr>";
}
?>
</table>
<?php
// if the user wants a detail view and the message id is set...
} elseif($_GET['p'] == 'view' && isset($_GET['mid'])) {
// if the users id is the recipients id and the message hadn't been viewed yet
if($userid == $pm->messages[0]['toid'] && !$pm->messages[0]['to_viewed']) {
// set the messages flag to viewed
$pm->viewed($pm->messages[0]['id']);
}
?>
<table class='table'>
<tr>
<td><b>From:</b></td>
<td><?php echo $pm->messages[0]['from']; ?></td>
<td colspan="2"></td>
</tr>
<tr>
<td><b>Date:</b></td>
<td><?php echo $pm->messages[0]['created']; ?></td>
<td colspan="2"></td>
</tr>
<tr>
<td><b>Subject:</b></td>
<td colspan="3"><?php echo $pm->messages[0]['title']; ?></td>
</tr>
<tr>
<td colspan="4" border="1"><?php echo $pm->render($pm->messages[0]['message']); ?></td>
</tr>
</table>
<div class="row">
<div class="col-lg-2 ">
<form name='reply' method='post' action='<?php echo $_SERVER['PHP_SELF']; ?>'>
<input type='hidden' name='rfrom' value='<?php echo $pm->messages[0]['from']; ?>' />
<input type='hidden' name='rsubject' value='Re: <?php echo $pm->messages[0]['title']; ?>' />
<input type='hidden' name='rmessage' value='[quote]<?php echo $pm->messages[0]['message']; ?>[/quote]' />
<input class='btn btn-success small' type='submit' name='reply' value='Reply' />
</form>
</div>
<div class="col-lg-2 col-lg-offset-3 ">
<form name='delete' method='post' action='<?php echo $_SERVER['PHP_SELF']; ?>'>
<input type='hidden' name='did' value='<?php echo $pm->messages[0]['id']; ?>' />
<input class='btn btn-warning small' type='submit' name='delete' value='Delete' />
</form>
</div>
</div>
<?php
}
if(isset($_POST['reply'])){
?>
<div class="row">
<br><br>
<form name="new" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<strong>To:</strong>
<input type='text' name='to' value='<?php if(isset($_POST['reply'])) { echo $_POST['rfrom']; } ?>' />
<strong>Subject:</strong>
<input type='text' name='subject' value='<?php if(isset($_POST['reply'])) { echo $_POST['rsubject']; } ?>' />
<strong>Message:</strong><br />
<textarea name='message'><?php if(isset($_POST['reply'])) { echo $_POST['rmessage']; } ?></textarea>
<input type='submit' name='newmessage' value='Send' />
</form>
</div>
</div>
</div>
</div>
<?php
}
require_once("footer.php");
?>
| 35.589342
| 171
| 0.476614
|
23e2c290e14f7ed2dda7dc7ee19e93bfe32d96c7
| 3,150
|
js
|
JavaScript
|
index.js
|
shinespark/sbi-message2mail
|
38f1c5c77f700d49760faf299821043f5a53e36d
|
[
"MIT"
] | null | null | null |
index.js
|
shinespark/sbi-message2mail
|
38f1c5c77f700d49760faf299821043f5a53e36d
|
[
"MIT"
] | null | null | null |
index.js
|
shinespark/sbi-message2mail
|
38f1c5c77f700d49760faf299821043f5a53e36d
|
[
"MIT"
] | null | null | null |
const fs = require('fs');
const path = require('path');
const puppeteer = require('puppeteer');
const {google} = require('googleapis');
require('dotenv').config();
const SBI = {
"loginUrl": "https://www.netbk.co.jp/contents/pages/wpl010101/i010101CT/DI01010210",
"messageBoxUrl": "https://www.netbk.co.jp/contents/pages/wpl200601/i200601CT/DI20060000"
}
// https://developers.google.com/gmail/api/quickstart/nodejs#step_3_set_up_the_sample
// https://github.com/googleapis/google-api-nodejs-client/blob/master/samples/gmail/send.js
const SCOPES = ['https://www.googleapis.com/auth/gmail.send'];
const TOKEN_PATH = path.join(__dirname, 'token.json');
let auth;
fs.readFile(path.join(__dirname, 'credentials.json'), (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
const {client_secret, client_id, redirect_uris} = JSON.parse(content).installed;
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, (err, token) => {
oAuth2Client.setCredentials(JSON.parse(token));
auth = oAuth2Client;
});
});
async function login(page) {
await page.goto(SBI.loginUrl, {waitUntil: 'networkidle2'});
await page.type('#userName', `${process.env.SBI_USERNAME}`);
await page.type('#loginPwdSet', `${process.env.SBI_PASSWORD}`);
await page.click('button[data-js="login"]');
}
async function getUnreadMessages(page) {
await page.goto(SBI.messageBoxUrl, {waitUntil: 'networkidle2'});
const unreadMessagesSelector = '.m-linkMail.ng-star-inserted:not(.m-already)';
const result = await page.$$eval(unreadMessagesSelector, unreadMessages => {
let list = [];
for (let i = 0; unreadMessages.length > i; i++) {
list.push({
href: unreadMessages[i].href,
text: unreadMessages[i].textContent.trim()
})
}
return list
});
console.log(result)
return result
}
async function sendMail(subject, body) {
console.log(subject);
const utf8Subject = `=?utf-8?B?${Buffer.from(subject).toString('base64')}?=`;
const messageParts = [
`From: sbi-message2mail <${process.env.FROM}>`,
`To: Yourself <${process.env.TO}>`,
'Content-Type: text/html; charset=utf-8',
'Content-Transfer-Encoding: 7bit',
'MIME-Version: 1.0',
`Subject: ${utf8Subject}`,
'',
`${body}`
];
const message = messageParts.join('\n');
// The body needs to be base64url encoded.
const encodedMessage = Buffer.from(message)
.toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '');
const gmail = google.gmail({version: 'v1', auth: auth});
return gmail.users.messages.send({
userId: 'me',
requestBody: {
raw: encodedMessage,
},
});
}
(async () => {
const browser = await puppeteer.launch({args: ['--no-sandbox', '--disable-setuid-sandbox']});
const page = await browser.newPage();
await login(page);
const unreadMessages = await getUnreadMessages(page);
// await captureAllPortfolio(page, 'service/portfolio', '.section-frame');
await browser.close();
})();
| 31.5
| 95
| 0.673016
|
d2acd8a59e2015841354e49474513b1affb1f4ed
| 1,554
|
dart
|
Dart
|
lib/utils/app_color.dart
|
luuthanhminh/flutter_twivideo
|
22b9d6dd5d7afc4fb46e776e635c85dc2d9c5dd7
|
[
"MIT"
] | null | null | null |
lib/utils/app_color.dart
|
luuthanhminh/flutter_twivideo
|
22b9d6dd5d7afc4fb46e776e635c85dc2d9c5dd7
|
[
"MIT"
] | null | null | null |
lib/utils/app_color.dart
|
luuthanhminh/flutter_twivideo
|
22b9d6dd5d7afc4fb46e776e635c85dc2d9c5dd7
|
[
"MIT"
] | null | null | null |
import 'package:flutter/material.dart';
class AppColors {
static const Color jadeGreen = Color(0xFF26a93c);
static const Color lipstick = Color(0xFFe91e55);
static const Color warmGrey = Color(0xFF808080);
static const Color warmGrey2 = Color(0x50979797);
static const Color white82 = Color(0x82f8f8f8);
static const Color white3= Color(0xFFd8d8d8);
static const Color paleGrey = Color(0xFFe9e2e8);
static const Color paleGreyTwo = Color(0xFFf9f0f8);
static const Color paleGreyThree = Color(0xFFeaf3f7);
static const Color darkGreyBlue = Color(0xFF394e72);
static const Color steel = Color(0xFF8e8e93);
static const Color steel012 = Color(0x128e8e93);
static const Color denimBlue = Color(0xFF395997);
static const Color black30 = Color(0x30000000);
static const Color tabBarColor = Colors.white;
static const Color brightBlue = Color(0xFF007aff);
static const Color black = Colors.black;
static const Color greyishBrown = Color(0xFF3d3d3d);
static const Color eggShell = Color(0xFFfef5bf);
static const Color sunflowerYellow = Color(0xFFfcd803);
static const Color coolGrey = Color(0xFF9e9ea6);
static const Color blueSlidable = Color(0xFF077CC6);
static const Color redSlidable = Color(0xFFE20002);
static const Color rosyPink = Color(0xFFf55e87);
static const Color blueGrey = Color(0xFF929eb1);
static const Color whiteF6 = Color(0xFFf6f6f6);
static const Color fireEngineRed = Color(0xFFe20002);
static const Color cerulean = Color(0xFF077cc6);
static const Color white = Colors.white;
}
| 44.4
| 57
| 0.76834
|
583c10a1812d8730f08aaf85211b6a72c5fcc93b
| 3,065
|
ps1
|
PowerShell
|
scripts/deploy.ps1
|
totollygeek/serverless-with-fn
|
161e4d513112e0e263f263cbdfdf78bb4422a344
|
[
"Apache-2.0"
] | null | null | null |
scripts/deploy.ps1
|
totollygeek/serverless-with-fn
|
161e4d513112e0e263f263cbdfdf78bb4422a344
|
[
"Apache-2.0"
] | null | null | null |
scripts/deploy.ps1
|
totollygeek/serverless-with-fn
|
161e4d513112e0e263f263cbdfdf78bb4422a344
|
[
"Apache-2.0"
] | null | null | null |
# This will do a clean deploy of an application in Fn and two functions,
# along with the stats ASP.NET Core application
# This script should be run from the .\scripts folder
# We initialize some variables used below
$appName = 'fndotnet'
$mySqlContainerName = 'mysql0'
$volumeMap = "$($PSScriptRoot):/scripts"
$prometheusYamlMap = "$($PSScriptRoot)/config/prometheus.yml:/etc/prometheus/prometheus.yml"
function Exec([scriptblock] $cmd, [string] $message) {
Write-Host "+--------------------------"
Write-Host "| $message..."
Write-Host "+------------"
& $cmd
Write-Host -ForegroundColor Green "+-------+"
Write-Host -ForegroundColor Green "| Done! |"
Write-Host -ForegroundColor Green "+-------+"
}
# Run MySQL in docker
Exec {
& docker run `
--name $mySqlContainerName `
-p 3306:3306 -v $volumeMap `
-e MYSQL_ROOT_PASSWORD='secret123!' `
-d mysql
} "Starting MySQL container"
$logCount = 0;
do {
Write-Host -ForegroundColor Yellow "Waiting for 5 more seconds for MySQL to be up and running"
Start-Sleep -Seconds 5
$logCount = 0;
$output = (docker logs $mySqlContainerName 2>&1)
foreach ($line in $output) {
if ($line -like "*Plugin ready for connections*") { $logCount++ }
}
Write-Host -ForegroundColor Green "Found $logCount instances"
} while ($logCount -lt 2)
# Create database
Exec {
& docker exec -i $mySqlContainerName sh /scripts/createdb.sh
} "Creating database inside container"
# Start the Fn Server
Exec {
& fn start -d
} "Running Fn Server"
# Start the Fn UI
Exec {
& docker run `
--name=ui --rm -it `
-d --link fnserver:api `
-p 4000:4000 `
-e "FN_API_URL=http://api:8080" fnproject/ui
} "Starting Fn UI"
# Start Prometheus
Exec {
& docker run `
--rm `
--name=prometheus `
-d -p 9090:9090 `
-v $prometheusYamlMap `
--add-host="fnserver:172.17.0.1" prom/prometheus
} "Starting Prometheus"
# Start Grafana
Exec {
& docker run `
--name=grafana `
-d -p 5000:3000 `
--add-host="prometheus:172.17.0.1" grafana/grafana
} "Starting Grafana"
# Create the app
Exec {
& fn create app $appName
} "Creating Fn app $appName"
# Deploy the detect function
Exec {
# Change location to detect function
Set-Location ../src/detect
& fn --verbose deploy --app $appName --local
} "Deploy function `"detect`""
# Deploy the save function
Exec {
# Change location to the save function
Set-Location ../save
& fn --verbose deploy --app $appName --local
} "Deploy function `"save`""
$DB_ADDRESS = docker inspect --type container -f '{{.NetworkSettings.IPAddress}}' $mySqlContainerName
& fn config app $appName DB_ADDRESS $DB_ADDRESS
$FN_ADDRESS = docker inspect --type container -f '{{.NetworkSettings.IPAddress}}' fnserver
& fn config app $appName FN_ADDRESS $FN_ADDRESS
# Build stats container image first
Exec {
Set-Location ../stats
& docker build -t stats:latest .
Set-Location ../../scripts
} "Building stats docker image"
Exec {
& docker run --name=stats -e ASPNETCORE_ENVIRONMENT=Development -e DB_ADDRESS=$DB_ADDRESS -p 8888:80 -d stats:latest
} "Starting `"stats`" container"
| 25.541667
| 117
| 0.688091
|
c9985be410a55fb54aa57f5757129503ef89bced
| 567
|
ts
|
TypeScript
|
src/index.ts
|
extend-chrome/storage
|
66b6189274496506eb951fa60c774230ed2c0280
|
[
"MIT"
] | 26
|
2020-06-13T07:21:59.000Z
|
2022-03-24T08:39:30.000Z
|
src/index.ts
|
extend-chrome/storage
|
66b6189274496506eb951fa60c774230ed2c0280
|
[
"MIT"
] | 11
|
2020-06-08T22:31:02.000Z
|
2022-02-07T02:19:12.000Z
|
src/index.ts
|
extend-chrome/storage
|
66b6189274496506eb951fa60c774230ed2c0280
|
[
"MIT"
] | 1
|
2019-08-21T12:01:05.000Z
|
2019-08-21T12:01:05.000Z
|
import { getBucket } from './bucket'
/**
* Buckets for each storage area.
*/
export const storage = {
local: getBucket<Record<string, any>>('local', 'local'),
sync: getBucket<Record<string, any>>('sync', 'sync'),
managed: getBucket<Record<string, any>>('managed', 'managed'),
}
// Workaround for @rollup/plugin-typescript
export * from './types'
export { getBucket }
/**
* Deprecated. Use `getBucket`.
*/
export const useBucket = <T extends object>(
areaName: 'local' | 'sync' | 'managed',
bucketName: string,
) => getBucket<T>(bucketName, areaName)
| 24.652174
| 64
| 0.664903
|
f1ef31cad542618e02eacec944028bc4f5d742c0
| 454
|
rb
|
Ruby
|
metadata.rb
|
OpSitters/opsit_role
|
5df1b58d6e95f1433ce9a8c2145b6f4b1ab78a70
|
[
"Apache-2.0"
] | null | null | null |
metadata.rb
|
OpSitters/opsit_role
|
5df1b58d6e95f1433ce9a8c2145b6f4b1ab78a70
|
[
"Apache-2.0"
] | null | null | null |
metadata.rb
|
OpSitters/opsit_role
|
5df1b58d6e95f1433ce9a8c2145b6f4b1ab78a70
|
[
"Apache-2.0"
] | null | null | null |
name 'opsit_role'
maintainer 'OpSitters'
maintainer_email 'oss@opsitters.com'
version '1.0.1'
license 'Apache 2.0'
description 'OpSitters base role'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
depends "opsit_libs"
depends "opsit_ops"
%w{
chef-solo-search
ntp
ohai
sudo
users
}.each do |cb|
depends cb
end
%w{ debian ubuntu centos redhat }.each do |os|
supports os
end
| 18.916667
| 72
| 0.669604
|
2a805faf3230fd4b9c6ef2818ca9d2ccce17d395
| 71
|
css
|
CSS
|
css/styles.css
|
Makiz7791/vid.customer-reviews
|
7644c82fd61539cdf9950334189414d80db5f5c6
|
[
"MIT"
] | null | null | null |
css/styles.css
|
Makiz7791/vid.customer-reviews
|
7644c82fd61539cdf9950334189414d80db5f5c6
|
[
"MIT"
] | null | null | null |
css/styles.css
|
Makiz7791/vid.customer-reviews
|
7644c82fd61539cdf9950334189414d80db5f5c6
|
[
"MIT"
] | null | null | null |
body {
font-family: DM Sans, arial, sans-serif;
color: #000;;
}
| 17.75
| 44
| 0.591549
|
a11b27794b6d816e5168b260065b46eee94475c6
| 862
|
ts
|
TypeScript
|
src/services/user/__tests__/user.controller.spec.ts
|
ynwd/fastify-di
|
9048a907cab6909296683d31144da1a03dea6bb1
|
[
"MIT"
] | 1
|
2021-05-16T04:04:40.000Z
|
2021-05-16T04:04:40.000Z
|
src/services/user/__tests__/user.controller.spec.ts
|
ynwd/fastify-di
|
9048a907cab6909296683d31144da1a03dea6bb1
|
[
"MIT"
] | null | null | null |
src/services/user/__tests__/user.controller.spec.ts
|
ynwd/fastify-di
|
9048a907cab6909296683d31144da1a03dea6bb1
|
[
"MIT"
] | null | null | null |
import { FastifyInstance } from 'fastify'
import { createServer, serviceContainer } from '../../../core'
import { UserService } from '../user.service'
let server: FastifyInstance
let service: UserService
beforeAll(async () => {
server = await createServer({ logger: false })
service = serviceContainer.get('UserService')
service.deleteAll()
})
afterAll(() => {
server.close()
})
test('GET /user', async done => {
const result = await server.inject({
url: '/user',
method: 'GET'
})
expect(result.payload).toBe('{"error":true,"message":"User not found"}')
done()
})
test('POST /user', async done => {
const result = await server.inject({
url: '/user',
method: 'POST',
payload: {
email: 'pram@diversa.id',
username: 'zaid',
password: 'secret'
}
})
expect(result.statusCode).toBe(200)
done()
})
| 21.55
| 74
| 0.62645
|
0ad897a47198d48f39f5af0d0dc3a902c65e47da
| 335
|
cs
|
C#
|
DriftySquirrel/Assets/Plugins/StansAssets/Foundation/APIModules/Public/Tests/Models/SA_TestConfig.cs
|
ElectriVellum/DriftySquirrel
|
6b4a576029c8b3d1293518188ec9f38f0767508f
|
[
"MIT"
] | null | null | null |
DriftySquirrel/Assets/Plugins/StansAssets/Foundation/APIModules/Public/Tests/Models/SA_TestConfig.cs
|
ElectriVellum/DriftySquirrel
|
6b4a576029c8b3d1293518188ec9f38f0767508f
|
[
"MIT"
] | null | null | null |
DriftySquirrel/Assets/Plugins/StansAssets/Foundation/APIModules/Public/Tests/Models/SA_TestConfig.cs
|
ElectriVellum/DriftySquirrel
|
6b4a576029c8b3d1293518188ec9f38f0767508f
|
[
"MIT"
] | null | null | null |
using UnityEngine;
using System.Collections;
using System;
using TypeReferences;
using SA.Foundation.Tests;
namespace SA.Foundation.Tests {
[Serializable]
public class SA_TestConfig {
[ClassExtends(typeof(SA_BaseTest))]
public ClassTypeReference TestReference;
public bool StopsNextTestsIfFail;
}
}
| 25.769231
| 48
| 0.740299
|
cdf97f8a96a457ded9e14df226162918dad7aaed
| 207
|
cs
|
C#
|
BloomFilter/BloomFilter/Utilities/HashFunctionDotNet.cs
|
cagaray/bloom-filter
|
385a1200e828e5ab728965ab10f30d1db0ebded0
|
[
"MIT"
] | null | null | null |
BloomFilter/BloomFilter/Utilities/HashFunctionDotNet.cs
|
cagaray/bloom-filter
|
385a1200e828e5ab728965ab10f30d1db0ebded0
|
[
"MIT"
] | null | null | null |
BloomFilter/BloomFilter/Utilities/HashFunctionDotNet.cs
|
cagaray/bloom-filter
|
385a1200e828e5ab728965ab10f30d1db0ebded0
|
[
"MIT"
] | null | null | null |
namespace BloomFilter.Utilities
{
public class HashFunctionDotNet<T> : IHashFunction<T>
{
public int ComputeHash(T value)
{
return value.GetHashCode();
}
}
}
| 18.818182
| 57
| 0.584541
|
b0bd79a348ed8b5dfc8c43840a20e6830ef6b75f
| 304
|
py
|
Python
|
remove_file.py
|
Kondziowy/PythonBasicTraining
|
b7f98a4263faee6f94179a0786ba7eb2dd1e2191
|
[
"BSD-3-Clause"
] | 1
|
2018-07-31T10:19:26.000Z
|
2018-07-31T10:19:26.000Z
|
remove_file.py
|
Kondziowy/PythonBasicTraining
|
b7f98a4263faee6f94179a0786ba7eb2dd1e2191
|
[
"BSD-3-Clause"
] | null | null | null |
remove_file.py
|
Kondziowy/PythonBasicTraining
|
b7f98a4263faee6f94179a0786ba7eb2dd1e2191
|
[
"BSD-3-Clause"
] | 2
|
2018-10-16T14:03:26.000Z
|
2021-11-03T11:03:20.000Z
|
import os
file_to_remove = os.path.join(os.getcwd(), "non_existent_file")
print("Do you want to remove %s? Please answer yes or no" % file_to_remove)
answer = input()
answer_is_true = bool(answer)
if answer_is_true:
print("Removing file %s" % file_to_remove)
os.unlink(file_to_remove)
| 25.333333
| 76
| 0.717105
|
db954c6324bf8588f5269450fec0ecd79ddf610d
| 13,523
|
php
|
PHP
|
frontend/views/tbl-permohonan/view.php
|
sgntkeroro/e-Perolehan
|
fc6961d0686c5ccf53ed2c8bf1b6ffbba27d4496
|
[
"BSD-3-Clause"
] | null | null | null |
frontend/views/tbl-permohonan/view.php
|
sgntkeroro/e-Perolehan
|
fc6961d0686c5ccf53ed2c8bf1b6ffbba27d4496
|
[
"BSD-3-Clause"
] | null | null | null |
frontend/views/tbl-permohonan/view.php
|
sgntkeroro/e-Perolehan
|
fc6961d0686c5ccf53ed2c8bf1b6ffbba27d4496
|
[
"BSD-3-Clause"
] | null | null | null |
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\helpers\Url;
/* @var $this yii\web\View */
/* @var $model frontend\models\TblPermohonan */
$this->title = 'ID : '.$model->permohonan_id;
$sokong = $model->sokongan;
$nombor = 1;
?>
<style type="text/css">
.table
{
/*border-left: 2px solid;
border-top: 2px solid;*/
border-spacing:0;
border-collapse: collapse;
}
table td
{
/*border-right: 2px solid;
border-bottom: 2px solid;*/
padding: 2mm;
}
.divInlineLeft {
display: inline;
float: left
}
.divInlineRight {
display: inline;
float: right
}
.span {
display:inline-block;
width: 270px;
}
</style>
<div>
<div class="panel panel-primary" align="center">
<!-- Default panel contents -->
<div class="panel-heading">
<?= Html::a('<span class="glyphicon glyphicon-home" aria-hidden="true"></span>', ['/site/index'], [
'class' => 'btn btn-info',
'data-toggle'=>'tooltip',
'title'=>'HOME'
]); ?>
<?= Html::a('<span class="glyphicon glyphicon-list-alt" aria-hidden="true"></span>',
['index'], [
'class' => 'btn btn-info',
'data-toggle'=>'tooltip',
'title'=>'Senarai Permohonan'
]); ?>
</div><br>
<div class="panel panel-info" style="width:99%;">
<div class="panel-heading">
<h4><b>BUTIRAN PERMOHONAN</b></h4><br>
<?= Html::a('<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>', ['update', 'id' => $model->permohonan_id], [
'class' => 'btn btn-success btn-sm']) ?>
<?= Html::a('<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>', ['delete', 'id' => $model->permohonan_id], [
'class' => 'btn btn-danger btn-sm',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
<?= Html::a('<span class="glyphicon glyphicon-file" aria-hidden="true"></span>', ['pdf', 'id' => $model->permohonan_id], [
'class' => 'btn btn-info btn-sm',
'target'=>'_blank',
'data-toggle'=>'tooltip',
'title'=>'Will open the generated PDF file in a new window'
]); ?>
</div>
<div class="panel-body">
<p>
<!-- Table -->
<table class="table">
<thead>
<th>Permohonan ID</th>
<th>Nama Pemohon</th>
<th>Tarikh Permohonan</th>
<th>Pusat Kos</th>
<th>Status Sokongan</th>
<th>Komen</th>
</thead>
<tbody>
<tr>
<td><?= $model->permohonan_id ?></td>
<td>
<?php foreach ($viewAtas as $mod_nama): ?>
<?= $mod_nama['mod_nama'] ?>
<?php endforeach; ?>
</td>
<td><?= $model->permohonan_tarikh ?></td>
<td><?= $model->permohonan_pusatKos ?></td>
<td style = "background-color:#FFD700"><?= $sokong->sok_sokongan ?></td>
<td style = "background-color:#FFD700"><?= $model->permohonan_komenpnc ?></td>
</tr>
</tbody>
</table>
</p>
</div>
</div>
<div class="panel panel-info" style="width:99%;">
<div class="panel-heading">
<h4><b>NOTIFIKASI</b></h4>
</div>
<div class="panel-body">
<p>
Sila hantar notifikasi untuk makluman kepada pihak cspi.<br><br>
<?= Html::a('Hantar Notifikasi ke CSPI', ['tbl-email/create'], [
'class' => 'btn btn-info btn-sm']) ?>
</p>
</div>
</div>
<div class="panel panel-info" style="width:99%;">
<div class="panel-heading">
<h4><b>SURAT PENGESAHAN</b></h4>
<?= Html::a('<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>', ['updatesuratsah', 'id' => $model->permohonan_id], [
'class' => 'btn btn-success btn-sm']) ?>
</div>
<div class="panel-body">
<p>
<!-- Table -->
<table class="table">
<thead>
<th>No. Permohonan</th>
<th>Surat</th>
<th>Tarikh Surat</th>
<th>Deskripsi</th>
</thead>
<tbody>
<tr>
<td>
<?= $model->permohonan_id ?>
</td>
<td>
<?php foreach ($suratSah as $suratSah_nama): ?>
<?= Html::a($suratSah_nama['suratSah_nama'], ['list', 'id' => $suratSah_nama->suratSah_id], [
'target'=>'_blank',
'data-toggle'=>'tooltip',
'title'=>'Will open the generated PDF file in a new window'
]); ?>
<?php endforeach; ?>
</td>
<td>
<?php foreach ($suratSah as $suratSah_tarikh): ?>
<?= $suratSah_tarikh['suratSah_tarikh'] ?>
<?php endforeach; ?>
</td>
<td>
<?php foreach ($suratSah as $suratSah_deskripsi): ?>
<?= $suratSah_deskripsi['suratSah_deskripsi'] ?>
<?php endforeach; ?>
</td>
</tr>
</tbody>
</table>
</p>
</div>
</div>
<div class="panel-body" align="center">
<div class="alert alert-info span" role="alert">
<b><?= Html::tag('span', 'Status Permohonan', [
'title'=>'Anda dikehendaki memuatnaik salinan surat pengesahan yang telah disahkan dan ditandatangan oleh Dekan / PTJ terlebih dahulu supaya permohonan anda akan diproses',
'data-toggle'=>'tooltip',
'style'=>'cursor:pointer;'
]); ?></b><br><br>
<font color="black">
<?php foreach ($viewStatus as $statMohon_status): ?>
<?= $statMohon_status['statMohon_status'] ?>
<?php endforeach; ?>
</font>
</div>
<div class="alert alert-warning span" role="alert">
<b><?= Html::tag('span', 'Status Mesyuarat', [
'title'=>'Dikemaskini setelah mesyuarat',
'data-toggle'=>'tooltip',
'style'=>'cursor:pointer;'
]); ?></b><br><br>
<font color="black">
<?php foreach ($viewStatus as $statMesyua_status): ?>
<?= Html::a( $statMesyua_status['statMesyua_status'],
['status', 'id' => $statMesyua_status['permohonan_id']]) ?>
<?php endforeach; ?>
</font>
</div>
<div class="alert alert-danger span" role="alert">
<b><?= Html::tag('span', 'Status', [
'title'=>'Status ini menunjukkan sama ada permohonan ini sudah selesai atau pun belum',
'data-toggle'=>'tooltip',
'style'=>'cursor:pointer;'
]); ?></b><br><br>
<font color="black">
<?php foreach ($viewStatus as $status_status): ?>
<?= $status_status['status_status'] ?>
<?php endforeach; ?>
</font>
</div>
</div>
<div class="panel panel-info" style="width:99%;">
<div class="panel-heading"><h4><b>JADUAL PERALATAN</b></h4></div>
<div class="panel-body">
<P>
<div align="center" class="table-responsive">
<table class="table-bordered table-striped table-hover text-center" style="font-size: 12px;">
<thead>
<tr style="background-color:#D3D3D3; font-size: 14px;">
<td class="text-left" style="padding:2mm;">Bil.</td>
<td class="text-left" style="padding:2mm;">Peralatan</td>
<td class="text-left" style="padding:2mm;">Kod Akaun</td>
<td class="text-left" style="padding:2mm;">Kuantiti</td>
<td class="text-left" style="padding:2mm;">Harga Seunit</td>
<td class="text-left" style="padding:2mm;">Jumlah Harga</td>
<td class="text-left" style="padding:2mm;">*<br>Kelulusan Jawatankuasa</td>
<td class="text-left" style="padding:2mm;">**<br>Kategori Pelanggan</td>
<td class="text-left" style="padding:2mm;">Tujuan Pembelian</td>
<td class="text-left" style="padding:2mm;">***<br>Kategori Permohonan</td>
<td class="text-left" style="padding:2mm;">Jenis Peruntukan</td>
<td class="text-left" style="padding:2mm;">Program Baru & Tahap Pengajian</td>
<td class="text-left" style="padding:2mm;">Tahun Disediakan</td>
<td class="text-left" style="padding:2mm;">Nama Pegawai & Jawatan</td>
<td class="text-left" style="padding:2mm;">Lokasi cadangan</td>
</tr>
</thead>
<tbody>
<?php $nombor = $nombor; foreach ($view as $row){
echo "<tr>";
echo "<td>".$nombor++."</td>";
echo "<td class='text-left'>".$row['alat_nama']."</td>";
echo "<td>".$row['alat_kodAkaun']."</td>";
echo "<td>".$row['alat_kuantiti']."</td>";
echo "<td>".$row['alat_hargaUnit']."</td>";
echo "<td>".$row['alat_jumlahHarga']."</td>";
echo "<td>".$row['jk_id']."</td>";
echo "<td>".$row['katPelanggan_id']."</td>";
echo "<td class='text-left'>".$row['alat_tujuan']."</td>";
echo "<td>".$row['katPermohonan_id']."</td>";
echo "<td>".$row['jen_nama']."</td>";
echo "<td>".$row['alat_programBaru']."<br><br>".$row['alat_tahap']."</td>";
echo "<td>".$row['tahun_tahun']."</td>";
echo "<td>".$row['alat_pegawai']."<br><br>".$row['alat_jawatan']."</td>";
echo "<td class='text-left'>".$row['alat_lokasi']."</td>";
echo "</tr>";
}
?>
</tbody>
</table>
</div>
</P>
<p>
<font face="arial">
<br><b>N O T A</b><br>
<table class="table table-bordered" style="font-size: 12px; width:50%">
<tr>
<td><b>*</b><br>
1 - JAPD <br>
2 - JPPK / JTICT <br><br></td>
<td><b>**</b><br>
1 - Staf Akademik <br>
2 - Staf Pentadbiran <br>
3 - Pelajar<br><br></td>
<td><b>***</b><br>
1 - Tambahan kepada yang sedia ada <br>
2 - Gantian bagi yang dilupuskan <br>
3 - Permohonan baru<br><br></td>
</tr>
</table>
</font>
</p>
</div>
</div>
</div>
</div>
<?php
$js = <<< 'SCRIPT'
/* To initialize BS3 tooltips set this below */
$(function () {
$("[data-toggle='tooltip']").tooltip();
});;
/* To initialize BS3 popovers set this below */
$(function () {
$("[data-toggle='popover']").popover();
});
SCRIPT;
// Register tooltip/popover initialization javascript
$this->registerJs($js);
?>
| 43.066879
| 188
| 0.398063
|
42129b3dca0f9355a276da4b7891d509df896cbf
| 1,432
|
cs
|
C#
|
NeuralNetLearning/Maths/Activations/ReluActivation.cs
|
nikolaimerritt/NeuralNet
|
e145f0cfb7e4a88408afc2a4f463f10225986859
|
[
"MIT"
] | null | null | null |
NeuralNetLearning/Maths/Activations/ReluActivation.cs
|
nikolaimerritt/NeuralNet
|
e145f0cfb7e4a88408afc2a4f463f10225986859
|
[
"MIT"
] | null | null | null |
NeuralNetLearning/Maths/Activations/ReluActivation.cs
|
nikolaimerritt/NeuralNet
|
e145f0cfb7e4a88408afc2a4f463f10225986859
|
[
"MIT"
] | null | null | null |
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Double;
using NeuralNetLearning.Serialization;
namespace NeuralNetLearning.Maths.Activations
{
public class ReluActivation : Activation
{
[SerializableHyperParameter("leak")]
private readonly double _leak = 0;
public ReluActivation(double leak)
{
_leak = leak;
}
public ReluActivation()
{ }
public override Vector<double> Apply(Vector<double> input)
{
double[] activation = new double[input.Count];
for (int i = 0; i < activation.Length; i++)
activation[i] = input[i] > 0 ? input[i] : _leak * input[i];
return new DenseVector(activation);
}
public override Matrix<double> ApplyDerivative(Vector<double> input)
{
double[] deriv = new double[input.Count];
for (int i = 0; i < deriv.Length; i++)
if (input[i] > 0)
deriv[i] = 1;
else if (input[i] == 0)
deriv[i] = (1 + _leak) / 2;
else
deriv[i] = _leak;
return new DiagonalMatrix(deriv.Length, deriv.Length, deriv);
}
//public override void WriteToFile(string filepath)
// => HyperParamEncoder.EncodeToFile(this.GetType().Name, filepath, ("leak", _leak));
}
}
| 31.130435
| 96
| 0.554469
|
66fda841f74b9b15869bb95915fd7a614c3c67e7
| 1,254
|
swift
|
Swift
|
Buok/CommonViews/BuokmarkFlagView.swift
|
kimhyebeen/Buok-iOS
|
4a1c2cd70a544865463b6b1ad5fd468998d895cb
|
[
"Apache-2.0"
] | 6
|
2021-03-08T09:07:30.000Z
|
2021-06-19T10:23:02.000Z
|
Buok/CommonViews/BuokmarkFlagView.swift
|
kimhyebeen/Buok-iOS
|
4a1c2cd70a544865463b6b1ad5fd468998d895cb
|
[
"Apache-2.0"
] | 5
|
2021-04-14T03:06:01.000Z
|
2021-05-22T23:39:02.000Z
|
Buok/CommonViews/BuokmarkFlagView.swift
|
kimhyebeen/Buok-iOS
|
4a1c2cd70a544865463b6b1ad5fd468998d895cb
|
[
"Apache-2.0"
] | 1
|
2021-04-03T14:48:19.000Z
|
2021-04-03T14:48:19.000Z
|
//
// BuokmarkFlagView.swift
// Buok
//
// Copyright © 2021 Buok. All rights reserved.
//
import UIKit
class BuokmarkFlagView: UIView {
let flagLine = UIView()
let flagView = UIView()
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
private func setupView() {
setupFlagLine()
setupFlagView()
}
private func setupFlagLine() {
flagLine.backgroundColor = .white
self.addSubview(flagLine)
flagLine.snp.makeConstraints { make in
make.width.equalTo(2)
make.top.bottom.leading.equalToSuperview()
}
}
private func setupFlagView() {
flagView.layer.cornerRadius = 8
flagView.layer.maskedCorners = [.layerMaxXMinYCorner, .layerMaxXMaxYCorner]
flagView.layer.backgroundColor = UIColor.heroPrimaryPink.cgColor
self.addSubview(flagView)
flagView.snp.makeConstraints { make in
make.top.trailing.equalToSuperview()
make.leading.equalTo(flagLine.snp.trailing)
make.bottom.equalToSuperview().offset(-16)
}
}
}
| 24.115385
| 83
| 0.603668
|
bedea7e139a7104f17752631350407306546cb77
| 1,462
|
ts
|
TypeScript
|
src/pure-function-helpers/message-file-name.ts
|
zixia/wechaty-puppet-wechat4u
|
bcda65dab56d9b9c0e01303cd055b242dbe34610
|
[
"Apache-2.0"
] | 16
|
2018-07-26T09:11:17.000Z
|
2019-11-06T10:00:39.000Z
|
src/pure-function-helpers/message-file-name.ts
|
zixia/wechaty-puppet-wechat4u
|
bcda65dab56d9b9c0e01303cd055b242dbe34610
|
[
"Apache-2.0"
] | 21
|
2018-06-29T18:18:16.000Z
|
2019-08-15T04:28:30.000Z
|
src/pure-function-helpers/message-file-name.ts
|
zixia/wechaty-puppet-wechat4u
|
bcda65dab56d9b9c0e01303cd055b242dbe34610
|
[
"Apache-2.0"
] | 10
|
2018-07-26T09:11:36.000Z
|
2019-10-15T15:51:54.000Z
|
import {
WebAppMsgType,
WebMessageRawPayload,
WebMessageType,
} from '../web-schemas.js'
export function messageFileName (
rawPayload: WebMessageRawPayload,
): string {
let filename = rawPayload.FileName || rawPayload.MediaId || rawPayload.MsgId
const re = /\.[a-z0-9]{1,7}$/i
if (!re.test(filename)) {
if (rawPayload.MMAppMsgFileExt) {
filename += '.' + rawPayload.MMAppMsgFileExt
} else {
filename += messageExtname(rawPayload)
}
}
return filename
}
export function messageExtname (
rawPayload: WebMessageRawPayload,
): string {
let ext: string
// const type = this.type()
switch (rawPayload.MsgType) {
case WebMessageType.EMOTICON:
ext = '.gif'
break
case WebMessageType.IMAGE:
ext = '.jpg'
break
case WebMessageType.VIDEO:
case WebMessageType.MICROVIDEO:
ext = '.mp4'
break
case WebMessageType.VOICE:
ext = '.mp3'
break
case WebMessageType.APP:
switch (rawPayload.AppMsgType) {
case WebAppMsgType.URL:
ext = '.url' // XXX
break
default:
ext = '.' + rawPayload.MsgType
break
}
break
case WebMessageType.TEXT:
if (rawPayload.SubMsgType === WebMessageType.LOCATION) {
ext = '.jpg'
}
ext = '.' + rawPayload.MsgType
break
default:
ext = '.' + rawPayload.MsgType
}
return ext
}
| 19.756757
| 78
| 0.594391
|
1cd428144c914840ec00de4247028dcb08f548ea
| 700
|
lua
|
Lua
|
HIVE/SceneNodeEditor/nodes/CreateJetTransferTexture/jettrans.lua
|
digirea/HIVE
|
8896b0cc858c1ad0683888b925f71c0f0d71bf9d
|
[
"MIT"
] | null | null | null |
HIVE/SceneNodeEditor/nodes/CreateJetTransferTexture/jettrans.lua
|
digirea/HIVE
|
8896b0cc858c1ad0683888b925f71c0f0d71bf9d
|
[
"MIT"
] | null | null | null |
HIVE/SceneNodeEditor/nodes/CreateJetTransferTexture/jettrans.lua
|
digirea/HIVE
|
8896b0cc858c1ad0683888b925f71c0f0d71bf9d
|
[
"MIT"
] | null | null | null |
function CreateJetTransferTexture(property)
-- Create 1D transfer function texture
-- Jet color table from OSPray example
-- r, g, b, alpha
local tf =
{ 0 , 0 , 0.562493 , 1.0
, 0 , 0 , 1 , 1.0
, 0 , 1 , 1 , 1.0
, 0.500008 , 1 , 0.500008 , 1.0
, 1 , 1 , 0 , 1.0
, 1 , 0 , 0 , 1.0
, 0.500008 , 0 , 0 , 1.0 }
local width = #tf / 4
local tfTex = GenTexture()
tfTex:Create2D(tf, 3, width, 1); -- 3 = RGBA32F
return {
Image = function ()
return tfTex:ImageData()
end
}
end
| 28
| 52
| 0.404286
|
3d599741602a0c5bd40dd5c275c046a3a77695ae
| 779
|
dart
|
Dart
|
LibTest/io/InternetAddress/type_A01_t02.dart
|
tvolkert/co19
|
435727789062a45da3d20da09024651fdeb8cafe
|
[
"BSD-3-Clause"
] | null | null | null |
LibTest/io/InternetAddress/type_A01_t02.dart
|
tvolkert/co19
|
435727789062a45da3d20da09024651fdeb8cafe
|
[
"BSD-3-Clause"
] | null | null | null |
LibTest/io/InternetAddress/type_A01_t02.dart
|
tvolkert/co19
|
435727789062a45da3d20da09024651fdeb8cafe
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
* for details. All rights reserved. Use of this source code is governed by a
* BSD-style license that can be found in the LICENSE file.
*/
/**
* @assertion InternetAddressType type
* The type of the [InternetAddress] specified what IP protocol.
* @description Checks that type is set to [IPv6] for IPv6 addresses
* @author iarkh@unipro.ru
*/
import "../../../Utils/expect.dart";
import "dart:io";
check(String addr) {
InternetAddress address = new InternetAddress(addr);
Expect.equals(InternetAddressType.IPv6, address.type);
}
main() {
check("19:abc:14:128:22:11:a13d:0");
check("::");
check("::1");
check("::11:124:a");
check("11:124:a::");
check("11:124:a::d:113");
}
| 26.862069
| 77
| 0.679076
|
6d59a37ad8891f769bfd1acff9b5878f64445774
| 753
|
ts
|
TypeScript
|
src/app.module.ts
|
2021-summer-hackerthon/server
|
5e3cf6ad866497c323fb85a175d29aebc96f9e42
|
[
"MIT"
] | null | null | null |
src/app.module.ts
|
2021-summer-hackerthon/server
|
5e3cf6ad866497c323fb85a175d29aebc96f9e42
|
[
"MIT"
] | null | null | null |
src/app.module.ts
|
2021-summer-hackerthon/server
|
5e3cf6ad866497c323fb85a175d29aebc96f9e42
|
[
"MIT"
] | null | null | null |
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ormConfig } from './config/ormConfig';
import { UserModule } from './user/user.module';
import { TokenModule } from './token/token.module';
import { HotplaceModule } from './hotplace/hotplace.module';
import { UploadModule } from './upload/upload.module';
import { CommentModule } from './comment/comment.module';
@Module({
imports: [
TypeOrmModule.forRoot(ormConfig),
UserModule,
TokenModule,
HotplaceModule,
UploadModule,
CommentModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule { }
| 30.12
| 60
| 0.702523
|
5e207d035d55da4d91f878f902dd1d11fe2d6430
| 1,212
|
dart
|
Dart
|
public/day_03/solution.dart
|
dumazy/aoc21
|
a0240a381e9b047dfb82dd91a3427a84f1cb1f30
|
[
"MIT"
] | null | null | null |
public/day_03/solution.dart
|
dumazy/aoc21
|
a0240a381e9b047dfb82dd91a3427a84f1cb1f30
|
[
"MIT"
] | null | null | null |
public/day_03/solution.dart
|
dumazy/aoc21
|
a0240a381e9b047dfb82dd91a3427a84f1cb1f30
|
[
"MIT"
] | null | null | null |
// find the input at adventofcode.com
import 'dart:math';
import 'values.dart';
void main() {
_calculate(values);
}
void _calculate(List<String> values) {
final matrix = values.map(asDigits).toList();
final gammaArray = List.generate(matrix.width, (index) {
final column = matrix.getColumn(index);
return column.sum > matrix.height / 2 ? 1 : 0;
});
final epsilonArray = gammaArray.map((i) => i == 0 ? 1 : 0).toList();
final gamma = gammaArray.asInt;
final epsilon = epsilonArray.asInt;
print('Result: ${gamma * epsilon}');
}
typedef Matrix = List<List<int>>;
extension MatrixExtensions on Matrix {
List<int> getColumn(int index) => map((row) => row[index]).toList();
int get width => map((row) => row.length).reduce(max);
int get height => length;
}
extension BitArrayExtensions on List<int> {
int get asInt => int.parse(this.map((i) => i.toString()).join(), radix: 2);
int get sum => reduce((a, b) => a + b);
}
List<int> asDigits(String number) {
return number.split('').map((b) => int.parse(b)).toList();
}
final testValues = [
'00100',
'11110',
'10110',
'10111',
'10101',
'01111',
'00111',
'11100',
'10000',
'11001',
'00010',
'01010',
];
| 21.642857
| 77
| 0.628713
|
5331c638c4d6b4f6af5a8c6a2d2e119b720a851b
| 6,534
|
ps1
|
PowerShell
|
functions/New-PSPropertySet.ps1
|
jdhitsolutions/PSTypeExtensionTools
|
a558a2363dc4ac5179d86502c24f2ac6b0cd31fa
|
[
"MIT"
] | 35
|
2017-11-12T15:14:45.000Z
|
2022-02-05T02:05:46.000Z
|
functions/New-PSPropertySet.ps1
|
jdhitsolutions/PSTypeExtensionTools
|
a558a2363dc4ac5179d86502c24f2ac6b0cd31fa
|
[
"MIT"
] | 21
|
2017-10-31T18:53:30.000Z
|
2021-08-10T22:50:57.000Z
|
functions/New-PSPropertySet.ps1
|
jdhitsolutions/PSTypeExtensionTools
|
a558a2363dc4ac5179d86502c24f2ac6b0cd31fa
|
[
"MIT"
] | 11
|
2017-11-11T16:10:12.000Z
|
2021-08-12T07:21:40.000Z
|
Function New-PSPropertySet {
[cmdletbinding(SupportsShouldProcess, DefaultParameterSetName = "new")]
Param(
[Parameter(Position = 0, Mandatory, HelpMessage = "Enter the object typename.")]
[ValidateNotNullOrEmpty()]
[string]$Typename,
[Parameter(Mandatory, HelpMessage = "Enter the new property set name. It should be alphanumeric.")]
[ValidatePattern("^\w+$")]
[string]$Name,
[Parameter(Mandatory, HelpMessage = "Enter the existing property names or aliases to belong to this property set.")]
[ValidateNotNullOrEmpty()]
[string[]]$Properties,
[Parameter(Mandatory, HelpMessage = "Enter the name of the .ps1xml file to create.")]
[ValidatePattern("\.ps1xml$")]
[string]$FilePath,
[Parameter(HelpMessage = "Append to an existing file.", ParameterSetName = "append")]
[switch]$Append,
[Parameter(HelpMessage = "Don't overwrite an existing file.", ParameterSetName = "new")]
[switch]$NoClobber
)
Begin {
Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] Starting $($myinvocation.mycommand)"
Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] Set typename $typename to proper case"
$TypeName = _convertTypeName $TypeName
$settings = [System.Xml.XmlWriterSettings]::new()
$settings.Indent = $True
$newComment = @"
This file was created with New-PSPropertySet from the
PSTypeExtensionTools module which you can install from
the PowerShell Gallery.
Use Update-TypeData to append this file in your PowerShell session.
Created $(Get-Date)
"@
} #begin
Process {
Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Creating a property set called $Name for $Typename"
#convert file path to a true file system path.
$cPath = Join-Path -Path (Convert-Path (Split-Path $filepath)) -ChildPath (Split-Path $FilePath -Leaf)
if ($Append -AND (-Not (Test-Path $FilePath))) {
Write-Warning "Failed to find $Filepath for appending."
Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Ending $($myinvocation.mycommand)"
#bail out
return
}
elseif ($Append) {
Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Appending to $filepath"
[xml]$doc = Get-Content $cPath
$members = $doc.types.SelectNodes("Type[Name='$typeName']").Members
if ($members) {
Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Appending to existing typename entry"
}
else {
Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Creating a new typename entry"
$newType = $doc.CreateNode("element", "Type", $null)
$tName = $doc.CreateElement("Name")
$tName.InnerText = $typename
[void]($newType.AppendChild($tname))
$members = $doc.CreateNode("element", "Members", $null)
$IsNewType = $True
}
$propSet = $doc.CreateNode("element", "PropertySet", $null)
$eName = $doc.CreateElement("Name")
$eName.InnerText = $Name
[void]($propset.AppendChild($eName))
$ref = $doc.CreateNode("element", "ReferencedProperties", $null)
foreach ($item in $properties) {
$prop = $doc.CreateElement("Name")
Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Adding property $item"
$prop.InnerText = $item
[void]($ref.AppendChild($prop))
}
[void]($propset.AppendChild($ref))
[void]($members.AppendChild($propset))
if ($IsnewType) {
Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Appending new type"
[void]($newType.AppendChild($members))
[void]($doc.types.AppendChild($newtype))
}
} #else append
else {
Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Creating a new XML document"
<#
use a random temp name to create the xml file. At the end of the process copy the temp file
to the specified file path. This makes it possible to use -WhatIf
#>
$tmpFile = [System.IO.Path]::GetTempFileName()
$doc = [System.Xml.XmlWriter]::Create($tmpFile, $settings)
$doc.WriteStartDocument()
$doc.WriteWhitespace("`n")
$doc.WriteComment($newComment)
$doc.WriteWhitespace("`n")
$doc.WriteStartElement("Types")
$doc.WriteStartElement("Type")
Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Defining type as $Typename"
$doc.WriteElementString("Name", $TypeName)
$doc.WriteStartElement("Members")
$doc.WriteStartElement("PropertySet")
#the property set name
Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Defining property set name $Name"
$doc.WriteElementString("Name", $Name)
$doc.WriteStartElement("ReferencedProperties")
foreach ($item in $properties) {
Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Adding property $item"
$doc.WriteElementString("Name", $item)
}
#end type
Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Closing and saving file."
$doc.WriteEndElement()
$doc.WriteEndDocument()
$doc.Close()
$doc.Dispose()
}
if ($PSCmdlet.ShouldProcess($cpath)) {
if ((-Not $Append) -AND (Test-Path $tmpFile)) {
Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Copying temp file to $cpath"
if ($NoClobber -AND (Test-Path $cpath)) {
Write-Warning "The file $cpath exists and NoClobber was specified."
}
else {
Copy-Item -Path $tmpFile -Destination $cpath
}
#always clean up the temp file
Remove-Item -Path $tmpFile -WhatIf:$false -ErrorAction SilentlyContinue
}
else {
Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Saving to $cpath"
$doc.Save($cpath)
}
}
} #process
End {
Write-Verbose "[$((Get-Date).TimeofDay) END ] Ending $($myinvocation.mycommand)"
} #end
} #close New-PSPropertySet
| 42.154839
| 124
| 0.572084
|
76ba63bc9bc0594aea859aaea1f0ad6c324435c8
| 470
|
h
|
C
|
src/num/md_wrapper.h
|
Zhitao-Li/bart
|
e2e3cc68cbe6e4d1ce8f0be455b599ec48c0a03a
|
[
"BSD-3-Clause"
] | 189
|
2015-10-28T15:36:23.000Z
|
2022-03-27T10:30:17.000Z
|
src/num/md_wrapper.h
|
Zhitao-Li/bart
|
e2e3cc68cbe6e4d1ce8f0be455b599ec48c0a03a
|
[
"BSD-3-Clause"
] | 158
|
2015-11-17T18:55:08.000Z
|
2022-02-15T15:36:44.000Z
|
src/num/md_wrapper.h
|
Zhitao-Li/bart
|
e2e3cc68cbe6e4d1ce8f0be455b599ec48c0a03a
|
[
"BSD-3-Clause"
] | 153
|
2015-10-25T02:30:45.000Z
|
2022-03-28T07:03:34.000Z
|
void zfmac_gpu_batched_loop(unsigned int N, const long dims[__VLA(N)], const long ostr[__VLA(N)], _Complex float* optr, const long istr1[__VLA(N)], const _Complex float* iptr1, const long istr2[__VLA(N)], const _Complex float* iptr2);
void zfmacc_gpu_batched_loop(unsigned int N, const long dims[__VLA(N)], const long ostr[__VLA(N)], _Complex float* optr, const long istr1[__VLA(N)], const _Complex float* iptr1, const long istr2[__VLA(N)], const _Complex float* iptr2);
| 235
| 235
| 0.76383
|
b886a1d13423a66b65792f9873f4aad3fb9092fa
| 8,837
|
h
|
C
|
tf2_src/utils/tfstats/regexp/include/jm/fileiter.h
|
d3fc0n6/TeamFortress2
|
1b81dded673d49adebf4d0958e52236ecc28a956
|
[
"MIT"
] | 4
|
2021-10-03T05:16:55.000Z
|
2021-12-28T16:49:27.000Z
|
tf2_src/utils/tfstats/regexp/include/jm/fileiter.h
|
Counter2828/TeamFortress2
|
1b81dded673d49adebf4d0958e52236ecc28a956
|
[
"MIT"
] | null | null | null |
tf2_src/utils/tfstats/regexp/include/jm/fileiter.h
|
Counter2828/TeamFortress2
|
1b81dded673d49adebf4d0958e52236ecc28a956
|
[
"MIT"
] | 3
|
2022-02-02T18:09:58.000Z
|
2022-03-06T18:54:39.000Z
|
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
/*
*
* Copyright (c) 1998-9
* Dr John Maddock
*
* Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and
* that both that copyright notice and this permission notice appear
* in supporting documentation. Dr John Maddock makes no representations
* about the suitability of this software for any purpose.
* It is provided "as is" without express or implied warranty.
*
*/
/*
*
* FILE fileiter.h
* VERSION 2.12
*
* this file declares various platform independent file and directory
* iterators, plus binary file input in the form of class map_file.
*
*/
#ifndef __FILEITER_H
#define __FILEITER_H
#include <jm/jm_cfg.h>
#if (defined(__WIN32__) || defined(_WIN32) || defined(WIN32)) && !defined(JM_NO_WIN32)
#define FI_W32
#include <windows.h>
JM_NAMESPACE(__JM)
typedef WIN32_FIND_DATA _fi_find_data;
typedef HANDLE _fi_find_handle;
JM_END_NAMESPACE
#define _fi_invalid_handle INVALID_HANDLE_VALUE
#define _fi_dir FILE_ATTRIBUTE_DIRECTORY
#else
#include <stdio.h>
#include <ctype.h>
#ifndef JM_NO_STL
#include <iterator>
#include <list>
#if defined(__SUNPRO_CC) && !defined(JM_NO_NAMESPACES)
using __JM_STD::list;
#endif
#endif
#include <assert.h>
#include <dirent.h>
#ifndef MAX_PATH
#define MAX_PATH 256
#endif
JM_NAMESPACE(__JM)
struct _fi_find_data
{
unsigned dwFileAttributes;
char cFileName[MAX_PATH];
};
struct _fi_priv_data;
typedef _fi_priv_data* _fi_find_handle;
#define _fi_invalid_handle NULL
#define _fi_dir 1
_fi_find_handle _fi_FindFirstFile(const char* lpFileName, _fi_find_data* lpFindFileData);
bool _fi_FindNextFile(_fi_find_handle hFindFile, _fi_find_data* lpFindFileData);
bool _fi_FindClose(_fi_find_handle hFindFile);
JM_END_NAMESPACE
#ifdef FindFirstFile
#undef FindFirstFile
#endif
#ifdef FindNextFile
#undef FindNextFile
#endif
#ifdef FindClose
#undef FindClose
#endif
#define FindFirstFile _fi_FindFirstFile
#define FindNextFile _fi_FindNextFile
#define FindClose _fi_FindClose
#endif
JM_NAMESPACE(__JM)
#ifdef FI_W32 // win32 mapfile
class JM_IX_DECL mapfile
{
HANDLE hfile;
HANDLE hmap;
const char* _first;
const char* _last;
public:
typedef const char* iterator;
mapfile(){ hfile = hmap = 0; _first = _last = 0; }
mapfile(const char* file){ hfile = hmap = 0; _first = _last = 0; open(file); }
~mapfile(){ close(); }
void open(const char* file);
void close();
const char* begin(){ return _first; }
const char* end(){ return _last; }
size_t size(){ return _last - _first; }
bool valid(){ return (hfile != 0) && (hfile != INVALID_HANDLE_VALUE); }
};
#elif !defined(JM_NO_STL) // use POSIX API to emulate the memory map:
class JM_IX_DECL mapfile_iterator;
class JM_IX_DECL mapfile
{
typedef char* pointer;
FILE* hfile;
long int _size;
pointer* _first;
pointer* _last;
mutable __JM_STD::list<pointer*> condemed;
enum sizes
{
buf_size = 4096
};
void lock(pointer* node)const;
void unlock(pointer* node)const;
public:
typedef mapfile_iterator iterator;
mapfile(){ hfile = 0; _size = 0; _first = _last = 0; }
mapfile(const char* file){ hfile = 0; _size = 0; _first = _last = 0; open(file); }
~mapfile(){ close(); }
void open(const char* file);
void close();
iterator begin()const;
iterator end()const;
unsigned long size()const{ return _size; }
bool valid()const{ return hfile != 0; }
friend class mapfile_iterator;
};
class JM_IX_DECL mapfile_iterator : public JM_RA_ITERATOR(char, long)
{
typedef mapfile::pointer pointer;
pointer* node;
const mapfile* file;
unsigned long offset;
long position()const
{
return file ? ((node - file->_first) * mapfile::buf_size + offset) : 0;
}
void position(long pos)
{
if(file)
{
node = file->_first + (pos / mapfile::buf_size);
offset = pos % mapfile::buf_size;
}
}
public:
mapfile_iterator() { node = 0; file = 0; offset = 0; }
mapfile_iterator(const mapfile* f, long position)
{
file = f;
node = f->_first + position / mapfile::buf_size;
offset = position % mapfile::buf_size;
if(file)
file->lock(node);
}
mapfile_iterator(const mapfile_iterator& i)
{
file = i.file;
node = i.node;
offset = i.offset;
if(file)
file->lock(node);
}
~mapfile_iterator()
{
if(file && node)
file->unlock(node);
}
mapfile_iterator& operator = (const mapfile_iterator& i);
char operator* ()const
{
assert(node >= file->_first);
assert(node < file->_last);
return file ? *(*node + sizeof(int) + offset) : char(0);
}
mapfile_iterator& operator++ ();
mapfile_iterator operator++ (int);
mapfile_iterator& operator-- ();
mapfile_iterator operator-- (int);
mapfile_iterator& operator += (long off)
{
position(position() + off);
return *this;
}
mapfile_iterator& operator -= (long off)
{
position(position() - off);
return *this;
}
friend inline bool operator==(const mapfile_iterator& i, const mapfile_iterator& j)
{
return (i.file == j.file) && (i.node == j.node) && (i.offset == j.offset);
}
#ifndef JM_NO_NOT_EQUAL
friend inline bool operator!=(const mapfile_iterator& i, const mapfile_iterator& j)
{
return !(i == j);
}
#endif
friend inline bool operator<(const mapfile_iterator& i, const mapfile_iterator& j)
{
return i.position() < j.position();
}
friend mapfile_iterator operator + (const mapfile_iterator& i, long off);
friend mapfile_iterator operator - (const mapfile_iterator& i, long off);
friend inline long operator - (const mapfile_iterator& i, const mapfile_iterator& j)
{
return i.position() - j.position();
}
};
#endif
// _fi_sep determines the directory separator, either '\\' or '/'
JM_IX_DECL extern const char* _fi_sep;
struct file_iterator_ref
{
_fi_find_handle hf;
_fi_find_data _data;
long count;
};
class JM_IX_DECL file_iterator : public JM_INPUT_ITERATOR(const char*, __JM_STDC::ptrdiff_t)
{
char* _root;
char* _path;
char* ptr;
file_iterator_ref* ref;
public:
file_iterator();
file_iterator(const char* wild);
~file_iterator();
file_iterator(const file_iterator&);
file_iterator& operator=(const file_iterator&);
const char* root() { return _root; }
const char* path() { return _path; }
_fi_find_data* data() { return &(ref->_data); }
void next();
file_iterator& operator++() { next(); return *this; }
file_iterator operator++(int);
const char* operator*() { return path(); }
friend inline bool operator == (const file_iterator& f1, const file_iterator& f2)
{
return ((f1.ref->hf == _fi_invalid_handle) && (f1.ref->hf == _fi_invalid_handle));
}
#ifndef JM_NO_NOT_EQUAL
friend inline bool operator != (const file_iterator& f1, const file_iterator& f2)
{
return !(f1 == f2);
}
#endif
};
inline bool operator < (const file_iterator& f1, const file_iterator& f2)
{
return false;
}
class JM_IX_DECL directory_iterator : public JM_INPUT_ITERATOR(const char*, __JM_STDC::ptrdiff_t)
{
char* _root;
char* _path;
char* ptr;
file_iterator_ref* ref;
public:
directory_iterator();
directory_iterator(const char* wild);
~directory_iterator();
directory_iterator(const directory_iterator& other);
directory_iterator& operator=(const directory_iterator& other);
const char* root() { return _root; }
const char* path() { return _path; }
_fi_find_data* data() { return &(ref->_data); }
void next();
directory_iterator& operator++() { next(); return *this; }
directory_iterator operator++(int);
const char* operator*() { return path(); }
static const char* separator() { return _fi_sep; }
friend inline bool operator == (const directory_iterator& f1, const directory_iterator& f2)
{
return ((f1.ref->hf == _fi_invalid_handle) && (f1.ref->hf == _fi_invalid_handle));
}
#ifndef JM_NO_NOT_EQUAL
friend inline bool operator != (const directory_iterator& f1, const directory_iterator& f2)
{
return !(f1 == f2);
}
#endif
};
inline bool operator < (const directory_iterator& f1, const directory_iterator& f2)
{
return false;
}
JM_END_NAMESPACE
#if !defined(JM_NO_NAMESPACES) && !defined(JM_NO_USING)
using __JM::directory_iterator;
using __JM::file_iterator;
using __JM::mapfile;
#endif
#endif // __WINITER_H
| 23.948509
| 97
| 0.672174
|
0349ee081974f0aa75e958748a6b7d13c9286364
| 5,978
|
ps1
|
PowerShell
|
deprecated/Disable-InactiveUserProfile.ps1
|
johnsarie27/AWSReporting
|
9d102b4c2453d4d68066575521c2a149bbf50cb4
|
[
"Apache-2.0"
] | 5
|
2019-10-31T06:25:45.000Z
|
2022-01-21T20:09:44.000Z
|
deprecated/Disable-InactiveUserProfile.ps1
|
johnsarie27/AWSReporting
|
9d102b4c2453d4d68066575521c2a149bbf50cb4
|
[
"Apache-2.0"
] | 5
|
2019-02-15T22:54:39.000Z
|
2019-03-21T22:21:39.000Z
|
deprecated/Disable-InactiveUserProfile.ps1
|
johnsarie27/AWSReporting
|
9d102b4c2453d4d68066575521c2a149bbf50cb4
|
[
"Apache-2.0"
] | 1
|
2021-07-02T23:27:57.000Z
|
2021-07-02T23:27:57.000Z
|
function Disable-InactiveUserProfile {
<# =========================================================================
.SYNOPSIS
Disable unused IAM User Profile
.DESCRIPTION
Disable any IAM User Profiles that has not been used in 90 or more days
.PARAMETER ProfileName
AWS Credential Profile name
.PARAMETER Credential
AWS Credential Object
.PARAMETER Age
Age (in days) past which the keys should be disabled
.PARAMETER All
All users within the AWS account
.PARAMETER User
AWS User object
.PARAMETER ReportOnly
Report non-compliant users only
.INPUTS
Amazon.IdentityManagement.Model.User[].
.OUTPUTS
System.Object.
.EXAMPLE
PS C:\> Disable-InactiveUserProfile -ProfileName MyAWSAccount
Deactivate all profiles if not used in 90 days for MyAWSAccount
.NOTES
The identity running this function requires the following permissions:
- iam:ListUsers
- iam:GetLoginProfile
- iam:DeleteLoginProfile
========================================================================= #>
[CmdletBinding(DefaultParameterSetName = 'all')]
Param(
[Parameter(HelpMessage='AWS credential profile name')]
[ValidateScript({ (Get-AWSCredential -ListProfileDetail).ProfileName -contains $_ })]
[string] $ProfileName,
[Parameter(HelpMessage = 'AWS Credential Object')]
[ValidateNotNullOrEmpty()]
[Amazon.Runtime.AWSCredentials] $Credential,
[Parameter(HelpMessage = 'Age to disable accounts')]
[ValidateRange(30, 365)]
[int] $Age = 90,
[Parameter(HelpMessage = 'All users in account', ParameterSetName = 'all')]
[switch] $All,
[Parameter(Mandatory, ValueFromPipeline, HelpMessage = 'User name', ParameterSetName = 'user')]
[ValidateNotNullOrEmpty()]
[Amazon.IdentityManagement.Model.User[]] $User,
[Parameter(HelpMessage = 'Report non-compliant users only')]
[switch] $ReportOnly
)
Begin {
# CREATE RESULTS ARRAY
$results = [System.Collections.Generic.List[System.Object]]::new()
# SET CREDENTIALS
if ( $PSBoundParameters.ContainsKey('ProfileName') ) { $awsParams = @{ ProfileName = $ProfileName } }
if ( $PSBoundParameters.ContainsKey('Credential') ) { $awsParams = @{ Credential = $Credential } }
# GET ALL USERS IN AWS ACCOUNT
if ( $PSCmdlet.ParameterSetName -eq 'all' ) { $User = Get-IAMUserList @awsParams }
# SET VARS
$date = Get-Date
$badDate = Get-Date -Date "0001-01-01 00:00"
}
Process {
foreach ( $u in $User ) {
# SET COMMON VARS
$awsParams['UserName'] = $u.UserName
# THE CMDLET Get-IAMLoginProfile HAS ISSUES AND DOES NOT RESPECT STANDARDS
# LIKE ERRORACTION. THEREFORE, THE COMMANDS BELOW THAT UTILIZE Get-IAMloginProfile
# WILL OUTPUT ERROR MESSAGES WHEN UNABLE TO LOCATE A LOGIN PROFILE
try {
$hasLoginProfile = Get-IAMLoginProfile @awsParams -ErrorAction Stop
Write-Verbose ('Found login profile for user: [{0}]' -f $u.UserName)
}
catch {
$hasLoginProfile = $null
Write-Verbose ('No login profile found for user: [{0}]' -f $u.UserName)
}
# IF USER HAS A VALID LOGIN PROFILE
if ( $hasLoginProfile ) {
# VALIDATE LAST LOGIN DATE
if ( $u.PasswordLastUsed -eq $badDate ) {
$timeSinceLastLogin = New-TimeSpan -Start $u.CreateDate -End $date
}
else {
$timeSinceLastLogin = New-TimeSpan -Start $u.PasswordLastUsed -End $date
}
# IF DAYS SINCE LAST LOGIN GREATER OR EQUAL TO AGE
if ( $timeSinceLastLogin.Days -ge $Age ) {
# CREATE CUSTOM OBJECT
$new = @{
Arn = $u.Arn
CreateDate = $u.CreateDate
PasswordLastUsed = $u.PasswordLastUsed
DaysSinceLastUsed = $timeSinceLastLogin.Days
UserName = $u.UserName
UserId = $u.UserId
}
# CHECK FOR REPORT ONLY
if ( $PSBoundParameters.ContainsKey('ReportOnly') ) {
# REPORT USER
Write-Verbose ('No login for user [{0}] in {1} or more days' -f $awsParams['UserName'], $Age)
$new['Action'] = 'Report user'
}
else {
# DISABLE USER
try {
Remove-IAMLoginProfile @awsParams -Force
Write-Verbose ('DISABLED USER [{0}] in account [{1}]' -f $awsParams['UserName'], $ProfileName)
$new['Action'] = 'User profile disabled'
}
catch {
Write-Warning ('User [{0}] was not disabled. Error message: {1}' -f $awsParams['UserName'], $u.Exception.Message)
$new['Action'] = 'Error: {0}' -f $u.Exception.Message
}
}
# ADD TO THE LIST
$results.Add([PSCustomObject] $new)
}
}
}
}
End {
# WRITE VERBOSE OUTPUT
if ( $PSBoundParameters.ContainsKey('ReportOnly') ) {
Write-Verbose ('{0} user profile(s) reported. None disabled.' -f $results.Count)
}
else {
Write-Verbose ('{0} user profile(s) disabled.' -f $results.Count)
}
# RETURN REVOKED KEYS
$results
}
}
| 39.853333
| 141
| 0.521412
|
20043ee28180e90bb1886c98f4db6a56a3e43d01
| 60
|
py
|
Python
|
mlflow/version.py
|
jkthompson/mlflow
|
7fde53e497c50b4eb4da1e9988710695b8c2e093
|
[
"Apache-2.0"
] | null | null | null |
mlflow/version.py
|
jkthompson/mlflow
|
7fde53e497c50b4eb4da1e9988710695b8c2e093
|
[
"Apache-2.0"
] | null | null | null |
mlflow/version.py
|
jkthompson/mlflow
|
7fde53e497c50b4eb4da1e9988710695b8c2e093
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2018 Databricks, Inc.
VERSION = "1.12.1.dev0"
| 12
| 33
| 0.683333
|
753e3db58006945bffa61f7bcc775b5e4ccbbfe7
| 7,093
|
ps1
|
PowerShell
|
Tests/pyc/test_pyc.ps1
|
btddg28/ironpython
|
8006238c19d08db5db9bada39d765143e631059e
|
[
"Apache-2.0"
] | 1,872
|
2015-01-02T18:56:47.000Z
|
2022-03-31T07:34:39.000Z
|
Tests/pyc/test_pyc.ps1
|
btddg28/ironpython
|
8006238c19d08db5db9bada39d765143e631059e
|
[
"Apache-2.0"
] | 675
|
2015-02-27T09:01:01.000Z
|
2022-03-31T14:03:25.000Z
|
Tests/pyc/test_pyc.ps1
|
btddg28/ironpython
|
8006238c19d08db5db9bada39d765143e631059e
|
[
"Apache-2.0"
] | 278
|
2015-01-02T03:48:20.000Z
|
2022-03-29T20:40:44.000Z
|
#####################################################################################
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# This source code is subject to terms and conditions of the Apache License, Version 2.0. A
# copy of the license can be found in the License.html file at the root of this distribution. If
# you cannot locate the Apache License, Version 2.0, please send an email to
# ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
# by the terms of the Apache License, Version 2.0.
#
# You must not remove this notice, or any other, from this software.
#
#
#####################################################################################
#USAGE: powershell %CD%\test_pyc.ps1 ..\..\Public\Tools\Scripts
#------------------------------------------------------------------------------
#--Sanity
if ($env:DLR_BIN -eq $null) {
echo "Cannot run this test without DLR_BIN being set!"
exit 1
}
if (! (test-path $env:DLR_BIN\ipy.exe)) {
echo "Cannot run this test without ipy.exe being built!"
exit 1
}
if ([System.Environment]::Version.Major -eq 4) {
echo "http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=24497"
exit 0
}
#------------------------------------------------------------------------------
#--Prereqs and globals
set-alias IPY_CMD $env:DLR_BIN\ipy.exe
$CURRPATH = split-path -parent $MyInvocation.MyCommand.Definition
$TOOLSPATH = $args[0]
if (! (test-path "$TOOLSPATH\pyc.py")) {
echo "Cannot run this test without access to $TOOLSPATH\pyc.py!"
exit 1
}
$FINALEXIT = 0 #We'll use this value for the final exit code of this script
$SLEEP_TIME = 3
pushd $TOOLSPATH #We'll invoke Pyc from Tools\Scripts
function prepare-testcase {
#Kill off any stagnant test processes
foreach ($x in @("winforms_hw")) {
stop-process -name $x 2> $null
sleep $SLEEP_TIME
$proc_list = @(get-process | where-object { $_.ProcessName -match "^$x" })
if ($proc_list.Length -ne 0) {
echo "FAILED: $x is currently running - $proc_list"
$FINALEXIT = 1
}
}
#Remove existing crud
rm -force *.dll
rm -force *.exe
#Copy over prereqs for running pyc.py
cp -force $env:DLR_BIN\IronPython*dll .
cp -force $env:DLR_BIN\Microsoft.*dll .
}
function testcase-helper ($cmd, $expected_files, $exe, $expected_exe_exitcode, $expected_exe_stdout, $arguments) {
prepare-testcase
echo "------------------------------------------------------------------------------"
echo "TEST CASE: $cmd"
#--Run pyc.py
$cmd_array = $cmd.split(" ")
IPY_CMD pyc.py $cmd_array
if (! $?) {
echo "FAILED: IPY_CMD pyc.py $cmd"
$FINALEXIT = 1
return
}
#--Ensure pyc.py generated all expected files
foreach($x in $expected_files) {
if (! (test-path $PWD\$x)) {
echo "FAILED: $PWD\$x was not generated!"
$FINALEXIT = 1
return
}
}
#--Ensure the exe we will run has been generated
if (! (test-path $PWD\$exe)) {
echo "FAILED: $PWD\$exe was not generated!"
$FINALEXIT = 1
return
}
testcase-runner $cmd $exe $expected_exe_exitcode $expected_exe_stdout $arguments
}
function testcase-runner ($cmd, $exe, $expected_exe_exitcode, $expected_exe_stdout, $arguments) {
#--Run the generated exe
$command = Get-Command "$PWD\$exe"
echo $arguments
$exe_out = &$command $arguments
if ($LASTEXITCODE -ne $expected_exe_exitcode) {
echo "FAILED: actual exit code, $LASTEXITCODE, of $exe was not the expected value ($expected_exe_exitcode)"
$FINALEXIT = 1
return
}
#--Consoleless applications are a special case
if ($cmd.Contains("/target:winexe")) {
if ($exe_out -ne $null) {
echo "FAILED: there should be no console output instead of '$exe_out' for $exe."
$FINALEXIT = 1
return
}
#The real expected exe stdout is hidden in the MainWindowTitle
$temp_name = $exe.Split(".exe")[0]
sleep $SLEEP_TIME
$exe_out = (get-process | where-object { $_.ProcessName -match "^$temp_name" }).MainWindowTitle
stop-process -name $temp_name 2> $null
}
if ($exe_out -ne $expected_exe_stdout) {
echo "FAILED: '$exe_out' was not the expected output ($expected_exe_stdout) for $exe."
$FINALEXIT = 1
return
}
echo ""
echo "PASSED"
echo ""
}
#------------------------------------------------------------------------------
#--Test cases
#--Console HelloWorld
testcase-helper "/main:$CURRPATH\console_hw.py" @("console_hw.exe", "console_hw.dll") "console_hw.exe" 0 "(Compiled) Hello World"
#--Console HelloWorld with a single dependency
testcase-helper "$CURRPATH\other_hw.py /main:$CURRPATH\console_hw.py" @("console_hw.exe", "console_hw.dll") "console_hw.exe" 0 "(Compiled) Hello World"
#--Console HelloWorld w/ args
testcase-helper "/main:$CURRPATH\console_hw_args.py" @("console_hw_args.exe", "console_hw_args.dll") "console_hw_args.exe" 0 "(Compiled) Hello World ['foo']" "foo"
#--WinForms HelloWorld
testcase-helper "/main:$CURRPATH\winforms_hw.py /target:winexe" @("winforms_hw.exe", "winforms_hw.dll") "winforms_hw.exe" 0 "(Compiled WinForms) Hello World"
#--Console Package
testcase-helper "/main:$CURRPATH\pycpkgtest.py $CURRPATH\pkg\a.py $CURRPATH\pkg\b.py $CURRPATH\pkg\__init__.py " @("pycpkgtest.exe", "pycpkgtest.dll") "pycpkgtest.exe" 0 "<module 'pkg.b' from 'pkg\b'>"
#--CPython standard library is a very special case
function test-stdcpymodule {
echo "Generating a precompiled module for the entire CPython standard library..."
. $CURRPATH\stdmodules_ok.ps1
#Generate the DLL
pushd "$env:DLR_ROOT\External.LCA_RESTRICTED\Languages\CPython\27\lib"
IPY_CMD -X:Frames $TOOLSPATH\Pyc.py /out:cpystdlib /target:dll $STDMODULES
if (! $?) {
echo "Failed to run Pyc against the CPython standard library!"
$FINALEXIT = 1
}
if (test-path "$PWD\cpystdlib.dll") {
copy -force "$PWD\cpystdlib.dll" $TOOLSPATH\
rm -force "$PWD\cpystdlib.dll"
}
else {
echo "Failed to generate the '$PWD\cpystdlib.dll' precompiled module!"
$FINALEXIT = 1
}
popd
#Minimal verification
$TEMP_OUT = IPY_CMD -s -E -c "import os" 2>&1
if ($?) {
echo "Should not be able to import os w/o the standard library!"
echo $TEMP_OUT
$FINALEXIT = 1
}
$TEMP_OUT = IPY_CMD -s -E -c "import clr;clr.AddReference('cpystdlib.dll');import os;print os.__name__"
if (! $?) {
echo "Should be able to import os w/ precompiled standard library!"
echo $TEMP_OUT
$FINALEXIT = 1
}
if (! $TEMP_OUT.Contains("os")) {
echo "'print os.__name__' resulted in unexpected output!"
echo $TEMP_OUT
$FINALEXIT = 1
}
}
#http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=26593
#test-stdcpymodule
#------------------------------------------------------------------------------
#Cleanup and exit
rm -force *.dll
rm -force *.exe
popd
exit $FINALEXIT
| 33.616114
| 201
| 0.61032
|
da4b6000921cf6f104a9e64fa177a5387962ad8a
| 6,346
|
php
|
PHP
|
app/Blueprint/Generators/GraphQLSchemaGenerator.php
|
ibagayoko/ilara
|
9143ad71f8727b820b80af197b902b47a8bb4e1e
|
[
"MIT"
] | null | null | null |
app/Blueprint/Generators/GraphQLSchemaGenerator.php
|
ibagayoko/ilara
|
9143ad71f8727b820b80af197b902b47a8bb4e1e
|
[
"MIT"
] | 5
|
2021-03-10T03:05:14.000Z
|
2022-02-26T21:49:23.000Z
|
app/Blueprint/Generators/GraphQLSchemaGenerator.php
|
ibagayoko/ilara
|
9143ad71f8727b820b80af197b902b47a8bb4e1e
|
[
"MIT"
] | null | null | null |
<?php
namespace App\Blueprint\Generators;
use Blueprint\Contracts\Generator;
use Blueprint\Models\Column;
use Blueprint\Models\Model;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Str;
class GraphQLSchemaGenerator implements Generator
{
const INDENT = ' ';
protected $stubs_path ;
/** @var \Illuminate\Contracts\Filesystem\Filesystem */
private $files;
public function __construct($files)
{
$this->files = $files;
$this->stubs_path = dirname(__DIR__) . '../../Console/stubs/';
}
public function output(array $tree): array
{
$output = [];
$stub = $this->getStub('type');
/** @var \Blueprint\Models\Model $model */
foreach ($tree['models'] as $model) {
$path = $this->getPath($model, 'query');
$pathMut = $this->getPath($model, 'mutation');
$this->files->put(
$path,
$this->populateStub($stub, $model)
);
$this->files->put(
$pathMut,
$this->populateMutStub($this->getStub('mutation'), $model)
);
$output['created'][] = $path;
$output['created'][] = $pathMut;
}
return $output;
}
protected function populateStub(string $stub, Model $model)
{
// Type definition
$stub = str_replace('DummyType', $model->name(), $stub);
$body = $this->buildFields($model);
$stub = str_replace('// ...', trim($body), $stub);
// $mutationBody = $this->buildMutationFields($model);
// $stub = str_replace('DummyFields', trim($mutationBody), $stub);
// Query definition
$stub = str_replace('QuerySingle', Str::lower($model->name()), $stub);
$stub = str_replace('QueryMultiple', Str::lower(Str::plural($model->name())), $stub);
return $stub;
}
protected function populateMutStub(string $stub, Model $model)
{
// Type definition
$stub = str_replace('DummyType', $model->name(), $stub);
// $body = $this->buildFields($model);
// $stub = str_replace('// ...', trim($body), $stub);
$mutationBody = $this->buildMutationFields($model);
$stub = str_replace('DummyFields', trim($mutationBody), $stub);
// Query definition
// $stub = str_replace('QuerySingle', Str::lower($model->name()), $stub);
// $stub = str_replace('QueryMultiple', Str::lower(Str::plural($model->name())), $stub);
return $stub;
}
private function buildFields(Model $model)
{
$columns = $model->columns();
if (empty($columns)) {
return '';
}
$fields = '';
/** @var Column $column */
foreach ($columns as $column) {
$field = '';
$name = $column->name();
$dataType = Str::studly($column->dataType());
$dataType = $dataType=='Id'? 'ID' : $dataType;
$dataType = $dataType=='Integer'? 'Int' : $dataType;
$dataType = $dataType=='Text'? 'String' : $dataType;
$dataType = $dataType=='Decimal'? 'Float' : $dataType;
$belongTo ='';
if(Str::endsWith($column->name(), '_id')){
$name = Str::substr($column->name(), 0, -3);
$class = $dataType= Str::studly($column->attributes()[0] ?? $name);
$belongTo = ' @belongsTo';
}
$field = self::INDENT . $name . ': ' .$dataType;
if (!in_array('nullable' , $column->modifiers())) {
$field .= '!';
}
$field .= $belongTo;
$fields .= $field .PHP_EOL;
}
if($model->usesTimestamps()){
$fields .= self::INDENT . 'created_at: DateTime' . PHP_EOL;
$fields .= self::INDENT . 'updated_at: DateTime' . PHP_EOL;
}
return $fields;
}
private function buildMutationFields(Model $model)
{
$columns = $model->columns();
if (empty($columns)) {
return '';
}
$fields = '';
/** @var Column $column */
foreach ($columns as $column) {
$field = '';
$name = $column->name();
$dataType = Str::studly($column->dataType());
$dataType = $dataType=='Id'? 'ID' : $dataType;
$dataType = $dataType=='Integer'? 'Int' : $dataType;
$dataType = $dataType=='Text'? 'String' : $dataType;
$dataType = $dataType=='Decimal'? 'Float' : $dataType;
$belongTo ='';
if(Str::endsWith($column->name(), '_id')){
$name = Str::substr($column->name(), 0, -3);
$class = $dataType= Str::studly($column->attributes()[0] ?? $name);
$belongTo = ' @belongsTo';
}
$field = $name . ': ' .$dataType;
if (!in_array('nullable' , $column->modifiers())) {
$field .= '!';
}
// $field .= $belongTo;
$fields .= $field .', ' ;
}
if($model->usesTimestamps()){
// $fields .= self::INDENT . 'created_at: DateTime' . PHP_EOL;
// $fields .= self::INDENT . 'updated_at: DateTime' . PHP_EOL;
}
$fields = Str::beforeLast($fields, ',');
return $fields;
}
protected function getPath(Model $model, $postfix='')
{
$name = Str::snake($model->name());
$folder = Str::snake(Str::beforeLast($name, '_'), '/');
$folder = Str::finish($folder, '/');
$fpath = base_path('graphql/'. $folder );
$fs = new Filesystem;
if (!$fs->exists($fpath)) $fs->makeDirectory($fpath, 0755, true);
$postfix = Str::start($postfix, '.');
return base_path('graphql/'. $folder . $name . $postfix.'.graphql');
}
private function getStub(string $stub)
{
static $stubs = [];
if (empty($stubs[$stub])) {
$stubs[$stub] = $this->files->get($this->stubs_path . '/schema/' . $stub . '.stub');
}
return $stubs[$stub];
}
}
| 30.219048
| 96
| 0.489127
|
232d6c056bf2853161d751502f1efe48b9297235
| 5,887
|
lua
|
Lua
|
client/main.lua
|
vwxyzzett/td-atmrob
|
d0259d1c841e5f5d2f577db1de98a6c9425c2880
|
[
"Apache-2.0"
] | null | null | null |
client/main.lua
|
vwxyzzett/td-atmrob
|
d0259d1c841e5f5d2f577db1de98a6c9425c2880
|
[
"Apache-2.0"
] | null | null | null |
client/main.lua
|
vwxyzzett/td-atmrob
|
d0259d1c841e5f5d2f577db1de98a6c9425c2880
|
[
"Apache-2.0"
] | 1
|
2022-02-15T12:53:47.000Z
|
2022-02-15T12:53:47.000Z
|
ESX = nil
local startrob = false
local dosyaprop = false
local hsn = 0
Citizen.CreateThread(function ()
while ESX == nil do
TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
Citizen.Wait(5)
end
end)
local doktousb = {
{x = -1056.88 , y = -233.17, z = 44.02}
}
local start = {
{x = 1268.49 , y = -1710.37, z = 54.77}
}
local dosya = {
{x = 1274.34 , y = -1713.73, z = 54.77, isOpen = false}
}
local lester = {
{x = 1275.72 , y = -1710.29, z = 55.10}
}
--[[Citizen.CreateThread(function()
for k,v in pairs(Config.npc) do
local ped_hash = -1248528957
RequestModel(ped_hash)
while not HasModelLoaded(ped_hash) do
Citizen.Wait(1)
end
ped = CreatePed(1, ped_hash, v.coords, v.heading, false, true)
SetBlockingOfNonTemporaryEvents(ped, true)
SetEntityInvincible(ped, true)
FreezeEntityPosition(ped, true)
end
end)]]
function DrawText3Ds(x,y,z, text)
local onScreen,_x,_y=World3dToScreen2d(x,y,z)
local px,py,pz=table.unpack(GetGameplayCamCoords())
SetTextScale(0.35, 0.35)
SetTextFont(4)
SetTextProportional(1)
SetTextColour(255, 255, 255, 215)
SetTextEntry("STRING")
SetTextCentre(1)
AddTextComponentString(text)
DrawText(_x,_y)
local factor = (string.len(text)) / 500
DrawRect(_x,_y+0.0125, 0.0002+ factor, 0.025, 0, 0, 0, 50)
end
Citizen.CreateThread(function ()
while true do
Citizen.Wait(5)
local playerPed = GetPlayerPed(-1)
local coords, shn = GetEntityCoords(PlayerPedId()), true
for k,v in pairs(start) do
if GetDistanceBetweenCoords(coords, v.x, v.y, v.z, true) < 1 then
DrawText3Ds(v.x, v.y, v.z+0.50, "[E] Bilgisayarı Hackle")
if IsControlJustReleased(0,119) then
if not startrob then
if GetCurrentResourceName() == 'td-atmrob' then
exports["aex-bar"]:taskBar(5000, "Hackleniyor! ")
exports['mythic_notify']:SendAlert("inform", "Dökümanları Al!")
startrob = true
else
TriggerEvent('mythic_notify:client:SendAlert', { type = 'error', text = 'Kanki scriptin ismini neden değiştiriyosun amskdklamsd!'})
end
else
exports['mythic_notify']:SendAlert("inform", "Şuan bunu yapamazsın!")
end
else
end
end
end
if startrob then
for a,b in pairs(dosya) do
if GetDistanceBetweenCoords(coords, b.x, b.y, b.z, true) < 1 then
DrawText3Ds(b.x, b.y, b.z+0.50, "[E] Dosyaları Al ")
if IsControlJustReleased(0,119) then
exports["aex-bar"]:taskBar(5000, "Dosyalar Alınıyor! ")
TriggerEvent('td-atmrob:toggle:file')
TriggerServerEvent('td-atmrob:giveitem')
startrob = false
ClearPedTasks(PlayerPedId())
-- b-.isOpen = true
--hsn = hsn
-- if hsn31 == Config.Standalone then
-- b.isOpen = false
-- hsn = 0
--end
end
end
end
end
end
end)
RegisterNetEvent('td-atmrob:toggle:file')
AddEventHandler('td-atmrob:toggle:file', function()
local player = PlayerPedId()
if ( DoesEntityExist( player ) and not IsEntityDead( player )) then
GiveWeaponToPed(player, 0x88C78EB7, 1, false, true);
end
end)
RegisterNetEvent('td-atmrob:toggle:filedo')
AddEventHandler('td-atmrob:toggle:filedo', function()
local player = PlayerPedId()
if ( DoesEntityExist( player ) and not IsEntityDead( player )) then
--GiveWeaponToPed(player, 0x88C78EB7, 1, false, true);
RemoveWeaponFromPed(player, 0x88C78EB7)
end
end)
function loadAnimDict(dict)
RequestAnimDict(dict)
while not HasAnimDictLoaded(dict) do
Citizen.Wait(5)
end
end
Citizen.CreateThread(function ()
while true do
Citizen.Wait(5)
local playerPed = GetPlayerPed(-1)
local coords, shn = GetEntityCoords(PlayerPedId()), true
for k,v in pairs(doktousb) do
if GetDistanceBetweenCoords(coords, v.x, v.y, v.z, true) < 1 then
DrawText3Ds(v.x, v.y, v.z+0.50, "[E] Dök. USB\'ye Cevir")
if IsControlJustReleased(0,119) then
ESX.TriggerServerCallback("hasan:itemkontrol", function(var)
if var then
loadAnimDict( "mini@repair" )
TaskPlayAnim( PlayerPedId(), "mini@repair", "fixing_a_ped", 8.0, 1.0, -1, 16, 0, 0, 0, 0 )
exports["aex-bar"]:taskBar(4000, "Dosyalar çevriliyor!")
TriggerServerEvent("hasan:itemver2", "usefulusb")
TriggerServerEvent("hasan:itemsil2", "documents")
TriggerEvent('td-atmrob:toggle:filedo')
elseif not var then
exports['mythic_notify']:SendAlert("inform", "Dökümanların Yok!")
end
end, "documents")
else
end
end
end
end
end)
RegisterNetEvent('td-atmrob:client:start')
AddEventHandler('td-atmrob:client:start', function()
local entity, distance = ESX.Game.GetClosestObject({
'prop_fleeca_atm',
})
if distance ~= -1 and distance <= 1.5 then
if entity ~= nil then
exports["aex-bar"]:taskBar(2500, "USB TAKILIYOR!")
exports["aex-bar"]:taskBar(2500, "SISTEM HACKLENIYOR!")
TriggerServerEvent('td-atmrob:givemoney')
end
else
exports['mythic_notify']:SendAlert("inform", "Sadece Soygun İçin Kullanabilirsiniz!")
end
end)
| 27.381395
| 137
| 0.573807
|
a9692e9c93fa02535b2fbe3ec8293648d273f706
| 1,709
|
html
|
HTML
|
templates/googlemaps.html
|
Fuchai/cs330final
|
a753155cd94ea5192dddcea46dcd45ad5ed2df6d
|
[
"Apache-2.0"
] | null | null | null |
templates/googlemaps.html
|
Fuchai/cs330final
|
a753155cd94ea5192dddcea46dcd45ad5ed2df6d
|
[
"Apache-2.0"
] | null | null | null |
templates/googlemaps.html
|
Fuchai/cs330final
|
a753155cd94ea5192dddcea46dcd45ad5ed2df6d
|
[
"Apache-2.0"
] | null | null | null |
{% extends "headerbase.html" %}
{% block title %}
Restaurant Locator
{% endblock %}
{% block styles %}
{{ super() }}
<link href="../css/googlemap.css" rel="stylesheet" type="text/css">
<link href="../css/sidebar.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" integrity="sha384-DNOHZ68U8hZfKXOrtjWvjxusGo9WQnrNx2sqG0tfsghAvtVlRW3tvkXWZh58N9jp" crossorigin="anonymous">
{% endblock %}
{#{% block signinbutton %}#}
{# <a class="btn btn-sm btn-secondary" href="/signin">Sign up & Log in</a>#}
{#{% endblock %}#}
{% block content %}
{{super()}}
<div class="map"></div>
{% endblock %}
{% block headerslot %}
{{super()}}
{% for message in get_flashed_messages() %}
<div class="alert alert-warning d-flex justify-content-between align-items-center">
{{message}}
<button type="button" class="btn btn-secondary text-center" data-dismiss="alert"> close</button>
</div>
{% endfor %}
{% endblock headerslot%}
{%block scripts%}
{{super()}}
<script src="js/yelpAPI.js"></script>
<script src="js/googlemaps.js"></script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAsidkmuLavmoPyURZMxIyBZ0_lB4XqUAI&callback=initMap">
</script>
<!-- jQuery Custom Scroller CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.concat.min.js"></script>
<script src="js/sidebar.js"></script>
{%endblock%}
{% block sidebar %}
{% include "sidebar.html" %}
{% endblock %}
| 34.877551
| 197
| 0.686366
|
8e7e900d37d542a6895a43395cc77137f9e3cf13
| 7,475
|
js
|
JavaScript
|
frontend/src/components/Filter/CalendarFilter.spec.js
|
lumawelhot/Luma-varaukset
|
09d873d5b4140b0ab51eebd4ef7fdcee0a829e4c
|
[
"MIT"
] | 1
|
2021-12-30T12:34:19.000Z
|
2021-12-30T12:34:19.000Z
|
frontend/src/components/Filter/CalendarFilter.spec.js
|
lumawelhot/Luma-varaukset
|
09d873d5b4140b0ab51eebd4ef7fdcee0a829e4c
|
[
"MIT"
] | 119
|
2021-05-25T10:42:53.000Z
|
2022-03-11T11:01:04.000Z
|
frontend/src/components/Filter/CalendarFilter.spec.js
|
lumawelhot/Luma-varaukset
|
09d873d5b4140b0ab51eebd4ef7fdcee0a829e4c
|
[
"MIT"
] | 3
|
2021-05-18T04:31:26.000Z
|
2021-05-25T17:09:05.000Z
|
import React from 'react'
import '@testing-library/jest-dom/extend-expect'
import { render, fireEvent, waitFor } from '@testing-library/react'
import CalendarFilter from './CalendarFilter'
import '../../i18n'
const events = [
{
'title': 'Maanjäristysten alueellisuus ja niiden vaikutukset',
'start': '2021-07-09T09:00:00+0300',
'end': '2021-07-09T13:30:00+0300',
'resourceids': [4],
'grades': [1],
'booked': false,
'inPersonVisit': false,
'remoteVisit': true
},
{
'title': 'Lämpösäteily ja ilmastonmuutos',
'start': '2021-06-15T08:30:00+0300',
'end': '2021-06-15T14:30:00+0300',
'resourceids': [2],
'grades': [2],
'booked': false,
'inPersonVisit': true,
'remoteVisit': false
}
]
describe('Calendar filtering works', () => {
it('Filtering by visitType inPerson', async () => {
const filterFunction = () => () => { return true }
const setFilterFunction = jest.fn()
const component = render(
<CalendarFilter filterFunction={filterFunction} setFilterFunction={setFilterFunction} />
)
await waitFor(() => new Promise((res) => setTimeout(res, 0)))
let button = await component.findByText('Lähiopetus')
fireEvent.click(button)
await waitFor(() => new Promise((res) => setTimeout(res, 0)))
const receivedFilterFunction = setFilterFunction.mock.calls[0][0]()
const localEvents = events.filter(event => receivedFilterFunction(event))
expect(localEvents).toHaveLength(1)
})
it('Filtering by visitType remote', async () => {
const filterFunction = () => () => { return true }
const setFilterFunction = jest.fn()
const component = render(
<CalendarFilter filterFunction={filterFunction} setFilterFunction={setFilterFunction} />
)
await waitFor(() => new Promise((res) => setTimeout(res, 0)))
let button = await component.findByText('Etäopetus')
fireEvent.click(button)
await waitFor(() => new Promise((res) => setTimeout(res, 0)))
const receivedFilterFunction = setFilterFunction.mock.calls[0][0]()
const localEvents = events.filter(event => receivedFilterFunction(event))
expect(localEvents).toHaveLength(1)
})
it('Filtering by visitType deselect all', async () => {
const filterFunction = () => () => { return true }
const setFilterFunction = jest.fn()
const component = render(
<CalendarFilter filterFunction={filterFunction} setFilterFunction={setFilterFunction} />
)
await waitFor(() => new Promise((res) => setTimeout(res, 0)))
let button = await component.findByText('Etäopetus')
fireEvent.click(button)
button = await component.findByText('Lähiopetus')
fireEvent.click(button)
await waitFor(() => new Promise((res) => setTimeout(res, 0)))
const receivedFilterFunction = setFilterFunction.mock.calls[1][0]()
const localEvents = events.filter(event => receivedFilterFunction(event))
expect(localEvents).toHaveLength(0)
})
it('Filtering by scienceClass', async () => {
const filterFunction = () => () => { return true }
const setFilterFunction = jest.fn()
const component = render(
<CalendarFilter filterFunction={filterFunction} setFilterFunction={setFilterFunction} />
)
await waitFor(() => new Promise((res) => setTimeout(res, 0)))
let button = await component.findByText('FOTONI')
fireEvent.click(button)
await waitFor(() => new Promise((res) => setTimeout(res, 0)))
const receivedFilterFunction = setFilterFunction.mock.calls[0][0]()
const localEvents = events.filter(event => receivedFilterFunction(event))
expect(localEvents).toHaveLength(1)
})
it('Filtering by scienceClass deselect all', async () => {
const filterFunction = () => () => { return true }
const setFilterFunction = jest.fn()
const component = render(
<CalendarFilter filterFunction={filterFunction} setFilterFunction={setFilterFunction} />
)
await waitFor(() => new Promise((res) => setTimeout(res, 0)))
let button = await component.findByText('SUMMAMUTIKKA')
fireEvent.click(button)
button = await component.findByText('FOTONI')
fireEvent.click(button)
button = await component.findByText('LINKKI')
fireEvent.click(button)
button = await component.findByText('GEOPISTE')
fireEvent.click(button)
button = await component.findByText('GADOLIN')
fireEvent.click(button)
await waitFor(() => new Promise((res) => setTimeout(res, 0)))
const receivedFilterFunction = setFilterFunction.mock.calls[4][0]()
const localEvents = events.filter(event => receivedFilterFunction(event))
expect(localEvents).toHaveLength(0)
})
it('Filtering by grade', async () => {
const filterFunction = () => () => { return true }
const setFilterFunction = jest.fn()
const component = render(
<CalendarFilter filterFunction={filterFunction} setFilterFunction={setFilterFunction} />
)
await waitFor(() => new Promise((res) => setTimeout(res, 0)))
let button = await component.findByText('1. – 2. luokka')
fireEvent.click(button)
await waitFor(() => new Promise((res) => setTimeout(res, 0)))
const receivedFilterFunction = setFilterFunction.mock.calls[0][0]()
const localEvents = events.filter(event => receivedFilterFunction(event))
expect(localEvents).toHaveLength(1)
})
it('Filtering by grade deselect all', async () => {
const filterFunction = () => () => { return true }
const setFilterFunction = jest.fn()
const component = render(
<CalendarFilter filterFunction={filterFunction} setFilterFunction={setFilterFunction} />
)
await waitFor(() => new Promise((res) => setTimeout(res, 0)))
let button = await component.findByText('Varhaiskasvatus')
fireEvent.click(button)
button = await component.findByText('1. – 2. luokka')
fireEvent.click(button)
button = await component.findByText('3. – 6. luokka')
fireEvent.click(button)
button = await component.findByText('7. – 9. luokka')
fireEvent.click(button)
button = await component.findByText('Toinen aste')
fireEvent.click(button)
await waitFor(() => new Promise((res) => setTimeout(res, 0)))
const receivedFilterFunction = setFilterFunction.mock.calls[4][0]()
const localEvents = events.filter(event => receivedFilterFunction(event))
expect(localEvents).toHaveLength(0)
})
/* it('Show none works', async () => {
const filterFunction = () => () => { return true }
const setFilterFunction = jest.fn()
const component = render(
<CalendarFilter filterFunction={filterFunction} setFilterFunction={setFilterFunction} />
)
await waitFor(() => new Promise((res) => setTimeout(res, 0)))
let button = await component.findByText('Poista kaikki')
fireEvent.click(button)
await waitFor(() => new Promise((res) => setTimeout(res, 0)))
let receivedFilterFunction = setFilterFunction.mock.calls[0][0]()
let localEvents = events.filter(event => receivedFilterFunction(event))
expect(localEvents).toHaveLength(0)
await waitFor(() => new Promise((res) => setTimeout(res, 0)))
button = await component.findByText('Näytä kaikki')
fireEvent.click(button)
await waitFor(() => new Promise((res) => setTimeout(res, 0)))
receivedFilterFunction = setFilterFunction.mock.calls[1][0]()
localEvents = events.filter(event => receivedFilterFunction(event))
expect(localEvents).toHaveLength(2)
}) */
})
| 40.846995
| 94
| 0.676789
|
ff2872b28f8c916dddf8527b91ef237d7511666f
| 8,859
|
py
|
Python
|
lhotse/features/kaldifeat.py
|
stachu86/lhotse
|
d5e78154db2d4d52f15aaadc8882f76eb5b77640
|
[
"Apache-2.0"
] | null | null | null |
lhotse/features/kaldifeat.py
|
stachu86/lhotse
|
d5e78154db2d4d52f15aaadc8882f76eb5b77640
|
[
"Apache-2.0"
] | null | null | null |
lhotse/features/kaldifeat.py
|
stachu86/lhotse
|
d5e78154db2d4d52f15aaadc8882f76eb5b77640
|
[
"Apache-2.0"
] | null | null | null |
from abc import ABC
from dataclasses import asdict, dataclass
from typing import Any, Dict, List, Optional, Sequence, Union
import numpy as np
import torch
from lhotse.features.base import FeatureExtractor, register_extractor
from lhotse.utils import EPSILON, Seconds, is_module_available
@dataclass
class KaldifeatFrameOptions:
sampling_rate: int = 16000
frame_shift: Seconds = 0.01
frame_length: Seconds = 0.025
dither: float = 0.0 # default was 1.0
preemph_coeff: float = 0.97
remove_dc_offset: bool = True
window_type: str = "povey"
round_to_power_of_two: bool = True
blackman_coeff: float = 0.42
snip_edges: bool = False # default was True (won't work with Lhotse)
def to_dict(self) -> Dict[str, Any]:
d = asdict(self)
d["samp_freq"] = float(d.pop("sampling_rate"))
d["frame_shift_ms"] = d.pop("frame_shift") * 1000.0
d["frame_length_ms"] = d.pop("frame_length") * 1000.0
return d
@staticmethod
def from_dict(data: Dict[str, Any]) -> "KaldifeatFrameOptions":
data = data.copy()
if "samp_freq" in data:
data["sampling_rate"] = int(data.pop("samp_freq"))
for key in ["frame_shift_ms", "frame_length_ms"]:
if key in data:
data[key.replace("_ms", "")] = data.pop(key) / 1000
return KaldifeatFrameOptions(**data)
@dataclass
class KaldifeatMelOptions:
num_bins: int = 80 # default was 23
low_freq: float = 20.0
high_freq: float = -400.0 # default was 0.0
vtln_low: float = 100.0
vtln_high: float = -500.0
debug_mel: bool = False
htk_mode: bool = False
def to_dict(self) -> Dict[str, Any]:
return asdict(self)
@staticmethod
def from_dict(data: Dict[str, Any]) -> "KaldifeatMelOptions":
return KaldifeatMelOptions(**data)
class KaldifeatExtractor(FeatureExtractor, ABC):
"""
Base class with shared implementation for kaldifeat feature extractors.
Derived classes are expected to set ``self.extractor`` inside ``__init__``.
"""
def __init__(self, config: Optional[Any] = None) -> None:
super().__init__(config=config)
assert is_module_available(
"kaldifeat"
), 'To use kaldifeat extractors, please "pip install kaldifeat" first.'
@property
def device(self) -> Union[str, torch.device]:
return self.config.device
def extract_batch(
self,
samples: Union[
np.ndarray, torch.Tensor, Sequence[np.ndarray], Sequence[torch.Tensor]
],
sampling_rate: int,
) -> Union[np.ndarray, torch.Tensor, List[np.ndarray], List[torch.Tensor]]:
return self.extract(samples=samples, sampling_rate=sampling_rate)
def extract(
self,
samples: Union[
np.ndarray, torch.Tensor, Sequence[np.ndarray], Sequence[torch.Tensor]
],
sampling_rate: int,
) -> Union[np.ndarray, torch.Tensor, List[np.ndarray], List[torch.Tensor]]:
# Check for sampling rate compatibility.
expected_sr = self.config.frame_opts.sampling_rate
assert sampling_rate == expected_sr, (
f"Mismatched sampling rate: extractor expects {expected_sr}, "
f"got {sampling_rate}"
)
# kaldifeat expects a list of 1D torch tensors.
# If we got a torch tensor / list of torch tensors in the input,
# we'll also return torch tensors. If we got numpy arrays, we
# will convert back to numpy.
maybe_as_numpy = lambda x: x
input_is_list = False
if isinstance(samples, list):
input_is_list = True
pass # nothing to do with `samples`
elif samples.ndim > 1:
samples = list(samples)
else:
# The user passed an array/tensor of shape (num_samples,)
samples = [samples]
for idx in range(len(samples)):
if isinstance(samples[idx], np.ndarray):
samples[idx] = torch.from_numpy(samples[idx])
maybe_as_numpy = lambda x: x.numpy()
if samples[idx].ndim == 2:
# ndim could be > 1 if the input is a list of arrays/tensors.
samples[idx] = samples[idx].squeeze()
# Actual feature extraction.
result = self.extractor(samples, chunk_size=self.config.chunk_size)
# If all items are of the same shape, concatenate
if len(result) == 1:
if input_is_list:
return [maybe_as_numpy(result[0])]
else:
return maybe_as_numpy(result[0])
elif all(item.shape == result[0].shape for item in result[1:]):
return maybe_as_numpy(torch.stack(result, dim=0))
else:
return [maybe_as_numpy(r) for r in result]
@property
def frame_shift(self) -> Seconds:
return self.config.frame_opts.frame_shift
@dataclass
class KaldifeatFbankConfig:
frame_opts: KaldifeatFrameOptions = KaldifeatFrameOptions()
mel_opts: KaldifeatMelOptions = KaldifeatMelOptions()
use_energy: bool = False
energy_floor: float = EPSILON # default was 0.0
raw_energy: bool = True
htk_compat: bool = False
use_log_fbank: bool = True
use_power: bool = True
device: Union[str, torch.device] = "cpu"
# This is an extra setting compared to kaldifeat FbankOptions:
# by default, we'll ask kaldifeat to compute the feats in chunks
# to avoid excessive memory usage.
chunk_size: Optional[int] = 1000
def to_dict(self) -> Dict[str, Any]:
d = asdict(self)
d["frame_opts"] = self.frame_opts.to_dict()
d["mel_opts"] = self.mel_opts.to_dict()
return d
@staticmethod
def from_dict(data: Dict[str, Any]) -> "KaldifeatFbankConfig":
frame_opts = KaldifeatFrameOptions.from_dict(data.pop("frame_opts"))
mel_opts = KaldifeatMelOptions.from_dict(data.pop("mel_opts"))
return KaldifeatFbankConfig(frame_opts=frame_opts, mel_opts=mel_opts, **data)
@register_extractor
class KaldifeatFbank(KaldifeatExtractor):
"""Log Mel energy filter bank feature extractor based on ``kaldifeat`` package."""
name = "kaldifeat-fbank"
config_type = KaldifeatFbankConfig
def __init__(self, config: Optional[KaldifeatFbankConfig] = None) -> None:
super().__init__(config)
import kaldifeat
self.extractor = kaldifeat.Fbank(
kaldifeat.FbankOptions.from_dict(self.config.to_dict())
)
def feature_dim(self, sampling_rate: int) -> int:
return self.config.mel_opts.num_bins
@staticmethod
def mix(
features_a: np.ndarray, features_b: np.ndarray, energy_scaling_factor_b: float
) -> np.ndarray:
return np.log(
np.maximum(
# protection against log(0); max with EPSILON is adequate since these are energies (always >= 0)
EPSILON,
np.exp(features_a) + energy_scaling_factor_b * np.exp(features_b),
)
)
@staticmethod
def compute_energy(features: np.ndarray) -> float:
return float(np.sum(np.exp(features)))
@dataclass
class KaldifeatMfccConfig:
frame_opts: KaldifeatFrameOptions = KaldifeatFrameOptions()
mel_opts: KaldifeatMelOptions = KaldifeatMelOptions(num_bins=23)
num_ceps: int = 13
use_energy: bool = False
energy_floor: float = EPSILON # default was 0.0
raw_energy: bool = True
cepstral_lifter: float = 22.0
htk_compat: bool = False
device: Union[str, torch.device] = "cpu"
# This is an extra setting compared to kaldifeat FbankOptions:
# by default, we'll ask kaldifeat to compute the feats in chunks
# to avoid excessive memory usage.
chunk_size: Optional[int] = 1000
def to_dict(self) -> Dict[str, Any]:
d = asdict(self)
d["frame_opts"] = self.frame_opts.to_dict()
d["mel_opts"] = self.mel_opts.to_dict()
return d
@staticmethod
def from_dict(data: Dict[str, Any]) -> "KaldifeatMfccConfig":
frame_opts = KaldifeatFrameOptions.from_dict(data.pop("frame_opts"))
mel_opts = KaldifeatMelOptions.from_dict(data.pop("mel_opts"))
return KaldifeatMfccConfig(frame_opts=frame_opts, mel_opts=mel_opts, **data)
@register_extractor
class KaldifeatMfcc(KaldifeatExtractor):
"""MFCC feature extractor based on ``kaldifeat`` package."""
name = "kaldifeat-mfcc"
config_type = KaldifeatMfccConfig
def __init__(self, config: Optional[KaldifeatMfccConfig] = None) -> None:
super().__init__(config)
import kaldifeat
self.extractor = kaldifeat.Mfcc(
kaldifeat.MfccOptions.from_dict(self.config.to_dict())
)
def feature_dim(self, sampling_rate: int) -> int:
return self.config.num_ceps
| 34.741176
| 112
| 0.6468
|
e2f42806018eea53dd93c2a054516986740fe4cb
| 847
|
py
|
Python
|
MLBook/14 MCMC/lcg.py
|
AjayKrP/Machine-Learning
|
d039e99bbe09845174a845786099cfdd9a6913cb
|
[
"MIT"
] | null | null | null |
MLBook/14 MCMC/lcg.py
|
AjayKrP/Machine-Learning
|
d039e99bbe09845174a845786099cfdd9a6913cb
|
[
"MIT"
] | null | null | null |
MLBook/14 MCMC/lcg.py
|
AjayKrP/Machine-Learning
|
d039e99bbe09845174a845786099cfdd9a6913cb
|
[
"MIT"
] | null | null | null |
# Code from Chapter 14 of Machine Learning: An Algorithmic Perspective
# by Stephen Marsland (http://seat.massey.ac.nz/personal/s.r.marsland/MLBook.html)
# You are free to use, change, or redistribute the code in any way you wish for
# non-commercial purposes, but please maintain the name of the original author.
# This code comes with no warranty of any kind.
# Stephen Marsland, 2008
# The linear congruential pseudo-random number generator
from numpy import *
def lcg(x0,n):
# These choices show the periodicity very well
# Better choices are a = 16,807 m = 2**31 -1 c = 0
# Or m = 2**32 a = 1,664,525 c = 1,013,904,223
a = 23
m = 197
c = 0
rnd = zeros((n))
rnd[0] = mod(a*x0 + c,m)
for i in range(1,n):
rnd[i] = mod(a*rnd[i-1]+c,m)
return rnd
print lcg(3,80)
| 26.46875
| 82
| 0.639906
|
11144af78e4c5c966996602e755f5429753f46f5
| 2,901
|
swift
|
Swift
|
UFO Emoji/UFO Emoji/GameTransitions/GameOver.swift
|
StarPlayrX/UFOEmoji2020
|
ad30d2693645bce0dad78b28100b769867ded0f6
|
[
"MIT"
] | null | null | null |
UFO Emoji/UFO Emoji/GameTransitions/GameOver.swift
|
StarPlayrX/UFOEmoji2020
|
ad30d2693645bce0dad78b28100b769867ded0f6
|
[
"MIT"
] | null | null | null |
UFO Emoji/UFO Emoji/GameTransitions/GameOver.swift
|
StarPlayrX/UFOEmoji2020
|
ad30d2693645bce0dad78b28100b769867ded0f6
|
[
"MIT"
] | null | null | null |
//
// GameOver.swift
// UF Emoji
//
// Created by todd on 12/7/15.
// Copyright © 2015 Todd Bruss. All rights reserved.
//
import SpriteKit
class GameOver: SKScene {
weak var gd = gameDelegate
override init(size: CGSize ) {
super.init(size: size)
self.removeAllActions()
self.removeAllChildren()
self.removeFromParent()
}
deinit {
if hasActions() {
removeAllActions()
}
if !children.isEmpty {
removeAllChildren()
}
removeFromParent()
}
func runner() {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.view?.isMultipleTouchEnabled = true
self.view?.allowsTransparency = false
self.view?.isAsynchronous = true
self.view?.isOpaque = true
self.view?.clipsToBounds = true
self.view?.ignoresSiblingOrder = true
self.view?.showsFPS = showsFPS
self.view?.showsNodeCount = showsNodeCount
self.view?.showsPhysics = showsPhysics
self.view?.showsFields = showsFields
self.view?.showsDrawCount = showsDrawCount
self.view?.showsQuadCount = showsQuadCount
self.view?.shouldCullNonVisibleNodes = true
self.view?.preferredFramesPerSecond = 61
self.anchorPoint = CGPoint(x: 0.5, y: 0.5)
let my = loadScores()
var scorelabel = "🎲"
if my.score == my.hscore {
scorelabel = "💎"
}
let message = "🎯 " + scorelabel
self.backgroundColor = SKColor.black
/* Game Over Message */
let label = SKLabelNode(fontNamed: emojifontname)
label.text = message
label.fontSize = 68
label.horizontalAlignmentMode = .center
label.verticalAlignmentMode = .center
label.position = CGPoint(x: 0, y: 64 )
/* Show the Score */
let label2 = SKLabelNode(fontNamed: "Emulogic")
label2.text = String( my.score )
label2.fontSize = 34
label2.horizontalAlignmentMode = .center
label2.verticalAlignmentMode = .center
label2.fontColor = SKColor.white
label2.position = CGPoint(x: 0, y: -64)
self.addChild(label)
self.addChild(label2)
}
DispatchQueue.main.asyncAfter(deadline: .now() + 4.0) { [weak self] in
self?.gd?.runGameMenu()
}
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 26.135135
| 78
| 0.521889
|
5de0866d172736958bd7f785d6d2b2f265c6201b
| 495
|
hpp
|
C++
|
contracts/vapaeetokens/vapaeetokens.dispatcher.hpp
|
vapaee/vapaee.io-source
|
b2b0c07850a817629055a848b9239a59dc10b545
|
[
"MIT"
] | 7
|
2019-06-09T03:52:14.000Z
|
2020-03-01T13:27:24.000Z
|
contracts/vapaeetokens/vapaeetokens.dispatcher.hpp
|
vapaee/vapaee.io-source
|
b2b0c07850a817629055a848b9239a59dc10b545
|
[
"MIT"
] | 27
|
2019-12-28T12:29:12.000Z
|
2022-03-02T04:08:55.000Z
|
contracts/vapaeetokens/vapaeetokens.dispatcher.hpp
|
vapaee/vapaee.io-source
|
b2b0c07850a817629055a848b9239a59dc10b545
|
[
"MIT"
] | 2
|
2019-11-29T22:32:47.000Z
|
2021-02-18T23:47:47.000Z
|
#define HANDLER void
#define EOSIO_DISPATCH_VAPAEE( TYPE, MEMBERS, HANDLERS ) \
extern "C" { \
void apply( uint64_t receiver, uint64_t code, uint64_t action ) { \
if( code == receiver ) { \
switch( action ) { \
EOSIO_DISPATCH_HELPER( TYPE, MEMBERS ) \
} \
} \
name handler = eosio::name(string("h") + eosio::name(action).to_string()); \
switch( handler.value ) { \
EOSIO_DISPATCH_HELPER( TYPE, HANDLERS ) \
} \
} \
} \
| 30.9375
| 82
| 0.567677
|
436d414bc859777a812013f024f0d9364d271498
| 2,184
|
ts
|
TypeScript
|
packages/rc-hooks/date/src/hooks/useWeekView.ts
|
yi-tuan/hooks
|
b4e343f267073a52e6a544a32c6719971d633187
|
[
"Apache-2.0"
] | 45
|
2020-07-14T07:01:13.000Z
|
2020-10-12T08:45:20.000Z
|
packages/rc-hooks/date/src/hooks/useWeekView.ts
|
yi-tuan/hooks
|
b4e343f267073a52e6a544a32c6719971d633187
|
[
"Apache-2.0"
] | 1
|
2020-10-13T03:09:40.000Z
|
2020-10-13T03:09:40.000Z
|
packages/rc-hooks/date/src/hooks/useWeekView.ts
|
yi-tuan/hooks
|
b4e343f267073a52e6a544a32c6719971d633187
|
[
"Apache-2.0"
] | 13
|
2020-07-14T11:05:59.000Z
|
2020-10-13T08:59:31.000Z
|
/**
* @file useWeekPanel 获取周面板
*/
import {useCallback, useEffect} from 'react';
import {IWeekPanelViewData, IWeekPanelViewItem, PanelType} from '@co-hooks/date';
import {useShallowState} from '@rc-hooks/use';
import {usePanel} from './usePanel';
export interface IWeekPanelView extends IWeekPanelViewData {
setCurrentWeek: (week: IWeekPanelViewItem) => void;
setCurrentWeekVirtual: (week: IWeekPanelViewItem) => void;
prevYear: () => void;
nextYear: () => void;
prevMonth: () => void;
nextMonth: () => void;
changeToYear: () => void;
changeToMonth: () => void;
}
export function useWeekView(part: string): IWeekPanelView {
const panel = usePanel(part);
const weekView = panel.getWeekPanel();
const changeToYear = useCallback(() => panel.setCurrentType(PanelType.YEAR), []);
const changeToMonth = useCallback(() => panel.setCurrentType(PanelType.MONTH), []);
const prevYear = useCallback(() => panel.prevYear(), []);
const nextYear = useCallback(() => panel.nextYear(), []);
const prevMonth = useCallback(() => panel.prevMonth(), []);
const nextMonth = useCallback(() => panel.nextMonth(), []);
const setCurrentWeek = useCallback((week: IWeekPanelViewItem) => {
weekView.setCurrentWeek(week);
// 当前不在主面板里面,进行面板跳转
if (panel !== weekView) {
// 根据是Week还是Date进行跳转
panel.setCurrentType(panel.getPanelType());
}
}, []);
const setCurrentWeekVirtual = useCallback((week: IWeekPanelViewItem) => {
weekView.setCurrentWeek(week, true);
}, []);
const update = (): IWeekPanelViewData => panel.getWeekPanel().getDatePanelView();
const [viewer, setViewer] = useShallowState(update);
useEffect(() => {
const callback = (): void => {
setViewer(update());
};
panel.addListener('repaint', callback);
return () => panel.removeListener('repaint', callback);
}, [panel]);
return {
...viewer,
setCurrentWeek,
setCurrentWeekVirtual,
nextYear,
prevYear,
prevMonth,
nextMonth,
changeToYear,
changeToMonth
};
}
| 29.513514
| 87
| 0.621795
|
df9195a098d8489da02d8006357030a253a66cfa
| 11,175
|
cs
|
C#
|
QLite/WebControls/QueryView.cs
|
known/QLite
|
d8626f420bceff25b5f35850cc1951b182ba5ffe
|
[
"MIT"
] | null | null | null |
QLite/WebControls/QueryView.cs
|
known/QLite
|
d8626f420bceff25b5f35850cc1951b182ba5ffe
|
[
"MIT"
] | null | null | null |
QLite/WebControls/QueryView.cs
|
known/QLite
|
d8626f420bceff25b5f35850cc1951b182ba5ffe
|
[
"MIT"
] | null | null | null |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using Known.QLite.Helpers;
namespace Known.QLite.WebControls
{
[ToolboxData("<{0}:QueryView runat=\"server\"></{0}:QueryView>")]
public class QueryView : GridView
{
public QueryView()
{
BorderWidth = 0;
AutoGenerateColumns = false;
LineFields = 3;
Filters = new List<IDataField>();
PageSize = int.Parse(ConfigurationManager.AppSettings["PageSize"] ?? "10");
}
public string QueryCssClass { get; set; }
public string ConnectionName { get; set; }
public string EntityName { get; set; }
public string MergeColumns { get; set; }
public string MergeRows { get; set; }
public int LineFields { get; set; }
protected List<IDataField> Filters { get; private set; }
public void AddFilter(string fieldName, object value)
{
AddFilter(fieldName, QueryOperator.Equal, value);
}
public void AddFilter(string fieldName, QueryOperator queryOperator, object value)
{
Filters.Add(new BoundDataField
{
DataField = fieldName,
Operator = queryOperator,
Value = Convert.ToString(value)
});
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!string.IsNullOrEmpty(EntityName))
{
var fields = Columns.OfType<IDataField>();
DataSource = GetQueryResult(fields, EntityName);
}
}
protected override void OnPreRender(EventArgs e)
{
DataBind();
if (!string.IsNullOrEmpty(MergeColumns))
{
var columns = Array.ConvertAll<string, int>(MergeColumns.Split(','), s => int.Parse(s));
this.MergeColumns(columns);
}
if (!string.IsNullOrEmpty(MergeRows))
{
var rows = Array.ConvertAll<string, int>(MergeRows.Split(','), s => int.Parse(s));
this.MergeRows(rows);
}
}
protected override void Render(HtmlTextWriter writer)
{
var fields = Columns.OfType<IDataField>()
.Where(f => f.Operator != QueryOperator.None)
.ToList();
if (fields.Count > 0)
{
var table = CreateQueryTable(fields);
table.RenderControl(writer);
}
base.Render(writer);
}
protected override void OnPageIndexChanging(GridViewPageEventArgs e)
{
PageIndex = e.NewPageIndex;
}
protected override void InitializePager(GridViewRow row, int columnSpan, PagedDataSource pagedDataSource)
{
int recordCount = pagedDataSource.DataSourceCount;
int pageIndex = pagedDataSource.CurrentPageIndex + 1;
int pageCount = pagedDataSource.PageCount;
row.Cells.Clear();
var cell = row.AddCell<TableCell>(columnSpan);
cell.Style["border"] = "none";
cell.HorizontalAlign = HorizontalAlign.Right;
cell.AddLiteralControl("共{0}条 第{1}/{2}页 每页{3}条", recordCount, pageIndex, pageCount, PageSize);
CreatePagerLinkButton(cell, PagerButtonType.First, pageIndex, pageCount);
CreatePagerLinkButton(cell, PagerButtonType.Previous, pageIndex, pageCount);
CreatePagerLinkButton(cell, PagerButtonType.Next, pageIndex, pageCount);
CreatePagerLinkButton(cell, PagerButtonType.Last, pageIndex, pageCount);
}
protected virtual object GetQueryResult(IEnumerable<IDataField> fields, string entityName)
{
var columns = fields.Where(f => f.Visible && !string.IsNullOrEmpty(f.DataField))
.Select(f => f.DataField)
.ToArray();
Filters.AddRange(fields.Where(f => f.Operator != QueryOperator.None));
var where = Filters.Select(f => new
{
Expression = DataFieldHelper.GetExpression(f),
Name = f.DataField,
Value = GetDataFieldValue(f)
})
.Where(f => f.Value != null && f.Value.Trim() != "")
.ToList();
var sort = fields.Where(f => !string.IsNullOrEmpty(f.SortExpression))
.Select(f => f.SortExpression)
.ToArray();
var helper = DbHelperFactory.Create(ConnectionName);
var parameters = helper.CreateParameters();
string columnString = columns.Length == 0 ? "*" : string.Join(",", columns);
string commandText = string.Format("SELECT {0} FROM {1}", columnString, entityName);
if (where.Count > 0)
{
var whereString = string.Join(" AND ", where.Select(w => w.Expression).ToArray());
commandText += string.Format(" WHERE {0}", whereString);
where.ForEach(w => parameters.Add(w.Name, w.Value));
}
if (sort.Length > 0)
{
commandText += string.Format(" ORDER BY {0}", string.Join(",", sort));
}
var dataSource = new DataTable();
helper.Fill(dataSource, commandText, parameters);
return dataSource;
}
protected virtual Table CreateQueryTable(List<IDataField> fields)
{
int rowCount = (int)Math.Ceiling(fields.Count / (double)LineFields);
var table = new Table();
table.ID = "QueryForm";
table.Width = Unit.Percentage(100);
table.CssClass = QueryCssClass;
TableRow row = null;
for (int i = 0; i < fields.Count; i++)
{
if (i % LineFields == 0)
{
row = table.NewRow();
}
var field = fields[i];
field.Value = GetDataFieldValue(field);
var th = row.AddCell<TableHeaderCell>();
th.Text = field.HeaderText + ":";
var td = row.AddCell<TableCell>();
if (i == fields.Count - 1)
{
int columnSpan = 2 * (LineFields - (i % LineFields + 1)) + 1;
if (columnSpan > 1)
{
td.ColumnSpan = columnSpan;
}
}
var control = DataFieldHelper.CreateFieldControl(field);
td.Controls.Add(control);
if (field.ControlType == ControlType.Date)
{
((WebControl)control).CssClass = "date";
}
if (control is ListControl)
{
if (!string.IsNullOrEmpty(field.CodeCategory))
{
var helper = new PageHelper();
helper.PopulateListControl((ListControl)control, field.CodeCategory, field.Value, field.EmptyText);
}
else if (!string.IsNullOrEmpty(field.CodeValues))
{
var helper = new PageHelper();
var codes = new List<object>();
var codeValues = field.CodeValues.Split(';');
Array.ForEach<string>(codeValues, c => codes.Add(new
{
Code = c.Split('|')[0],
Text = c.Split('|')[1]
}));
helper.PopulateListControl((ListControl)control, codes, "Code", "Text", field.Value, field.EmptyText);
}
}
else if (control is ITextControl && !string.IsNullOrEmpty(field.Value))
{
((ITextControl)control).Text = field.Value;
}
else if (control is ICheckBoxControl)
{
((ICheckBoxControl)control).Checked = field.Value.Equals("on", StringComparison.OrdinalIgnoreCase);
}
if (i == LineFields - 1 || (fields.Count <= LineFields && i == fields.Count - 1))
{
var cell = row.AddCell<TableCell>();
cell.Style["text-align"] = "center";
if (rowCount > 1)
{
cell.RowSpan = rowCount;
}
var button = cell.AddControl<Button>("ButtonQuery");
button.OnClientClick = "javascript:showLoading();";
button.Text = "查询";
button.Click += delegate { DataBind(); };
}
}
return table;
}
protected virtual string GetDataFieldValue(IDataField field)
{
return Page.Request.Form[field.DataField] ?? field.Value;
}
private void CreatePagerLinkButton(TableCell cell, PagerButtonType buttonType, int pageIndex, int pageCount)
{
var button = new LinkButton();
button.CommandName = "Page";
switch (buttonType)
{
case PagerButtonType.First:
button.ToolTip = button.Text = "首页";
button.CommandArgument = "First";
button.Enabled = (pageIndex > 1);
break;
case PagerButtonType.Previous:
button.ToolTip = button.Text = "上一页";
button.CommandArgument = "Prev";
button.Enabled = (pageIndex > 1);
break;
case PagerButtonType.Next:
button.ToolTip = button.Text = "下一页";
button.CommandArgument = "Next";
button.Enabled = (pageIndex + 1 <= pageCount);
break;
case PagerButtonType.Last:
button.ToolTip = button.Text = "尾页";
button.CommandArgument = "Last";
button.Enabled = (pageIndex + 1 <= pageCount);
break;
}
cell.AddLiteralControl(" ");
cell.Controls.Add(button);
}
private enum PagerButtonType
{
First,
Previous,
Next,
Last
}
}
}
| 39.073427
| 127
| 0.481074
|
3f3b2a77db5cfc7ad0a3af435dc20b1129426c51
| 1,726
|
ps1
|
PowerShell
|
Functions/Get-JSMProcessingStatusEntry.ps1
|
exactmike/JobSetManager
|
8e52a0ef362fe423d366092fb2f7f91a6a07cd53
|
[
"MIT"
] | 1
|
2018-07-08T06:02:08.000Z
|
2018-07-08T06:02:08.000Z
|
Functions/Get-JSMProcessingStatusEntry.ps1
|
exactmike/poshRSJobFlowManager
|
8e52a0ef362fe423d366092fb2f7f91a6a07cd53
|
[
"MIT"
] | null | null | null |
Functions/Get-JSMProcessingStatusEntry.ps1
|
exactmike/poshRSJobFlowManager
|
8e52a0ef362fe423d366092fb2f7f91a6a07cd53
|
[
"MIT"
] | 1
|
2020-07-15T23:53:58.000Z
|
2020-07-15T23:53:58.000Z
|
function Get-JSMProcessingStatusEntry
{
<#
.SYNOPSIS
Gets entries from the module scope array variablle JSMProcessingLoopStatus
.DESCRIPTION
Gets all entries or specified entries (by JobName or EntryID) from the module scope array variable JSMProcessingLoopStatus
.EXAMPLE
PS C:\> Get-JSMProcessingStatusEntry
Gets all entries from the JSMProcessingLoopStatus module array variable.
#>
[CmdletBinding(DefaultParameterSetName = 'All')]
param
(
# EntryID of Entry you want to retrieve
[Parameter(Mandatory, ParameterSetName = 'EntryID', ValueFromPipeline, ValueFromPipelineByPropertyName)]
[int32[]]
$EntryID
,
# JobName of Job entries that you want to retrieve
[Parameter(Mandatory, ParameterSetName = 'JobName', ValueFromPipeline, ValueFromPipelineByPropertyName)]
[string[]]
$JobName
)
begin
{
if (-not $(Test-ExistsJSMProcessingStatus))
{
throw('JSMProcessingLoopStatus is not initialized')
Return
}
}
process
{
switch ($PSCmdlet.ParameterSetName)
{
'EntryID'
{
foreach ($i in $EntryID)
{
$script:JSMProcessingLoopStatus.where( {$_.EntryID -eq $i})
}
}
'All'
{
$script:JSMProcessingLoopStatus
}
'JobName'
{
foreach ($j in $JobName)
{
$script:JSMProcessingLoopStatus.where({$_.JobName -like $j})
}
}
}
}
end
{
}
}
| 26.96875
| 130
| 0.54635
|
b35829957542c4d9b959727d95d83e5c13e2f5b0
| 3,344
|
py
|
Python
|
large_vocab_adt_dafx2018/features.py
|
mcartwright/dafx2018_adt
|
057ac6b1e39cd0c80554d52535cc9d88b6316c74
|
[
"BSD-2-Clause"
] | 6
|
2019-02-28T05:43:58.000Z
|
2021-03-02T17:05:13.000Z
|
large_vocab_adt_dafx2018/features.py
|
mcartwright/dafx2018_adt
|
057ac6b1e39cd0c80554d52535cc9d88b6316c74
|
[
"BSD-2-Clause"
] | null | null | null |
large_vocab_adt_dafx2018/features.py
|
mcartwright/dafx2018_adt
|
057ac6b1e39cd0c80554d52535cc9d88b6316c74
|
[
"BSD-2-Clause"
] | 1
|
2020-02-07T17:10:40.000Z
|
2020-02-07T17:10:40.000Z
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division
import librosa
import scipy.signal
import numpy as np
from .utils import read_audio
FRAME_INTERVAL = 0.01 # s
def cq_matrix(bins_per_octave, num_bins, f_min, fft_len, sr):
"""
Compute center frequencies of the log-spaced filterbank
Parameters
----------
bins_per_octave : int
num_bins : int
f_min : float
fft_len : int
sr : float
Returns
-------
c_mat
"""
# note range goes from -1 to bpo*num_oct for boundary issues
f_cq = f_min * 2 ** ((np.arange(-1, num_bins+1)) / bins_per_octave)
# centers in bins
kc = np.round(f_cq * (fft_len / sr)).astype(int)
c_mat = np.zeros([num_bins, int(np.round(fft_len / 2))])
for k in range(1, kc.shape[0]-1):
l1 = kc[k]-kc[k-1]
w1 = scipy.signal.triang((l1 * 2) + 1)
l2 = kc[k+1]-kc[k]
w2 = scipy.signal.triang((l2 * 2) + 1)
wk = np.hstack([w1[0:l1], w2[l2:]]) # concatenate two halves
c_mat[k-1, kc[k-1]:(kc[k+1]+1)] = wk / np.sum(wk) # normalized to unit sum;
return c_mat
def onset_detection_fn(x, f_win_size, f_hop_size, f_bins_per_octave, f_octaves, f_fmin, sr, mean_filter_size):
"""
Filter bank for onset pattern calculation
"""
# calculate frequency constant-q transform
f_win = scipy.signal.hanning(f_win_size)
x_spec = librosa.stft(x,
n_fft=f_win_size,
hop_length=f_hop_size,
win_length=f_win_size,
window=f_win)
x_spec = np.abs(x_spec) / (2 * np.sum(f_win))
f_cq_mat = cq_matrix(f_bins_per_octave, f_octaves * f_bins_per_octave, f_fmin, f_win_size, sr)
x_cq_spec = np.dot(f_cq_mat, x_spec[:-1, :])
# subtract moving mean
b = np.concatenate([[1], np.ones(mean_filter_size, dtype=float) / -mean_filter_size])
od_fun = scipy.signal.lfilter(b, 1, x_cq_spec, axis=1)
# half-wave rectify
od_fun = np.maximum(0, od_fun)
# post-process OPs
od_fun = np.log10(1 + 1000*od_fun)
return od_fun, x_cq_spec
def extract_features(audio_file_path, sr=22050, channel=1):
x, sr = read_audio(audio_file_path, mono=True, sr=sr)
f_win_size = 1024
f_hop_size = int(round(FRAME_INTERVAL * sr))
f_bins_per_octave = 8
f_octaves = 8
f_fmin = 40
mean_filter_size = 22
# normalize
x /= np.max(np.abs(x))
od_fun, x_cq_spec = onset_detection_fn(x,
f_win_size,
f_hop_size,
f_bins_per_octave,
f_octaves,
f_fmin,
sr,
mean_filter_size)
logf_stft = librosa.power_to_db(x_cq_spec).astype('float32')
od_fun = np.abs(od_fun).astype('float32')
# reshape for model
ms_input_array = np.moveaxis(logf_stft, 1, 0)
ms_input_array = np.expand_dims(ms_input_array, axis=2)
os_input_array = np.moveaxis(od_fun, 1, 0)
os_input_array = np.clip(os_input_array / 2.25, 0, 1)
os_input_array = np.expand_dims(os_input_array, axis=2)
return ms_input_array, os_input_array, sr
| 31.54717
| 110
| 0.58134
|
660fc4978c7513eaf5583fc522a8ee74ebb46435
| 8,846
|
py
|
Python
|
resources/parser.py
|
ohhdemgirls/GrabIt
|
516c0f25d562aa396c12df2c80b78156a80565f1
|
[
"MIT"
] | 1
|
2020-06-18T01:57:27.000Z
|
2020-06-18T01:57:27.000Z
|
resources/parser.py
|
ohhdemgirls/GrabIt
|
516c0f25d562aa396c12df2c80b78156a80565f1
|
[
"MIT"
] | null | null | null |
resources/parser.py
|
ohhdemgirls/GrabIt
|
516c0f25d562aa396c12df2c80b78156a80565f1
|
[
"MIT"
] | null | null | null |
import argparse
import logging
import sys
import os
from resources.config import Config
class Singleton(type):
def __init__(self, *args, **kwargs):
self.__instance = None
super().__init__(*args, **kwargs)
def __call__(self, *args, **kwargs):
if self.__instance is None:
self.__instance = super().__call__(*args, **kwargs)
return self.__instance
else:
return self.__instance
class Parser(metaclass=Singleton):
def __init__(self):
self.config_class = Config(os.path.join(os.path.dirname(__file__), "config.json"))
self.config = self.config_class.config
parser = argparse.ArgumentParser(description="Archives submissions from Reddit")
parser.add_argument(
"subreddit",
nargs="?",
help="Enter a subreddit, user, submission url or text file to backup",
)
parser.add_argument("-p", "--posts", help="Number of posts to grab on each cycle")
parser.add_argument("--search", help="Search for submissions in a subreddit")
parser.add_argument("--sort", help='Sort submissions by "relevance", "comments", "hot", "new", "top", or "controversial"')
parser.add_argument("--time_filter", help='Filter sorted submissions by "all", "day", "hour", "month", "week", or "year" (search only)')
parser.add_argument("-w", "--wait", help="Wait time in seconds between each cycle")
parser.add_argument("-c", "--cycles", help="Number to times to repeat after wait time")
parser.add_argument("-o", "--output", help="Set base directory")
parser.add_argument("-t", "--output_template", help="Specify output template")
parser.add_argument("--allow_nsfw", help="Include nsfw posts", action="store_true")
parser.add_argument("-v", "--verbose", help="Set verbose", action="store_true")
parser.add_argument("--pushshift", help="Only use pushshift to grab submissions", action="store_true")
parser.add_argument("--ignore_duplicate", help="Ignore duplicate media submissions", action="store_true")
parser.add_argument("--blacklist", help="Avoid downloading a user or subreddit")
parser.add_argument("--reddit_id", help="Reddit client ID")
parser.add_argument("--reddit_secret", help="Reddit client secret")
parser.add_argument("--imgur_cookie", help="Imgur authautologin cookie")
parser.add_argument("--db_location", help="Set location of database file")
self.args = parser.parse_args()
self.subreddit = self.args.subreddit
self.allow_nsfw = self.args.allow_nsfw
self.verbose = self.args.verbose
self.pushshift = self.args.pushshift
self.ignore_duplicate = self.args.ignore_duplicate
def checkArgs(self):
# wait
if self.args.wait and self.args.subreddit:
try:
self.wait = int(self.args.wait)
except ValueError:
self.logger.error("Please enter an integer in seconds to wait")
sys.exit()
else:
self.wait = self.config.get("general").get("wait_time", self.config_class.default_config["general"]["wait_time"])
self.logger.debug("Wait time set to {} seconds".format(self.wait))
# cycles
if self.args.cycles and self.args.subreddit:
try:
self.cycles = int(self.args.cycles)
except ValueError:
self.logger.error("Please enter an integer in seconds to wait")
sys.exit()
else:
self.cycles = self.config.get("general").get("cycles", self.config_class.default_config["general"]["cycles"])
self.logger.debug("Cycles set to {}.".format(self.cycles))
# posts
if self.args.posts and self.args.subreddit:
try:
self.posts = int(self.args.posts)
except ValueError:
self.logger.error("Please enter an inter for the number of posts")
sys.exit()
else:
self.posts = self.config.get("general").get("posts", self.config_class.default_config["general"]["posts"])
self.logger.debug("Posts to download set to {}".format(self.posts))
# output, sets base_dir
if self.args.output and self.args.subreddit:
self.base_dir = os.path.abspath(self.args.output)
self.ifNotExistMakeDir(self.base_dir)
else:
self.base_dir = os.getcwd()
self.output = self.args.output
self.logger.debug("Base directory for download set to {}".format(self.base_dir))
# search
self.search = None
if self.args.search:
self.search = self.args.search
self.logger.debug('Reddit search set to "{}"'.format(self.search))
# sort
self.sort = self.config["general"]["sort"]
self.sort = self.config.get("general").get("sort", self.config_class.default_config["general"]["sort"])
if (
self.args.sort
and (
self.args.sort.lower() == "relevance"
or self.args.sort.lower() == "new"
or self.args.sort.lower() == "top"
or self.args.sort.lower() == "comments"
)
and self.args.subreddit
and self.args.search
):
self.sort = self.args.sort.lower()
elif (
self.args.sort
and (
self.args.sort.lower() == "hot"
or self.args.sort.lower() == "new"
or self.args.sort.lower() == "top"
or self.args.sort.lower() == "controversial"
)
and self.args.subreddit
):
self.sort = self.args.sort.lower()
elif self.args.sort and self.subreddit:
self.logger.error("Incorrect use of sort: {}\nCheck https://github.com/LameLemon/GrabIt for help".format(self.args.sort.lower()))
sys.exit()
self.logger.debug("Reddit sorting set to {}".format(self.sort))
# time_filter
self.time_filter = self.config.get("general").get("time_filter", self.config_class.default_config["general"]["time_filter"])
if (
self.args.time_filter
and (
self.args.time_filter.lower() == "all"
or self.args.time_filter.lower() == "day"
or self.args.time_filter.lower() == "hour"
or self.args.time_filter.lower() == "month"
or self.args.time_filter.lower() == "week"
or self.args.time_filter.lower() == "year"
)
and self.args.subreddit
):
self.time_filter = self.args.time_filter.lower()
elif self.args.time_filter and self.subreddit:
self.logger.error("Please enter all, day, hour, month, week, or year for time_filter")
sys.exit()
self.logger.debug("Reddit time_filter set to {}".format(self.time_filter))
# blacklist
if self.args.blacklist:
self.config["reddit"]["blacklist"].append(self.args.blacklist)
self.logger.info('Added "{}" to the blacklist'.format(self.args.blacklist))
# reddit api credentials
if self.args.reddit_id:
self.config["reddit"]["creds"]["client_id"] = self.args.reddit_id
if self.args.reddit_secret:
self.config["reddit"]["creds"]["client_secret"] = self.args.reddit_secret
# imgur authautologin cookie
if self.args.imgur_cookie:
if not self.config.get("imgur"):
self.config["imgur"] = {
"authautologin": self.args.imgur_cookie
}
else:
self.config["imgur"]["authautologin"] = self.args.imgur_cookie
# set database location
if self.args.db_location:
self.config["general"]["database_location"] = self.args.db_location
db_path = os.path.dirname(self.args.db_location)
self.ifNotExistMakeDir(db_path)
self.db_location = self.args.db_location
else:
self.db_location = self.config["general"]["database_location"]
self.config_class.write_config()
# output template
if self.args.output_template:
self.template = self.args.output_template
else:
self.template = os.path.join("%(subreddit)s", "%(author)s", "%(id)s-%(title)s.%(ext)s")
def setupLogger(self):
""" Called after logger initialised in Grabber"""
self.logger = logging.getLogger(__name__)
def ifNotExistMakeDir(self, dir):
if not os.path.exists(dir):
os.makedirs(dir)
def reload_parser(self):
self.config_class.load_config()
| 42.941748
| 144
| 0.59541
|
43b6d0073e4884bff5f041dd7b063ac48e197cb8
| 748
|
ts
|
TypeScript
|
5 cloudfunction/Angular/app.routing.module.ts
|
YaeLing/sampleCode
|
0da8f2e9c306e2b5f619c8a697e1b55f5cecc1a0
|
[
"MIT"
] | null | null | null |
5 cloudfunction/Angular/app.routing.module.ts
|
YaeLing/sampleCode
|
0da8f2e9c306e2b5f619c8a697e1b55f5cecc1a0
|
[
"MIT"
] | null | null | null |
5 cloudfunction/Angular/app.routing.module.ts
|
YaeLing/sampleCode
|
0da8f2e9c306e2b5f619c8a697e1b55f5cecc1a0
|
[
"MIT"
] | null | null | null |
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LoginComponent } from './loginComponent';
import { ProductsComponent } from './productsComponent';
import { QrcodeComponent } from './qrcodeComponent';
import { AccountsComponent } from './accountsComponent';
const routes: Routes = [
{ path: '', redirectTo: '/products', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: 'products', component: ProductsComponent },
{ path: 'qrcode', component: QrcodeComponent },
{ path: 'accounts', component: AccountsComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
| 34
| 61
| 0.68984
|
1a51f56e9ef0d547d513ed03e886d40057c96b93
| 1,091
|
py
|
Python
|
Virtual Assistant/API/ipGeoLocation.py
|
Codingmace/JARVIS
|
826d8eeaac9472511ffe5cae6f6924aa041cc723
|
[
"MIT"
] | 1
|
2021-02-06T13:08:37.000Z
|
2021-02-06T13:08:37.000Z
|
Virtual Assistant/API/ipGeoLocation.py
|
Codingmace/JARVIS
|
826d8eeaac9472511ffe5cae6f6924aa041cc723
|
[
"MIT"
] | null | null | null |
Virtual Assistant/API/ipGeoLocation.py
|
Codingmace/JARVIS
|
826d8eeaac9472511ffe5cae6f6924aa041cc723
|
[
"MIT"
] | null | null | null |
import requests
from variables import rapidApiKey
def ipLocation(ipAddress):
url = "https://ip-location5.p.rapidapi.com/get_geo_info"
payload = "ip="+ipAddress
headers = {
'content-type': "application/x-www-form-urlencoded",
'x-rapidapi-key': rapidApiKey,
'x-rapidapi-host': "ip-location5.p.rapidapi.com"
}
response = requests.request("POST", url, data=payload, headers=headers)
dataResponse = response.json()
# print(response.text)
neededData = ['ip','region','city','latitude','longitude']
importantData = []
for data in neededData:
importantData.append(dataResponse[data])
# print(neededData)
# print(importantData)
return response
"""
{
"ip":"45.16.197.205"
"continent":{2 items
"code":"NA"
"name":"North America"
}
"country":{5 items
"code":"US"
"name":"United States"
"capital":"Washington"
"currency":"USD"
"phone-code":"1"
}
"region":"Texas"
"city":"Richardson"
"latitude":32.9483
"longitude":-96.7299
}
"""
| 21.82
| 75
| 0.603116
|
e6aa96759af6ccc5a20e63915fa373ae9f025365
| 3,717
|
h
|
C
|
pySurfaceHierarchy/src/TangentParam/param_util.h
|
msraig/pfcnn
|
ae8530efeb795e50495dc1758ced61b0d02a677f
|
[
"MIT"
] | 18
|
2020-04-23T08:09:51.000Z
|
2022-02-27T05:34:39.000Z
|
pySurfaceHierarchy/src/TangentParam/param_util.h
|
msraig/pfcnn
|
ae8530efeb795e50495dc1758ced61b0d02a677f
|
[
"MIT"
] | 5
|
2020-06-25T05:19:16.000Z
|
2022-03-06T08:24:16.000Z
|
pySurfaceHierarchy/src/TangentParam/param_util.h
|
msraig/pfcnn
|
ae8530efeb795e50495dc1758ced61b0d02a677f
|
[
"MIT"
] | 5
|
2020-05-14T10:29:56.000Z
|
2021-02-05T01:26:19.000Z
|
#pragma once
#include <cmath>
#include <vector>
#include "TNT\tnt_matrix.h"
#include "TriMeshDef.hpp"
inline int get_axis_map_p2p(const TriMesh::Point& centN, const TriMesh::Point& nbN, int anum,
const std::vector<TriMesh::Point>& centAxes, const std::vector<TriMesh::Point>& nbAxes) {
// rotation mat from nbN to centN
TNT::Matrix<double> rot_mat(3, 3, 0.0);
{
//set Identity rotation
rot_mat[0][0] = rot_mat[1][1] = rot_mat[2][2] = 1.0;
auto prdct = OpenMesh::cross(nbN, centN);
double sin_theta = prdct.length();
if (!is_valid(sin_theta)) {
std::cout << "Cannot rotate and match two normal vectors" << std::endl << nbN << std::endl << centN; //std::exit(0);
}
else if (sin_theta == 0.0)
{ // parallel, do nothing
}
else {
auto rot_axis = (1.0 / sin_theta) * prdct;
auto cos_theta = OpenMesh::dot(nbN, centN);
TNT::Matrix<double> K(3, 3);
K[0][1] = -rot_axis[2]; K[1][0] = -K[0][1];
K[0][2] = rot_axis[1]; K[2][0] = -K[0][2];
K[1][2] = -rot_axis[0]; K[2][1] = -K[1][2];
auto K2 = K*K;
rot_mat = rot_mat + TNT::mult(sin_theta, K) + TNT::mult(1 - cos_theta, K2);
}
}
auto mult_tntmat_vec3 = [](TNT::Matrix<double>& mat, TriMesh::Point& v)->TriMesh::Point {
TriMesh::Point ret;
for (int i = 0; i < 3; i++)
{
ret[i] = mat[i][0] * v[0] + mat[i][1] * v[1] + mat[i][2] * v[2];
}
return ret;
};
// search permutation
auto centAxis = centAxes[0];
int cls_nb_axis = -1;
double cls_max = -10;
for (int nba_itr = 0; nba_itr < anum; nba_itr++) {
auto nb_axis = nbAxes[nba_itr];
double dpt = dot(centAxis, mult_tntmat_vec3(rot_mat, nb_axis));
if (dpt > cls_max)
{
cls_max = dpt; cls_nb_axis = nba_itr;
}
}
return cls_nb_axis;
}
/*
inline void get_axis_map(TriMesh* mesh, const std::vector<std::vector<TriMesh::Point>>& axes,
std::map<std::pair<int, int>, int>& edge_permute) {
for (auto vh : *mesh->get_vertices_list())
{
auto eh = vh->edge;
do
{
auto nvh = eh->vert;
if (vh->id < nvh->id)
{
// rotation mat from nbN to centN
TNT::Matrix<double> rot_mat(3, 3, 0.0);
{
//set Identity rotation
rot_mat[0][0] = rot_mat[1][1] = rot_mat[2][2] = 1.0;
TriMesh::Point centN = vh->normal, nbN = nvh->normal;
auto prdct = Geex::cross(nbN, centN);
double sin_theta = prdct.length();
if (!is_valid(sin_theta)) { std::cout << "Cannot rotate and match two normal vectors"; std::exit(0); }
if (sin_theta == 0.0)
{ // parallel, do nothing
}
else {
auto rot_axis = (1.0 / sin_theta) * prdct;
auto cos_theta = Geex::dot(nbN, centN);
TNT::Matrix<double> K(3, 3);
K[0][1] = -rot_axis[2]; K[1][0] = -K[0][1];
K[0][2] = rot_axis[1]; K[2][0] = -K[0][2];
K[1][2] = -rot_axis[0]; K[2][1] = -K[1][2];
auto K2 = K*K;
rot_mat = rot_mat + TNT::mult(sin_theta, K) + TNT::mult(1 - cos_theta, K2);
}
}
auto mult_tntmat_vec3 = [](TNT::Matrix<double>& mat, TriMesh::Point& v)->TriMesh::Point {
TriMesh::Point ret;
for (int i = 0; i < 3; i++)
{
ret[i] = mat[i][0] * v[0] + mat[i][1] * v[1] + mat[i][2] * v[2];
}
return ret;
};
// search permutation
{
auto centAxis = axes[vh->id][0];
int anum = axes[0].size();
int cls_nb_axis = -1;
double cls_max = -10;
for (int nba_itr = 0; nba_itr < anum; nba_itr++) {
auto nb_axis = axes[nvh->id][nba_itr];
double dpt = dot(centAxis, mult_tntmat_vec3(rot_mat, nb_axis));
if (dpt > cls_max)
{
cls_max = dpt; cls_nb_axis = nba_itr;
}
}
edge_permute[std::pair<int, int>(vh->id, nvh->id)] = cls_nb_axis;
}
}
eh = eh->pair->next;
} while (eh != vh->edge);
}
}
*/
| 29.267717
| 120
| 0.57116
|
ef8020efcb0c5c8fc3302ed9701c67008dffaa50
| 3,971
|
h
|
C
|
APCAppCore/APCAppCore/DataSubstrate/APCUser.h
|
chb/AppCore
|
3284a7a6803cc635795a8a260531df6a1e937b19
|
[
"BSD-3-Clause"
] | null | null | null |
APCAppCore/APCAppCore/DataSubstrate/APCUser.h
|
chb/AppCore
|
3284a7a6803cc635795a8a260531df6a1e937b19
|
[
"BSD-3-Clause"
] | null | null | null |
APCAppCore/APCAppCore/DataSubstrate/APCUser.h
|
chb/AppCore
|
3284a7a6803cc635795a8a260531df6a1e937b19
|
[
"BSD-3-Clause"
] | 1
|
2020-11-19T13:35:25.000Z
|
2020-11-19T13:35:25.000Z
|
//
// APCUser.h
// APCAppCore
//
// Copyright (c) 2015, Apple Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#import <Foundation/Foundation.h>
#import <HealthKit/HealthKit.h>
NS_ASSUME_NONNULL_BEGIN
typedef NS_ENUM(NSInteger, APCUserConsentSharingScope) {
APCUserConsentSharingScopeNone = 0,
APCUserConsentSharingScopeStudy,
APCUserConsentSharingScopeAll,
};
@protocol APCUser <NSObject>
#pragma mark Demographics
@property (copy, nonatomic, nullable) NSString *name;
@property (copy, nonatomic, nullable) NSString *email;
@property (copy, nonatomic, nullable) NSString *password;
@property (copy, nonatomic, nullable) NSString *sessionToken;
@property (strong, nonatomic, nullable) NSDate *birthDate;
@property (nonatomic) HKBiologicalSex biologicalSex;
@property (nonatomic) HKBloodType bloodType;
@property (copy, nonatomic, nullable) NSString *ethnicity;
@property (strong, nonatomic, nullable) NSData *profileImage;
@property (copy, nonatomic, nullable) NSNumber *homeLocationLong;
@property (copy, nonatomic, nullable) NSNumber *homeLocationLat;
@property (copy, nonatomic, nullable) NSString *homeLocationAddress;
#pragma mark Vitals, Conditions & Meds
@property (strong, nonatomic, nullable) HKQuantity *bodyheight;
@property (strong, nonatomic, nullable) HKQuantity *bodyweight;
@property (strong, nonatomic, nullable) NSDate *sleepTime;
@property (strong, nonatomic, nullable) NSDate *wakeUpTime;
@property (copy, nonatomic, nullable) NSString *medicalConditions;
@property (copy, nonatomic, nullable) NSString *medications;
#pragma mark Consenting
@property (nonatomic) APCUserConsentSharingScope sharingScope; // NOT stored to CoreData, reflected in "sharedOptionSelection"
@property (nonatomic) BOOL userConsented;
@property (nonatomic) BOOL serverConsented;
@property (strong, nonatomic, nullable) NSDate *consentSignatureDate;
@property (copy, nonatomic, nullable) NSString *consentSignatureName;
@property (strong, nonatomic, nullable) NSData *consentSignatureImage;
#pragma mark Signup/Signin
@property (nonatomic) BOOL signedUp;
@property (nonatomic) BOOL signedIn;
@property (nonatomic) BOOL secondaryInfoSaved;
- (void)signUpOnCompletion:(void(^)(NSError *__nullable error))callback;
- (void)withdrawStudyOnCompletion:(void (^)(NSError *__nullable error))callback;
@end
NS_ASSUME_NONNULL_END
| 32.54918
| 131
| 0.780408
|
bb57b370274be6960ca0d6e21ca0bc10fb4d1823
| 1,621
|
cs
|
C#
|
Tower Defense/Assets/_Main/Scripts/Utilities/Audio/Audio Sliders/AudioSlider.cs
|
Horothenic/tower-defense
|
a9692e2551404c439dbb653cf120ecf05a190875
|
[
"MIT"
] | null | null | null |
Tower Defense/Assets/_Main/Scripts/Utilities/Audio/Audio Sliders/AudioSlider.cs
|
Horothenic/tower-defense
|
a9692e2551404c439dbb653cf120ecf05a190875
|
[
"MIT"
] | 29
|
2021-01-15T02:31:51.000Z
|
2021-01-18T21:25:10.000Z
|
Tower Defense/Assets/_Main/Scripts/Utilities/Audio/Audio Sliders/AudioSlider.cs
|
Horothenic/tower-defense
|
a9692e2551404c439dbb653cf120ecf05a190875
|
[
"MIT"
] | null | null | null |
using System;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using Zenject;
namespace Utilities.Audio
{
public class AudioSlider : MonoBehaviour
{
#region FIELDS
[Inject] protected AudioManager audioManager = null;
[Header("COMPONENTS")]
[SerializeField] private Image audioTypeImage = null;
[SerializeField] protected Slider audioSlider = null;
[Header("CONFIGURATION")]
[SerializeField] private Sprite onSprite = null;
[SerializeField] private Sprite offSprite = null;
#endregion
#region EVENTS
protected UnityAction<float> newValueSelected;
protected Func<bool> isMuted;
#endregion
#region BEHAVIORS
protected virtual void Start()
{
audioSlider.onValueChanged.AddListener(SetNewValue);
UpdateSprite();
}
private void Reset()
{
audioTypeImage = GetComponentInChildren<Image>();
audioSlider = GetComponentInChildren<Slider>();
}
protected void SetNewValue(float newValue)
{
newValueSelected.Invoke(newValue / audioSlider.maxValue);
UpdateSprite();
}
protected void UpdateSprite()
{
SetSprite(isMuted() ? offSprite : onSprite);
}
protected void UpdateSliderPosition(float value)
{
audioSlider.value = value;
}
private void SetSprite(Sprite sprite)
{
audioTypeImage.sprite = sprite;
}
#endregion
}
}
| 22.830986
| 69
| 0.599013
|
7f41ff1698114cf853a70240de0c540fad05a698
| 1,904
|
php
|
PHP
|
platform/plugins/gallery/src/Providers/HookServiceProvider.php
|
ttungbmt/laragis
|
783140681f4913ae30a6a7b14e743811d993a153
|
[
"MIT"
] | 1
|
2020-07-25T15:28:33.000Z
|
2020-07-25T15:28:33.000Z
|
platform/plugins/gallery/src/Providers/HookServiceProvider.php
|
ttungbmt/laragis
|
783140681f4913ae30a6a7b14e743811d993a153
|
[
"MIT"
] | 5
|
2020-05-20T02:12:09.000Z
|
2022-02-27T10:38:40.000Z
|
platform/plugins/gallery/src/Providers/HookServiceProvider.php
|
ttungbmt/laragis
|
783140681f4913ae30a6a7b14e743811d993a153
|
[
"MIT"
] | null | null | null |
<?php
namespace Botble\Gallery\Providers;
use Assets;
use Illuminate\Support\ServiceProvider;
class HookServiceProvider extends ServiceProvider
{
/**
* @throws \Throwable
*/
public function boot()
{
add_action(BASE_ACTION_META_BOXES, [$this, 'addGalleryBox'], 13, 2);
if (function_exists('shortcode')) {
add_shortcode('gallery', trans('plugins/gallery::gallery.gallery_images'),
trans('plugins/gallery::gallery.add_gallery_short_code'), [$this, 'render']);
shortcode()->setAdminConfig('gallery', view('plugins/gallery::partials.short-code-admin-config')->render());
}
}
/**
* @param string $context
* @param $object
*/
public function addGalleryBox($context, $object)
{
if ($object && in_array(get_class($object),
config('plugins.gallery.general.supported', [])) && $context == 'advanced') {
Assets::addStylesDirectly(['vendor/core/plugins/gallery/css/admin-gallery.css'])
->addScriptsDirectly(['vendor/core/plugins/gallery/js/gallery-admin.js'])
->addScripts(['sortable']);
add_meta_box('gallery_wrap', trans('plugins/gallery::gallery.gallery_box'), [$this, 'galleryMetaField'],
get_class($object), $context, 'default');
}
}
/**
* @return string
* @throws \Throwable
*/
public function galleryMetaField()
{
$value = null;
$args = func_get_args();
if ($args[0] && $args[0]->id) {
$value = gallery_meta_data($args[0]);
}
return view('plugins/gallery::gallery-box', compact('value'))->render();
}
/**
* @param $shortcode
* @return string
*/
public function render($shortcode)
{
return render_galleries($shortcode->limit ? $shortcode->limit : 6);
}
}
| 29.292308
| 120
| 0.58771
|
31c11c84a2aa763cef6f1f0090eb0f8f54197ac7
| 3,559
|
go
|
Go
|
private/keys/ops_db_test.go
|
VerseApp/ssb
|
628285b56f8cf0b5c2acf4c906390d7a88f63929
|
[
"Apache-2.0",
"MIT"
] | 133
|
2018-10-26T10:37:01.000Z
|
2022-03-23T20:48:29.000Z
|
private/keys/ops_db_test.go
|
VerseApp/ssb
|
628285b56f8cf0b5c2acf4c906390d7a88f63929
|
[
"Apache-2.0",
"MIT"
] | 114
|
2018-12-27T19:46:02.000Z
|
2022-03-29T14:23:44.000Z
|
private/keys/ops_db_test.go
|
VerseApp/ssb
|
628285b56f8cf0b5c2acf4c906390d7a88f63929
|
[
"Apache-2.0",
"MIT"
] | 20
|
2019-06-03T05:14:25.000Z
|
2022-03-23T16:12:59.000Z
|
// SPDX-FileCopyrightText: 2021 The Go-SSB Authors
//
// SPDX-License-Identifier: MIT
package keys
import (
"context"
"testing"
"github.com/dgraph-io/badger/v3"
"github.com/stretchr/testify/require"
librarian "go.cryptoscope.co/margaret/indexes"
libbadger "go.cryptoscope.co/margaret/indexes/badger"
"go.cryptoscope.co/ssb/repo"
"modernc.org/kv"
)
type opIndexNew struct {
DB **badger.DB
Type interface{}
Index *librarian.SeqSetterIndex
}
func (op opIndexNew) Do(t *testing.T, env interface{}) {
*op.Index = libbadger.NewIndex(*op.DB, op.Type)
require.NotNil(t, *op.Index, "libbadger.NewIndex returned nil")
}
type opIndexGet struct {
Index *librarian.SeqSetterIndex
Addr librarian.Addr
ExpValue interface{}
ExpGetErr string
ExpObsErr string
}
func (op opIndexGet) Do(t *testing.T, env interface{}) {
obs, gerr := (*op.Index).Get(context.TODO(), op.Addr)
if op.ExpGetErr == "" {
require.NoError(t, gerr, "unexpected error on idx.Get")
} else {
require.EqualError(t, gerr, op.ExpGetErr, "expected different error on idx.Get")
}
v, verr := obs.Value()
if op.ExpObsErr == "" {
require.NoError(t, verr, "unexpected error opening observable after idx.Get")
} else {
require.EqualError(t, verr, op.ExpObsErr, "expected different error opening observable after idx.Get")
}
require.Equal(t, op.ExpValue, v, "wrong value for addr:%q", op.Addr)
}
type opDBCreate struct {
Name string
ExpErr string
DB **badger.DB
}
func (op opDBCreate) Do(t *testing.T, env interface{}) {
var err error
*(op.DB), err = repo.OpenBadgerDB(op.Name)
if op.ExpErr == "" {
require.NoError(t, err, "unexpected error on kv.Create")
} else {
require.EqualError(t, err, op.ExpErr, "expected different error on kv.Create")
}
}
type opDBOpen struct {
Name string
ExpErr string
DB **badger.DB
}
func (op opDBOpen) Do(t *testing.T, env interface{}) {
var err error
*(op.DB), err = repo.OpenBadgerDB(op.Name)
if op.ExpErr == "" {
require.NoError(t, err, "unexpected error on kv.Open")
} else {
require.EqualError(t, err, op.ExpErr, "expected different error on kv.Open")
}
}
type opDBClose struct {
DB *kv.DB
ExpErr string
}
func (op opDBClose) Do(t *testing.T, env interface{}) {
err := op.DB.Close()
if op.ExpErr == "" {
require.NoError(t, err, "error closing db")
} else {
require.EqualErrorf(t, err, op.ExpErr, "expected close error %q but got: %v", op.ExpErr, err)
}
}
type opDBSet struct {
DB *kv.DB
Key, Value []byte
ExpErr string
}
func (op opDBSet) Do(t *testing.T, env interface{}) {
err := op.DB.Set(op.Key, op.Value)
if op.ExpErr == "" {
require.NoError(t, err, "error setting value in db")
} else {
require.EqualErrorf(t, err, op.ExpErr, "expected error setting value in db %q but got: %v", op.ExpErr, err)
}
}
type opDBGet struct {
DB **badger.DB
Key []byte
Log bool
ExpValue []byte
ExpErr string
}
func (op opDBGet) Do(t *testing.T, env interface{}) {
(*op.DB).View(func(txn *badger.Txn) error {
val, err := txn.Get(op.Key)
if op.ExpErr == "" {
require.NoError(t, err, "error getting value from db")
} else {
require.EqualErrorf(t, err, op.ExpErr, "expected error getting value from db %q but got: %v", op.ExpErr, err)
return nil
}
data, err := val.ValueCopy(nil)
if err != nil {
require.NoError(t, err, "did not get value")
return nil
}
if op.Log {
t.Logf("DB.Get - Key:%x Value:%x Exp:%x", op.Key, data, op.ExpValue)
}
require.Equal(t, op.ExpValue, data, "read wrong value from db")
return nil
})
}
| 23.11039
| 112
| 0.670413
|
385421c2e6a87e0f916d5094262fa6ac3d011df6
| 837
|
dart
|
Dart
|
lib/src/features/compose/misc/metadata_viewmodel.dart
|
MBaumgartenBR/elpcd_dart
|
d23a343fb05452d83c6ea226a37f61e99d3f13f1
|
[
"MIT"
] | 2
|
2020-05-20T17:54:08.000Z
|
2020-07-30T17:40:55.000Z
|
lib/src/features/compose/misc/metadata_viewmodel.dart
|
MBaumgartenBR/ElPCD
|
d23a343fb05452d83c6ea226a37f61e99d3f13f1
|
[
"MIT"
] | 4
|
2020-10-29T12:26:54.000Z
|
2020-11-12T15:36:11.000Z
|
lib/src/features/compose/misc/metadata_viewmodel.dart
|
mbaumgartenbr/elpcd_dart
|
d23a343fb05452d83c6ea226a37f61e99d3f13f1
|
[
"MIT"
] | 1
|
2020-07-30T17:42:16.000Z
|
2020-07-30T17:42:16.000Z
|
const kMetadadosEArqBrasil = <String>{
'Registro de Abertura',
'Registro de Desativação',
'Reativação da Classe',
'Registro de Mudança de Nome de Classe',
'Registro de Deslocamento de Classe',
'Registro de Extinção',
'Indicador de Classe Ativa/Inativa',
'Prazo de Guarda na Fase Corrente',
'Evento que Determina a Contagem do Prazo de Guarda na Fase Corrente',
'Prazo de Guarda na Fase Intermediária',
'Evento que Determina a Contagem do Prazo de Guarda na Fase Intermediária',
'Destinação Final',
'Registro de Alteração',
'Observações',
};
class MetadataViewModel {
MetadataViewModel({required this.type, this.content = ''});
final String type;
String content;
bool get isEmpty => content.isEmpty;
bool get isNotEmpty => content.isNotEmpty;
Map<String, String> toMap() => {type: content};
}
| 27.9
| 77
| 0.721625
|
4fca900cd81c9fe8232e237e1d15f7c35e517ff1
| 417
|
rb
|
Ruby
|
spec/ruby/core/thread/initialize_spec.rb
|
olsemeno/jruby
|
106dcc283f5be0dd9e9c0b0d73f604e3655321ed
|
[
"Ruby",
"Apache-2.0"
] | 2,793
|
2019-07-28T02:15:11.000Z
|
2022-03-30T02:52:20.000Z
|
spec/ruby/core/thread/initialize_spec.rb
|
olsemeno/jruby
|
106dcc283f5be0dd9e9c0b0d73f604e3655321ed
|
[
"Ruby",
"Apache-2.0"
] | 4,590
|
2015-01-01T01:36:06.000Z
|
2022-03-31T23:45:59.000Z
|
spec/ruby/core/thread/initialize_spec.rb
|
olsemeno/jruby
|
106dcc283f5be0dd9e9c0b0d73f604e3655321ed
|
[
"Ruby",
"Apache-2.0"
] | 617
|
2015-01-01T02:03:55.000Z
|
2022-03-17T22:36:36.000Z
|
require_relative '../../spec_helper'
require_relative 'fixtures/classes'
describe "Thread#initialize" do
describe "already initialized" do
before do
@t = Thread.new { sleep }
end
after do
@t.kill
@t.join
end
it "raises a ThreadError" do
-> {
@t.instance_eval do
initialize {}
end
}.should raise_error(ThreadError)
end
end
end
| 14.892857
| 39
| 0.589928
|
5d7ff57b5c2c8a3bf27e87bb779cbca23e13083c
| 2,346
|
sql
|
SQL
|
trms.sql
|
2004javausf/Project1PattonZ
|
ed238b5ce9bd93982155096500dca2e9031d5c99
|
[
"MIT"
] | null | null | null |
trms.sql
|
2004javausf/Project1PattonZ
|
ed238b5ce9bd93982155096500dca2e9031d5c99
|
[
"MIT"
] | 2
|
2020-06-18T17:34:22.000Z
|
2021-01-21T01:17:57.000Z
|
trms.sql
|
2004javausf/Project1PattonZ
|
ed238b5ce9bd93982155096500dca2e9031d5c99
|
[
"MIT"
] | null | null | null |
CREATE TABLE EMPLOYEE(
EMP_ID NUMBER PRIMARY KEY,
NAME_FIRST VARCHAR2 (50),
NAME_LAST VARCHAR2 (50),
EMAIL VARCHAR2 (50),
USER_NAME VARCHAR2 (50),
PASS_WORD VARCHAR2 (50),
AVAIL_REIM NUMBER);
INSERT INTO EMPLOYEE VALUES (3, 'Dave', 'Patton', 'davepat@email.com', 'DP', 'pass', 1000);
INSERT INTO EMPLOYEE VALUES (4, 'Jamie', 'Price', 'jamieprice@email.com', 'JP', 'pass', 1000);
CREATE TABLE TRMSFORM(
FORM_ID NUMBER PRIMARY KEY,
EMP_ID NUMBER,
NAME_FIRST VARCHAR2 (50),
NAME_LAST VARCHAR2 (50),
EMAIL VARCHAR2 (50),
COURSE_TITLE VARCHAR2 (50),
COURSE_TYPE VARCHAR2 (50),
COURSE_START_DATE VARCHAR2 (50),
COURSE_LOCATION VARCHAR2 (50),
COURSE_COST NUMBER,
GRADE_FORMAT VARCHAR (50),
MIN_GRADE VARCHAR2 (50),
ADD_DOC VARCHAR2 (50),
FINAL_GRADE VARCHAR2 (50),
SUP_APPDEN VARCHAR2 (50),
DH_APPDEN VARCHAR2 (50),
BENCO_APPDEN VARCHAR2 (50),
REIM_AMOUNT NUMBER);
DROP TABLE TRMSFORM;
CREATE SEQUENCE IDSEQ START WITH 100;
INSERT INTO EMPLOYEE VALUES (1, 'Zach', 'Patton', 'zacharypatton1991@gmail.com', 'ZP', 'pass', 1000);
SELECT * FROM EMPLOYEE WHERE EMP_ID = 1;
CREATE OR REPLACE PROCEDURE MAKEREQUEST
(EMP_ID IN NUMBER, NAME_FIRST IN VARCHAR2, NAME_LAST IN VARCHAR2, EMAIL IN VARCHAR2, COURSE_TITLE IN VARCHAR2, COURSE_TYPE IN VARCHAR2, COURSE_START_DATE IN VARCHAR2, COURSE_LOCATION IN VARCHAR2, COURSE_COST IN NUMBER, GRADE_FORMAT IN VARCHAR2, MIN_GRADE IN VARCHAR2)
AS
BEGIN
INSERT INTO TRMSFORM VALUES (IDSEQ.NEXTVAL, EMP_ID, NAME_FIRST, NAME_LAST, EMAIL, COURSE_TITLE, COURSE_TYPE, COURSE_START_DATE, COURSE_LOCATION, COURSE_COST, GRADE_FORMAT, MIN_GRADE, 'N/A', 'AWAITING', 'AWAITING APPROVAL', 'AWAITING APPROVAL', 'AWAITING APPROVAL', 0);
COMMIT;
END;
/
EXECUTE MAKEREQUEST(1, 'Zach', 'Patton', 'zacharypatton1991@gmail.com', 'RevPro', 'Software DevOp', '04-JULY-2020', 'Online', 200, 'Pass/Fail', 'Pass');
ALTER SESSION SET NLS_DATE_FORMAT = 'MM-DD-YYYY';
SELECT FORM_ID, COURSE_TITLE FROM TRMSFORM WHERE EMP_ID=1;
CREATE TABLE SUPERVISOR(
SUP_USER_NAME VARCHAR2(50) PRIMARY KEY,
SUP_PASS_WORD VARCHAR2 (50));
INSERT INTO SUPERVISOR VALUES ('ZP', 'pass');
CREATE TABLE DEPHEAD(
DH_USER_NAME VARCHAR2 (50) pRIMARY KEY,
DH_PASS_WORD VARCHAR2 (50));
INSERT INTO DEPHEAD VALUES ('DP', 'pass');
CREATE TABLE BENCO(
BC_USER_NAME VARCHAR2 (50) PRIMARY KEY,
BC_PASS_WORD VARCHAR2 (50));
INSERT INTO BENCO VALUES ('JP', 'pass');
| 32.136986
| 269
| 0.758738
|
0d90804e952325cfa8bb029621fe1cc9572a56af
| 1,912
|
cs
|
C#
|
sources/Interop/Windows/Windows/um/winioctl/FORMAT_EX_PARAMETERS.cs
|
JeremyKuhne/terrafx.interop.windows
|
337dab04103688027ccfbee0180568de552283de
|
[
"MIT"
] | null | null | null |
sources/Interop/Windows/Windows/um/winioctl/FORMAT_EX_PARAMETERS.cs
|
JeremyKuhne/terrafx.interop.windows
|
337dab04103688027ccfbee0180568de552283de
|
[
"MIT"
] | null | null | null |
sources/Interop/Windows/Windows/um/winioctl/FORMAT_EX_PARAMETERS.cs
|
JeremyKuhne/terrafx.interop.windows
|
337dab04103688027ccfbee0180568de552283de
|
[
"MIT"
] | null | null | null |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/winioctl.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop.Windows;
/// <include file='FORMAT_EX_PARAMETERS.xml' path='doc/member[@name="FORMAT_EX_PARAMETERS"]/*' />
public unsafe partial struct FORMAT_EX_PARAMETERS
{
/// <include file='FORMAT_EX_PARAMETERS.xml' path='doc/member[@name="FORMAT_EX_PARAMETERS.MediaType"]/*' />
public MEDIA_TYPE MediaType;
/// <include file='FORMAT_EX_PARAMETERS.xml' path='doc/member[@name="FORMAT_EX_PARAMETERS.StartCylinderNumber"]/*' />
[NativeTypeName("DWORD")]
public uint StartCylinderNumber;
/// <include file='FORMAT_EX_PARAMETERS.xml' path='doc/member[@name="FORMAT_EX_PARAMETERS.EndCylinderNumber"]/*' />
[NativeTypeName("DWORD")]
public uint EndCylinderNumber;
/// <include file='FORMAT_EX_PARAMETERS.xml' path='doc/member[@name="FORMAT_EX_PARAMETERS.StartHeadNumber"]/*' />
[NativeTypeName("DWORD")]
public uint StartHeadNumber;
/// <include file='FORMAT_EX_PARAMETERS.xml' path='doc/member[@name="FORMAT_EX_PARAMETERS.EndHeadNumber"]/*' />
[NativeTypeName("DWORD")]
public uint EndHeadNumber;
/// <include file='FORMAT_EX_PARAMETERS.xml' path='doc/member[@name="FORMAT_EX_PARAMETERS.FormatGapLength"]/*' />
[NativeTypeName("WORD")]
public ushort FormatGapLength;
/// <include file='FORMAT_EX_PARAMETERS.xml' path='doc/member[@name="FORMAT_EX_PARAMETERS.SectorsPerTrack"]/*' />
[NativeTypeName("WORD")]
public ushort SectorsPerTrack;
/// <include file='FORMAT_EX_PARAMETERS.xml' path='doc/member[@name="FORMAT_EX_PARAMETERS.SectorNumber"]/*' />
[NativeTypeName("WORD [1]")]
public fixed ushort SectorNumber[1];
}
| 45.52381
| 145
| 0.729079
|
14fb3e7e778f88a45b4b9ee4d392ac0d5a64f072
| 184
|
ts
|
TypeScript
|
pipeline.ts
|
emilniklas/pipeline.ts
|
afbc40c224e88a2e4df6bd3ab4520aea43d3d936
|
[
"MIT"
] | null | null | null |
pipeline.ts
|
emilniklas/pipeline.ts
|
afbc40c224e88a2e4df6bd3ab4520aea43d3d936
|
[
"MIT"
] | null | null | null |
pipeline.ts
|
emilniklas/pipeline.ts
|
afbc40c224e88a2e4df6bd3ab4520aea43d3d936
|
[
"MIT"
] | null | null | null |
/// <reference path="typings/tsd.d.ts" />
export * from "./src/pipeline"
export * from "./src/types"
import _Middleware from "./src/middleware"
export const Middleware = _Middleware
| 23
| 42
| 0.711957
|
1a5e949455541a42e802e76788aa01684ed7fd1f
| 775
|
py
|
Python
|
scripts/coverage_check.py
|
jbenden/pipeline
|
43c5196e466324007cf6e2e173d4610102d6a838
|
[
"MIT"
] | 30
|
2017-12-05T11:12:06.000Z
|
2021-11-06T18:27:58.000Z
|
scripts/coverage_check.py
|
jbenden/pipeline
|
43c5196e466324007cf6e2e173d4610102d6a838
|
[
"MIT"
] | 112
|
2017-10-15T12:13:38.000Z
|
2021-01-12T22:29:58.000Z
|
scripts/coverage_check.py
|
jbenden/pipeline
|
43c5196e466324007cf6e2e173d4610102d6a838
|
[
"MIT"
] | 6
|
2018-08-12T17:01:52.000Z
|
2021-08-17T06:05:24.000Z
|
#!/usr/bin/env python
import sys
def percentage(total, missing):
return (total - missing) * 100.0 / total
statements_total = int(sys.argv[1])
statements_missing = int(sys.argv[2])
statements_percentage = percentage(statements_total, statements_missing)
branches_total = int(sys.argv[3])
branches_missing = int(sys.argv[4])
branches_percentage = percentage(branches_total, branches_missing)
print("statement coverage: total: %4d, missing: %4d, percentage: %5.2f%%"
% (statements_total, statements_missing, statements_percentage))
print("branch coverage: total: %4d, missing: %4d, percentage: %5.2f%%"
% (branches_total, branches_missing, branches_percentage))
print("total coverage: %5.3f%%" % ((statements_percentage + branches_percentage) / 2.0))
| 35.227273
| 88
| 0.740645
|
1b36c8dab0e93ff70c1b095b190dbef95ebe26b1
| 514
|
rb
|
Ruby
|
config/routes.rb
|
kriti-rai/concert-spotter
|
949167498de2fae26defd8bab2835b3c38c73f85
|
[
"MIT"
] | 6
|
2019-04-21T01:00:04.000Z
|
2020-08-19T00:49:22.000Z
|
config/routes.rb
|
kriti-rai/concert-spotter
|
949167498de2fae26defd8bab2835b3c38c73f85
|
[
"MIT"
] | 13
|
2020-02-25T21:39:22.000Z
|
2022-03-30T23:04:35.000Z
|
config/routes.rb
|
kriti-rai/concert-spotter
|
949167498de2fae26defd8bab2835b3c38c73f85
|
[
"MIT"
] | 2
|
2019-11-11T22:41:25.000Z
|
2020-04-12T18:46:07.000Z
|
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
namespace :api do
resources :hikes, only: [:index]
resources :users, only: [:create]
resources :sessions, only: [:create]
get '/show' => 'users#show'
post '/add_favorite' => 'users#add_favorite'
post '/delete_favorite' => 'users#delete_favorite'
post '/clear_favorites' => 'users#clear_favorites'
post '/logout' => 'sessions#logout'
end
end
| 32.125
| 101
| 0.684825
|
5d60f4453a4e2c0bff29e205fc60cc7dd8f2b7f5
| 5,548
|
cpp
|
C++
|
src/core/transform/ojph_colour_sse2.cpp
|
jpambrun/OpenJPH
|
9cce6ed4a74b3dd0f0cdc48d90b595cd0b8d9030
|
[
"BSD-2-Clause"
] | null | null | null |
src/core/transform/ojph_colour_sse2.cpp
|
jpambrun/OpenJPH
|
9cce6ed4a74b3dd0f0cdc48d90b595cd0b8d9030
|
[
"BSD-2-Clause"
] | null | null | null |
src/core/transform/ojph_colour_sse2.cpp
|
jpambrun/OpenJPH
|
9cce6ed4a74b3dd0f0cdc48d90b595cd0b8d9030
|
[
"BSD-2-Clause"
] | null | null | null |
/****************************************************************************/
// This software is released under the 2-Clause BSD license, included
// below.
//
// Copyright (c) 2019, Aous Naman
// Copyright (c) 2019, Kakadu Software Pty Ltd, Australia
// Copyright (c) 2019, The University of New South Wales, Australia
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/****************************************************************************/
// This file is part of the OpenJPH software implementation.
// File: ojph_colour_sse2.cpp
// Author: Aous Naman
// Date: 11 October 2019
/****************************************************************************/
#include <cmath>
#include "ojph_defs.h"
#include "ojph_arch.h"
#include "ojph_colour.h"
#ifdef OJPH_COMPILER_MSVC
#include <intrin.h>
#else
#include <x86intrin.h>
#endif
namespace ojph {
namespace local {
//////////////////////////////////////////////////////////////////////////
void sse2_cnvrt_float_to_si32_shftd(const float *sp, si32 *dp, float mul,
int width)
{
uint32_t rounding_mode = _MM_GET_ROUNDING_MODE();
_MM_SET_ROUNDING_MODE(_MM_ROUND_NEAREST);
__m128 shift = _mm_set1_ps(0.5f);
__m128 m = _mm_set1_ps(mul);
for (int i = (width + 3) >> 2; i > 0; --i, sp+=4, dp+=4)
{
__m128 t = _mm_loadu_ps(sp);
__m128 s = _mm_add_ps(t, shift);
s = _mm_mul_ps(s, m);
_mm_storeu_si128((__m128i*)dp, _mm_cvtps_epi32(s));
}
_MM_SET_ROUNDING_MODE(rounding_mode);
}
//////////////////////////////////////////////////////////////////////////
void sse2_cnvrt_float_to_si32(const float *sp, si32 *dp, float mul,
int width)
{
uint32_t rounding_mode = _MM_GET_ROUNDING_MODE();
_MM_SET_ROUNDING_MODE(_MM_ROUND_NEAREST);
__m128 m = _mm_set1_ps(mul);
for (int i = (width + 3) >> 2; i > 0; --i, sp+=4, dp+=4)
{
__m128 t = _mm_loadu_ps(sp);
__m128 s = _mm_mul_ps(t, m);
_mm_storeu_si128((__m128i*)dp, _mm_cvtps_epi32(s));
}
_MM_SET_ROUNDING_MODE(rounding_mode);
}
//////////////////////////////////////////////////////////////////////////
void sse2_cnvrt_si32_to_si32_shftd(const si32 *sp, si32 *dp, int shift,
int width)
{
__m128i sh = _mm_set1_epi32(shift);
for (int i = (width + 3) >> 2; i > 0; --i, sp+=4, dp+=4)
{
__m128i s = _mm_loadu_si128((__m128i*)sp);
s = _mm_add_epi32(s, sh);
_mm_storeu_si128((__m128i*)dp, s);
}
}
//////////////////////////////////////////////////////////////////////////
void sse2_rct_forward(const si32 *r, const si32 *g, const si32 *b,
si32 *y, si32 *cb, si32 *cr, int repeat)
{
for (int i = (repeat + 3) >> 2; i > 0; --i)
{
__m128i mr = _mm_load_si128((__m128i*)r);
__m128i mg = _mm_load_si128((__m128i*)g);
__m128i mb = _mm_load_si128((__m128i*)b);
__m128i t = _mm_add_epi32(mr, mb);
t = _mm_add_epi32(t, _mm_slli_epi32(mg, 1));
_mm_store_si128((__m128i*)y, _mm_srai_epi32(t, 2));
t = _mm_sub_epi32(mb, mg);
_mm_store_si128((__m128i*)cb, t);
t = _mm_sub_epi32(mr, mg);
_mm_store_si128((__m128i*)cr, t);
r += 4; g += 4; b += 4;
y += 4; cb += 4; cr += 4;
}
}
//////////////////////////////////////////////////////////////////////////
void sse2_rct_backward(const si32 *y, const si32 *cb, const si32 *cr,
si32 *r, si32 *g, si32 *b, int repeat)
{
for (int i = (repeat + 3) >> 2; i > 0; --i)
{
__m128i my = _mm_load_si128((__m128i*)y);
__m128i mcb = _mm_load_si128((__m128i*)cb);
__m128i mcr = _mm_load_si128((__m128i*)cr);
__m128i t = _mm_add_epi32(mcb, mcr);
t = _mm_sub_epi32(my, _mm_srai_epi32(t, 2));
_mm_store_si128((__m128i*)g, t);
__m128i u = _mm_add_epi32(mcb, t);
_mm_store_si128((__m128i*)b, u);
u = _mm_add_epi32(mcr, t);
_mm_store_si128((__m128i*)r, u);
y += 4; cb += 4; cr += 4;
r += 4; g += 4; b += 4;
}
}
}
}
| 37.486486
| 78
| 0.550108
|
25abe540a714bb0c1afe7c03abc176c8d4f0bc12
| 4,340
|
swift
|
Swift
|
OCBCDemo/OCBCDemo/ViewControllers/Transfer/Transfer+Extension.swift
|
lazyworkaholics/iOS-ocbc-mdt-demo
|
4d88a5fc773c4f6ac3000d85043024e29ebb9b58
|
[
"MIT"
] | null | null | null |
OCBCDemo/OCBCDemo/ViewControllers/Transfer/Transfer+Extension.swift
|
lazyworkaholics/iOS-ocbc-mdt-demo
|
4d88a5fc773c4f6ac3000d85043024e29ebb9b58
|
[
"MIT"
] | null | null | null |
OCBCDemo/OCBCDemo/ViewControllers/Transfer/Transfer+Extension.swift
|
lazyworkaholics/iOS-ocbc-mdt-demo
|
4d88a5fc773c4f6ac3000d85043024e29ebb9b58
|
[
"MIT"
] | null | null | null |
//
// TransferViewController+UIExtension.swift
// OCBCDemo
//
// Created by Pabbineedi Harsha on 31/10/21.
//
import UIKit
extension TransferViewController {
func setupUILayout() {
self.view.backgroundColor = UIColor.init(named: CUSTOM_COLOR.BACKGROUND.SECONDARY)
self.title = LITERAL.TRANSFER_TITLE
collectionView.backgroundColor = .clear
collectionView.register(TextFieldCell.self, forCellWithReuseIdentifier: TextFieldCell.reuseidentifier())
collectionView.register(ButtonCell.self, forCellWithReuseIdentifier: ButtonCell.reuseidentifier())
collectionView.delegate = self
collectionView.dataSource = self
collectionView.wrap(into: self, with: .zero)
activityindicator.hidesWhenStopped = true
activityindicator.color = UIColor.init(named: CUSTOM_COLOR.TINT.SECONDARY)
activityindicator.wrap(into: self.view, contentMode: .centerWithSize(CGSize.init(width: 20, height: 20)))
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard (_:)))
self.view.addGestureRecognizer(tapGesture)
}
@objc func dismissKeyboard (_ sender: UITapGestureRecognizer) {
for cell in collectionView.visibleCells {
if cell.isKind(of: TextFieldCell.self) {
(cell as! TextFieldCell).textField.resignFirstResponder()
}
}
}
func setupBarButtons() {
let rigthBarButton = UIBarButtonItem.init(title: "Logout", style: .done, target: self, action: #selector(logout))
rigthBarButton.tintColor = .white
navigationItem.rightBarButtonItem = rigthBarButton
let leftBarButton = UIBarButtonItem.init(image: UIImage.init(named: ICON.BACK), style: .done, target: self, action: #selector(back))
leftBarButton.tintColor = .white
navigationItem.leftBarButtonItem = leftBarButton
}
@objc fileprivate func logout() {
viewModel.logout()
}
@objc fileprivate func back() {
viewModel.back()
}
}
extension TransferViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 4
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.section == 3 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ButtonCell.reuseidentifier(), for: indexPath) as! ButtonCell
if cell.button == nil {
cell.setupLayout()
cell.delegate = self
}
cell.loadData(LITERAL.SEND, indexPath: indexPath)
return cell
}
else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: TextFieldCell.reuseidentifier(), for: indexPath) as! TextFieldCell
if cell.textField == nil {
cell.setupLayout( isLeftLabel: true)
}
switch indexPath.section {
case 0:
cell.loadData(leftLabelText: viewModel.getAccountName(), text: viewModel.getAccountNumber(), placeholder: "", indexPath: indexPath)
cell.textField.keyboardType = .numberPad
case 1:
cell.loadData(leftLabelText: LITERAL.AMOUNT, text: "", placeholder: "", indexPath: indexPath)
cell.textField.keyboardType = .decimalPad
default:
cell.loadData(leftLabelText: LITERAL.DESC, text: "", placeholder: "", indexPath: indexPath)
}
cell.textField.delegate = self
return cell
}
}
}
extension TransferViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let window = UIApplication.shared.windows[0]
return CGSize.init(width: window.rootViewController!.view.bounds.width, height: TextFieldCell.height)
}
}
| 38.75
| 160
| 0.654839
|
a183d05a3dd350aab5cacfdaa01c4d64030e9ce9
| 365
|
ts
|
TypeScript
|
src/core/errors/exceptions/swyft-ok.exception.ts
|
sabival89/swyft
|
c0d8b9d53b275474adbc7c79ec69c74465d671fb
|
[
"MIT"
] | 1
|
2021-05-05T14:32:44.000Z
|
2021-05-05T14:32:44.000Z
|
src/core/errors/exceptions/swyft-ok.exception.ts
|
sabival89/swyft
|
c0d8b9d53b275474adbc7c79ec69c74465d671fb
|
[
"MIT"
] | null | null | null |
src/core/errors/exceptions/swyft-ok.exception.ts
|
sabival89/swyft
|
c0d8b9d53b275474adbc7c79ec69c74465d671fb
|
[
"MIT"
] | null | null | null |
import { HttpException, HttpStatus } from '@nestjs/common';
/**
* Http OK Response
*/
export class Swyft_OKException extends HttpException {
/**
* Swyft Http OK Response Exception
* @param message
*/
constructor(message: string) {
super(
{
status: HttpStatus.OK,
message: message,
},
HttpStatus.OK
);
}
}
| 17.380952
| 59
| 0.60274
|
b0f42d8aba628bf5ac94071308e7261ea7373d80
| 55,132
|
c
|
C
|
retro/cores/nes/src/drivers/libretro/libretro.c
|
MatPoliquin/retro
|
c70c174a9818d1e97bc36e61abb4694d28fc68e1
|
[
"MIT-0",
"MIT"
] | 2,706
|
2018-04-05T18:28:50.000Z
|
2022-03-29T16:56:59.000Z
|
retro/cores/nes/src/drivers/libretro/libretro.c
|
MatPoliquin/retro
|
c70c174a9818d1e97bc36e61abb4694d28fc68e1
|
[
"MIT-0",
"MIT"
] | 242
|
2018-04-05T22:30:42.000Z
|
2022-03-19T01:55:11.000Z
|
retro/cores/nes/src/drivers/libretro/libretro.c
|
MatPoliquin/retro
|
c70c174a9818d1e97bc36e61abb4694d28fc68e1
|
[
"MIT-0",
"MIT"
] | 464
|
2018-04-05T19:10:34.000Z
|
2022-03-28T13:33:32.000Z
|
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include "libretro.h"
#include "../../fceu.h"
#include "../../fceu-endian.h"
#include "../../input.h"
#include "../../state.h"
#include "../../ppu.h"
#include "../../cart.h"
#include "../../x6502.h"
#include "../../git.h"
#include "../../palette.h"
#include "../../sound.h"
#include "../../file.h"
#include "../../cheat.h"
#include "../../ines.h"
#include "../../unif.h"
#include "../../fds.h"
#include "../../vsuni.h"
#include "../../video.h"
#include "libretro-common/include/streams/memory_stream.h"
#define NES_8_7_PAR (width * (8.0 / 7.0)) / height
#define NES_4_3 4.0 / 3.0
#if defined(_3DS)
void* linearMemAlign(size_t size, size_t alignment);
void linearFree(void* mem);
#endif
static retro_video_refresh_t video_cb = NULL;
static retro_input_poll_t poll_cb = NULL;
static retro_input_state_t input_cb = NULL;
static retro_audio_sample_batch_t audio_batch_cb = NULL;
static retro_environment_t environ_cb = NULL;
static bool use_overscan;
static bool use_raw_palette;
static bool use_par;
int turbo_enabler;
int turbo_delay;
static int regionoverride = -1;
/* emulator-specific variables */
/* overclock the console by adding dummy scanlines to PPU loop
* disables DMC DMA and WaveHi filling for these dummies
* doesn't work with new PPU */
unsigned overclocked = 0;
/* 7-bit samples have priority over overclocking */
unsigned skip_7bit_overclocking = 1;
unsigned normal_scanlines = 240;
unsigned extrascanlines = 0;
unsigned overclock_state = -1;
unsigned dendy = 0;
int FCEUnetplay;
#ifdef PSP
#include "pspgu.h"
static __attribute__((aligned(16))) uint16_t retro_palette[256];
#else
static uint16_t retro_palette[256];
#endif
static uint16_t* fceu_video_out;
/* Some timing-related variables. */
static int soundo = 1;
static volatile int nofocus = 0;
static int32_t *sound = 0;
static uint32_t JSReturn[2];
static uint32_t current_palette = 0;
int PPUViewScanline=0;
int PPUViewer=0;
/* extern forward decls.*/
extern FCEUGI *GameInfo;
extern uint8 *XBuf;
extern CartInfo iNESCart;
extern CartInfo UNIFCart;
/* emulator-specific callback functions */
void UpdatePPUView(int refreshchr) { }
const char * GetKeyboard(void)
{
return "";
}
int FCEUD_SendData(void *data, uint32 len)
{
return 1;
}
#define BUILD_PIXEL_RGB565(R,G,B) (((int) ((R)&0x1f) << RED_SHIFT) | ((int) ((G)&0x3f) << GREEN_SHIFT) | ((int) ((B)&0x1f) << BLUE_SHIFT))
#if defined (PSP)
#define RED_SHIFT 0
#define GREEN_SHIFT 5
#define BLUE_SHIFT 11
#define RED_EXPAND 3
#define GREEN_EXPAND 2
#define BLUE_EXPAND 3
#elif defined (FRONTEND_SUPPORTS_RGB565)
#define RED_SHIFT 11
#define GREEN_SHIFT 5
#define BLUE_SHIFT 0
#define RED_EXPAND 3
#define GREEN_EXPAND 2
#define BLUE_EXPAND 3
#define RED_MASK 0xF800
#define GREEN_MASK 0x7e0
#define BLUE_MASK 0x1f
#else
#define RED_SHIFT 10
#define GREEN_SHIFT 5
#define BLUE_SHIFT 0
#define RED_EXPAND 3
#define GREEN_EXPAND 3
#define BLUE_EXPAND 3
#endif
void FCEUD_SetPalette(unsigned char index, unsigned char r, unsigned char g, unsigned char b)
{
#ifdef FRONTEND_SUPPORTS_RGB565
retro_palette[index] = BUILD_PIXEL_RGB565(r >> RED_EXPAND, g >> GREEN_EXPAND, b >> BLUE_EXPAND);
#else
retro_palette[index] =
((r >> RED_EXPAND) << RED_SHIFT) | ((g >> GREEN_EXPAND) << GREEN_SHIFT) | ((b >> BLUE_EXPAND) << BLUE_SHIFT);
#endif
}
void FCEUD_GetPalette(unsigned char i, unsigned char *r, unsigned char *g, unsigned char *b)
{
}
bool FCEUD_ShouldDrawInputAids (void)
{
return 1;
}
static struct retro_log_callback log_cb;
static void default_logger(enum retro_log_level level, const char *fmt, ...) {}
void FCEUD_PrintError(char *c)
{
log_cb.log(RETRO_LOG_WARN, "%s", c);
}
void FCEUD_Message(char *s)
{
log_cb.log(RETRO_LOG_INFO, "%s", s);
}
void FCEUD_DispMessage(char *m)
{ struct retro_message msg;
msg.msg = m;
msg.frames = 180;
environ_cb(RETRO_ENVIRONMENT_SET_MESSAGE, &msg);
}
void FCEUD_NetworkClose(void)
{ }
void FCEUD_SoundToggle (void)
{
FCEUI_SetSoundVolume(100);
}
void FCEUD_VideoChanged (void)
{ }
FILE *FCEUD_UTF8fopen(const char *n, const char *m)
{
if (n)
return fopen(n, m);
else
return NULL;
}
#define MAX_PATH 1024
/*palette for FCEU*/
#define MAXPAL 25
struct st_palettes {
char name[32];
char desc[32];
unsigned int data[64];
};
struct st_palettes palettes[] = {
{ "asqrealc", "AspiringSquire's Real palette",
{ 0x6c6c6c, 0x00268e, 0x0000a8, 0x400094,
0x700070, 0x780040, 0x700000, 0x621600,
0x442400, 0x343400, 0x005000, 0x004444,
0x004060, 0x000000, 0x101010, 0x101010,
0xbababa, 0x205cdc, 0x3838ff, 0x8020f0,
0xc000c0, 0xd01474, 0xd02020, 0xac4014,
0x7c5400, 0x586400, 0x008800, 0x007468,
0x00749c, 0x202020, 0x101010, 0x101010,
0xffffff, 0x4ca0ff, 0x8888ff, 0xc06cff,
0xff50ff, 0xff64b8, 0xff7878, 0xff9638,
0xdbab00, 0xa2ca20, 0x4adc4a, 0x2ccca4,
0x1cc2ea, 0x585858, 0x101010, 0x101010,
0xffffff, 0xb0d4ff, 0xc4c4ff, 0xe8b8ff,
0xffb0ff, 0xffb8e8, 0xffc4c4, 0xffd4a8,
0xffe890, 0xf0f4a4, 0xc0ffc0, 0xacf4f0,
0xa0e8ff, 0xc2c2c2, 0x202020, 0x101010 }
},
{ "loopy", "Loopy's palette",
{ 0x757575, 0x271b8f, 0x0000ab, 0x47009f,
0x8f0077, 0xab0013, 0xa70000, 0x7f0b00,
0x432f00, 0x004700, 0x005100, 0x003f17,
0x1b3f5f, 0x000000, 0x000000, 0x000000,
0xbcbcbc, 0x0073ef, 0x233bef, 0x8300f3,
0xbf00bf, 0xe7005b, 0xdb2b00, 0xcb4f0f,
0x8b7300, 0x009700, 0x00ab00, 0x00933b,
0x00838b, 0x000000, 0x000000, 0x000000,
0xffffff, 0x3fbfff, 0x5f97ff, 0xa78bfd,
0xf77bff, 0xff77b7, 0xff7763, 0xff9b3b,
0xf3bf3f, 0x83d313, 0x4fdf4b, 0x58f898,
0x00ebdb, 0x000000, 0x000000, 0x000000,
0xffffff, 0xabe7ff, 0xc7d7ff, 0xd7cbff,
0xffc7ff, 0xffc7db, 0xffbfb3, 0xffdbab,
0xffe7a3, 0xe3ffa3, 0xabf3bf, 0xb3ffcf,
0x9ffff3, 0x000000, 0x000000, 0x000000 }
},
{ "quor", "Quor's palette",
{ 0x3f3f3f, 0x001f3f, 0x00003f, 0x1f003f,
0x3f003f, 0x3f0020, 0x3f0000, 0x3f2000,
0x3f3f00, 0x203f00, 0x003f00, 0x003f20,
0x003f3f, 0x000000, 0x000000, 0x000000,
0x7f7f7f, 0x405f7f, 0x40407f, 0x5f407f,
0x7f407f, 0x7f4060, 0x7f4040, 0x7f6040,
0x7f7f40, 0x607f40, 0x407f40, 0x407f60,
0x407f7f, 0x000000, 0x000000, 0x000000,
0xbfbfbf, 0x809fbf, 0x8080bf, 0x9f80bf,
0xbf80bf, 0xbf80a0, 0xbf8080, 0xbfa080,
0xbfbf80, 0xa0bf80, 0x80bf80, 0x80bfa0,
0x80bfbf, 0x000000, 0x000000, 0x000000,
0xffffff, 0xc0dfff, 0xc0c0ff, 0xdfc0ff,
0xffc0ff, 0xffc0e0, 0xffc0c0, 0xffe0c0,
0xffffc0, 0xe0ffc0, 0xc0ffc0, 0xc0ffe0,
0xc0ffff, 0x000000, 0x000000, 0x000000 }
},
{ "chris", "Chris Covell's palette",
{ 0x808080, 0x003DA6, 0x0012B0, 0x440096,
0xA1005E, 0xC70028, 0xBA0600, 0x8C1700,
0x5C2F00, 0x104500, 0x054A00, 0x00472E,
0x004166, 0x000000, 0x050505, 0x050505,
0xC7C7C7, 0x0077FF, 0x2155FF, 0x8237FA,
0xEB2FB5, 0xFF2950, 0xFF2200, 0xD63200,
0xC46200, 0x358000, 0x058F00, 0x008A55,
0x0099CC, 0x212121, 0x090909, 0x090909,
0xFFFFFF, 0x0FD7FF, 0x69A2FF, 0xD480FF,
0xFF45F3, 0xFF618B, 0xFF8833, 0xFF9C12,
0xFABC20, 0x9FE30E, 0x2BF035, 0x0CF0A4,
0x05FBFF, 0x5E5E5E, 0x0D0D0D, 0x0D0D0D,
0xFFFFFF, 0xA6FCFF, 0xB3ECFF, 0xDAABEB,
0xFFA8F9, 0xFFABB3, 0xFFD2B0, 0xFFEFA6,
0xFFF79C, 0xD7E895, 0xA6EDAF, 0xA2F2DA,
0x99FFFC, 0xDDDDDD, 0x111111, 0x111111 }
},
{ "matt", "Matthew Conte's palette",
{ 0x808080, 0x0000bb, 0x3700bf, 0x8400a6,
0xbb006a, 0xb7001e, 0xb30000, 0x912600,
0x7b2b00, 0x003e00, 0x00480d, 0x003c22,
0x002f66, 0x000000, 0x050505, 0x050505,
0xc8c8c8, 0x0059ff, 0x443cff, 0xb733cc,
0xff33aa, 0xff375e, 0xff371a, 0xd54b00,
0xc46200, 0x3c7b00, 0x1e8415, 0x009566,
0x0084c4, 0x111111, 0x090909, 0x090909,
0xffffff, 0x0095ff, 0x6f84ff, 0xd56fff,
0xff77cc, 0xff6f99, 0xff7b59, 0xff915f,
0xffa233, 0xa6bf00, 0x51d96a, 0x4dd5ae,
0x00d9ff, 0x666666, 0x0d0d0d, 0x0d0d0d,
0xffffff, 0x84bfff, 0xbbbbff, 0xd0bbff,
0xffbfea, 0xffbfcc, 0xffc4b7, 0xffccae,
0xffd9a2, 0xcce199, 0xaeeeb7, 0xaaf7ee,
0xb3eeff, 0xdddddd, 0x111111, 0x111111 }
},
{ "pasofami", "PasoFami/99 palette",
{ 0x7f7f7f, 0x0000ff, 0x0000bf, 0x472bbf,
0x970087, 0xab0023, 0xab1300, 0x8b1700,
0x533000, 0x007800, 0x006b00, 0x005b00,
0x004358, 0x000000, 0x000000, 0x000000,
0xbfbfbf, 0x0078f8, 0x0058f8, 0x6b47ff,
0xdb00cd, 0xe7005b, 0xf83800, 0xe75f13,
0xaf7f00, 0x00b800, 0x00ab00, 0x00ab47,
0x008b8b, 0x000000, 0x000000, 0x000000,
0xf8f8f8, 0x3fbfff, 0x6b88ff, 0x9878f8,
0xf878f8, 0xf85898, 0xf87858, 0xffa347,
0xf8b800, 0xb8f818, 0x5bdb57, 0x58f898,
0x00ebdb, 0x787878, 0x000000, 0x000000,
0xffffff, 0xa7e7ff, 0xb8b8f8, 0xd8b8f8,
0xf8b8f8, 0xfba7c3, 0xf0d0b0, 0xffe3ab,
0xfbdb7b, 0xd8f878, 0xb8f8b8, 0xb8f8d8,
0x00ffff, 0xf8d8f8, 0x000000, 0x000000 }
},
{ "crashman", "CrashMan's palette",
{ 0x585858, 0x001173, 0x000062, 0x472bbf,
0x970087, 0x910009, 0x6f1100, 0x4c1008,
0x371e00, 0x002f00, 0x005500, 0x004d15,
0x002840, 0x000000, 0x000000, 0x000000,
0xa0a0a0, 0x004499, 0x2c2cc8, 0x590daa,
0xae006a, 0xb00040, 0xb83418, 0x983010,
0x704000, 0x308000, 0x207808, 0x007b33,
0x1c6888, 0x000000, 0x000000, 0x000000,
0xf8f8f8, 0x267be1, 0x5870f0, 0x9878f8,
0xff73c8, 0xf060a8, 0xd07b37, 0xe09040,
0xf8b300, 0x8cbc00, 0x40a858, 0x58f898,
0x00b7bf, 0x787878, 0x000000, 0x000000,
0xffffff, 0xa7e7ff, 0xb8b8f8, 0xd8b8f8,
0xe6a6ff, 0xf29dc4, 0xf0c0b0, 0xfce4b0,
0xe0e01e, 0xd8f878, 0xc0e890, 0x95f7c8,
0x98e0e8, 0xf8d8f8, 0x000000, 0x000000 }
},
{ "mess", "MESS palette",
{ 0x747474, 0x24188c, 0x0000a8, 0x44009c,
0x8c0074, 0xa80010, 0xa40000, 0x7c0800,
0x402c00, 0x004400, 0x005000, 0x003c14,
0x183c5c, 0x000000, 0x000000, 0x000000,
0xbcbcbc, 0x0070ec, 0x2038ec, 0x8000f0,
0xbc00bc, 0xe40058, 0xd82800, 0xc84c0c,
0x887000, 0x009400, 0x00a800, 0x009038,
0x008088, 0x000000, 0x000000, 0x000000,
0xfcfcfc, 0x3cbcfc, 0x5c94fc, 0x4088fc,
0xf478fc, 0xfc74b4, 0xfc7460, 0xfc9838,
0xf0bc3c, 0x80d010, 0x4cdc48, 0x58f898,
0x00e8d8, 0x000000, 0x000000, 0x000000,
0xfcfcfc, 0xa8e4fc, 0xc4d4fc, 0xd4c8fc,
0xfcc4fc, 0xfcc4d8, 0xfcbcb0, 0xfcd8a8,
0xfce4a0, 0xe0fca0, 0xa8f0bc, 0xb0fccc,
0x9cfcf0, 0x000000, 0x000000, 0x000000 }
},
{ "zaphod-cv", "Zaphod's VS Castlevania palette",
{ 0x7f7f7f, 0xffa347, 0x0000bf, 0x472bbf,
0x970087, 0xf85898, 0xab1300, 0xf8b8f8,
0xbf0000, 0x007800, 0x006b00, 0x005b00,
0xffffff, 0x9878f8, 0x000000, 0x000000,
0xbfbfbf, 0x0078f8, 0xab1300, 0x6b47ff,
0x00ae00, 0xe7005b, 0xf83800, 0x7777ff,
0xaf7f00, 0x00b800, 0x00ab00, 0x00ab47,
0x008b8b, 0x000000, 0x000000, 0x472bbf,
0xf8f8f8, 0xffe3ab, 0xf87858, 0x9878f8,
0x0078f8, 0xf85898, 0xbfbfbf, 0xffa347,
0xc800c8, 0xb8f818, 0x7f7f7f, 0x007800,
0x00ebdb, 0x000000, 0x000000, 0xffffff,
0xffffff, 0xa7e7ff, 0x5bdb57, 0xe75f13,
0x004358, 0x0000ff, 0xe7005b, 0x00b800,
0xfbdb7b, 0xd8f878, 0x8b1700, 0xffe3ab,
0x00ffff, 0xab0023, 0x000000, 0x000000 }
},
{ "zaphod-smb", "Zaphod's VS SMB palette",
{ 0x626a00, 0x0000ff, 0x006a77, 0x472bbf,
0x970087, 0xab0023, 0xab1300, 0xb74800,
0xa2a2a2, 0x007800, 0x006b00, 0x005b00,
0xffd599, 0xffff00, 0x009900, 0x000000,
0xff66ff, 0x0078f8, 0x0058f8, 0x6b47ff,
0x000000, 0xe7005b, 0xf83800, 0xe75f13,
0xaf7f00, 0x00b800, 0x5173ff, 0x00ab47,
0x008b8b, 0x000000, 0x91ff88, 0x000088,
0xf8f8f8, 0x3fbfff, 0x6b0000, 0x4855f8,
0xf878f8, 0xf85898, 0x595958, 0xff009d,
0x002f2f, 0xb8f818, 0x5bdb57, 0x58f898,
0x00ebdb, 0x787878, 0x000000, 0x000000,
0xffffff, 0xa7e7ff, 0x590400, 0xbb0000,
0xf8b8f8, 0xfba7c3, 0xffffff, 0x00e3e1,
0xfbdb7b, 0xffae00, 0xb8f8b8, 0xb8f8d8,
0x00ff00, 0xf8d8f8, 0xffaaaa, 0x004000 }
},
{ "vs-drmar", "VS Dr. Mario palette",
{ 0x5f97ff, 0x000000, 0x000000, 0x47009f,
0x00ab00, 0xffffff, 0xabe7ff, 0x000000,
0x000000, 0x000000, 0x000000, 0x000000,
0xe7005b, 0x000000, 0x000000, 0x000000,
0x5f97ff, 0x000000, 0x000000, 0x000000,
0x000000, 0x8b7300, 0xcb4f0f, 0x000000,
0xbcbcbc, 0x000000, 0x000000, 0x000000,
0x000000, 0x000000, 0x000000, 0x000000,
0x00ebdb, 0x000000, 0x000000, 0x000000,
0x000000, 0xff9b3b, 0x000000, 0x000000,
0x83d313, 0x000000, 0x3fbfff, 0x000000,
0x0073ef, 0x000000, 0x000000, 0x000000,
0x00ebdb, 0x000000, 0x000000, 0x000000,
0x000000, 0x000000, 0xf3bf3f, 0x000000,
0x005100, 0x000000, 0xc7d7ff, 0xffdbab,
0x000000, 0x000000, 0x000000, 0x000000 }
},
{ "vs-cv", "VS Castlevania palette",
{ 0xaf7f00, 0xffa347, 0x008b8b, 0x472bbf,
0x970087, 0xf85898, 0xab1300, 0xf8b8f8,
0xf83800, 0x007800, 0x006b00, 0x005b00,
0xffffff, 0x9878f8, 0x00ab00, 0x000000,
0xbfbfbf, 0x0078f8, 0xab1300, 0x6b47ff,
0x000000, 0xe7005b, 0xf83800, 0x6b88ff,
0xaf7f00, 0x00b800, 0x6b88ff, 0x00ab47,
0x008b8b, 0x000000, 0x000000, 0x472bbf,
0xf8f8f8, 0xffe3ab, 0xf87858, 0x9878f8,
0x0078f8, 0xf85898, 0xbfbfbf, 0xffa347,
0x004358, 0xb8f818, 0x7f7f7f, 0x007800,
0x00ebdb, 0x000000, 0x000000, 0xffffff,
0xffffff, 0xa7e7ff, 0x5bdb57, 0x6b88ff,
0x004358, 0x0000ff, 0xe7005b, 0x00b800,
0xfbdb7b, 0xffa347, 0x8b1700, 0xffe3ab,
0xb8f818, 0xab0023, 0x000000, 0x007800 }
},
{ "vs-smb", "VS SMB/VS Ice Climber palette",
{ 0xaf7f00, 0x0000ff, 0x008b8b, 0x472bbf,
0x970087, 0xab0023, 0x0000ff, 0xe75f13,
0xbfbfbf, 0x007800, 0x5bdb57, 0x005b00,
0xf0d0b0, 0xffe3ab, 0x00ab00, 0x000000,
0xbfbfbf, 0x0078f8, 0x0058f8, 0x6b47ff,
0x000000, 0xe7005b, 0xf83800, 0xf87858,
0xaf7f00, 0x00b800, 0x6b88ff, 0x00ab47,
0x008b8b, 0x000000, 0x000000, 0x3fbfff,
0xf8f8f8, 0x006b00, 0x8b1700, 0x9878f8,
0x6b47ff, 0xf85898, 0x7f7f7f, 0xe7005b,
0x004358, 0xb8f818, 0x0078f8, 0x58f898,
0x00ebdb, 0xfbdb7b, 0x000000, 0x000000,
0xffffff, 0xa7e7ff, 0xb8b8f8, 0xf83800,
0xf8b8f8, 0xfba7c3, 0xffffff, 0x00ffff,
0xfbdb7b, 0xffa347, 0xb8f8b8, 0xb8f8d8,
0xb8f818, 0xf8d8f8, 0x000000, 0x007800 }
},
{ "nintendo-vc", "Virtual Console palette",
{ 0x494949, 0x00006a, 0x090063, 0x290059,
0x42004a, 0x490000, 0x420000, 0x291100,
0x182700, 0x003010, 0x003000, 0x002910,
0x012043, 0x000000, 0x000000, 0x000000,
0x747174, 0x003084, 0x3101ac, 0x4b0194,
0x64007b, 0x6b0039, 0x6b2101, 0x5a2f00,
0x424900, 0x185901, 0x105901, 0x015932,
0x01495a, 0x101010, 0x000000, 0x000000,
0xadadad, 0x4a71b6, 0x6458d5, 0x8450e6,
0xa451ad, 0xad4984, 0xb5624a, 0x947132,
0x7b722a, 0x5a8601, 0x388e31, 0x318e5a,
0x398e8d, 0x383838, 0x000000, 0x000000,
0xb6b6b6, 0x8c9db5, 0x8d8eae, 0x9c8ebc,
0xa687bc, 0xad8d9d, 0xae968c, 0x9c8f7c,
0x9c9e72, 0x94a67c, 0x84a77b, 0x7c9d84,
0x73968d, 0xdedede, 0x000000, 0x000000 }
},
{ "yuv-v3", "FBX's YUV-V3 palette",
{ 0x666666, 0x002A88, 0x1412A7, 0x3B00A4,
0x5C007E, 0x6E0040, 0x6C0700, 0x561D00,
0x333500, 0x0C4800, 0x005200, 0x004C18,
0x003E5B, 0x000000, 0x000000, 0x000000,
0xADADAD, 0x155FD9, 0x4240FF, 0x7527FE,
0xA01ACC, 0xB71E7B, 0xB53120, 0x994E00,
0x6B6D00, 0x388700, 0x0D9300, 0x008C47,
0x007AA0, 0x000000, 0x000000, 0x000000,
0xFFFFFF, 0x64B0FF, 0x9290FF, 0xC676FF,
0xF26AFF, 0xFF6ECC, 0xFF8170, 0xEA9E22,
0xBCBE00, 0x88D800, 0x5CE430, 0x45E082,
0x48CDDE, 0x4F4F4F, 0x000000, 0x000000,
0xFFFFFF, 0xC0DFFF, 0xD3D2FF, 0xE8C8FF,
0xFAC2FF, 0xFFC4EA, 0xFFCCC5, 0xF7D8A5,
0xE4E594, 0xCFEF96, 0xBDF4AB, 0xB3F3CC,
0xB5EBF2, 0xB8B8B8, 0x000000, 0x000000 }
},
{ "unsaturated-final", "FBX's Unsaturated-Final palette",
{ 0x676767, 0x001F8E, 0x23069E, 0x40008E,
0x600067, 0x67001C, 0x5B1000, 0x432500,
0x313400, 0x074800, 0x004F00, 0x004622,
0x003A61, 0x000000, 0x000000, 0x000000,
0xB3B3B3, 0x205ADF, 0x5138FB, 0x7A27EE,
0xA520C2, 0xB0226B, 0xAD3702, 0x8D5600,
0x6E7000, 0x2E8A00, 0x069200, 0x008A47,
0x037B9B, 0x101010, 0x000000, 0x000000,
0xFFFFFF, 0x62AEFF, 0x918BFF, 0xBC78FF,
0xE96EFF, 0xFC6CCD, 0xFA8267, 0xE29B26,
0xC0B901, 0x84D200, 0x58DE38, 0x46D97D,
0x49CED2, 0x494949, 0x000000, 0x000000,
0xFFFFFF, 0xC1E3FF, 0xD5D4FF, 0xE7CCFF,
0xFBC9FF, 0xFFC7F0, 0xFFD0C5, 0xF8DAAA,
0xEBE69A, 0xD1F19A, 0xBEF7AF, 0xB6F4CD,
0xB7F0EF, 0xB2B2B2, 0x000000, 0x000000 }
},
{ "sony-cxa2025as-us", "Sony CXA2025AS US palette",
{ 0x585858, 0x00238C, 0x00139B, 0x2D0585,
0x5D0052, 0x7A0017, 0x7A0800, 0x5F1800,
0x352A00, 0x093900, 0x003F00, 0x003C22,
0x00325D, 0x000000, 0x000000, 0x000000,
0xA1A1A1, 0x0053EE, 0x153CFE, 0x6028E4,
0xA91D98, 0xD41E41, 0xD22C00, 0xAA4400,
0x6C5E00, 0x2D7300, 0x007D06, 0x007852,
0x0069A9, 0x000000, 0x000000, 0x000000,
0xFFFFFF, 0x1FA5FE, 0x5E89FE, 0xB572FE,
0xFE65F6, 0xFE6790, 0xFE773C, 0xFE9308,
0xC4B200, 0x79CA10, 0x3AD54A, 0x11D1A4,
0x06BFFE, 0x424242, 0x000000, 0x000000,
0xFFFFFF, 0xA0D9FE, 0xBDCCFE, 0xE1C2FE,
0xFEBCFB, 0xFEBDD0, 0xFEC5A9, 0xFED18E,
0xE9DE86, 0xC7E992, 0xA8EEB0, 0x95ECD9,
0x91E4FE, 0xACACAC, 0x000000, 0x000000 }
},
{ "pal", "PAL palette",
{ 0x808080, 0x0000BA, 0x3700BF, 0x8400A6,
0xBB006A, 0xB7001E, 0xB30000, 0x912600,
0x7B2B00, 0x003E00, 0x00480D, 0x003C22,
0x002F66, 0x000000, 0x050505, 0x050505,
0xC8C8C8, 0x0059FF, 0x443CFF, 0xB733CC,
0xFE33AA, 0xFE375E, 0xFE371A, 0xD54B00,
0xC46200, 0x3C7B00, 0x1D8415, 0x009566,
0x0084C4, 0x111111, 0x090909, 0x090909,
0xFEFEFE, 0x0095FF, 0x6F84FF, 0xD56FFF,
0xFE77CC, 0xFE6F99, 0xFE7B59, 0xFE915F,
0xFEA233, 0xA6BF00, 0x51D96A, 0x4DD5AE,
0x00D9FF, 0x666666, 0x0D0D0D, 0x0D0D0D,
0xFEFEFE, 0x84BFFF, 0xBBBBFF, 0xD0BBFF,
0xFEBFEA, 0xFEBFCC, 0xFEC4B7, 0xFECCAE,
0xFED9A2, 0xCCE199, 0xAEEEB7, 0xAAF8EE,
0xB3EEFF, 0xDDDDDD, 0x111111, 0x111111 }
},
{ "bmf-final2", "BMF's Final 2 palette",
{ 0x525252, 0x000080, 0x08008A, 0x2C007E,
0x4A004E, 0x500006, 0x440000, 0x260800,
0x0A2000, 0x002E00, 0x003200, 0x00260A,
0x001C48, 0x000000, 0x000000, 0x000000,
0xA4A4A4, 0x0038CE, 0x3416EC, 0x5E04DC,
0x8C00B0, 0x9A004C, 0x901800, 0x703600,
0x4C5400, 0x0E6C00, 0x007400, 0x006C2C,
0x005E84, 0x000000, 0x000000, 0x000000,
0xFFFFFF, 0x4C9CFF, 0x7C78FF, 0xA664FF,
0xDA5AFF, 0xF054C0, 0xF06A56, 0xD68610,
0xBAA400, 0x76C000, 0x46CC1A, 0x2EC866,
0x34C2BE, 0x3A3A3A, 0x000000, 0x000000,
0xFFFFFF, 0xB6DAFF, 0xC8CAFF, 0xDAC2FF,
0xF0BEFF, 0xFCBCEE, 0xFAC2C0, 0xF2CCA2,
0xE6DA92, 0xCCE68E, 0xB8EEA2, 0xAEEABE,
0xAEE8E2, 0xB0B0B0, 0x000000, 0x000000 }
},
{ "bmf-final3", "BMF's Final 3 palette",
{ 0x686868, 0x001299, 0x1A08AA, 0x51029A,
0x7E0069, 0x8E001C, 0x7E0301, 0x511800,
0x1F3700, 0x014E00, 0x005A00, 0x00501C,
0x004061, 0x000000, 0x000000, 0x000000,
0xB9B9B9, 0x0C5CD7, 0x5035F0, 0x8919E0,
0xBB0CB3, 0xCE0C61, 0xC02B0E, 0x954D01,
0x616F00, 0x1F8B00, 0x01980C, 0x00934B,
0x00819B, 0x000000, 0x000000, 0x000000,
0xFFFFFF, 0x63B4FF, 0x9B91FF, 0xD377FF,
0xEF6AFF, 0xF968C0, 0xF97D6C, 0xED9B2D,
0xBDBD16, 0x7CDA1C, 0x4BE847, 0x35E591,
0x3FD9DD, 0x606060, 0x000000, 0x000000,
0xFFFFFF, 0xACE7FF, 0xD5CDFF, 0xEDBAFF,
0xF8B0FF, 0xFEB0EC, 0xFDBDB5, 0xF9D28E,
0xE8EB7C, 0xBBF382, 0x99F7A2, 0x8AF5D0,
0x92F4F1, 0xBEBEBE, 0x000000, 0x000000 }
},
{ "composite-direct-fbx", "FBX's Composite Direct palette",
{ 0x656565, 0x00127D, 0x18008E, 0x360082,
0x56005D, 0x5A0018, 0x4F0500, 0x381900,
0x1D3100, 0x003D00, 0x004100, 0x003B17,
0x002E55, 0x000000, 0x000000, 0x000000,
0xAFAFAF, 0x194EC8, 0x472FE3, 0x6B1FD7,
0x931BAE, 0x9E1A5E, 0x993200, 0x7B4B00,
0x5B6700, 0x267A00, 0x008200, 0x007A3E,
0x006E8A, 0x000000, 0x000000, 0x000000,
0xFFFFFF, 0x64A9FF, 0x8E89FF, 0xB676FF,
0xE06FFF, 0xEF6CC4, 0xF0806A, 0xD8982C,
0xB9B40A, 0x83CB0C, 0x5BD63F, 0x4AD17E,
0x4DC7CB, 0x4C4C4C, 0x000000, 0x000000,
0xFFFFFF, 0xC7E5FF, 0xD9D9FF, 0xE9D1FF,
0xF9CEFF, 0xFFCCF1, 0xFFD4CB, 0xF8DFB1,
0xEDEAA4, 0xD6F4A4, 0xC5F8B8, 0xBEF6D3,
0xBFF1F1, 0xB9B9B9, 0x000000, 0x000000 }
},
{ "pvm-style-d93-fbx", "FBX's PVM Style D93 palette",
{ 0x696B63, 0x001774, 0x1E0087, 0x340073,
0x560057, 0x5E0013, 0x531A00, 0x3B2400,
0x243000, 0x063A00, 0x003F00, 0x003B1E,
0x00334E, 0x000000, 0x000000, 0x000000,
0xB9BBB3, 0x1453B9, 0x4D2CDA, 0x671EDE,
0x98189C, 0x9D2344, 0xA03E00, 0x8D5500,
0x656D00, 0x2C7900, 0x008100, 0x007D42,
0x00788A, 0x000000, 0x000000, 0x000000,
0xFFFFFF, 0x69A8FF, 0x9691FF, 0xB28AFA,
0xEA7DFA, 0xF37BC7, 0xF28E59, 0xE6AD27,
0xD7C805, 0x90DF07, 0x64E53C, 0x45E27D,
0x48D5D9, 0x4E5048, 0x000000, 0x000000,
0xFFFFFF, 0xD2EAFF, 0xE2E2FF, 0xE9D8FF,
0xF5D2FF, 0xF8D9EA, 0xFADEB9, 0xF9E89B,
0xF3F28C, 0xD3FA91, 0xB8FCA8, 0xAEFACA,
0xCAF3F3, 0xBEC0B8, 0x000000, 0x000000 }
},
{ "ntsc-hardware-fbx", "FBX's NTSC Hardware palette",
{ 0x6A6D6A, 0x001380, 0x1E008A, 0x39007A,
0x550056, 0x5A0018, 0x4F1000, 0x382100,
0x213300, 0x003D00, 0x004000, 0x003924,
0x002E55, 0x000000, 0x000000, 0x000000,
0xB9BCB9, 0x1850C7, 0x4B30E3, 0x7322D6,
0x951FA9, 0x9D285C, 0x963C00, 0x7A5100,
0x5B6700, 0x227700, 0x027E02, 0x007645,
0x006E8A, 0x000000, 0x000000, 0x000000,
0xFFFFFF, 0x68A6FF, 0x9299FF, 0xB085FF,
0xD975FD, 0xE377B9, 0xE58D68, 0xCFA22C,
0xB3AF0C, 0x7BC211, 0x55CA47, 0x46CB81,
0x47C1C5, 0x4A4D4A, 0x000000, 0x000000,
0xFFFFFF, 0xCCEAFF, 0xDDDEFF, 0xECDAFF,
0xF8D7FE, 0xFCD6F5, 0xFDDBCF, 0xF9E7B5,
0xF1F0AA, 0xDAFAA9, 0xC9FFBC, 0xC3FBD7,
0xC4F6F6, 0xBEC1BE, 0x000000, 0x000000 }
},
{ "nes-classic-fbx-fs", "FBX's NES-Classic FS palette",
{ 0x60615F, 0x000083, 0x1D0195, 0x340875,
0x51055E, 0x56000F, 0x4C0700, 0x372308,
0x203A0B, 0x0F4B0E, 0x194C16, 0x02421E,
0x023154, 0x000000, 0x000000, 0x000000,
0xA9AAA8, 0x104BBF, 0x4712D8, 0x6300CA,
0x8800A9, 0x930B46, 0x8A2D04, 0x6F5206,
0x5C7114, 0x1B8D12, 0x199509, 0x178448,
0x206B8E, 0x000000, 0x000000, 0x000000,
0xFBFBFB, 0x6699F8, 0x8974F9, 0xAB58F8,
0xD557EF, 0xDE5FA9, 0xDC7F59, 0xC7A224,
0xA7BE03, 0x75D703, 0x60E34F, 0x3CD68D,
0x56C9CC, 0x414240, 0x000000, 0x000000,
0xFBFBFB, 0xBED4FA, 0xC9C7F9, 0xD7BEFA,
0xE8B8F9, 0xF5BAE5, 0xF3CAC2, 0xDFCDA7,
0xD9E09C, 0xC9EB9E, 0xC0EDB8, 0xB5F4C7,
0xB9EAE9, 0xABABAB, 0x000000, 0x000000 }
},
{ "nescap", "RGBSource's NESCAP palette",
{ 0x646365, 0x001580, 0x1D0090, 0x380082,
0x56005D, 0x5A001A, 0x4F0900, 0x381B00,
0x1E3100, 0x003D00, 0x004100, 0x003A1B,
0x002F55, 0x000000, 0x000000, 0x000000,
0xAFADAF, 0x164BCA, 0x472AE7, 0x6B1BDB,
0x9617B0, 0x9F185B, 0x963001, 0x7B4800,
0x5A6600, 0x237800, 0x017F00, 0x00783D,
0x006C8C, 0x000000, 0x000000, 0x000000,
0xFFFFFF, 0x60A6FF, 0x8F84FF, 0xB473FF,
0xE26CFF, 0xF268C3, 0xEF7E61, 0xD89527,
0xBAB307, 0x81C807, 0x57D43D, 0x47CF7E,
0x4BC5CD, 0x4C4B4D, 0x000000, 0x000000,
0xFFFFFF, 0xC2E0FF, 0xD5D2FF, 0xE3CBFF,
0xF7C8FF, 0xFEC6EE, 0xFECEC6, 0xF6D7AE,
0xE9E49F, 0xD3ED9D, 0xC0F2B2, 0xB9F1CC,
0xBAEDED, 0xBAB9BB, 0x000000, 0x000000 }
}
};
unsigned retro_api_version(void)
{
return RETRO_API_VERSION;
}
void retro_set_video_refresh(retro_video_refresh_t cb)
{
video_cb = cb;
}
void retro_set_audio_sample(retro_audio_sample_t cb)
{ }
void retro_set_audio_sample_batch(retro_audio_sample_batch_t cb)
{
audio_batch_cb = cb;
}
void retro_set_input_poll(retro_input_poll_t cb)
{
poll_cb = cb;
}
void retro_set_input_state(retro_input_state_t cb)
{
input_cb = cb;
}
void retro_set_controller_port_device(unsigned a, unsigned b)
{}
void retro_set_environment(retro_environment_t cb)
{
static const struct retro_variable vars[] = {
{ "fceumm_palette", "Color Palette; asqrealc|loopy|quor|chris|matt|pasofami|crashman|mess|zaphod-cv|zaphod-smb|vs-drmar|vs-cv|vs-smb|nintendo-vc|yuv-v3|unsaturated-final|sony-cxa2025as-us|pal|bmf-final2|bmf-final3|composite-direct-fbx|pvm-style-d93-fbx|ntsc-hardware-fbx|nes-classic-fbx-fs|nescap|raw" },
{ "fceumm_nospritelimit", "No Sprite Limit; disabled|enabled" },
{ "fceumm_overclocking", "Overclocking; disabled|2x" },
{ "fceumm_overscan", "Crop Overscan; enabled|disabled" },
{ "fceumm_turbo_enable", "Turbo Enable; None|Player 1|Player 2|Both" },
{ "fceumm_turbo_delay", "Turbo Delay (in frames); 3|5|10|15|30|60|1|2" },
{ "fceumm_aspect", "Preferred aspect ratio; 8:7 PAR|4:3" },
{ "fceumm_region", "Region Override; Auto|NTSC|PAL|Dendy" },
{ NULL, NULL },
};
environ_cb = cb;
cb(RETRO_ENVIRONMENT_SET_VARIABLES, (void*)vars);
}
void retro_get_system_info(struct retro_system_info *info)
{
info->need_fullpath = false;
info->valid_extensions = "fds|nes|unf|unif";
#ifdef GIT_VERSION
info->library_version = "git" GIT_VERSION;
#else
info->library_version = "(SVN)";
#endif
info->library_name = "FCEUmm";
info->block_extract = false;
}
void retro_get_system_av_info(struct retro_system_av_info *info)
{
unsigned width = use_overscan ? 256 : (256 - 16);
unsigned height = use_overscan ? 240 : (240 - 16);
info->geometry.base_width = width;
info->geometry.base_height = height;
info->geometry.max_width = width;
info->geometry.max_height = height;
info->geometry.aspect_ratio = use_par ? NES_8_7_PAR : NES_4_3;
info->timing.sample_rate = 32050.0;
if (FSettings.PAL || dendy)
info->timing.fps = 838977920.0/16777215.0;
else
info->timing.fps = 1008307711.0/16777215.0;
info->timing.sample_rate = 32040.5;
}
static void check_system_specs(void)
{
// TODO - when we get it running at fullspeed on PSP, set to 4
unsigned level = 5;
environ_cb(RETRO_ENVIRONMENT_SET_PERFORMANCE_LEVEL, &level);
}
void retro_init(void)
{
enum retro_pixel_format rgb565;
log_cb.log=default_logger;
environ_cb(RETRO_ENVIRONMENT_GET_LOG_INTERFACE, &log_cb);
#ifdef FRONTEND_SUPPORTS_RGB565
rgb565 = RETRO_PIXEL_FORMAT_RGB565;
if(environ_cb(RETRO_ENVIRONMENT_SET_PIXEL_FORMAT, &rgb565))
log_cb.log(RETRO_LOG_INFO, "Frontend supports RGB565 - will use that instead of XRGB1555.\n");
#endif
}
static void retro_set_custom_palette (void)
{
uint8_t i,r,g,b;
use_raw_palette = false;
if (current_palette == 0)
{
FCEU_ResetPalette(); /* Do palette reset*/
return;
}
if (current_palette == 26) /* raw palette */
{
use_raw_palette = true;
for (i = 0; i < 64; i++)
{
r = (((i >> 0) & 0xF) * 255) / 15;
g = (((i >> 4) & 0x3) * 255) / 3;
FCEUD_SetPalette( i, r, g, 0);
}
return;
}
/* Setup this palette*/
for ( i = 0; i < 64; i++ )
{
r = palettes[current_palette-1].data[i] >> 16;
g = ( palettes[current_palette-1].data[i] & 0xff00 ) >> 8;
b = ( palettes[current_palette-1].data[i] & 0xff );
FCEUD_SetPalette( i, r, g, b);
FCEUD_SetPalette( i+64, r, g, b);
FCEUD_SetPalette( i+128, r, g, b);
FCEUD_SetPalette( i+192, r, g, b);
}
}
/* Set variables for NTSC(1) / PAL(2) / Dendy(3)
* Dendy has PAL framerate and resolution, but ~NTSC timings,
* and has 50 dummy scanlines to force 50 fps. */
void FCEUD_RegionOverride(int region)
{
static int w = 0;
struct retro_system_av_info av_info;
switch (region)
{
case 0: /* auto */
dendy = 0;
w = (GameInfo->vidsys == GIV_PAL) ? 1 : 0;
break;
case 1: /* ntsc */
dendy = 0;
w = 0;
FCEU_DispMessage("Switched to NTSC");
break;
case 2: /* pal */
dendy = 0;
w = 1;
FCEU_DispMessage("Switched to PAL");
break;
case 3: /* dendy */
dendy = 1;
w = 0;
FCEU_DispMessage("Switched to Dendy");
break;
}
FSettings.PAL = w ;
PAL = w ? 1 : 0;
normal_scanlines = dendy ? 290 : 240;
totalscanlines = normal_scanlines + (overclock_state ? extrascanlines : 0);
FCEUPPU_SetVideoSystem(w || dendy);
SetSoundVariables();
// Update the geometry
retro_get_system_av_info(&av_info);
environ_cb(RETRO_ENVIRONMENT_SET_GEOMETRY, &av_info);
}
void retro_deinit (void)
{
FCEUI_CloseGame();
FCEUI_Sound(0);
FCEUI_Kill();
#if defined(_3DS)
linearFree(fceu_video_out);
#else
if (fceu_video_out)
free(fceu_video_out);
fceu_video_out = NULL;
#endif
}
void retro_reset(void)
{
ResetNES();
}
typedef struct
{
unsigned retro;
unsigned nes;
} keymap;
static const keymap bindmap[] = {
{ RETRO_DEVICE_ID_JOYPAD_A, JOY_A },
{ RETRO_DEVICE_ID_JOYPAD_B, JOY_B },
{ RETRO_DEVICE_ID_JOYPAD_SELECT, JOY_SELECT },
{ RETRO_DEVICE_ID_JOYPAD_START, JOY_START },
{ RETRO_DEVICE_ID_JOYPAD_UP, JOY_UP },
{ RETRO_DEVICE_ID_JOYPAD_DOWN, JOY_DOWN },
{ RETRO_DEVICE_ID_JOYPAD_LEFT, JOY_LEFT },
{ RETRO_DEVICE_ID_JOYPAD_RIGHT, JOY_RIGHT },
{ RETRO_DEVICE_ID_JOYPAD_X, JOY_A },
{ RETRO_DEVICE_ID_JOYPAD_Y, JOY_B },
};
static void check_variables(bool startup)
{
struct retro_variable var = {0};
struct retro_system_av_info av_info;
bool geometry_update = false;
unsigned old_regionoverride = regionoverride;
var.key = "fceumm_palette";
if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
{
unsigned orig_value = current_palette;
if (!strcmp(var.value, "asqrealc"))
current_palette = 0;
else if (!strcmp(var.value, "loopy"))
current_palette = 1;
else if (!strcmp(var.value, "quor"))
current_palette = 2;
else if (!strcmp(var.value, "chris"))
current_palette = 3;
else if (!strcmp(var.value, "matt"))
current_palette = 4;
else if (!strcmp(var.value, "matt"))
current_palette = 5;
else if (!strcmp(var.value, "pasofami"))
current_palette = 6;
else if (!strcmp(var.value, "crashman"))
current_palette = 7;
else if (!strcmp(var.value, "mess"))
current_palette = 8;
else if (!strcmp(var.value, "zaphod-cv"))
current_palette = 9;
else if (!strcmp(var.value, "zaphod-smb"))
current_palette = 10;
else if (!strcmp(var.value, "vs-drmar"))
current_palette = 11;
else if (!strcmp(var.value, "vs-cv"))
current_palette = 12;
else if (!strcmp(var.value, "vs-smb"))
current_palette = 13;
else if (!strcmp(var.value, "nintendo-vc"))
current_palette = 14;
else if (!strcmp(var.value, "yuv-v3"))
current_palette = 15;
else if (!strcmp(var.value, "unsaturated-final"))
current_palette = 16;
else if (!strcmp(var.value, "sony-cxa2025as-us"))
current_palette = 17;
else if (!strcmp(var.value, "pal"))
current_palette = 18;
else if (!strcmp(var.value, "bmf-final2"))
current_palette = 19;
else if (!strcmp(var.value, "bmf-final3"))
current_palette = 20;
else if (!strcmp(var.value, "composite-direct-fbx"))
current_palette = 21;
else if (!strcmp(var.value, "pvm-style-d93-fbx"))
current_palette = 22;
else if (!strcmp(var.value, "ntsc-hardware-fbx"))
current_palette = 23;
else if (!strcmp(var.value, "nes-classic-fbx-fs"))
current_palette = 24;
else if (!strcmp(var.value, "nescap"))
current_palette = 25;
else if (!strcmp(var.value, "raw"))
current_palette = 26;
if (current_palette != orig_value)
retro_set_custom_palette();
}
var.key = "fceumm_nospritelimit";
if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
{
int no_sprite_limit = (!strcmp(var.value, "enabled")) ? 1 : 0;
FCEUI_DisableSpriteLimitation(no_sprite_limit);
}
var.key = "fceumm_overclocking";
if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
{
bool do_reinit = false;
if (!strcmp(var.value, "disabled")
&& overclock_state != 0)
{
overclocked = 0;
skip_7bit_overclocking = 1;
extrascanlines = 0;
overclock_state = 0;
do_reinit = true;
}
else if (!strcmp(var.value, "2x")
&& overclock_state != 1)
{
overclocked = 1;
skip_7bit_overclocking = 1;
extrascanlines = 266;
overclock_state = 1;
do_reinit = true;
}
if (do_reinit && startup)
{
FCEU_KillVirtualVideo();
FCEU_InitVirtualVideo();
}
}
var.key = "fceumm_overscan";
if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
{
bool newval = (!strcmp(var.value, "disabled"));
if (newval != use_overscan)
{
use_overscan = newval;
geometry_update = true;
}
}
var.key = "fceumm_turbo_enable";
if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
{
if (!strcmp(var.value, "None"))
{
turbo_enabler = 0;
}
else if (!strcmp(var.value, "Player 1"))
{
turbo_enabler = 1;
}
else if (!strcmp(var.value, "Player 2"))
{
turbo_enabler = 2;
}
else if (!strcmp(var.value, "Both"))
{
turbo_enabler = 3;
}
}
var.key = "fceumm_turbo_delay";
if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
{
if (!strcmp(var.value, "1"))
{
turbo_delay = 1;
}
if (!strcmp(var.value, "2"))
{
turbo_delay = 2;
}
else if (!strcmp(var.value, "3"))
{
turbo_delay = 3;
}
else if (!strcmp(var.value, "5"))
{
turbo_delay = 5;
}
else if (!strcmp(var.value, "10"))
{
turbo_delay = 10;
}
else if (!strcmp(var.value, "15"))
{
turbo_delay = 15;
}
else if (!strcmp(var.value, "30"))
{
turbo_delay = 30;
}
else if (!strcmp(var.value, "60"))
{
turbo_delay = 60;
}
}
var.key = "fceumm_region";
if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
{
if (!strcmp(var.value, "Auto"))
regionoverride = 0;
else if (!strcmp(var.value, "NTSC"))
regionoverride = 1;
else if (!strcmp(var.value, "PAL"))
regionoverride = 2;
else if (!strcmp(var.value, "Dendy"))
regionoverride = 3;
}
if (regionoverride != old_regionoverride)
FCEUD_RegionOverride(regionoverride);
var.key = "fceumm_aspect";
if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
{
bool newval = (!strcmp(var.value, "8:7 PAR"));
if (newval != use_par)
{
use_par = newval;
geometry_update = true;
}
}
if (geometry_update)
{
retro_get_system_av_info(&av_info);
environ_cb(RETRO_ENVIRONMENT_SET_GEOMETRY, &av_info);
}
}
/*
* Flags to keep track of whether turbo
* was toggled on or off
* p0 - Player 1
* p1 - Player 2
* There are two values in array
* for Turbo A and Turbo B for
* each player
*/
unsigned char turbo_p0_toggle[] = {0,0};
unsigned char turbo_p1_toggle[] = {0,0};
static void FCEUD_UpdateInput(void)
{
unsigned i;
unsigned char pad[2];
pad[0] = 0;
pad[1] = 0;
poll_cb();
for ( i = 0; i < 8; i++)
pad[0] |= input_cb(0, RETRO_DEVICE_JOYPAD, 0, bindmap[i].retro) ? bindmap[i].nes : 0;
for ( i = 0; i < 8; i++)
pad[1] |= input_cb(1, RETRO_DEVICE_JOYPAD, 0, bindmap[i].retro) ? bindmap[i].nes : 0;
/*
* Turbo A and Turbo B buttons are
* mapped to Joypad X and Joypad Y
* in RetroArch joypad.
*
* We achieve this by keeping track of
* the number of times it increments
* the toggle counter and fire or not fire
* depending on whether the delay value has
* been reached.
*/
if (turbo_enabler == 1 || turbo_enabler == 3)
{
// Handle turbo buttons - player 1
for ( i = 8; i < 10; i++) {
if(input_cb(0, RETRO_DEVICE_JOYPAD, 0, bindmap[i].retro)) {
if (turbo_p0_toggle[i-8] == 0) {
pad[0] |= bindmap[i].nes;
}
turbo_p0_toggle[i-8]++;
if (turbo_p0_toggle[i-8] > turbo_delay) {
// Reset the toggle if
// delay value is reached
pad[0] |= bindmap[i].nes;
turbo_p0_toggle[i-8] = 0;
}
} else {
// If the button is not pressed, just reset the toggle
turbo_p0_toggle[i-8] = 0;
}
}
}
if (turbo_enabler == 2 || turbo_enabler == 3)
{
// Handle turbo buttons - player 2
for ( i = 8; i < 10; i++) {
if(input_cb(1, RETRO_DEVICE_JOYPAD, 0, bindmap[i].retro)) {
if (turbo_p1_toggle[i-8] == 0) {
pad[1] |= bindmap[i].nes;
}
turbo_p1_toggle[i-8]++;
if (turbo_p1_toggle[i-8] > turbo_delay) {
// Reset the toggle if
// delay value is reached
pad[1] |= bindmap[i].nes;
turbo_p1_toggle[i-8] = 0;
}
} else {
// If the button is not pressed, just reset the toggle
turbo_p1_toggle[i-8] = 0;
}
}
}
JSReturn[0] = pad[0] | (pad[1] << 8);
if (input_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R2))
{
FCEU_VSUniCoin(); /* Insert Coin VS System */
}
if (GameInfo->type == GIT_FDS) /* Famicom Disk System */
{
bool curL = input_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L);
bool curR = input_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R);
static bool prevL = false, prevR = false;
if (curL && !prevL)
{
FCEU_FDSSelect(); /* Swap FDisk side */
}
prevL = curL;
if (curR && !prevR)
{
FCEU_FDSInsert(-1); /* Insert or eject the disk */
}
prevR = curR;
}
}
void FCEUD_Update(uint8 *XBuf, int32 *Buffer, int Count)
{
}
static void retro_run_blit(uint8_t *gfx)
{
unsigned x, y;
#ifdef PSP
static unsigned int __attribute__((aligned(16))) d_list[32];
void* texture_vram_p = NULL;
#endif
uint16_t *fceu_video_out_ptr = NULL;
struct retro_framebuffer fb = {0};
unsigned incr = 0;
unsigned width = 256;
unsigned height = 240;
unsigned pitch = 512;
if (!use_overscan)
{
incr = 16;
width -= 16;
height -= 16;
#ifndef PSP
pitch -= 32;
gfx = gfx + 8 + 256 * 8;
#endif
}
#ifdef PSP
texture_vram_p = (void*) (0x44200000 - (256 * 256)); // max VRAM address - frame size
sceKernelDcacheWritebackRange(retro_palette,256 * 2);
sceKernelDcacheWritebackRange(XBuf, 256*240 );
sceGuStart(GU_DIRECT, d_list);
/* sceGuCopyImage doesnt seem to work correctly with GU_PSM_T8
* so we use GU_PSM_4444 ( 2 Bytes per pixel ) instead
* with half the values for pitch / width / x offset
*/
if (use_overscan)
sceGuCopyImage(GU_PSM_4444, 0, 0, 128, 240, 128, XBuf, 0, 0, 128, texture_vram_p);
else
sceGuCopyImage(GU_PSM_4444, 4, 4, 120, 224, 128, XBuf, 0, 0, 128, texture_vram_p);
sceGuTexSync();
sceGuTexImage(0, 256, 256, 256, texture_vram_p);
sceGuTexMode(GU_PSM_T8, 0, 0, GU_FALSE);
sceGuTexFunc(GU_TFX_REPLACE, GU_TCC_RGB);
sceGuDisable(GU_BLEND);
sceGuClutMode(GU_PSM_5650, 0, 0xFF, 0);
sceGuClutLoad(32, retro_palette);
sceGuFinish();
video_cb(texture_vram_p, width, height, 256);
#else
fb.width = width;
fb.height = height;
fb.access_flags = RETRO_MEMORY_ACCESS_WRITE;
fceu_video_out_ptr = fceu_video_out;
if (environ_cb(RETRO_ENVIRONMENT_GET_CURRENT_SOFTWARE_FRAMEBUFFER, &fb) && fb.format == RETRO_PIXEL_FORMAT_RGB565)
{
fceu_video_out_ptr = (uint16_t*)fb.data;
pitch = fb.pitch >> 1;
}
if (use_raw_palette)
{
extern uint8 PPU[4];
int deemp = (PPU[1] >> 5) << 2;
for (y = 0; y < height; y++, gfx += incr)
for ( x = 0; x < width; x++, gfx++)
fceu_video_out_ptr[y * width + x] = retro_palette[*gfx & 0x3F] | deemp;
}
else
{
for (y = 0; y < height; y++, gfx += incr)
for ( x = 0; x < width; x++, gfx++)
fceu_video_out_ptr[y * width + x] = retro_palette[*gfx];
}
video_cb(fceu_video_out_ptr, width, height, pitch);
#endif
}
void retro_run(void)
{
unsigned i;
uint8_t *gfx;
int32_t ssize = 0;
bool updated = false;
if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE, &updated) && updated)
check_variables(false);
FCEUD_UpdateInput();
FCEUI_Emulate(&gfx, &sound, &ssize, 0);
for (i = 0; i < ssize; i++)
sound[i] = (sound[i] << 16) | (sound[i] & 0xffff);
audio_batch_cb((const int16_t*)sound, ssize);
retro_run_blit(gfx);
}
static unsigned serialize_size = 0;
size_t retro_serialize_size(void)
{
if (serialize_size == 0)
{
/* Something arbitrarily big.*/
uint8_t *buffer = (uint8_t*)malloc(1000000);
memstream_set_buffer(buffer, 1000000);
FCEUSS_Save_Mem();
serialize_size = memstream_get_last_size();
free(buffer);
}
return serialize_size;
}
bool retro_serialize(void *data, size_t size)
{
if (size != retro_serialize_size())
return false;
memstream_set_buffer((uint8_t*)data, size);
FCEUSS_Save_Mem();
return true;
}
bool retro_unserialize(const void * data, size_t size)
{
if (size != retro_serialize_size())
return false;
memstream_set_buffer((uint8_t*)data, size);
FCEUSS_Load_Mem();
return true;
}
void retro_cheat_reset(void)
{
FCEU_ResetCheats();
}
void retro_cheat_set(unsigned index, bool enabled, const char *code)
{
char name[256];
uint16 a;
uint8 v;
int c;
int type = 1;
sprintf(name, "N/A");
if (FCEUI_DecodeGG(code, &a, &v, &c))
goto input_cheat;
/* Not a Game Genie code. */
if (FCEUI_DecodePAR(code, &a, &v, &c, &type))
goto input_cheat;
/* Not a Pro Action Replay code. */
return;
input_cheat:
FCEUI_AddCheat(name, a, v, c, type);
}
typedef struct cartridge_db
{
char title[256];
uint32_t crc;
} cartridge_db_t;
static const struct cartridge_db fourscore_db_list[] =
{
{
"Bomberman II (USA)",
0x1ebb5b42
},
#if 0
{
"Championship Bowling (USA)",
0xeac38105
},
#endif
{
"Chris Evert & Ivan Lendl in Top Players' Tennis (USA)",
0xf99e37eb
},
#if 0
{
"Crash 'n' the Boys - Street Challenge (USA)",
0xc7f0c457
},
#endif
{
"Four Players' Tennis (Europe)",
0x48b8ee58
},
{
"Danny Sullivan's Indy Heat (Europe)",
0x27ca0679,
},
{
"Gauntlet II (Europe)",
0x79f688bc
},
{
"Gauntlet II (USA)",
0x1b71ccdb
},
{
"Greg Norman's Golf Power (USA)",
0x1352f1b9
},
{
"Harlem Globetrotters (USA)",
0x2e6ee98d
},
{
"Ivan 'Ironman' Stewart's Super Off Road (Europe)",
0x05104517
},
{
"Ivan 'Ironman' Stewart's Super Off Road (USA)",
0x4b041b6b
},
{
"Kings of the Beach - Professional Beach Volleyball (USA)",
0xf54b34bd
},
{
"Magic Johnson's Fast Break (USA)",
0xc6c2edb5
},
{
"M.U.L.E. (USA)",
0x0939852f
},
{
"Monster Truck Rally (USA)",
0x2f698c4d
},
{
"NES Play Action Football (USA)",
0xb9b4d9e0
},
{
"Nightmare on Elm Street, A (USA)",
0xda2cb59a
},
{
"Nintendo World Cup (Europe)",
0x8da6667d
},
{
"Nintendo World Cup (Europe) (Rev A)",
0x7c16f819
},
{
"Nintendo World Cup (Europe) (Rev B)",
0x7f08d0d9
},
{
"Nintendo World Cup (USA)",
0xa22657fa
},
{
"R.C. Pro-Am II (Europe)",
0x308da987
},
{
"R.C. Pro-Am II (USA)",
0x9edd2159
},
{
"Rackets & Rivals (Europe)",
0x8fa6e92c
},
{
"Roundball - 2-on-2 Challenge (Europe)",
0xad0394f0
},
{
"Roundball - 2-on-2 Challenge (USA)",
0x6e4dcfd2
},
{
"Spot - The Video Game (Japan)",
0x0abdd5ca
},
{
"Spot - The Video Game (USA)",
0xcfae9dfa
},
{
"Smash T.V. (Europe)",
0x0b8f8128
},
{
"Smash T.V. (USA)",
0x6ee94d32
},
{
"Super Jeopardy! (USA)",
0xcf4487a2
},
{
"Super Spike V'Ball (Europe)",
0xc05a63b2
},
{
"Super Spike V'Ball (USA)",
0xe840fd21
},
{
"Super Spike V'Ball + Nintendo World Cup (USA)",
0x407d6ffd
},
{
"Swords and Serpents (Europe)",
0xd153caf6
},
{
"Swords and Serpents (France)",
0x46135141
},
{
"Swords and Serpents (USA)",
0x3417ec46
},
{
"Battle City (Japan) (4 Players Hack) http://www.romhacking.net/hacks/2142/",
0x69977c9e
},
{
"Bomberman 3 (Homebrew) http://tempect.de/senil/games.html",
0x2da5ece0
},
{
"K.Y.F.F. (Homebrew) http://slydogstudios.org/index.php/k-y-f-f/",
0x90d2e9f0
},
{
"Super PakPak (Homebrew) http://wiki.nesdev.com/w/index.php/Super_PakPak",
0x1394ded0
},
{
"Super Mario Bros. + Tetris + Nintendo World Cup (Europe)",
0x73298c87
},
{
"Super Mario Bros. + Tetris + Nintendo World Cup (Europe) (Rev A)",
0xf46ef39a
}
};
static const struct cartridge_db famicom_4p_db_list[] =
{
{
"Bakutoushi Patton-Kun (Japan) (FDS)",
0xc39b3bb2
},
{
"Bomber Man II (Japan)",
0x0c401790
},
{
"Championship Bowling (Japan)",
0x9992f445
},
{
"Downtown - Nekketsu Koushinkyoku - Soreyuke Daiundoukai (Japan)",
0x3e470fe0
},
{
"Ike Ike! Nekketsu Hockey-bu - Subette Koronde Dairantou (Japan)",
0x4f032933
},
{
"Kunio-kun no Nekketsu Soccer League (Japan)",
0x4b5177e9
},
{
"Moero TwinBee - Cinnamon Hakase o Sukue! (Japan)",
0x9f03b11f
},
{
"Moero TwinBee - Cinnamon Hakase wo Sukue! (Japan) (FDS)",
0x13205221
},
{
"Nekketsu Kakutou Densetsu (Japan)",
0x37e24797
},
{
"Nekketsu Koukou Dodgeball-bu (Japan)",
0x62c67984
},
{
"Nekketsu! Street Basket - Ganbare Dunk Heroes (Japan)",
0x88062d9a
},
{
"Super Dodge Ball (USA) (3-4p with Game Genie code GEUOLZZA)",
0x689971f9
},
{
"Super Dodge Ball (USA) (patched) http://www.romhacking.net/hacks/71/",
0x4ff17864
},
{
"U.S. Championship V'Ball (Japan)",
0x213cb3fb
},
{
"U.S. Championship V'Ball (Japan) (Beta)",
0xd7077d96
},
{
"Wit's (Japan)",
0xb1b16b8a
}
};
extern uint32_t iNESGameCRC32;
bool retro_load_game(const struct retro_game_info *game)
{
unsigned i, j;
char* dir=NULL;
char* sav_dir=NULL;
size_t fourscore_len = sizeof(fourscore_db_list) / sizeof(fourscore_db_list[0]);
size_t famicom_4p_len = sizeof(famicom_4p_db_list) / sizeof(famicom_4p_db_list[0]);
struct retro_input_descriptor desc[] = {
{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT, "D-Pad Left" },
{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP, "D-Pad Up" },
{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN, "D-Pad Down" },
{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "D-Pad Right" },
{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B, "B" },
{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A, "A" },
{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT, "Select" },
{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START, "Start" },
{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R2, "(VSSystem) Insert Coin" },
{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L, "(FDS) Disk Side Change" },
{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R, "(FDS) Insert/Eject Disk" },
{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_X, "Turbo A" },
{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_Y, "Turbo B" },
{ 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT, "D-Pad Left" },
{ 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP, "D-Pad Up" },
{ 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN, "D-Pad Down" },
{ 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "D-Pad Right" },
{ 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B, "B" },
{ 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A, "A" },
{ 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT, "Select" },
{ 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START, "Start" },
{ 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_X, "Turbo A" },
{ 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_Y, "Turbo B" },
{ 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT, "D-Pad Left" },
{ 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP, "D-Pad Up" },
{ 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN, "D-Pad Down" },
{ 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "D-Pad Right" },
{ 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B, "B" },
{ 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A, "A" },
{ 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT, "Select" },
{ 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START, "Start" },
{ 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_X, "Turbo A" },
{ 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_Y, "Turbo B" },
{ 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT, "D-Pad Left" },
{ 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP, "D-Pad Up" },
{ 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN, "D-Pad Down" },
{ 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "D-Pad Right" },
{ 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B, "B" },
{ 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A, "A" },
{ 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT, "Select" },
{ 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START, "Start" },
{ 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_X, "Turbo A" },
{ 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_Y, "Turbo B" },
{ 0 },
};
struct retro_memory_descriptor descs[64];
struct retro_memory_map mmaps;
if (!game)
return false;
PowerNES();
check_system_specs();
#if defined(_3DS)
fceu_video_out = (uint16_t*)linearMemAlign(256 * 240 * sizeof(uint16_t), 128);
#elif !defined(PSP)
fceu_video_out = (uint16_t*)malloc(256 * 240 * sizeof(uint16_t));
#endif
environ_cb(RETRO_ENVIRONMENT_SET_INPUT_DESCRIPTORS, desc);
if (environ_cb(RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY, &dir) && dir)
FCEUI_SetBaseDirectory(dir);
if (environ_cb(RETRO_ENVIRONMENT_GET_SAVE_DIRECTORY, &sav_dir) && sav_dir)
FCEUI_SetSaveDirectory(sav_dir);
FCEUI_Initialize();
FCEUI_SetSoundVolume(256);
FCEUI_Sound(32050);
GameInfo = (FCEUGI*)FCEUI_LoadGame(game->path, (uint8_t*)game->data, game->size);
if (!GameInfo)
{
struct retro_message msg;
char msg_local[256];
sprintf(msg_local, "ROM loading failed...");
msg.msg = msg_local;
msg.frames = 360;
if (environ_cb)
environ_cb(RETRO_ENVIRONMENT_SET_MESSAGE, (void*)&msg);
return false;
}
FCEUI_SetInput(0, SI_GAMEPAD, &JSReturn[0], 0);
FCEUI_SetInput(1, SI_GAMEPAD, &JSReturn[0], 0);
retro_set_custom_palette();
FCEUD_SoundToggle();
check_variables(true);
FCEUI_DisableFourScore(1);
for (i = 0; i < fourscore_len; i++)
{
if (fourscore_db_list[i].crc == iNESGameCRC32)
{
FCEUI_DisableFourScore(0);
break;
}
}
for (i = 0; i < famicom_4p_len; i++)
{
if (famicom_4p_db_list[i].crc == iNESGameCRC32)
{
FCEUI_SetInputFC(SIFC_4PLAYER, &JSReturn[0], 0);
break;
}
}
memset(descs, 0, sizeof(descs));
i = 0;
for (j = 0; j < 64; j++)
{
if (MMapPtrs[j] != NULL)
{
descs[i].ptr = MMapPtrs[j];
descs[i].start = j * 1024;
descs[i].len = 1024;
descs[i].select = 0;
i++;
}
}
mmaps.descriptors = descs;
mmaps.num_descriptors = i;
environ_cb(RETRO_ENVIRONMENT_SET_MEMORY_MAPS, &mmaps);
return true;
}
bool retro_load_game_special(
unsigned game_type,
const struct retro_game_info *info, size_t num_info
)
{
return false;
}
void retro_unload_game(void)
{
FCEUI_CloseGame();
#if defined(_3DS)
if (fceu_video_out)
linearFree(fceu_video_out);
#else
if (fceu_video_out)
free(fceu_video_out);
fceu_video_out = NULL;
#endif
}
unsigned retro_get_region(void)
{
return FSettings.PAL ? RETRO_REGION_PAL : RETRO_REGION_NTSC;
}
void *retro_get_memory_data(unsigned type)
{
uint8_t* data;
switch(type)
{
case RETRO_MEMORY_SAVE_RAM:
if (iNESCart.battery)
return iNESCart.SaveGame[0];
else if (UNIFCart.battery)
return UNIFCart.SaveGame[0];
else
data = NULL;
break;
case RETRO_MEMORY_SYSTEM_RAM:
// TODO: add ExWRAM(0x2000) support ?
data = RAM;
break;
default:
data = NULL;
break;
}
return data;
}
size_t retro_get_memory_size(unsigned type)
{
unsigned size;
switch(type)
{
case RETRO_MEMORY_SAVE_RAM:
if (iNESCart.battery)
size = iNESCart.SaveGameLen[0];
else if (UNIFCart.battery)
size = UNIFCart.SaveGameLen[0];
else
size = 0;
break;
case RETRO_MEMORY_SYSTEM_RAM:
// TODO: detect ExWRAM(0x2000) ?
// NES BASE RAM (0x800)
size = 0x800;
break;
default:
size = 0;
break;
}
return size;
}
| 29.435131
| 310
| 0.642295
|
1b2a4d1657fba0c193760390847ec89e8e397a24
| 1,302
|
rb
|
Ruby
|
bot.rb
|
gabriellesc/thm-slack-status-bot
|
b01b9b9e3dc8c7643330dfe3f89205991dbd88be
|
[
"MIT"
] | 1
|
2018-11-29T19:56:52.000Z
|
2018-11-29T19:56:52.000Z
|
bot.rb
|
gabriellesc/thm-slack-status-bot
|
b01b9b9e3dc8c7643330dfe3f89205991dbd88be
|
[
"MIT"
] | null | null | null |
bot.rb
|
gabriellesc/thm-slack-status-bot
|
b01b9b9e3dc8c7643330dfe3f89205991dbd88be
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env ruby
require "net/http"
require "json"
require "fortune_gem"
EMOJI_FILE = 'animal_emoji_list'
get_uri = URI('https://slack.com/api/users.profile.get')
res = Net::HTTP.start(get_uri.host,
get_uri.port,
:use_ssl => get_uri.scheme == 'https') do |http|
get_req = Net::HTTP::Get.new get_uri
get_req['X-Slack-User'] = ENV['USER_ID']
get_req['Authorization'] = "Bearer #{ENV['TOKEN']}"
http.request get_req
end
prev_status = res.body
begin
text = FortuneGem.give_fortune({:max_length => 100})
end while text == prev_status['status_text']
emojis = IO.readlines(EMOJI_FILE)
prng = Random.new
begin
emoji = ":#{emojis[prng.rand(emojis.size)].strip}:"
end while emoji == prev_status['status_emoji']
post_uri = URI('https://slack.com/api/users.profile.set')
Net::HTTP.start(post_uri.host,
post_uri.port,
:use_ssl => post_uri.scheme == 'https') do |http|
post_req = Net::HTTP::Post.new post_uri
post_req['Content-Type'] = 'application/json; charset=utf-8'
post_req['X-Slack-User'] = ENV['USER_ID']
post_req['Authorization'] = "Bearer #{ENV['TOKEN']}"
post_req.body = {
profile: {status_text: "#{text}", status_emoji: "#{emoji}", status_expiration: 0}
}.to_json
http.request(post_req)
end
| 31
| 85
| 0.658986
|
692b2b36af21d33ad532cbc39ace0b16ff57b143
| 7,244
|
rb
|
Ruby
|
lib/nyan_cat_formatter/common.rb
|
hedgesky/nyan-cat-formatter
|
54ead6ab8d35d4a50bc538740ad99b83a9cb3dd1
|
[
"MIT"
] | 371
|
2015-01-06T11:17:13.000Z
|
2022-03-29T20:17:07.000Z
|
lib/nyan_cat_formatter/common.rb
|
hedgesky/nyan-cat-formatter
|
54ead6ab8d35d4a50bc538740ad99b83a9cb3dd1
|
[
"MIT"
] | 7
|
2015-03-10T22:41:20.000Z
|
2017-08-02T06:55:56.000Z
|
lib/nyan_cat_formatter/common.rb
|
hedgesky/nyan-cat-formatter
|
54ead6ab8d35d4a50bc538740ad99b83a9cb3dd1
|
[
"MIT"
] | 44
|
2015-02-07T03:59:25.000Z
|
2022-03-24T23:38:08.000Z
|
# -*- coding: utf-8 -*-
module NyanCat
module Common
ESC = "\e["
NND = "#{ESC}0m"
PASS = '='
PASS_ARY = ['-', '_']
FAIL = '*'
ERROR = '!'
PENDING = '+'
VT100_CODES =
{
:black => 30,
:red => 31,
:green => 32,
:yellow => 33,
:blue => 34,
:magenta => 35,
:cyan => 36,
:white => 37,
:bold => 1,
}
VT100_CODE_VALUES = VT100_CODES.invert
def self.included(base)
base.class_eval do
attr_reader :current, :example_results, :color_index, :pending_count, :failure_count,
:example_count
end
end
# Increments the example count and displays the current progress
#
# @returns nothing
def tick(mark = PASS)
@example_results << mark
@current = (@current > @example_count) ? @example_count : @current + 1
dump_progress
end
# Determine which Ascii Nyan Cat to display. If tests are complete,
# Nyan Cat goes to sleep. If there are failing or pending examples,
# Nyan Cat is concerned.
#
# @return [String] Nyan Cat
def nyan_cat
if self.failed_or_pending? && self.finished?
ascii_cat('x')[@color_index%2].join("\n") #'~|_(x.x)'
elsif self.failed_or_pending?
ascii_cat('o')[@color_index%2].join("\n") #'~|_(o.o)'
elsif self.finished?
ascii_cat('-')[@color_index%2].join("\n") # '~|_(-.-)'
else
ascii_cat('^')[@color_index%2].join("\n") # '~|_(^.^)'
end
end
# Displays the current progress in all Nyan Cat glory
#
# @return nothing
def dump_progress
output.print(progress_lines.join("\n") + eol)
end
def progress_lines
[
nyan_trail.split("\n").each_with_index.inject([]) do |result, (trail, index)|
value = "#{scoreboard[index]}/#{@example_count}:"
result << format("%s %s", value, trail)
end
].flatten
end
# Determines how we end the trail line. If complete, return a newline etc.
#
# @return [String]
def eol
return "\n" if @current == @example_count
length = progress_lines.length - 1
length > 0 ? format("\e[1A" * length + "\r") : "\r"
end
# Calculates the current flight length
#
# @return [Fixnum]
def current_width
# padding_width + example_width + cat_length
padding_width + (@current * example_width) + cat_length
end
# Gets the padding for the current example count
#
# @return [Fixnum]
def padding_width
@example_count.to_s.length * 2 + 6
end
# A Unix trick using stty to get the console columns
#
# @return [Fixnum]
def terminal_width
if defined? JRUBY_VERSION
default_width = 80
else
default_width = `stty size`.split.map { |x| x.to_i }.reverse.first - 1
end
@terminal_width ||= default_width
end
# Creates a data store of pass, failed, and pending example results
# We have to pad the results here because sprintf can't properly pad color
#
# @return [Array]
def scoreboard
@pending_examples ||= []
@failed_examples ||= []
padding = @example_count.to_s.length
[ @current.to_s.rjust(padding),
success_color((@current - @pending_examples.size - @failed_examples.size).to_s.rjust(padding)),
pending_color(@pending_examples.size.to_s.rjust(padding)),
failure_color(@failed_examples.size.to_s.rjust(padding)) ]
end
# Creates a rainbow trail
#
# @return [String] the sprintf format of the Nyan cat
def nyan_trail
marks = @example_results.each_with_index.map{ |mark, i| highlight(mark) * example_width(i) }
marks.shift(current_width - terminal_width) if current_width >= terminal_width
nyan_cat.split("\n").each_with_index.map do |line, index|
format("%s#{line}", marks.join)
end.join("\n")
end
# Times a mark has to be repeated
def example_width(item = 1)
1
end
# Ascii version of Nyan cat. Two cats in the array allow Nyan to animate running.
#
# @param o [String] Nyan's eye
# @return [Array] Nyan cats
def ascii_cat(o = '^')
[[ "_,------, ",
"_| /\\_/\\ ",
"~|_( #{o} .#{o}) ",
" \"\" \"\" "
],
[ "_,------, ",
"_| /\\_/\\",
"^|__( #{o} .#{o}) ",
" \" \" \" \""
]]
end
# Colorizes the string with raindow colors of the rainbow
#
# @params string [String]
# @return [String]
def rainbowify(string)
c = colors[@color_index % colors.size]
@color_index += 1
"#{ESC}38;5;#{c}m#{string}#{NND}"
end
# Calculates the colors of the rainbow
#
# @return [Array]
def colors
@colors ||= (0...(6 * 7)).map do |n|
pi_3 = Math::PI / 3
n *= 1.0 / 6
r = (3 * Math.sin(n ) + 3).to_i
g = (3 * Math.sin(n + 2 * pi_3) + 3).to_i
b = (3 * Math.sin(n + 4 * pi_3) + 3).to_i
36 * r + 6 * g + b + 16
end
end
# Determines how to color the example. If pass, it is rainbowified, otherwise
# we assign red if failed or yellow if an error occurred.
#
# @return [String]
def highlight(mark = PASS)
case mark
when PASS; rainbowify PASS_ARY[@color_index%2]
when FAIL; "\e[31m#{mark}\e[0m"
when ERROR; "\e[33m#{mark}\e[0m"
when PENDING; "\e[33m#{mark}\e[0m"
else mark
end
end
# Converts a float of seconds into a minutes/seconds string
#
# @return [String]
def format_duration(duration)
seconds = ((duration % 60) * 100.0).round / 100.0 # 1.8.7 safe .round(2)
seconds = seconds.to_i if seconds.to_i == seconds # drop that zero if it's not needed
message = "#{seconds} second#{seconds == 1 ? "" : "s"}"
message = "#{(duration / 60).to_i} minute#{(duration / 60).to_i == 1 ? "" : "s"} and " + message if duration >= 60
message
end
# Determines if the specs have completed
#
# @returns [Boolean] true if finished; false otherwise
def finished?
(@current == @example_count)
end
# Determines if the any specs failed or are in pending state
#
# @returns [Boolean] true if failed or pending; false otherwise
def failed_or_pending?
(@failure_count.to_i > 0 || @pending_count.to_i > 0)
end
# Returns the cat length
#
# @returns [Fixnum]
def cat_length
nyan_cat.split("\n").group_by(&:size).max.first
end
def success_color(text)
wrap(text, :success)
end
def pending_color(text)
wrap(text, :pending)
end
def failure_color(text)
wrap(text, :failure)
end
def console_code_for(code_or_symbol)
if VT100_CODE_VALUES.has_key?(code_or_symbol)
code_or_symbol
else
VT100_CODES.fetch(code_or_symbol) do
console_code_for(:white)
end
end
end
def wrap(text, code_or_symbol)
if RSpec.configuration.color_enabled?
"\e[#{console_code_for(code_or_symbol)}m#{text}\e[0m"
else
text
end
end
end
end
| 27.439394
| 120
| 0.567918
|
797cdccedb2a6109317fc5e31379fa687419e0ae
| 417
|
php
|
PHP
|
app/Competence.php
|
safartech/clp
|
b5563ac6b08950c0ab645a1f0160ec5b5b5ef8fc
|
[
"MIT"
] | 1
|
2019-09-27T02:07:40.000Z
|
2019-09-27T02:07:40.000Z
|
app/Competence.php
|
safartech/clp
|
b5563ac6b08950c0ab645a1f0160ec5b5b5ef8fc
|
[
"MIT"
] | null | null | null |
app/Competence.php
|
safartech/clp
|
b5563ac6b08950c0ab645a1f0160ec5b5b5ef8fc
|
[
"MIT"
] | null | null | null |
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Competence extends Model
{
public function eleves(){
return $this->belongsToMany('App\Eleve','epc','competence_id')->withPivot(['id','validation','session_id']);
}
public function domaine(){
return $this->belongsTo('App\Domaine');
}
public function epcs(){
return $this->hasMany('App\Epc');
}
}
| 18.130435
| 116
| 0.635492
|
01e8dd517c29fc2e5f8a71a6f4dad3f61d00c3ab
| 21,668
|
lua
|
Lua
|
modules/mqtt/lua/mqtt.lua
|
czanyou/node.lua
|
1711425dd042ff5b6034a866653400fb00bede76
|
[
"Apache-2.0"
] | 19
|
2016-05-04T12:22:12.000Z
|
2021-11-04T17:36:44.000Z
|
modules/mqtt/lua/mqtt.lua
|
czanyou/node.lua
|
1711425dd042ff5b6034a866653400fb00bede76
|
[
"Apache-2.0"
] | 2
|
2015-11-01T12:48:13.000Z
|
2018-10-25T09:14:41.000Z
|
modules/mqtt/lua/mqtt.lua
|
czanyou/node.lua
|
1711425dd042ff5b6034a866653400fb00bede76
|
[
"Apache-2.0"
] | 6
|
2016-03-30T15:21:06.000Z
|
2020-10-27T06:48:48.000Z
|
--[[
Copyright 2016-2020 The Node.lua Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local core = require('core')
local uv = require('luv')
local packet = require('mqtt/packet')
local Packet = packet.Packet
local exports = {}
exports.DEFAULT_PORT = 1883
exports.KEEP_ALIVE_TIME = 60 -- seconds (maximum is 65535)
exports.MAX_RECONNECT_INTERVAL = 60 * 1000
-------------------------------------------------------------------------------
-- MQTTSocket
---@class MQTTSocket
local MQTTSocket = core.Emitter:extend()
exports.MQTTSocket = MQTTSocket
--[[
Create an MQTT client instance
`MQTTSocket` automatically handles the following:
* Regular server pings
* QoS flow
* Automatic reconnections
* Start publishing before being connected
@param {object} options
- {string} clientId
- {number} connectTimeout
- {number} keepalive
- {number} port
- {number} reconnectPeriod
- {function} callback
- {string} hostname
- {string} username
- {string} password
- {number} will
--]]
function MQTTSocket:initialize(options)
options = options or {}
self._outgoingStore = {} -- 用来存储需要 ACK 确认的请求消息
self.clientSocket = nil -- 相关的 TCP Socket
self.connectAckTimer = nil -- 等待 Connect ACK 超时定时器
self.connected = false -- 当收到了 connect ACK 消息, 表示 MQTT 已连接
self.debugEnabled = false -- 指出是否显示调试信息
self.destroyed = false -- 指出这个客户端是否已经被关闭了, 将不再重连等
self.keepAliveTimer = nil -- Keep Alive 保活 Timer
self.options = options
self.state = {} -- MQTT 客户端状态
self.reconnecting = false
self.server = nil
-- options
local clientId = ("lnode_" .. tostring(process.pid))
options.clientId = options.clientId or clientId
options.connectTimeout = options.connectTimeout or (30 * 1000) -- 30 * 1000 milliseconds, time to wait before a CONNACK is received
options.keepalive = options.keepalive or exports.KEEP_ALIVE_TIME -- 60 seconds, set to 0 to disable
options.reconnectPeriod = options.reconnectPeriod or 1000 -- 1000 milliseconds, interval between two reconnections. Disable auto reconnect by setting to 0.
-- state
local state = self.state
state.lastActivityIn = 0 -- 最后收到消息的时间
state.lastActivityOut = 0 -- 最后发出消息的时间
state.lastActivityPing = 0 -- 最后收到 ping 应答时间
state.lastConnectTime = 0 -- 最后一次发起连接的时间
state.nextMessageId = 0 -- 下一个消息 ID
state.reconnectCount = 0 -- 当前重连次数
state.reconnecting = false -- 正在重连中
state.reconnectInterval = options.reconnectPeriod -- 当前重连间隔
state.socketConnected = false -- 仅当已建立 TCP 连接
-- console.log('options', options)
end
--[[
Close the client, accepts the following options:
* `force`: passing it to true will close the client right away, without
waiting for the in-flight messages to be acked. This parameter is
optional.
* `callback`: will be called when the client is closed. This parameter is
optional.
-- ]]
function MQTTSocket:close(force, callback)
-- close(callback)
if (type(force) == 'funciton') then
callback = force
force = nil
end
if (self.destroyed) then
if (callback) then
callback()
end
return 0
end
if (self.connected) then
self:_sendDisconnect()
end
self:_onDisconnect()
if (self.keepAliveTimer) then
clearInterval(self.keepAliveTimer)
self.keepAliveTimer = nil
end
-- reset
self.options.callback = nil
self.state.reconnectInterval = 1000
self.destroyed = true -- Avoid recursion when _sendMessage() fails
if (callback) then
callback()
end
return 1
end
-- 显示错误消息, 但不会关闭当前连接
--
function MQTTSocket:emitError(errInfo)
self:_onDebug(errInfo)
self:emit('error', errInfo)
end
-- Parse MQTT message
-- ~~~~~~~~~~~~~~~~~~
-- MQTT 3.1 Specification: Section 2.1: Fixed header
--
-- Structure of an MQTT Control Packet:
-- byte 1: Message type and flags (DUP, QOS level, and Retain) fields
-- bytes 2-5: Remaining length field (between one and four bytes long)
-- bytes m- : Optional variable header and payload
--
-- Figure 2.2 - Fixed header format
--
-- | Bit | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
-- | - - - - - | - - - - - - - - - - - | - - | - - - - - | - - |
-- | byte 1 | Control Packet type | DUP | Qos | RET |
-- | byte 2… | Remaining Length |
-- The message type/flags and remaining length are already parsed and
-- removed from the message by the time this function is invoked.
-- Leaving just the optional variable header and payload.
-- @param {MQTTPacket} message -- 要处理的 MQTT 消息
function MQTTSocket:handleMessage(message)
local messageType = message.messageType
self.state.lastActivityIn = process.now()
-- TODO: packet.TYPE table should include "parser handler" function.
-- This would nicely collapse the if .. then .. elseif .. end.
if (messageType == packet.TYPE_CONACK) then
self:_handleConnectACK(message)
elseif (messageType == packet.TYPE_PUBLISH) then
self:_handlePublish(message)
elseif (messageType == packet.TYPE_PUBACK) then
self:_handlePublishACK(message)
elseif (messageType == packet.TYPE_SUBACK) then
self:_handleSubscribeACK(message)
elseif (messageType == packet.TYPE_UNSUBACK) then
self:_handleUnsubscribeACK(message)
elseif (messageType == packet.TYPE_PINGREQ) then
self:_sendPingResponse()
elseif (messageType == packet.TYPE_PINGRESP) then
self:_handlePingResponse(message)
else
local errorMessage = "handleMessage: Unknown message type: " .. tostring(messageType)
self:_onDebug(errorMessage)
end
end
-- 存储/读取指定 ID 的消息
-- @param {string} messageId
-- @param {MQTTPacket} message
-- @returns {MQTTPacket} message
function MQTTSocket:outgoingStore(messageId, message)
if (not messageId) then
return
end
if (message) then
message.timestamp = process.now()
self._outgoingStore[messageId] = message
else
return self._outgoingStore[messageId]
end
end
-- 弹出指定的 ID 的消息
-- - 当收到指定的请求 (publish, subscribe, unsubscribe) 的 ACK 消息时,调用这个方法
-- @param {string} messageId ACK 消息 ID
-- @returns {MQTTPacket} request 返回相关的请求消息
function MQTTSocket:popOutgoingMessage(messageId)
if (not messageId) then
return
end
local request = self._outgoingStore[messageId]
if (request) then
self._outgoingStore[messageId] = nil
end
return request
end
-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --
-- MQTT Private Methods
-- 检查是否已连接
-- @param {string} name
function MQTTSocket:_checkConnected(name, callback)
if (self.state.socketConnected == false) then
local errInfo = "" .. name .. ": Not connected"
self:emitError(errInfo)
if (callback) then
callback(nil, errInfo)
end
return false
end
return true
end
-- 处理定时器事件, 在定时器事件中可以处理心跳, 重连等工作
-- 每隔 1 秒调用一次,直到停止连接
function MQTTSocket:_checkKeepAlive()
if (self.destroyed) then
return
end
local now = process.now()
local options = self.options
if (self.connected) then
-- 定时发生 ping 消息,并检查会话是否超时
local lastActivity = self.state.lastActivityIn
local span = math.abs(now - lastActivity)
local keepalive = options.keepalive * 1000
--console.log('connected', span)
if (span > keepalive * 2) then
self:_onErrorEvent("session timeout")
elseif (span > keepalive) then
self:_sendPingRequest()
end
elseif (not self.connectAckTimer) then
-- 如果不在连接中,则定时发起重连
-- reconnect
local state = self.state
local span = math.abs(now - state.lastConnectTime)
if (span > state.reconnectInterval) then
state.reconnectInterval = math.min(state.reconnectInterval * 2, exports.MAX_RECONNECT_INTERVAL)
self:_onReconnect()
local host = self.server and self.server.host
console.info('mqtt.reconnect', host, span, state.reconnectCount, state.reconnectInterval)
end
end
end
-- 开始连接
function MQTTSocket:_onConnect()
-- #1. create socket
if (self.clientSocket) then
uv.close(self.clientSocket)
self.clientSocket = nil
end
self.clientSocket = uv.new_tcp()
if (self.clientSocket == nil) then
self:_onErrorEvent("connect: Couldn't open MQTT broker connection")
return
end
-- #2. set connect timeout
if (self.connectAckTimer) then
clearTimeout(self.connectAckTimer)
self.connectAckTimer = nil
end
local options = self.options
-- console.log('options', options)
local connectTimeout = options.connectTimeout
self.connectAckTimer = setTimeout(connectTimeout, function()
self:_onErrorEvent("connect timeout!")
end)
-- #3. connect
self.state.lastConnectTime = process.now()
local _onConnectCallback = function(err)
if (err) then
self:_onErrorEvent('connect failed: ' .. err)
else
self:_onSocketConnected()
end
end
-- #4. query dns
local servers = options.servers
local nextServerId = (servers.serverId or 0) + 1
if (nextServerId > #servers) then
nextServerId = 1
end
servers.serverId = nextServerId
local server = servers[nextServerId]
self.server = server
-- console.log('servers', servers)
local host = server.host
local port = server.port or exports.DEFAULT_PORT
local params = { socktype = "stream", family = "inet" }
uv.getaddrinfo(host, port, params, function(err, res)
if err then
self:_onErrorEvent('query dns failed: ' .. tostring(err))
elseif (not self.clientSocket) then
self:_onErrorEvent('query dns failed: invalid socket')
elseif (not res) or (not res[1]) then
self:_onErrorEvent('query dns failed: invalid response')
else
local dest = res[1]
self.state.address = { dest.addr, dest.port }
self.clientSocket:connect(dest.addr, dest.port, _onConnectCallback)
end
end)
return 0
end
function MQTTSocket:_onConnected(message)
local state = self.state
state.reconnectCount = 0
state.reconnectInterval = self.options.reconnectPeriod or 1000
self:emit('connect', message)
console.log('mqtt.connect', self.server and self.server.host)
end
-- 显示调试信息
--
function MQTTSocket:_onDebug(info)
if (self.debugEnabled) then
print(info)
end
end
-- 停止连接
-- - 发生严重错误等时候会调用
-- @param {string} info 关闭事件消息
function MQTTSocket:_onDisconnect(info)
-- close MQTT connection
if (self.connected) then
self.connected = false
self:emit('close', info)
self:emit('offline')
end
-- cancel connect timer
if (self.connectAckTimer) then
clearTimeout(self.connectAckTimer)
self.connectAckTimer = nil
end
-- close TCP connection
if (self.clientSocket) then
uv.close(self.clientSocket)
self.clientSocket = nil
end
-- reset
self.state.socketConnected = false
self._outgoingStore = {}
end
-- 显示严重错误消息, 且关闭当前连接
-- @param {string} errInfo
function MQTTSocket:_onErrorEvent(errInfo)
self:emit('error', errInfo)
self:_onDisconnect()
end
-- 重连, 会生产 'reconnect' 事件
-- - 由 KeepAlive 定时器调用
function MQTTSocket:_onReconnect()
local state = self.state
state.reconnecting = true
state.reconnectCount = (state.reconnectCount or 0) + 1
self:emit('reconnect', state.reconnectCount)
self:_onDisconnect()
self:_onConnect()
end
-- 当成功建立 Socket 连接
function MQTTSocket:_onSocketConnected()
local now = process.now();
local state = self.state
local options = self.options
local span = math.abs(now - state.lastConnectTime)
-- 必须大于最大重连间隔才重置重连间隔,避免反复连接和断开的 bug
state.socketConnected = true
state.lastActivityOut = process.now()
if (span > exports.MAX_RECONNECT_INTERVAL) then
state.reconnectInterval = options.reconnectPeriod
end
self.clientSocket:read_start(function(err, chunk)
-- console.log('read_start', chunk and #chunk)
if (err) then
self:_onErrorEvent('read_start: read failed: ' .. tostring(err))
elseif (not chunk) then
--print('read_start: empty chunk')
self:_onErrorEvent('read_start: read end!')
else
self:_handleMessageData(chunk)
end
end)
self:_sendConnect()
end
-- Handle received messages and maintain keep-alive PING messages
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--[[
This function must be invoked periodically (more often than the
exports.KEEP_ALIVE_TIME) which maintains the connection and
services the incoming subscribed topic messages.
Handle messages with backpressure support, one at a time.
Override at will, but __always call `callback`__, or the client
will hang.
@param {string} buffer 收到的数据
]]
function MQTTSocket:_handleMessageData(buffer)
-- Check for available client socket data
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if (buffer == nil or #buffer <= 0) then
return
end
if (self.lastBuffer) then
buffer = self.lastBuffer .. buffer
self.lastBuffer = nil
end
local emitError = function(error)
self:emit('error', error)
end
-- 检查连接状态
self:_checkConnected('_handleMessageData')
-- Parse individual messages (each must be at least 2 bytes long)
-- Decode "remaining length" (MQTT v3.1 specification pages 6 and 7)
local index = 1
local mqttMessage = nil
-- 解析并处理消息
while (index < #buffer) do
mqttMessage, index = packet.parse(buffer, index, emitError)
if (not mqttMessage) then
self.lastBuffer = buffer -- 缓存剩余的数据
break
end
self:handleMessage(mqttMessage)
end
end
-- Parse MQTT CONACK message
-- ~~~~~~~~~~~~~~~~~~~~~~~~~
-- MQTT 3.1 Specification: Section 3.2: CONACK Acknowledge connection
--
-- byte 1: Reserved value
-- byte 2: Connect return code, see MQTT.CONACK.errorMessage[]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function MQTTSocket:_handleConnectACK(message)
-- cancel connect timer
if (self.connectAckTimer) then
clearTimeout(self.connectAckTimer)
self.connectAckTimer = nil
end
-- 连接被服务器拒绝
if (message.returnCode ~= 0) then
self:_onErrorEvent("Connection refused: " .. tostring(message.errorMessage))
return
end
self.state.reconnecting = false
if (not self.connected) then
self.connected = true
self:_onConnected(message)
end
end
-- Parse MQTT PINGRESP message
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- MQTT 3.1 Specification: Section 3.13: PING response
-- messageFlags, -- byte
-- remainingLength, -- integer
-- message -- string
function MQTTSocket:_handlePingResponse(message)
self.state.lastActivityPing = process.now()
end
-- Parse MQTT PUBLISH message
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~
-- MQTT 3.1 Specification: Section 3.3: Publish message
--
-- Variable header ..
-- bytes 1- : Topic name and optional Message Identifier (if QOS > 0)
-- bytes m- : Payload
function MQTTSocket:_handlePublish(message)
local callback = self.options.callback
if (callback) then
callback(message.topic, message.payload)
end
self:emit('message', message.topic, message.payload)
end
function MQTTSocket:_handlePublishACK(message)
local messageId = message.messageId
if (not messageId) then
self:emitError("invalid messsage ID: ")
return
end
local request = self:popOutgoingMessage(messageId)
if (request == nil) then
self:emitError("No outgoing publish message: " .. tostring(messageId))
return
end
if (request.callback) then
request.callback()
end
end
function MQTTSocket:_handlePublishRel(message)
-- TODO: qos 2
end
function MQTTSocket:_handlePublishRec(message)
-- TODO: qos 2
end
-- Parse MQTT SUBACK message
-- ~~~~~~~~~~~~~~~~~~~~~~~~~
-- MQTT 3.1 Specification: Section 3.9: SUBACK Subscription acknowledgement
--
-- bytes 1,2: Message Identifier
-- bytes 3- : List of granted QOS for each subscribed topic
function MQTTSocket:_handleSubscribeACK(message)
local messageId = message.messageId
local request = self:popOutgoingMessage(messageId)
if (request == nil) then
self:emitError("No outgoing subscribe message: ", messageId)
return
end
local callback = request.callback
if (not callback) then
return
end
if (request.message ~= "subscribe") then
callback("Outstanding message wasn't SUBSCRIBE")
return
end
local topicCount = #(request.topics)
if (topicCount ~= message.length - 2) then
callback("Didn't received expected number of topics: " .. topicCount)
return
end
callback(nil, message)
end
-- Parse MQTT UNSUBACK message
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- MQTT 3.1 Specification: Section 3.11: UNSUBACK Unsubscription acknowledgement
--
-- bytes 1,2: Message Identifier
--
function MQTTSocket:_handleUnsubscribeACK(message)
local messageId = message.messageId or ''
local request = self:popOutgoingMessage(messageId)
if (request == nil) then
self:emitError("No outgoing unsubscribe message: " .. messageId)
return
end
local callback = request.callback
if (not callback) then
return
end
if (request.message ~= "unsubscribe") then
callback("Outstanding message wasn't UNSUBSCRIBE")
return
end
callback()
end
function MQTTSocket:_nextMessageId()
local state = self.state
state.nextMessageId = state.nextMessageId + 1
if (state.nextMessageId > 0xffff) then
state.nextMessageId = 1 -- Ensure 16 bit unsigned int
end
return state.nextMessageId
end
-- Transmit MQTT connect message
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function MQTTSocket:_sendConnect()
local options = self.options
local message = Packet:new()
message.messageType = packet.TYPE_CONNECT
message.will = options.will
message.clientId = options.clientId
message.keepalive = options.keepalive
message.username = options.username
message.password = options.password
return self:_sendMQTTPacket(message)
end
-- Transmit MQTT Disconnect message
-- ~~~~~~~~~~~~~~~~~~~~~~~~
-- MQTT 3.1 Specification: Section 3.14: Disconnect notification
--
-- bytes 1,2: Fixed message header, see MQTTSocket:_sendMessage()
function MQTTSocket:_sendDisconnect()
if (self.connected) then
self:_sendMessage(packet.TYPE_DISCONNECT)
end
end
-- Transmit MQTT Ping request message
-- ~~~~~~~~~~~~~~~~~~~~~~~~
-- MQTT 3.1 Specification: Section 3.13: PING request
function MQTTSocket:_sendPingRequest()
self:_checkConnected('_sendPingRequest')
if (self.connected) then
return self:_sendMessage(packet.TYPE_PINGREQ)
end
end
-- Transmit MQTT Ping response message
-- ~~~~~~~~~~~~~~~~~~~~~~~~
-- MQTT 3.1 Specification: Section 3.13: PING response
function MQTTSocket:_sendPingResponse()
self:_checkConnected('_sendPingResponse')
return self:_sendMessage(packet.TYPE_PINGRESP)
end
-- Transmit an MQTT message
-- ~~~~~~~~~~~~~~~~~~~~~~~~
-- MQTT 3.1 Specification: Section 2.1: Fixed header
--
-- byte 1: Message type and flags (DUP, QOS level, and Retain) fields
-- bytes 2-5: Remaining length field (between one and four bytes long)
-- bytes m- : Optional variable header and payload
-- @param {number} messageType -- enumeration
-- @param {string} payload -- string
-- @returns nil or error message
function MQTTSocket:_sendMessage(messageType, payload, callback)
local message = Packet:new(messageType, payload)
return self:_sendMQTTPacket(message, callback)
end
-- 发送 MQTT 消息包
-- @param {MQTTPacket} message
-- @param {function} callback
function MQTTSocket:_sendMQTTPacket(message, callback, ...)
if (callback) then
setImmediate(callback)
end
local messageData = message:build(...)
if (not messageData) then
self:_onDebug('invalid message: ', message)
return nil, 'Invalid message data'
end
--console.printBuffer(messageData)
if (not self.clientSocket) then
return messageData, 'Invalid MQTT client socket'
end
-- write
local status = self.clientSocket:write(messageData)
if (status == nil) then
self:_onErrorEvent("_sendMQTTPacket: write failed")
return nil, 'write MQTT packet failed'
end
--console.log('_sendMQTTPacket', messageData)
self.state.lastActivityOut = process.now()
return messageData
end
return exports
--]]
| 28.176853
| 159
| 0.65036
|
1733d912a56b3711f61a0f2d23c669d5645d7d95
| 2,635
|
cpp
|
C++
|
src/meta_optimization/pattern.cpp
|
cmccomb/CISAT
|
45b6864fc8c83eb1b8eee56f0f74912fecd3973d
|
[
"MIT"
] | 1
|
2021-08-30T23:06:03.000Z
|
2021-08-30T23:06:03.000Z
|
src/meta_optimization/pattern.cpp
|
THREDgroup/CISAT-cpp
|
45b6864fc8c83eb1b8eee56f0f74912fecd3973d
|
[
"MIT"
] | 2
|
2021-11-21T18:02:11.000Z
|
2022-03-28T20:51:58.000Z
|
src/meta_optimization/pattern.cpp
|
THREDgroup/CISAT-cpp
|
45b6864fc8c83eb1b8eee56f0f74912fecd3973d
|
[
"MIT"
] | null | null | null |
#include "../../include/meta_optimization/pattern.hpp"
PatternSearch::PatternSearch(std::string file_name){
seed_time();
parse_parameter_file(file_name);
}
void PatternSearch::solve(int max_iter){
// Do some initial things
current_iteration = 0;
std::vector<std::vector<long double> > fx_current;
long double new_val;
bool has_improved;
ParameterSet p_current;
long double comp;
// Find average initial quality
MultipleTeams MT1(best_parameters);
fx_best = MT1.solve();
// std::cout << "\nBeginning Optimization Routine, fx = " << fx_best << std::endl;
std::cout << "\nBeginning Optimization Routine" << std::endl;
while(current_iteration < max_iter){
// This variable will keep track of whether or not an improvement has been made
has_improved = false;
std::cout << "\tIteration " << current_iteration + 1 << " of " << max_iter << std::endl;
for(int i=0; i<variable_names.size(); i++){
for(int j=1; j>-2; j-=2){
// Modify the list of parameters
p_current = best_parameters;
new_val = variable_values[i] + j*step_sizes[i];
// Keep it all in range
if(new_val < lower_limits[i]){
new_val = lower_limits[i];
}
if(new_val > upper_limits[i]){
new_val = upper_limits[i];
}
std::cout << "\t\tTrying " << variable_names[i] << " = " << new_val << ", ";
p_current.set_from_pair(variable_names[i], new_val);
// Evalute the new combination
MultipleTeams MTR(p_current);
fx_current = MTR.solve();
comp = pareto_cliff_delta(fx_current, fx_best);
std::cout << "d = " << comp << std::endl;
// Keep track of the best solution
if(comp > 0){
std::cout << "\t\tImprovement." << std::endl;
variable_values[i] = new_val;
fx_best = fx_current;
best_parameters = p_current;
has_improved = true;
goto objective_improved_so_continue;
}
}
}
objective_improved_so_continue:
// If no improvement, update the stepsize values
if(!has_improved){
std::cout << "\t\tUpdating stepsizes." << std::endl;
for(int i=0; i<step_sizes.size(); i++){
step_sizes[i] /= 2.0;
}
}
current_iteration++;
}
}
| 35.608108
| 96
| 0.531309
|
da6ee94e41341639a30b7fa560dc8d31219399e3
| 1,276
|
php
|
PHP
|
lib/SteamCondenser/Servers/Packets/S2CCHALLENGEPacket.php
|
Fluxter/steam-condenser-php
|
8368619578a6fdb2a991fd0c0da26b37aaa2044e
|
[
"BSD-3-Clause"
] | 112
|
2015-01-16T02:40:52.000Z
|
2022-01-31T14:23:07.000Z
|
lib/SteamCondenser/Servers/Packets/S2CCHALLENGEPacket.php
|
Fluxter/steam-condenser-php
|
8368619578a6fdb2a991fd0c0da26b37aaa2044e
|
[
"BSD-3-Clause"
] | 6
|
2015-03-01T15:48:27.000Z
|
2021-01-29T18:20:55.000Z
|
lib/SteamCondenser/Servers/Packets/S2CCHALLENGEPacket.php
|
Fluxter/steam-condenser-php
|
8368619578a6fdb2a991fd0c0da26b37aaa2044e
|
[
"BSD-3-Clause"
] | 61
|
2015-01-05T15:42:16.000Z
|
2022-03-25T01:55:11.000Z
|
<?php
/**
* This code is free software; you can redistribute it and/or modify it under
* the terms of the new BSD License.
*
* Copyright (c) 2008-2014, Sebastian Staudt
*
* @license http://www.opensource.org/licenses/bsd-license.php New BSD License
*/
namespace SteamCondenser\Servers\Packets;
/**
* This packet class represents a S2C_CHALLENGE response replied by a game
* server
*
* It is used to provide a challenge number to a client requesting information
* from the game server.
*
* @author Sebastian Staudt
* @package steam-condenser
* @subpackage packets
* @see GameServer::updateChallengeNumber()
*/
class S2CCHALLENGEPacket extends SteamPacket {
/**
* Creates a new S2C_CHALLENGE response object based on the given data
*
* @param string $challengeNumber The raw packet data replied from the
* server
*/
public function __construct($challengeNumber) {
parent::__construct(SteamPacket::S2C_CHALLENGE_HEADER, $challengeNumber);
}
/**
* Returns the challenge number received from the game server
*
* @return int The challenge number provided by the game server
*/
public function getChallengeNumber() {
return $this->contentData->rewind()->getLong();
}
}
| 27.73913
| 81
| 0.696708
|
45bf8c2b1321dcb3661a777dcf47ac9ae122b85e
| 2,149
|
py
|
Python
|
DailyProgrammer/DP20120713B.py
|
DayGitH/Python-Challenges
|
bc32f1332a92fcc2dfa6f5ea4d95f8a8d64c3edf
|
[
"MIT"
] | 2
|
2020-12-23T18:59:22.000Z
|
2021-04-14T13:16:09.000Z
|
DailyProgrammer/DP20120713B.py
|
DayGitH/Python-Challenges
|
bc32f1332a92fcc2dfa6f5ea4d95f8a8d64c3edf
|
[
"MIT"
] | null | null | null |
DailyProgrammer/DP20120713B.py
|
DayGitH/Python-Challenges
|
bc32f1332a92fcc2dfa6f5ea4d95f8a8d64c3edf
|
[
"MIT"
] | null | null | null |
"""
Write a function graph(f, low, high, tests) that outputs a probability graph of the function f from range low to high
(inclusive) over tests tests (i.e., counting the frequencies of f() outputs). f takes no arguments and returns an
integer, low, high and tests are all integer values. For example, a function f that simulates two-dice rolls:
def two_dice():
return random.randint(1, 6) + random.randint(1, 6)
Then graph(f, 2, 12, 10000) should output something roughly like:
2: ##
3: #####
4: #######
5: ###########
6: #############
7: #################
8: #############
9: ###########
10: ########
11: #####
12: ##
For bonus points, output the graph with the numbers on the bottom and the bars drawn vertically.
"""
import random
def two_dice():
return random.randint(1, 6) + random.randint(1, 6)
def three_dice():
return random.randint(1, 6) + random.randint(1, 6) + random.randint(1, 6)
def graph(f, low, high, tests):
res = {i: 0 for i in range(low, high+1)}
for _ in range(tests):
try:
res[f()] += 1
except KeyError:
pass
print(res)
horizontal_print(res)
vertical_print(res)
def horizontal_print(res):
rounder = min([res[k] for k in res]) // 2
max_size = len(str(max(res)))
for k in res:
res[k] = int(round(res[k] / rounder))
print('{:>{max_size}}: {}'.format(k, '#' * res[k], max_size=max_size))
def vertical_print(res):
rounder = min([res[k] for k in res]) // 2
max_size = len(str(max(res)))
max_height = max([res[k] for k in res])
for k in res:
res[k] = int(round(res[k] / rounder))
res[k] = '{:>{max_height}}'.format('#' * res[k], max_height=max_height)
for i in range(max_height):
for k in res:
print('{:>{max_size}}'.format(res[k][i], max_size=max_size+1), end='')
print('')
print('=' * (max_size+1) * len(res))
for k in res:
print('{:>{max_size}}'.format(k, max_size=max_size+1), end='')
def main():
graph(two_dice, 2, 12, 100000)
graph(three_dice, 3, 18, 100000)
if __name__ == "__main__":
main()
| 25.282353
| 117
| 0.574221
|
dc6dd107cac4bc85bac1070b14be02001ea46ab7
| 285
|
ts
|
TypeScript
|
tests/intersperse.ts
|
ikatyang/types
|
97ae230c2214b56fa8dc593678b7ad2538e8f5a1
|
[
"MIT"
] | null | null | null |
tests/intersperse.ts
|
ikatyang/types
|
97ae230c2214b56fa8dc593678b7ad2538e8f5a1
|
[
"MIT"
] | null | null | null |
tests/intersperse.ts
|
ikatyang/types
|
97ae230c2214b56fa8dc593678b7ad2538e8f5a1
|
[
"MIT"
] | null | null | null |
import * as R_intersperse from '../ramda/dist/src/intersperse';
declare const object_array: object[];
declare const string: string;
// @dts-jest:pass
R_intersperse(string);
// @dts-jest:pass
R_intersperse(string, object_array);
// @dts-jest:pass
R_intersperse(string)(object_array);
| 23.75
| 63
| 0.757895
|
a1444c4d3f7956221dd1aa0d9288af45b096f849
| 1,707
|
ts
|
TypeScript
|
src/index.ts
|
ozeron/loc-pr-guard
|
47755e0cddb11dfa3f3209baab5dc65c5c149c45
|
[
"0BSD"
] | null | null | null |
src/index.ts
|
ozeron/loc-pr-guard
|
47755e0cddb11dfa3f3209baab5dc65c5c149c45
|
[
"0BSD"
] | null | null | null |
src/index.ts
|
ozeron/loc-pr-guard
|
47755e0cddb11dfa3f3209baab5dc65c5c149c45
|
[
"0BSD"
] | null | null | null |
import { Application, Context } from 'probot' // eslint-disable-line no-unused-vars
import { CheckStatus, CheckConclusion } from './types'
import fileFilter from './fileFilter'
const ADDITIONS_MAX_NUM = 1000
async function eventHandler (context: Context) {
const owner : string = context.payload.pull_request.base.repo.owner.login
const repo : string = context.payload.pull_request.base.repo.name
const name : string = 'loc-guard'
const head : string = context.payload.pull_request.head.sha
let status = 'queued' as CheckStatus
let opts = { owner, repo, name, 'head_sha': head, status }
await context.github.checks.create(opts)
const base = context.payload.pull_request.base.sha
const comparison = await context.github.repos.compareCommits({ owner, repo, base, head })
const files = comparison.data.files
const allAdditions = files.filter(fileFilter).reduce((a : number, e : any) => a + e.additions, 0)
status = 'completed' as CheckStatus
let conclusion = 'success' as CheckConclusion
const output : any = {}
output.title = `Checked LOC – It smaller than ${ADDITIONS_MAX_NUM}`
output.summary = 'It is ok'
if (allAdditions > ADDITIONS_MAX_NUM) {
conclusion = 'failure' as CheckConclusion
output.title = `Checked LOC – It ${allAdditions}, it's bigger than maximum ${ADDITIONS_MAX_NUM}`
output.summary = 'It is have problem'
}
const completedAt = (new Date()).toISOString()
const finalOpts = { owner, repo, name, 'head_sha': head, status, conclusion, 'completed_at': completedAt, output }
await context.github.checks.create(finalOpts)
}
export = (app: Application) => {
app.on(['pull_request.opened', 'pull_request.synchronize'], eventHandler)
}
| 40.642857
| 116
| 0.725835
|
cf5117c9f06d545977ffe872984504780c044e1f
| 2,197
|
rs
|
Rust
|
src/cluster/src/error.rs
|
simlay/fluvio
|
a42283200e667223d3a52b217d266db8927db4eb
|
[
"Apache-2.0"
] | null | null | null |
src/cluster/src/error.rs
|
simlay/fluvio
|
a42283200e667223d3a52b217d266db8927db4eb
|
[
"Apache-2.0"
] | null | null | null |
src/cluster/src/error.rs
|
simlay/fluvio
|
a42283200e667223d3a52b217d266db8927db4eb
|
[
"Apache-2.0"
] | null | null | null |
use std::io::Error as IoError;
use thiserror::Error;
use fluvio::FluvioError;
use k8_config::{ConfigError as K8ConfigError};
use k8_client::{ClientError as K8ClientError};
use crate::helm::HelmError;
use crate::check::CheckError;
/// The types of errors that can occur during cluster management
#[derive(Error, Debug)]
pub enum ClusterError {
/// An IO error occurred, such as opening a file or running a command.
#[error(transparent)]
IoError {
#[from]
/// The underlying IO error
source: IoError,
},
/// An error occurred with the Fluvio client.
#[error("Fluvio client error")]
FluvioError {
#[from]
/// The underlying Fluvio error
source: FluvioError,
},
/// An error occurred with the Kubernetes config.
#[error("Kubernetes config error")]
K8ConfigError {
#[from]
/// The underlying Kubernetes config error
source: K8ConfigError,
},
/// An error occurred with the Kubernetes client.
#[error("Kubernetes client error")]
K8ClientError {
#[from]
/// The underlying Kubernetes client error
source: K8ClientError,
},
/// An error occurred while running helm.
#[error("Helm client error")]
HelmError {
#[from]
/// The underlying Helm client error
source: HelmError,
},
/// An error that occurred during pre-installation checks
#[error("Fluvio pre-installation check failed")]
PreCheckError {
/// The pre-check error that occurred
#[from]
source: CheckError,
},
/// Timed out when waiting for SC service.
#[error("Timed out when waiting for SC service")]
SCServiceTimeout,
/// Timed out when waiting for SC port check.
#[error("Timed out when waiting for SC port check")]
SCPortCheckTimeout,
/// Timed out when waiting for DNS resolution.
#[error("Timed out when waiting for DNS resolution")]
SCDNSTimeout,
/// Timed out when waiting for SPU.
#[error("Timed out when waiting for SPU")]
SPUTimeout,
/// A different kind of error occurred.
#[error("An unknown error occurred: {0}")]
Other(String),
}
| 30.943662
| 74
| 0.637233
|
2f2220253437de4eb555702f85bfbe308593a503
| 15,508
|
js
|
JavaScript
|
projects/xl_app/src/utils/request.js
|
baikaifa/self-tool
|
5f3538ea9901cef0c9aabfa5ba43d77e68b0a2ea
|
[
"MIT"
] | null | null | null |
projects/xl_app/src/utils/request.js
|
baikaifa/self-tool
|
5f3538ea9901cef0c9aabfa5ba43d77e68b0a2ea
|
[
"MIT"
] | 9
|
2021-03-09T13:28:35.000Z
|
2022-02-26T15:55:59.000Z
|
projects/xl_app/src/utils/request.js
|
baikaifa/self-tool
|
5f3538ea9901cef0c9aabfa5ba43d77e68b0a2ea
|
[
"MIT"
] | null | null | null |
import axios from "axios"
import qs from 'Qs'
import Vue from 'vue' // vue主体
function getReco(path, params, noToken) {
path = 'http://118.144.88.218:7999' + path;
return new Promise((resolve, reject) => {
get(path, params, noToken).then(res => {
resolve(res);
}).catch(err => {
// alert("出错了 > post request ", err);
});
});
}
function postReco(path, params, noToken) {
path = 'http://mp.xunbao88.com.cn' + path;
// path = 'http://10.4.72.80:8081/miniprogram' + path;
return new Promise((resolve, reject) => {
post(path, params, noToken).then(res => {
resolve(res);
}).catch(err => {
// alert("出错了 > post request ", err);
});
});
}
function postVerificationCode(path, params, noToken) {
// path = 'http://mp.xunbao88.com.cn/miniprogram' + path;
path= path
console.log(path);
return new Promise((resolve, reject) => {
get(path, params, noToken).then(res => {
resolve(res);
}).catch(err => {
// alert("出错了 > post request ", err);
});
});
}
function getVerificationCode(path, params, noToken) {
// path = 'http://mp.xunbao88.com.cn/miniprogram' + path;
path = path;
console.log(path);
return new Promise((resolve, reject) => {
get(path, params, noToken).then(res => {
resolve(res);
}).catch(err => {
// alert("出错了 > post request ", err);
});
});
}
/**
* post方式获取商城相关数据
* @author xwj 2019-07-28
* @param {string} path 请求路径
* @param {object} params 请求参数
*/
function postMall(path, params, noToken) {
path = 'http://mp.xunbao88.com.cn' + path;
return new Promise((resolve, reject) => {
post(path, params, noToken).then(res => {
resolve(res);
}).catch(err => {
// alert("出错了 > post request ", err);
});
});
}
function postMall2(path, params, noToken) {
path = 'http://118.144.88.218:7999' + path;
return new Promise((resolve, reject) => {
post(path, params, noToken).then(res => {
resolve(res);
}).catch(err => {
// alert("出错了 > post request ", err);
});
});
}
//lwz
function postCao(path, params, noToken) {
path = 'http://mp.xunbao88.com.cn' + path;
return new Promise((resolve, reject) => {
post(path, params, noToken).then(res => {
resolve(res);
}).catch(err => {
// alert("出错了 > post request ", err);
});
});
}
function getStaticFile(path) {
// path = 'http://localhost:8085' + path;
return new Promise((resolve, reject) => {
get(path, {}, true).then(res => {
resolve(res);
}).catch(err => {
// alert("出错了 > post request ", err);
});
});
}
// 社区相关 by gaoxueli -begin
function groupGet(path, params, noToken) {
params=params||{};
//path = 'http://10.4.72.89:8080/wechat_business/xlyghapp' + path;
path = 'http://zdjqr.xunbao88.com.cn/wechatbusiness/xlyghapp' + path;
return new Promise((resolve, reject) => {
get(path, params, noToken).then(res => {
resolve(res);
}).catch(err => {
// alert("出错了 > post request ", err);
});
});
}
function groupPost(path, params, noToken) {
params=params||{};
//path = 'http://10.4.72.89:8080/wechat_business/xlyghapp' + path;
path = 'http://zdjqr.xunbao88.com.cn/wechatbusiness/xlyghapp' + path;
return new Promise((resolve, reject) => {
post(path, params, noToken).then(res => {
resolve(res);
}).catch(err => {
// alert("出错了 > post request ", err);
});
});
}
function talkGet(path, params, noToken) {
params=params||{};
path = 'http://118.145.5.141/wechatbackend' + path;
return new Promise((resolve, reject) => {
get(path, params, noToken).then(res => {
resolve(res);
}).catch(err => {
// alert("出错了 > post request ", err);
});
});
}
// 个人中心收益
function postIncome(path, params, noToken) {
path = 'http://xilehui.xunbao88.com.cn/cashback' + path;
// path = 'http://mp.xunbao88.com.cn/miniprogram' + path;
return new Promise((resolve, reject) => {
post(path, params, noToken).then(res => {
resolve(res);
}).catch(err => {
// alert("出错了 > post request ", err);
});
});
}
// 个人中心更换头像
function postAvatar(path, params, noToken) {
path = 'http://img.xunbao88.com.cn/upload/imgupload' + path;
return new Promise((resolve, reject) => {
post(path, params, noToken).then(res => {
resolve(res);
}).catch(err => {
// alert("出错了 > post request ", err);
});
});
}
// 发布作品
function postImgFabu(path, params, noToken) {
path = 'http://img.xunbao88.com.cn/upload/imgupload' + path;
return new Promise((resolve, reject) => {
postImg(path, params, noToken).then(res => {
resolve(res);
}).catch(err => {
// alert("出错了 > post request ", err);
});
});
}
// 个人中心
function postPersonal(path, params, noToken) {
path = 'http://mp.xunbao88.com.cn' + path;
// path = 'http://10.4.72.80:8081/miniprogram' + path;
return new Promise((resolve, reject) => {
post(path, params, noToken).then(res => {
resolve(res);
}).catch(err => {
// alert("出错了 > post request ", err);
});
});
}
/**
* 直接全路径post请求
*
* @param {string} path
* @param {object} params
*/
function postTo(path, params, noToken) {
return new Promise((resolve, reject) => {
post(path, params, noToken).then(res => {
resolve(res);
}).catch(err => {
// alert("出错了 > post request ", err);
});
});
}
/**
* 登陆相关post请求
*
* @param {string} path
* @param {object} params
*/
function postLogin(path, params, noToken) {
path = 'http://mp.xunbao88.com.cn' + path;
return new Promise((resolve, reject) => {
post(path, params, noToken).then(res => {
resolve(res);
}).catch(err => {
// alert("出错了 > post request ", err);
});
});
}
export const reqGroup = {
groupTagList: params => groupGet('/group/classify/list', params, true), // 群分类
groupList:params => groupGet('/group/list', params, true), // 群列表
joinGroup:params => groupGet('/group/applyjoin', params), // 加群
groupDetail:params => groupGet('/group/detail/get', params, true), // 群详情
groupMembers:params => groupGet('/group/member/list', params, true), // 群成员
groupTalk:params => talkGet('/robotMsgAction.do?method=getXlyghGroupMsgInfos', params, true), // 群聊
applyCooperation:params => groupPost('/group/cooperation/apply', params), // 申请合作
applyRes:params => groupGet('/group/cooperation/list', params), // 申请结果
}
// 社区相关 by gaoxueli -end
/**
* 商城相关请求
* @author xwj 2019-07-28
*/
export const reqMall = {
/**
* 类型数据接口
* @author xwj 2019-07-28
* @param {object} params {
* pageNo: 1
* pageSize: 20
* sort: 0 //0 综合 1销量 2 价格 3 佣金
* type:0// 0 每日推荐 1 新人专享 2 聚划算 3 淘抢购 4 精选专区 5 3.9元区 6 6.9元区 7 9.9元区
* }
*/
typeList: params => postMall('/mall/commodity/queryTypelist2', params, true),
/**
* 首页列表数据
* @author xwj 2019-07-28
*/
mainList: params => postMall2('/taobao_v2/guess_like', params, true),
// mainList: params => postMall('/mall/commodity/recommend', params, true),
}
export const reqReco = {
/**
* 搜索结果
* @author xwj 2019-06-22
*/
tbSearch: params => getReco('/taobao/search_item_v2', params, true),
jdSearch: params => getReco('/jd/search_item_v2', params, true),
/**
* 得到标签数据
* @author xwj 2019-06-24
*/
tagDatas: params => postReco('/mall/commodity/querylist', params, true),
/**
* 标签xml
* @author xwj 2019-06-24
*/
tagXml: () => getStaticFile('static/category.xml'),
/**
* 根据带商品ID的url得到转链内容
* @author xwj 2019-07-29
*/
getTransByCommLink: params => postTo('http://zdjqr.xunbao88.com.cn/wechatbusiness/commodityRecommend/commodityTransLink', params),
}
// 其他页面 zhangtong
export const reqOther = {
// 收益细则
inDetail: params => postReco('/bonus/list', params),
// 任务中心
taskCenter: params => postReco('/mission/list', params),
// 增加奖励
addIncome: params => postReco('/bonus/add', params),
// 个人中心
userInfo: params => postReco('/user/info/v1', params)
}
//种草相关页面lwz
export const caoApi = {
postDetail: params => postCao('/forum/recommend/topic/list', params),//帖子详情
commentList: params => postCao('/forum/topic/comment/detail', params),//评论列表
interactive: params => postCao('/forum/topic/update', params),//点赞,收藏的接口
addComment: params => postCao('/forum/topic/comment/add', params),//增加评论
postFollow: params => postCao('/forum/user/follow/list', params),//关注的接口
gainLabels:params=> postCao('/forum/tag/list', params, true),//获取标签
addBonus: params => postCao('/bonus/add', params),//增加奖励
hotSearch: params => postCao('/forum/tag/list', params),//热搜词
grassRedTip: params => postCao('/bonus/add', params), //阅读收益及收益记录
getWechartInfo: params => postTo('http://118.145.5.141/wechatbackend/wechatGroupManagement.do?method=getMemberInfoByWxid', params), //获取微信信息
/**
* 主列表数据
*
* @param url
* @param params
* @returns
*/
mainList: params => postCao('/forum/discovery/topic/list', params, true),
/**
* 搜索数据结果
*
* @param url
* @param params
* @returns
*/
mainSear: params => postCao('/forum/search/topic/list', params, true),
}
//个人页面 baikaifa
export const reqForgetpwd = {
gainCode:params=>getVerificationCode('http://auth2.xunbaotianxing.com/XlyghAppLoginServlet?method=getCode',params),
confirmSubmit:params=>getVerificationCode('http://auth2.xunbaotianxing.com/XlyghAppLoginServlet?method=setPasswd',params),
changeNickname:params=>postReco('/user/nickname/update',params),
wixinBind:params=>postReco('/user/bindWechat',params),
changewixinBind:params=>postReco('/user/getBindWechat',params),
confirmChange:params=>postVerificationCode('/XlyghAppLoginServlet?method=checkOldPhone',params),
confirmSetNewPhone:params=>getVerificationCode('http://auth2.xunbaotianxing.com/XlyghAppLoginServlet?method=bindPhone',params),
InviteCode:params=>postReco('/user/inviteCode/set',params),
getPersonalCode:params=>postReco('/user/inviteCode/get',params),
}
//发布作品 baikaifa
export const publishingWorks = {
getPublishingWorks:params=>postReco('/forum/my/topic/post',params),
getImgUrl:params=>postImgFabu('?act=app&userid=',params),
}
// 个人页面 huhuyuan
export const reqPersonal = {
// 上传用户头像到服务器
uploadAvatar: params => postImgFabu('?act=appavatar&userid=', params),
// 个人中心用户信息
userMessage: params => postPersonal('/user/info/v1', params),
// 设置页面用户信息
selfInfo: params => postPersonal('/user/setInfo', params),
// 用户邀请码
getInviteCode: params => postPersonal('/user/inviteCode/get', params),
getBeinvitedCode: params => postPersonal('/user/beinvitedCode/get', params),
// 保存用户头像
saveAvatar: params => postPersonal('/user/avatar/update', params),
// 用户绑定微信
wxBind: params => postPersonal('/user/getBindWechat', params),
//搜索订单结果
search: params => postIncome('/alliance.gsp?method=getOrderHistoryInfo', params),
//得到优惠券列表
couponList: params => postIncome('/alliance.gsp?method=getCounponSort', params),
//排序后的优惠券
uploadCouponList: params => postIncome('/alliance.gsp?method=updateCounponSort', params),
//累计收益
incList: params => postIncome('/alliance.gsp?method=getBillingDetails', params),
//得到即将到账
cosList: params => postIncome('/alliance.gsp?method=getPreIncomeDetails', params),
//得到购物红包
amoList: params => postIncome('/alliance.gsp?method=getQuotaDetails', params),
//喜乐币
xlbList: params => postPersonal('/bonus/list', params),
// 用户信息
userInfo: params => postIncome('/alliance.gsp?method=getUserInfo', params),
// 兑换
xlbTrans: params => postPersonal('/bonus/trans', params),
// 提现
cashDraw: params => postPersonal('/user/cash/draw', params),
// 用户余额
userBalance: params => postPersonal('/user/balance', params),
// 用户银行卡列表
userBankList: params => postPersonal('/user/bank/list', params),
// 银行卡列表
bankList: params => postPersonal('/user/bank/all', params),
// 添加银行卡
addBank: params => postPersonal('/user/bank/add', params),
// 删除银行卡
deleteBank: params => postPersonal('/user/bank/delete', params),
//我的粉丝
gainMyFans: params => postPersonal('/message/list',params),
//我的作品
gainWorks:params => postPersonal('/forum/my/topic/list',params),
//我的收藏
myCollections:params => postPersonal('/forum/my/storetopic/list',params),
//我的关注
getYourAttention:params => postPersonal('/message/list',params),//关注接口1
indexFollows:params => postPersonal('/forum/user/follow/list',params),//关注接口2
}
/**
* 用户登陆相关操作
* @author xwj 2019-07-31
*/
export const reqLogin = {
/**
* 进行登陆情况验证
*/
validLogin: params => postLogin('/login/isLogin', params, true),
/**
* 进行实际的登陆操作
*/
goLogin: params => postLogin('/login/login', params, true),
}
axios.defaults.timeout = 10000;
axios.defaults.headers = { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' };
function post(url, params, noToken) {
if (params && !params['token']) {
// TODO: 需要针对不需要token的页面,进行特殊操作
let token = Vue.prototype.appUtils.getToken(()=>{
get(url, params, noToken);
});
if (!token) {
if (!noToken) {
return;
}
}
params['token'] = token;
}
return new Promise((resolve, reject) => {
console.log(JSON.stringify(params));
try{
axios.post(url, qs.stringify(params)).then(res => {
res = typeof (res) === 'string' ? JSON.parse(res) : res;
res = res.data;
if (validResCode(res)) {
resolve(res);
} else {
// 帐号失效情况
reject(res);
}
}).catch(err => {
// alert("出错了 > post request " + url + "<>" + JSON.stringify(params), err);
console.log("出错了 > post request " + url + "<>" + JSON.stringify(params), err);
})
} catch (e) {
console.log(e);
reject();
}
})
}
function postImg(url, params, noToken) {
params = params || {};
if (!params['token']) {
// // 完善统一token处理
// TODO: 需要针对不需要token的页面,进行特殊操作
let token = Vue.prototype.appUtils.getToken(()=>{
get(url, params, noToken);
});
if (!token) {
if (!noToken) {
return;
}
}
params['token'] = token;
}
return new Promise((resolve, reject) => {
try{
axios.post(url+params.get("userid"), params).then(res => {
res = typeof (res) === 'string' ? JSON.parse(res) : res;
res = res.data;
if (validResCode(res)) {
resolve(res);
} else {
// 帐号失效情况
reject(res);
}
}).catch(err => {
// alert("出错了 > post request " + url + "<>" + JSON.stringify(params), err);
console.log("出错了 > post request " + url + "<>" + JSON.stringify(params), err);
})
} catch (e) {
console.log(e);
reject();
}
})
}
function get(url, params, noToken) {
params = params || {};
if (!params['token']) {
// // 完善统一token处理
// TODO: 需要针对不需要token的页面,进行特殊操作
let token = Vue.prototype.appUtils.getToken(()=>{
get(url, params, noToken);
});
if (!token) {
if (!noToken) {
return;
}
}
params['token'] = token;
}
return new Promise((resolve, reject) => {
try {
axios.get(url, { params: params }).then(res => {
res = typeof (res) === 'string' ? JSON.parse(res) : res;
res = res.data;
if (validResCode(res)) {
resolve(res);
} else {
// 帐号失效情况
reject(res);
}
}).catch(err => {
// alert("出错了 > get request " + url + "<>" + JSON.stringify(params), err);
console.log("出错了 > get request " + url + "<>" + JSON.stringify(params), err);
})
} catch (e) {
console.log(e);
reject();
}
})
}
function validResCode (res) {
if (!res.code) {
if (res.status) {
res.code = res.status + '';
} else if (res.state) {
res.code = res.state + '';
}
console.log(" unknow res code ... " + JSON.stringify(res));
}
if (res.code + '' === '401' || res.code + '' === '216') { // 不要问我为什么,要问后端各种同学版本
// 认为是帐号失效状态,进行刷新操作
if (Vue.prototype.sysEnv === 'pc') {
// 非app从新登陆,可能因此导致网页端 无限刷新问题 add xwj 201-08-01
Vue.prototype.webUtils.toWebLogin();
} else {
Vue.prototype.appUtils.refreshToken();
}
return false;
} else {
return true;
}
}
| 28.455046
| 141
| 0.637155
|
0aa088867161cb325679e25239bc45a89c65c753
| 1,477
|
cs
|
C#
|
OriginalClayResources/src/ClaySharp/IClayBehavior.cs
|
jdselig/ClayUnity
|
24b803f47751da83294c0edc0d2305e339224cd6
|
[
"MIT"
] | 90
|
2017-05-03T04:00:39.000Z
|
2022-03-31T06:24:17.000Z
|
OriginalClayResources/src/ClaySharp/IClayBehavior.cs
|
jdselig/ClayUnity
|
24b803f47751da83294c0edc0d2305e339224cd6
|
[
"MIT"
] | 3
|
2018-02-23T09:04:11.000Z
|
2021-06-22T22:18:41.000Z
|
OriginalClayResources/src/ClaySharp/IClayBehavior.cs
|
jdselig/ClayUnity
|
24b803f47751da83294c0edc0d2305e339224cd6
|
[
"MIT"
] | 18
|
2017-05-03T04:50:10.000Z
|
2022-03-31T06:24:23.000Z
|
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace ClaySharp {
public interface IClayBehavior {
object GetMember(Func<object> proceed, object self, string name);
object SetMember(Func<object> proceed, object self, string name, object value);
object InvokeMember(Func<object> proceed, object self, string name, INamedEnumerable<object> args);
object GetIndex(Func<object> proceed, object self, IEnumerable<object> keys);
object SetIndex(Func<object> proceed, object self, IEnumerable<object> keys, object value);
object GetMembers(Func<object> proceed, object self, IDictionary<string, object> members);
object Convert(Func<object> proceed, object self, Type type, bool isExplicit);
object BinaryOperation(Func<object> proceed, object self, ExpressionType operation, object value);
object InvokeMemberMissing(Func<object> proceed, object self, string name, INamedEnumerable<object> args);
object GetMemberMissing(Func<object> proceed, object self, string name);
object SetMemberMissing(Func<object> proceed, object self, string name, object value);
object ConvertMissing(Func<object> proceed, object self, Type type, bool isExplicit);
}
public interface INamedEnumerable<T> : IEnumerable<T> {
IEnumerable<T> Positional { get; }
IDictionary<string, T> Named { get; }
}
}
| 50.931034
| 115
| 0.704807
|
3880cc72692b38568c034e09cb84754ebd165953
| 549
|
php
|
PHP
|
tpl/safehouse/main.conf.php
|
bilicraft/BilicraftWebsite
|
ba0c9cb6b2d4f5da9a6a3160114fa92ae4db465c
|
[
"Apache-2.0"
] | null | null | null |
tpl/safehouse/main.conf.php
|
bilicraft/BilicraftWebsite
|
ba0c9cb6b2d4f5da9a6a3160114fa92ae4db465c
|
[
"Apache-2.0"
] | null | null | null |
tpl/safehouse/main.conf.php
|
bilicraft/BilicraftWebsite
|
ba0c9cb6b2d4f5da9a6a3160114fa92ae4db465c
|
[
"Apache-2.0"
] | null | null | null |
<?php
class config_tpl_safehouse_main{
function get_config(){
// 继承配置
$cfg = TPL::load_config('public/common');
return TPL::extend_config($cfg, array(
'css' => [
],
'less' => [
'safehouse/less/main'
],
'js' => [
'safehouse/js/main'
],
'navi' => [
[
'安全中心',
'./?c=safehouse'
]
]
));
}
}
| 21.115385
| 49
| 0.315118
|
af8673fd2f3f980c9766d0d85eeaac3a5193b93d
| 874
|
py
|
Python
|
pros/grpc-py/src/CameraAIClinent.py
|
LightSun/study-grpc
|
900cfb4154654e75100f295b762f4cf48100b564
|
[
"Apache-2.0"
] | null | null | null |
pros/grpc-py/src/CameraAIClinent.py
|
LightSun/study-grpc
|
900cfb4154654e75100f295b762f4cf48100b564
|
[
"Apache-2.0"
] | null | null | null |
pros/grpc-py/src/CameraAIClinent.py
|
LightSun/study-grpc
|
900cfb4154654e75100f295b762f4cf48100b564
|
[
"Apache-2.0"
] | null | null | null |
from __future__ import print_function
import logging
import grpc
import CameraAI_pb2
import CameraAI_pb2_grpc
def run():
# NOTE(gRPC Python Team): .close() is possible on a channel and should be
# used in circumstances in which the with statement does not fit the needs
# of the code.
with grpc.insecure_channel('localhost:50051') as channel:
stub = CameraAI_pb2_grpc.CameraAIStub(channel)
keyInfo = CameraAI_pb2.AIKeyInfo(unloadingPointId="p_123",recognizeSheetId="reg_123",presetId=1,isLastPreset=True,cameraAddr="21")
response = stub.GetResult(CameraAI_pb2.AIReq(keyInfo=keyInfo,type=CameraAI_pb2.AIType.RECOGNIZE,imageObjectName="adb/d.jpg"))
print("Greeter client received msg: " + response.msg)
print("Greeter client received data: " + response.data)
if __name__ == '__main__':
logging.basicConfig()
run()
| 34.96
| 138
| 0.742563
|
4413a9d184942cb268a314aed1c7c334a1fbdf09
| 11,564
|
py
|
Python
|
ssvm_evaluation/utils.py
|
aalto-ics-kepaco/lcms2struct_exp
|
5baa3edd0e58d24f739efd4086031f6fbdba6ad9
|
[
"MIT"
] | null | null | null |
ssvm_evaluation/utils.py
|
aalto-ics-kepaco/lcms2struct_exp
|
5baa3edd0e58d24f739efd4086031f6fbdba6ad9
|
[
"MIT"
] | null | null | null |
ssvm_evaluation/utils.py
|
aalto-ics-kepaco/lcms2struct_exp
|
5baa3edd0e58d24f739efd4086031f6fbdba6ad9
|
[
"MIT"
] | null | null | null |
####
#
# The MIT License (MIT)
#
# Copyright 2021, 2022 Eric Bach <eric.bach@aalto.fi>
#
# 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.
#
####
import os
import re
import pandas as pd
import glob
from typing import Dict, Optional, Tuple
from pandas.api.types import is_float, is_bool, is_integer
# ----------------------------------------------------------------------------------------------------------------------
# Helper scripts to load the result of our experiments
# ----------------------------------------------------------------------------------------------------------------------
def dict2fn(d: Dict, sep: str = "__", pref: Optional[str] = None, ext: Optional[str] = None) -> str:
"""
:param d: dictionary, input (key, value)-pairs
:param sep: string, used to separate the key=value pairs in the filename
:param pref: string, added as prefix to the filename. The prefix and rest of the filename is separated by the string
specified in the 'sep' parameter
:param ext: string, added as extension to the filename. The extension is separated by the systems file-extension
separator, e.g. '.'.
:return: string, compiled filename
"""
out = []
for k, v in sorted(d.items()):
if v is None:
out.append("{}".format(k))
else:
out.append("{}={}".format(k, v))
out = sep.join(out)
if pref is not None:
out = sep.join([pref, out])
if ext is not None:
out = os.extsep.join([out, ext])
return out
def fn2dict(params: str) -> Tuple[Dict, bool, Optional[str], Optional[str]]:
"""
Roughly the inverse function of "dict2fn".
:param params: string, filename to split up
:return:
"""
param_name_pattern = re.compile(r'(?:[a-zA-Z0-9]+_?)+=')
# Debugging outputs do have an additional prefix which we need to remove
if params.startswith("debug__"):
params = params.removeprefix("debug__")
is_debug = True
pref = "debug"
else:
# FIXME: we only support "debug" as prefix, here
is_debug = False
pref = None
# Get the file extension (assume that there is no "." in the filename that does NOT separate the extension)
_ext_idx = params.find(os.extsep)
if _ext_idx >= 0:
ext = params[(_ext_idx + 1):]
else:
ext = None
# Split the filename and extract the (key, value)-pairs
ks = [m.removesuffix("=") for m in param_name_pattern.findall(params)]
vs = [v.removesuffix("__") for v in param_name_pattern.split(params) if len(v) > 0]
assert len(ks) == len(vs)
# Construct the output dictionary
out = {}
for k, v in zip(ks, vs):
if is_bool(v):
out[k] = bool(v)
elif is_integer(v):
out[k] = int(v)
elif is_float(v):
out[k] = int(v)
else:
assert isinstance(v, str)
out[k] = v
return out, is_debug, pref, ext
def load_topk__publication(
setting: Dict, agg_setting: Dict, basedir: str = ".", top_k_method: str = "csi",
load_max_model_number: bool = False
) -> pd.DataFrame:
"""
Load the Top-k accuracies in the "publications" folder. These are the results for the SSVM (exp_ver >= 3)
:param setting: dictionary, specifying the parameters of the experiments for which the results should be loaded.
:param agg_setting: dictionary, specifying the parameter of the margin score aggregation, that means how are the
molecular candidates identified when choosing the margin score.
:param basedir: string, directory containing the results
:param top_k_method: string, specifies which top-k accuracy calculation method should be used. We always use the one
used in the original SIRIUS publication [1].
:param load_max_model_number: boolean, indicating whether only the results of the averaged marginals for the maximum
number of available SSVM models should be loaded.
:return: dataframe, containing all results (row-wise concatenation) that match the "setting" and "agg_setting"
:references:
[1] Dührkop, Kai / Shen, Huibin / Meusel, Marvin / Rousu, Juho / Böcker, Sebastian
Searching molecular structure databases with tandem mass spectra using CSI:FingerID
2015
"""
assert top_k_method == "csi", "We always use the top-k accuracy calculated as in the original SIRIUS publication."
# Collect result data-frames. There might be several, e.g. if the "setting" dictionary contains wildcards (*) for
# some parameters, such as the dataset.
df = []
# Prefix of the result file depending on whether only the results for the maximum number of SSVM models should be
# loaded.
_top_k_fn = "top_k__max_models" if load_max_model_number else "top_k"
# Iterate over all result files matching the parameters
for ifn in sorted(glob.glob(
os.path.join(
basedir, dict2fn(setting), dict2fn(agg_setting, pref="combined"), os.extsep.join([_top_k_fn, "tsv"])
)
)):
# Parse the actual parameters from the basename (the setting might contain wildcards)
params, _, _, _ = fn2dict(ifn.split(os.sep)[-3]) # /path/to/PARAMS/not/file.tsv --> PARAMS
# Read the top-k performance results
_df = pd.read_csv(ifn, sep="\t", dtype={"scoring_method": str, "top_k_method": str})
# Restrict the results to the one with the specified top-k accuracy method
_df = _df[_df["top_k_method"] == top_k_method]
assert _df["top_k_method"].nunique() == 1, "There should be only two different top-k accuracy method."
# Add the parameters to the dataframe
for k, v in params.items():
if k not in _df.columns:
_df[k] = v
df.append(_df)
# All loaded results are concatenated into a single dataframe
df = pd.concat(df, ignore_index=True)
return df
def load_topk__comparison(setting: Dict, agg_setting: Dict, basedir: str = ".", top_k_method: str = "csi") \
-> pd.DataFrame:
"""
Load the Top-k accuracies in the "comparison" folder. These are the results for the comparison methods, i.e.
RT filtering, LogP scoring and RO score integration approaches.
:param setting: dictionary, specifying the parameters of the experiments for which the results should be loaded.
:param agg_setting: dictionary, specifying the parameter of the margin score aggregation, that means how are the
molecular candidates identified when choosing the margin score.
:param basedir: string, directory containing the results
:param top_k_method: string, specifies which top-k accuracy calculation method should be used. We always use the one
used in the original SIRIUS publication [1].
:return: dataframe, containing all results (row-wise concatenation) that match the "setting" and "agg_setting"
:references:
[1] Dührkop, Kai / Shen, Huibin / Meusel, Marvin / Rousu, Juho / Böcker, Sebastian
Searching molecular structure databases with tandem mass spectra using CSI:FingerID
2015
"""
spl_pattern = re.compile(r"spl=([0-9]+)")
assert top_k_method == "csi", "We always use the top-k accuracy calculated as in the original SIRIUS publication."
# Collect result data-frames. There might be several, e.g. if the "setting" dictionary contains wildcards (*) for
# some parameters, such as the dataset.
df = []
# Input directory
idir = os.path.join(basedir, dict2fn(setting))
for ifn in sorted(glob.glob(
os.path.join(idir, dict2fn({"spl": "*", "cand_agg_id": agg_setting["cand_agg_id"]}, pref="top_k", ext="tsv"))
)):
# Parse the actual parameters from the basename (the setting might contain wildcards)
params, _, _, _ = fn2dict(ifn.split(os.sep)[-2]) # /path/to/PARAMS/file.tsv --> PARAMS
# Read the top-k performance results
_df = pd.read_csv(ifn, sep="\t", converters={"scoring_method": str})
# Restrict the specified top-k method
_df = _df[_df["top_k_method"] == top_k_method]
assert _df["top_k_method"].nunique() == 1
# Add the parameters to the dataframe
for k, v in params.items():
if k not in _df.columns:
_df[k] = v
# The scoring method label should include the "score_int_app" which distinguishes the different filtering
# approaches using the predicted retention times
_df.loc[_df["scoring_method"] == "MS + RT", "scoring_method"] = "MS + RT (%s)" % params["score_int_app"]
# Add the evaluation split index
eval_indx = spl_pattern.findall(os.path.basename(ifn).removesuffix(os.extsep + "tsv"))
assert len(eval_indx) == 1
_df["eval_indx"] = int(eval_indx[0])
df.append(_df)
if len(df) > 0:
df = pd.concat(df, ignore_index=True).rename({"ds": "dataset"}, axis=1)
# Compute the accuracy and add it as column
df["top_k_acc"] = (df["correct_leq_k"] / df["seq_length"]) * 100
else:
# Empty dataframe
df = pd.DataFrame(df)
return df
def load_topk__cand_set_info(setting: Dict, basedir: str = ".") -> pd.DataFrame:
"""
Load the Top-k accuracies in the "comparison" folder. These are the results for the comparison methods, i.e.
RT filtering, LogP scoring and RO score integration approaches.
"""
df = []
for ifn in sorted(glob.glob(
os.path.join(basedir, dict2fn(setting), dict2fn({"spl": "*"}, pref="cand_set_info", ext="tsv"))
)):
# Parse the actual parameters from the basename (the setting might contain wildcards)
params, _, _, _ = fn2dict(ifn.split(os.sep)[-2]) # /path/to/PARAMS/file.tsv --> PARAMS
# Read the top-k performance results
_df = pd.read_csv(ifn, sep="\t")
# Add the parameters to the dataframe
for k, v in params.items():
if k not in _df.columns:
_df[k] = v
# Add the evaluation split index
_df["eval_indx"] = int(
os.path.basename(ifn).removesuffix(os.extsep + "tsv").removeprefix("top_k__").split("=")[1]
)
df.append(_df)
df = pd.concat(df, ignore_index=True)
return df
if __name__ == "__main__":
out = fn2dict(
"debug__ds=AU_003__mol_feat=bouwmeester__smiles_can__mol_id=inchikey1__ms2scorer=sirius__sd__correct_mf__norm__rt_predictor=svr__score_int_app=filtering__global"
)
print(out)
| 38.165017
| 169
| 0.649256
|
475ceb4223fe2badfdeb2adda98943a0b7d7bae8
| 524
|
rb
|
Ruby
|
metadata.rb
|
criteo-cookbooks/w32time
|
8f8eed389ac34daf53692114b67176baeeaee557
|
[
"Apache-2.0"
] | 1
|
2018-03-08T21:34:50.000Z
|
2018-03-08T21:34:50.000Z
|
metadata.rb
|
criteo-cookbooks/w32time
|
8f8eed389ac34daf53692114b67176baeeaee557
|
[
"Apache-2.0"
] | 2
|
2016-11-18T14:23:35.000Z
|
2016-12-07T03:23:20.000Z
|
metadata.rb
|
criteo-cookbooks/w32time
|
8f8eed389ac34daf53692114b67176baeeaee557
|
[
"Apache-2.0"
] | 1
|
2016-11-17T12:24:05.000Z
|
2016-11-17T12:24:05.000Z
|
name 'w32time'
maintainer 'Nicolas BENOIT'
maintainer_email 'sre-core-infra@criteo.com'
license 'Apache-2.0'
description 'This cookbook configure w32time'
long_description 'Installs/Configures w32time'
chef_version '>= 12.16' if respond_to?(:chef_version)
issues_url 'https://github.com/criteo-cookbooks/w32time' if respond_to? :issues_url
source_url 'https://github.com/criteo-cookbooks/w32time' if respond_to? :source_url
version '0.1.4'
supports 'windows'
| 43.666667
| 89
| 0.700382
|
d67ef92a89de3ed1af5ea0e7cf511dae398fc023
| 923
|
cs
|
C#
|
Database-centric-architecture/server/PetFoodShop.Foods/Controllers/CategoriesController.cs
|
Domin1k/Microservices
|
5334f243a1879d392b2412b9082aacedc3cac608
|
[
"MIT"
] | 4
|
2020-07-21T16:40:45.000Z
|
2021-02-22T13:53:49.000Z
|
Database-centric-architecture/server/PetFoodShop.Foods/Controllers/CategoriesController.cs
|
Domin1k/Microservices
|
5334f243a1879d392b2412b9082aacedc3cac608
|
[
"MIT"
] | 11
|
2020-07-17T06:31:37.000Z
|
2022-03-02T09:58:25.000Z
|
Database-centric-architecture/server/PetFoodShop.Foods/Controllers/CategoriesController.cs
|
Domin1k/Microservices
|
5334f243a1879d392b2412b9082aacedc3cac608
|
[
"MIT"
] | 1
|
2020-07-21T16:40:59.000Z
|
2020-07-21T16:40:59.000Z
|
namespace PetFoodShop.Foods.Controllers
{
using Microsoft.AspNetCore.Mvc;
using PetFoodShop.Controllers;
using PetFoodShop.Foods.Services;
using System.Threading.Tasks;
public class CategoriesController : ApiController
{
private readonly IFoodCategoryService foodCategoryService;
public CategoriesController(IFoodCategoryService foodCategoryService)
{
this.foodCategoryService = foodCategoryService;
}
[HttpGet("all")]
public async Task<IActionResult> GetAll()
{
var results = await this.foodCategoryService.AllAsync();
return this.Ok(results);
}
[HttpGet("{id}/brands")]
public async Task<IActionResult> GetCategoryBrands(int id)
{
var results = await this.foodCategoryService.CategoryBrandsAsync(id);
return this.Ok(results);
}
}
}
| 28.84375
| 81
| 0.651138
|
8e53b2d1ad76845022ae7bfe101045bf475f5cd6
| 582
|
js
|
JavaScript
|
src/utils/make-link.js
|
ivankristianto/wp-local-docker-v2
|
c2b1b3736e012b6f844d7fe0a862b2a6f1c0d5a4
|
[
"MIT"
] | 391
|
2018-10-10T17:29:03.000Z
|
2022-03-31T00:43:22.000Z
|
src/utils/make-link.js
|
ivankristianto/wp-local-docker-v2
|
c2b1b3736e012b6f844d7fe0a862b2a6f1c0d5a4
|
[
"MIT"
] | 231
|
2018-10-13T15:49:23.000Z
|
2022-03-31T14:20:10.000Z
|
src/utils/make-link.js
|
ivankristianto/wp-local-docker-v2
|
c2b1b3736e012b6f844d7fe0a862b2a6f1c0d5a4
|
[
"MIT"
] | 81
|
2018-11-30T14:30:28.000Z
|
2022-03-30T15:12:41.000Z
|
const chalk = require( 'chalk' );
const terminalLink = require( 'terminal-link' );
const stripAnsi = require( 'strip-ansi' );
function makeLink( text, link ) {
if ( ! terminalLink.isSupported ) {
return link !== stripAnsi( text ) ? `${ text } (${ link })` : link;
}
return terminalLink( text, link );
}
function replaceLinks( text, links ) {
let output = text;
Object.keys( links ).forEach( ( label ) => {
output = output.replace( label, makeLink( chalk.cyanBright( label ), links[ label ] ) );
} );
return output;
}
module.exports = {
makeLink,
replaceLinks,
};
| 21.555556
| 90
| 0.642612
|
f62f1a39f186141cf5bcc647a9be7668ac6314ad
| 7,801
|
cpp
|
C++
|
app/src/main/engine/android/esutil_android.cpp
|
qige023/learning-opengles3-android
|
cbe0742637a6eeed41c76756021913cc570cc30e
|
[
"MIT"
] | 10
|
2015-05-06T17:59:51.000Z
|
2019-12-03T10:08:23.000Z
|
app/src/main/engine/android/esutil_android.cpp
|
qige023/OpenGL-ES3-Programming-On-Android
|
cbe0742637a6eeed41c76756021913cc570cc30e
|
[
"MIT"
] | null | null | null |
app/src/main/engine/android/esutil_android.cpp
|
qige023/OpenGL-ES3-Programming-On-Android
|
cbe0742637a6eeed41c76756021913cc570cc30e
|
[
"MIT"
] | null | null | null |
//
// This file contains the Android implementation of the windowing functions.
#include <android/log.h>
#include <android/keycodes.h>
#include <android/input.h>
#include <android_native_app_glue.h>
#include <time.h>
#include <iostream>
#include <stdexcept>
using std::cout;
using std::cerr;
using std::endl;
#include "esutil.h"
#include "esfile.h"
#include "android/buf_android.hpp"
///
// Global extern. The application must declare this function
// that runs the application.
//
extern ESScene *esCreateScene(ESContext *esContext);
static int esMain(ESContext *esContext) {
cout << "exec esMain..." << endl;
ESScene *scene = esCreateScene(esContext);
AAssetManager *assetManager = (( ANativeActivity * ) esContext->platformData)->assetManager;
ESFileWrapper::setAssetmanager(assetManager);
if(scene != NULL) {
esContext->scene = scene;
GLboolean result = esCreateWindow(esContext, "Simple VertexShader", 320, 240,
ES_WINDOW_RGB | ES_WINDOW_DEPTH);
if (result != GL_TRUE) {
throw new std::runtime_error("Unable to create EGL native window.");
return false;
}
scene->initScene(esContext);
return TRUE;
}
return FALSE;
}
//////////////////////////////////////////////////////////////////
//
// Private Functions
//
//
///
// GetCurrentTime()
//
static float GetCurrentTime() {
struct timespec clockRealTime;
clock_gettime( CLOCK_MONOTONIC, &clockRealTime);
double curTimeInSeconds = clockRealTime.tv_sec
+ (double) clockRealTime.tv_nsec / 1e9;
return (float) curTimeInSeconds;
}
///
// Android callback for onAppCmd
//
static void HandleCommand(struct android_app *pApp, int32_t cmd) {
ESContext *esContext = (ESContext *) pApp->userData;
switch (cmd) {
case APP_CMD_SAVE_STATE:
cout << "HandleCommand APP_CMD_SAVE_STATE" << endl;
// the OS asked us to save the state of the app
break;
case APP_CMD_INIT_WINDOW:
cout << "HandleCommand APP_CMD_INIT_WINDOW" << endl;
esContext->platformData = (void *) pApp->activity;
esContext->eglNativeDisplay = EGL_DEFAULT_DISPLAY;
esContext->eglNativeWindow = pApp->window;
cout.rdbuf(new outlogbuf());
cerr.rdbuf(new outlogbuf());
// Call the main entry point for the app
if (esMain(esContext) != GL_TRUE) {
exit(0); //@TEMP better way to exit?
}
break;
case APP_CMD_TERM_WINDOW:
cout << "HandleCommand APP_CMD_TERM_WINDOW" << endl;
delete esContext->scene;
cout.rdbuf(0);
cerr.rdbuf(0);
//reset esContext
memset(esContext, 0, sizeof(ESContext));
break;
case APP_CMD_LOST_FOCUS:
cout << "HandleCommand APP_CMD_LOST_FOCUS" << endl;
// if the app lost focus, avoid unnecessary processing (like monitoring the accelerometer)
break;
case APP_CMD_GAINED_FOCUS:
cout << "HandleCommand APP_CMD_GAINED_FOCUS" << endl;
// bring back a certain functionality, like monitoring the accelerometer
break;
}
}
///
// Android callback for onAppInput
//
static int32_t HandleInput(struct android_app* pApp, AInputEvent* event) {
ESContext *esContext = (ESContext *) pApp->userData;
int32_t eventType = AInputEvent_getType(event);
int32_t eventSource = AInputEvent_getSource(event);
int32_t eventAction;
float motionX, motionY;
size_t pointerIndex;
int32_t pointerId ,pointerCount;
switch (eventType) {
case AINPUT_EVENT_TYPE_MOTION:
switch (eventSource) {
case AINPUT_SOURCE_TOUCHSCREEN:
eventAction = AMotionEvent_getAction(event) & AMOTION_EVENT_ACTION_MASK;
pointerIndex = (AMotionEvent_getAction(event) & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
pointerId = AMotionEvent_getPointerId(event, pointerIndex);
motionX = AMotionEvent_getX(event, pointerId);
motionY = AMotionEvent_getY(event, pointerId);
switch (eventAction) {
case AMOTION_EVENT_ACTION_MOVE:
//http://stackoverflow.com/questions/9028357/android-multitouch-second-finger-action-move-ignored
cout << "HandleInput AMOTION_EVENT_ACTION_MOVE" << endl;
pointerCount = AMotionEvent_getPointerCount(event);
for(int i = 0; i < pointerCount; ++i) {
pointerIndex = i;
pointerId = AMotionEvent_getPointerId(event, pointerIndex);
motionX = AMotionEvent_getX(event, pointerId);
motionY = AMotionEvent_getY(event, pointerId);
if(esContext->onMotionListener != NULL) {
esContext->onMotionListener->onMotionMove(pointerId, motionX, motionY);
cout <<"pointerId: "<< pointerId << " X: " << motionX << " Y: " << motionY << endl;
}
}
break;
case AMOTION_EVENT_ACTION_DOWN:
case AMOTION_EVENT_ACTION_POINTER_DOWN:
cout << "HandleInput AMOTION_EVENT_ACTION_POINTER_DOWN" << endl;
if(esContext->onMotionListener != NULL) {
esContext->onMotionListener->onMotionDown(pointerId, motionX, motionY);
cout <<"pointerId: "<< pointerId << " X: " << motionX << " Y: " << motionY << endl;
}
break;
case AMOTION_EVENT_ACTION_UP:
case AMOTION_EVENT_ACTION_POINTER_UP:
cout << "HandleInput AMOTION_EVENT_ACTION_UP" << endl;
if(esContext->onMotionListener != NULL) {
esContext->onMotionListener->onMotionUp(pointerId, motionX, motionY);
cout <<"pointerId: "<< pointerId << " X: " << motionX << " Y: " << motionY << endl;
}
break;
}
break;
case AINPUT_SOURCE_TRACKBALL:
break;
}
return 0;
break;
case AINPUT_EVENT_TYPE_KEY:
switch (AKeyEvent_getKeyCode(event))
case AKEYCODE_BACK:
return 0;
break;
default:
return 0;
}
}
//////////////////////////////////////////////////////////////////
//
// Public Functions
//
///
// android_main()
//
// Main entrypoint for Android application
//
void android_main(struct android_app *pApp) {
ESContext *esContext = new ESContext();
float lastTime;
// Make sure glue isn't stripped.
app_dummy();
// Initialize the context
memset(esContext, 0, sizeof(ESContext));
pApp->userData = esContext;
pApp->onAppCmd = HandleCommand;
//设置输入事件的处理函数,如触摸响应
pApp->onInputEvent = HandleInput;
lastTime = GetCurrentTime();
while (TRUE) {
int ident;
int events;
struct android_poll_source *pSource;
while ((ident = ALooper_pollAll(0, NULL, &events, (void **) &pSource))
>= 0) {
if (pSource != NULL) {
pSource->process(pApp, pSource);
}
if (pApp->destroyRequested != 0) {
return;
}
}
if (esContext->eglNativeWindow == NULL) {
continue;
}
// Call app update function
if (esContext->scene != NULL) {
float curTime = GetCurrentTime();
float deltaTime = (curTime - lastTime);
lastTime = curTime;
esContext->scene->update(esContext, deltaTime);
esContext->scene->render(esContext);
eglSwapBuffers(esContext->eglDisplay, esContext->eglSurface);
}
}
}
| 31.329317
| 145
| 0.596077
|
dfd8ca95467fa6806d61852aa1962ac6ff668760
| 375
|
cs
|
C#
|
libsw/FFXIVDataHandler/Structs/Header.cs
|
Project-Novum/ffxiv-tools
|
3852aa560bc9307bebe7d96974885a5c60e3df6e
|
[
"MIT"
] | 2
|
2022-01-05T06:37:29.000Z
|
2022-01-05T18:59:49.000Z
|
libsw/FFXIVDataHandler/Structs/Header.cs
|
Project-Novum/ffxiv-tools
|
3852aa560bc9307bebe7d96974885a5c60e3df6e
|
[
"MIT"
] | null | null | null |
libsw/FFXIVDataHandler/Structs/Header.cs
|
Project-Novum/ffxiv-tools
|
3852aa560bc9307bebe7d96974885a5c60e3df6e
|
[
"MIT"
] | 2
|
2022-01-05T13:53:13.000Z
|
2022-01-05T18:50:19.000Z
|
namespace FFXIVDataHandler.Structs;
public class Header
{
public char[] Type { get; }
public byte[] Unknown { get; }
public int PayloadSize { get; }
public Header(BinaryReader reader)
{
Type = reader.ReadChars(4);
Unknown = reader.ReadBytes(4);
PayloadSize = reader.ReadInt32();
reader.BaseStream.Position += 1;
}
}
| 22.058824
| 41
| 0.621333
|
1321235d4b8496c4f562fe38b1128961f597281b
| 1,109
|
rb
|
Ruby
|
spec/git_log_extraction_spec.rb
|
sushil10018/git_timelog
|
3753d0d2b362af01e73271330c3f43598315bc4d
|
[
"MIT"
] | null | null | null |
spec/git_log_extraction_spec.rb
|
sushil10018/git_timelog
|
3753d0d2b362af01e73271330c3f43598315bc4d
|
[
"MIT"
] | null | null | null |
spec/git_log_extraction_spec.rb
|
sushil10018/git_timelog
|
3753d0d2b362af01e73271330c3f43598315bc4d
|
[
"MIT"
] | null | null | null |
require "spec_helper"
describe GitTimelog do
# TODO: Refactor
describe '#git_timelog' do
it "should extract git commits" do
expect(git_timelog).to eql(`git log --pretty=format:"git__title:%sgit__description:%bgit__date:%cd" --author="#{current_author}" --since='6am'} --reverse --all`)
end
end
# TODO: Refactor
describe '#current_author' do
it "should return authors name" do
expect(current_author).to eql(`git config user.name`)
end
end
describe '#user_input' do
it "should accpet user option" do
user_input
end
end
describe '#json_format' do
it "should return json formatted update" do
formatted_json = json_format
puts formatted_json
expect(formatted_json).to eql(formatted_json) # LOL
end
end
describe '#to_clipboard' do
it "should copy ordered list to clipboard" do
to_clipboard
puts "Ordered List copied to clipboard. Paste to test."
end
it "should copy unordered list to clipboard" do
to_clipboard('unordered')
puts "Unordered List copied to clipboard"
end
end
end
| 25.790698
| 167
| 0.6844
|
ae59d44f7e51a53f79c605cee6ef10dc99c394de
| 2,450
|
cshtml
|
C#
|
WebObs.MVC/Views/Security/Register.cshtml
|
cihatfurkaneken/school-management
|
c566af9851469e0c07d31f594361cde46c817a7b
|
[
"MIT"
] | 1
|
2021-06-04T14:38:09.000Z
|
2021-06-04T14:38:09.000Z
|
WebObs.MVC/Views/Security/Register.cshtml
|
cihatfurkaneken/school-management
|
c566af9851469e0c07d31f594361cde46c817a7b
|
[
"MIT"
] | null | null | null |
WebObs.MVC/Views/Security/Register.cshtml
|
cihatfurkaneken/school-management
|
c566af9851469e0c07d31f594361cde46c817a7b
|
[
"MIT"
] | null | null | null |
@model WebObs.MVC.Models.Security.RegisterViewModel
@{
ViewData["Title"] = "Register";
Layout = "~/Views/Shared/_LayoutSecurity.cshtml";
}
<div class="account-pages"></div>
<div class="clearfix"></div>
<div class="wrapper-page">
<div class="m-t-40 card-box">
<div class="text-center">
</div>
<div class="panel-body">
<form class="form-horizontal m-t-20" asp-controller="Security" asp-action="Register" method="post">
<div class="text-center">
<a href="/Security/Register" class="text-center"><h4 class="display-4">Kayıt Ol</h4></a><br />
</div>
<div class="form-group ">
<div class="col-xs-12">
<input id="email" asp-for="@Model.Email" class="form-control" type="email" required="" placeholder="Email">
</div>
</div>
<div class="form-group ">
<div class="col-xs-12">
<input id="userName" asp-for="@Model.UserName" class="form-control" type="text" required="" placeholder="Kullanıcı Adı">
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<input id="password" asp-for="@Model.Password" class="form-control" type="password" required="" placeholder="Şifre">
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<input id="confirmedPassword" asp-for="@Model.ConfirmedPassword" class="form-control" type="password" required="" placeholder="Şifre Tekrar">
</div>
</div>
<div class="form-group text-center m-t-40">
<div class="col-xs-12">
<button type="submit" class="btn btn-custom btn-bordred btn-block waves-effect waves-light">
Kaydet
</button>
</div>
</div>
<div class="row">
<div class="col-sm-12 text-center">
<p class="text-muted">Zaten üyeyim.<a href="/Security/Login" class="text-primary m-l-5"><b>Giriş Yap</b></a></p>
</div>
</div>
</form>
</div>
</div>
</div>
| 42.241379
| 165
| 0.473878
|
1a9b43d89422c6eadfc739afdde0d6ab6efcead3
| 326
|
py
|
Python
|
python3/tls/client_test1.py
|
jtraver/dev
|
c7cd2181594510a8fa27e7325566ed2d79371624
|
[
"MIT"
] | null | null | null |
python3/tls/client_test1.py
|
jtraver/dev
|
c7cd2181594510a8fa27e7325566ed2d79371624
|
[
"MIT"
] | null | null | null |
python3/tls/client_test1.py
|
jtraver/dev
|
c7cd2181594510a8fa27e7325566ed2d79371624
|
[
"MIT"
] | null | null | null |
#!/usr/local/bin/python3.7
# https://docs.python.org/3/library/ssl.html
import socket
import ssl
hostname = 'www.python.org'
context = ssl.create_default_context()
with socket.create_connection((hostname, 443)) as sock:
with context.wrap_socket(sock, server_hostname=hostname) as ssock:
print(ssock.version())
| 23.285714
| 70
| 0.742331
|
1f0ed89ab0e8d38d11236a3adbf22b9d814dd150
| 3,335
|
cs
|
C#
|
src/Collections/Artemis.Plugins.PhilipsHue/RGB.NET/HueRGBDeviceProvider.cs
|
skedgyedgy/Artemis.Plugins
|
25ee578a864578548959fe778e6839ef31e29fce
|
[
"MIT"
] | null | null | null |
src/Collections/Artemis.Plugins.PhilipsHue/RGB.NET/HueRGBDeviceProvider.cs
|
skedgyedgy/Artemis.Plugins
|
25ee578a864578548959fe778e6839ef31e29fce
|
[
"MIT"
] | null | null | null |
src/Collections/Artemis.Plugins.PhilipsHue/RGB.NET/HueRGBDeviceProvider.cs
|
skedgyedgy/Artemis.Plugins
|
25ee578a864578548959fe778e6839ef31e29fce
|
[
"MIT"
] | null | null | null |
using System;
using System.Collections.Generic;
using System.Linq;
using Artemis.Plugins.PhilipsHue.RGB.NET.Hue;
using Q42.HueApi;
using Q42.HueApi.Interfaces;
using Q42.HueApi.Models.Groups;
using Q42.HueApi.Streaming;
using Q42.HueApi.Streaming.Models;
using RGB.NET.Core;
namespace Artemis.Plugins.PhilipsHue.RGB.NET
{
public class HueRGBDeviceProvider : AbstractRGBDeviceProvider
{
#region Constructors
public HueRGBDeviceProvider()
{
if (_instance != null) throw new InvalidOperationException($"There can be only one instance of type {nameof(HueRGBDeviceProvider)}");
_instance = this;
}
#endregion
#region Properties & Fields
private static HueRGBDeviceProvider _instance;
public static HueRGBDeviceProvider Instance => _instance ?? new HueRGBDeviceProvider();
public List<HueClientDefinition> ClientDefinitions { get; } = new();
#endregion
#region Methods
/// <inheritdoc />
protected override void InitializeSDK()
{
// Each client definition has its own connection initialized in LoadDevices
}
/// <inheritdoc />
protected override IEnumerable<IRGBDevice> LoadDevices()
{
HueDeviceUpdateTrigger updateTrigger = (HueDeviceUpdateTrigger) GetUpdateTrigger();
foreach (HueClientDefinition clientDefinition in ClientDefinitions)
{
// Create a temporary for this definition
ILocalHueClient client = new LocalHueClient(clientDefinition.Ip);
client.Initialize(clientDefinition.AppKey);
// Get the entertainment groups, no point continuing without any entertainment groups
IReadOnlyList<Group> entertainmentGroups = AsyncHelper.RunSync(client.GetEntertainmentGroups);
if (!entertainmentGroups.Any())
continue;
// Get all lights once, all devices can use this list to identify themselves
List<Light> lights = AsyncHelper.RunSync(client.GetLightsAsync).ToList();
foreach (Group entertainmentGroup in entertainmentGroups.OrderBy(g => int.Parse(g.Id)))
{
StreamingHueClient streamingClient = new(clientDefinition.Ip, clientDefinition.AppKey, clientDefinition.ClientKey);
StreamingGroup streamingGroup = new(entertainmentGroup.Locations);
AsyncHelper.RunSync(async () => await streamingClient.Connect(entertainmentGroup.Id));
updateTrigger.ClientGroups.Add(streamingClient, streamingGroup);
foreach (string lightId in entertainmentGroup.Lights.OrderBy(int.Parse))
{
HueDeviceInfo deviceInfo = new(entertainmentGroup, lightId, lights);
HueDevice device = new(deviceInfo, new HueUpdateQueue(updateTrigger, lightId, streamingGroup));
yield return device;
}
}
}
}
/// <inheritdoc />
protected override IDeviceUpdateTrigger CreateUpdateTrigger(int id, double updateRateHardLimit) => new HueDeviceUpdateTrigger();
#endregion
}
}
| 39.702381
| 145
| 0.63928
|
df5fb97e954df48237c1335566132a51eaefb81d
| 7,521
|
cs
|
C#
|
ExchangeFormat/Form1.Designer.cs
|
Asteriskx/ExchangeFormatter
|
1f6b5c9488b0254791f69944699b9daaf5b89a5a
|
[
"MIT"
] | 3
|
2017-08-26T21:38:39.000Z
|
2017-10-30T05:49:17.000Z
|
ExchangeFormat/Form1.Designer.cs
|
Asteriskx/ExchangeFormatter
|
1f6b5c9488b0254791f69944699b9daaf5b89a5a
|
[
"MIT"
] | null | null | null |
ExchangeFormat/Form1.Designer.cs
|
Asteriskx/ExchangeFormatter
|
1f6b5c9488b0254791f69944699b9daaf5b89a5a
|
[
"MIT"
] | null | null | null |
namespace ExchangeFormat
{
partial class Form1
{
/// <summary>
/// 必要なデザイナー変数です。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 使用中のリソースをすべてクリーンアップします。
/// </summary>
/// <param name="disposing">マネージ リソースを破棄する場合は true を指定し、その他の場合は false を指定します。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows フォーム デザイナーで生成されたコード
/// <summary>
/// デザイナー サポートに必要なメソッドです。このメソッドの内容を
/// コード エディターで変更しないでください。
/// </summary>
private void InitializeComponent()
{
this.ExchangeButton = new System.Windows.Forms.Button();
this.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.NowProcessCheck = new System.Windows.Forms.ToolStripStatusLabel();
this.label1 = new System.Windows.Forms.Label();
this.OldFormat = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.NewFormat = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.Grep = new System.Windows.Forms.TextBox();
this.statusStrip1.SuspendLayout();
this.SuspendLayout();
//
// ExchangeButton
//
this.ExchangeButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.ExchangeButton.Font = new System.Drawing.Font("メイリオ", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
this.ExchangeButton.ForeColor = System.Drawing.Color.GhostWhite;
this.ExchangeButton.Location = new System.Drawing.Point(405, 139);
this.ExchangeButton.Name = "ExchangeButton";
this.ExchangeButton.Size = new System.Drawing.Size(132, 52);
this.ExchangeButton.TabIndex = 0;
this.ExchangeButton.Text = "Exchange";
this.ExchangeButton.UseVisualStyleBackColor = true;
this.ExchangeButton.Click += new System.EventHandler(this.ExchangeButton_Click);
//
// statusStrip1
//
this.statusStrip1.BackColor = System.Drawing.Color.SteelBlue;
this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.NowProcessCheck});
this.statusStrip1.Location = new System.Drawing.Point(0, 203);
this.statusStrip1.Name = "statusStrip1";
this.statusStrip1.Size = new System.Drawing.Size(549, 22);
this.statusStrip1.TabIndex = 1;
this.statusStrip1.Text = "statusStrip1";
//
// NowProcessCheck
//
this.NowProcessCheck.ForeColor = System.Drawing.SystemColors.Control;
this.NowProcessCheck.Name = "NowProcessCheck";
this.NowProcessCheck.Size = new System.Drawing.Size(55, 17);
this.NowProcessCheck.Text = "準備完了";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("メイリオ", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
this.label1.ForeColor = System.Drawing.SystemColors.Control;
this.label1.Location = new System.Drawing.Point(30, 69);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(83, 18);
this.label1.TabIndex = 2;
this.label1.Text = "OldFormat : ";
//
// OldFormat
//
this.OldFormat.Location = new System.Drawing.Point(128, 68);
this.OldFormat.Name = "OldFormat";
this.OldFormat.Size = new System.Drawing.Size(409, 19);
this.OldFormat.TabIndex = 3;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("メイリオ", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
this.label2.ForeColor = System.Drawing.SystemColors.Control;
this.label2.Location = new System.Drawing.Point(30, 107);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(90, 18);
this.label2.TabIndex = 4;
this.label2.Text = "NewFormat : ";
//
// NewFormat
//
this.NewFormat.Location = new System.Drawing.Point(128, 106);
this.NewFormat.Name = "NewFormat";
this.NewFormat.Size = new System.Drawing.Size(409, 19);
this.NewFormat.TabIndex = 5;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("メイリオ", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
this.label3.ForeColor = System.Drawing.SystemColors.Control;
this.label3.Location = new System.Drawing.Point(30, 31);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(75, 18);
this.label3.TabIndex = 6;
this.label3.Text = "GrepPath : ";
//
// Grep
//
this.Grep.Location = new System.Drawing.Point(128, 30);
this.Grep.Name = "Grep";
this.Grep.Size = new System.Drawing.Size(409, 19);
this.Grep.TabIndex = 7;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
this.ClientSize = new System.Drawing.Size(549, 225);
this.Controls.Add(this.Grep);
this.Controls.Add(this.label3);
this.Controls.Add(this.NewFormat);
this.Controls.Add(this.label2);
this.Controls.Add(this.OldFormat);
this.Controls.Add(this.label1);
this.Controls.Add(this.statusStrip1);
this.Controls.Add(this.ExchangeButton);
this.Name = "Form1";
this.Text = "ExchangeFormatter";
this.statusStrip1.ResumeLayout(false);
this.statusStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button ExchangeButton;
private System.Windows.Forms.StatusStrip statusStrip1;
private System.Windows.Forms.ToolStripStatusLabel NowProcessCheck;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox OldFormat;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox NewFormat;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox Grep;
}
}
| 45.581818
| 160
| 0.569206
|
f414f2c819ddcbb4c4b08fde4dc8a74f85a1498c
| 28,413
|
cs
|
C#
|
Ao3TrackReader/Ao3TrackReader/Data/SyncedStorage.cs
|
Antyos/Ao3-Tracker
|
55634d20a6796f0cc10009db23ad1e1b8228fbd3
|
[
"Apache-2.0"
] | 8
|
2017-11-30T14:33:42.000Z
|
2021-12-27T07:29:08.000Z
|
Ao3TrackReader/Ao3TrackReader/Data/SyncedStorage.cs
|
Antyos/Ao3-Tracker
|
55634d20a6796f0cc10009db23ad1e1b8228fbd3
|
[
"Apache-2.0"
] | 10
|
2017-04-27T11:47:35.000Z
|
2020-10-26T13:24:40.000Z
|
Ao3TrackReader/Ao3TrackReader/Data/SyncedStorage.cs
|
Antyos/Ao3-Tracker
|
55634d20a6796f0cc10009db23ad1e1b8228fbd3
|
[
"Apache-2.0"
] | 4
|
2018-03-21T02:51:42.000Z
|
2022-01-26T16:07:29.000Z
|
/*
Copyright 2017 Alexis Ryan
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.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Threading;
using Ao3TrackReader.Helper;
namespace Ao3TrackReader.Data
{
public class SyncedStorage
{
ReaderWriterLockSlim ReadWriteLock { get; } = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
Dictionary<long, Work> storage;
Dictionary<long, Work> unsynced;
enum SyncState
{
Disabled = -1,
Syncing = 0,
Ready = 1,
Delayed = 2
}
SyncState serversync = SyncState.Disabled;
long last_sync = 0;
long no_sync_until = 0;
readonly Uri url_base = new Uri("https://wenchy.net/ao3track/api/");
struct Authorization
{
public string username;
public string credential;
public string ToBase64()
{
return Convert.ToBase64String(Encoding.UTF8.GetBytes(this.username + '\n' + this.credential));
}
};
public event EventHandler BeginSyncEvent;
public event EventHandler<EventArgs<bool>> EndSyncEvent;
public bool IsSyncing
{
get { return serversync == SyncState.Syncing; }
}
public bool CanSync
{
get { return serversync != SyncState.Disabled; }
}
public string Username
{
get { return App.Database.GetVariable("authorization.username") ?? ""; }
}
public bool HaveCredentials
{
get { return !string.IsNullOrWhiteSpace(App.Database.GetVariable("authorization.username")) && !string.IsNullOrWhiteSpace(App.Database.GetVariable("authorization.credential")); }
}
private HttpClient HttpClient { get; set; }
public SyncedStorage()
{
HttpClientHandler httpClientHandler = new HttpClientHandler()
{
AllowAutoRedirect = false,
UseCookies = false,
//httpClientHandler.MaxConnectionsPerServer = 2;
MaxRequestContentBufferSize = 1 << 20
};
HttpClient = new HttpClient(httpClientHandler);
// Time synchronization.
var startTime = DateTime.UtcNow.ToUnixTime();
HttpClient.GetAsync(new Uri(url_base, "Values/Time")).ContinueWith(async (task) =>
{
if (task.IsCanceled || task.IsFaulted) return;
var endTime = DateTime.UtcNow.ToUnixTime();
var response = task.Result;
var content = await response.Content.ReadAsStringAsync();
var serverTime = JsonConvert.DeserializeObject<long>(content);
Extensions.UnixTimeOffset = serverTime - (startTime + endTime) / 2;
});
storage = new Dictionary<long, Work>();
unsynced = new Dictionary<long, Work>();
var database = App.Database;
database.TryGetVariable("last_sync", long.TryParse, out last_sync);
Authorization authorization;
authorization.username = database.GetVariable("authorization.username") ?? "";
authorization.credential = database.GetVariable("authorization.credential") ?? "";
if (String.IsNullOrWhiteSpace(authorization.username) || String.IsNullOrWhiteSpace(authorization.credential))
{
serversync = SyncState.Disabled;
}
else
{
HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Ao3track", authorization.ToBase64());
serversync = SyncState.Syncing;
}
foreach (var it in database.GetItems())
{
storage[it.workid] = it;
if (storage[it.workid].Timestamp > last_sync)
{
unsynced[it.workid] = storage[it.workid];
}
}
}
private CancellationTokenSource DelayedSyncCTS { get; set; } = null;
public Task DelayedSyncAsync(int timeout)
{
return Task.Run(() =>
{
using (ReadWriteLock.WriteLock())
{
//console.log("delayedsync: timeout = %i", timeout);
var now = DateTime.UtcNow.Ticks / 10000;
if (DelayedSyncCTS != null)
{
//console.log("delayedsync: existing pending sync in %i", no_sync_until - now);
// If the pending sync is going to happen before timeout would elapse, just let it happen
if (no_sync_until <= now + timeout) { return; }
DelayedSyncCTS.Cancel();
DelayedSyncCTS = null;
}
//console.log("delayedsync: setting up timeout callback");
no_sync_until = now + timeout;
serversync = SyncState.Delayed;
var cts = DelayedSyncCTS = new CancellationTokenSource();
Task.Delay(timeout, DelayedSyncCTS.Token).ContinueWith(task =>
{
using (ReadWriteLock.WriteLock())
{
cts.Dispose();
if (cts == DelayedSyncCTS) DelayedSyncCTS = null;
if (task.IsCompleted && serversync != SyncState.Syncing) DoSyncAsync(true);
}
});
}
});
}
public void DoSyncAsync(bool force = false)
{
Task.Factory.StartNew(() =>
{
using (ReadWriteLock.UpgradeableReadLock())
{
var settings = new JsonSerializerSettings()
{
MissingMemberHandling = MissingMemberHandling.Ignore
};
Dictionary<long, Work> items;
Dictionary<long, Work> current;
long time;
long old_sync;
Task<HttpResponseMessage> responseTask;
HttpResponseMessage response;
Task<string> contentTask;
string content;
using (ReadWriteLock.WriteLock())
{
if (serversync == SyncState.Disabled)
{
EndSyncEvent?.Invoke(this, new EventArgs<bool>(false));
//console.warn("dosync: FAILED. No credentials");
return;
}
// if we have waiting readers do it now
if (ReadWriteLock.WaitingReadCount > 0)
{
force = true;
}
// Enforce 5 minutes gap between server sync. Don't want to hammer the server while scrolling through a fic
var now = DateTime.UtcNow.Ticks / 10000;
if (!force && now < no_sync_until)
{
//console.log("dosync: have to wait %i for timeout", no_sync_until - now);
DelayedSyncAsync((int)(no_sync_until - now));
return;
}
serversync = SyncState.Syncing; // set to syncing!
if (DelayedSyncCTS != null)
{
DelayedSyncCTS.Cancel();
DelayedSyncCTS = null;
}
no_sync_until = now + 5 * 60 * 1000;
BeginSyncEvent?.Invoke(this, EventArgs.Empty);
//console.log("dosync: sending GET request");
responseTask = HttpClient.GetAsync(new Uri(url_base, "Values?after=" + last_sync));
responseTask.TryWait();
response = responseTask.IsFaulted ? null : responseTask.Result;
if (response == null || !response.IsSuccessStatusCode)
{
using (ReadWriteLock.WriteLock())
{
//console.error("dosync: FAILED %s", response.ReasonPhrase);
if (response != null && response.StatusCode == HttpStatusCode.Forbidden)
serversync = SyncState.Disabled;
else
serversync = SyncState.Ready;
EndSyncEvent?.Invoke(this, new EventArgs<bool>(false));
return;
}
}
contentTask = response.Content.ReadAsStringAsync();
contentTask.Wait();
content = contentTask.Result;
old_sync = last_sync;
try
{
items = JsonConvert.DeserializeObject<Dictionary<long, Work>>(content, settings);
}
catch (Exception e)
{
App.Log(e);
serversync = SyncState.Disabled;
EndSyncEvent?.Invoke(this, new EventArgs<bool>(false));
return;
}
Dictionary<long, Work> newitems = new Dictionary<long, Work>();
foreach (var item in items)
{
item.Value.workid = item.Key;
// Highest time value of incoming item is our new sync time
if (item.Value.Timestamp > last_sync)
{
last_sync = item.Value.Timestamp;
}
Work old = null;
if (!storage.ContainsKey(item.Key) || (old = storage[item.Key]).LessThanOrEqual(item.Value))
{
// Remove from unsynced list (if it exists)
if (unsynced.ContainsKey(item.Key)) { unsynced.Remove(item.Key); }
// Grab the new details
newitems[item.Key] = storage[item.Key] = item.Value;
if (old == null || item.Value.location == null || item.Value.location == 0 || (old != null && item.Value.number > old.number))
{
WorkEvents.TryGetEvent(item.Key)?.OnChapterNumChanged(this, item.Value);
}
else
{
WorkEvents.TryGetEvent(item.Key)?.OnLocationChanged(this, item.Value);
}
}
// This kinda shouldn't happen, but apparently it did... we can deal with it though
else
{
// Update the timestamp to newer than newest
if (storage[item.Key].Timestamp <= item.Value.Timestamp) { storage[item.Key].Timestamp = item.Value.Timestamp + 1; }
else { item.Value.Timestamp += 1; }
// set as unsynced
unsynced[item.Key] = storage[item.Key];
}
}
App.Database.SaveItems(newitems.Values.ToReadOnly());
current = unsynced;
unsynced = new Dictionary<long, Work>();
time = last_sync;
if (current.Count == 0)
{
App.Database.SaveVariable("last_sync", last_sync);
serversync = SyncState.Ready;
EndSyncEvent?.Invoke(this, new EventArgs<bool>(true));
return;
}
}
foreach (var item in current.Values)
{
if (item.Timestamp > time)
{
time = item.Timestamp;
}
}
var json = JsonConvert.SerializeObject(current);
var postBody = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
responseTask = HttpClient.PostAsync(new Uri(url_base, "Values"), postBody);
responseTask.TryWait();
response = responseTask.IsFaulted ? null : responseTask.Result;
if (response == null || !response.IsSuccessStatusCode)
{
using (ReadWriteLock.WriteLock())
{
//console.error("dosync: FAILED %s", response.ReasonPhrase);
if (response != null && response.StatusCode == HttpStatusCode.Forbidden)
{
last_sync = 0;
serversync = SyncState.Disabled;
}
else
{
last_sync = old_sync;
serversync = SyncState.Ready;
unsynced = current;
}
App.Database.SaveVariable("last_sync", last_sync);
EndSyncEvent?.Invoke(this, new EventArgs<bool>(false));
return;
}
}
contentTask = response.Content.ReadAsStringAsync();
contentTask.Wait();
content = contentTask.Result;
try
{
items = JsonConvert.DeserializeObject<Dictionary<long, Work>>(content, settings);
}
catch (Exception e)
{
App.Log(e);
using (ReadWriteLock.WriteLock())
{
serversync = SyncState.Disabled;
App.Database.SaveVariable("last_sync", 0L);
last_sync = 0;
EndSyncEvent?.Invoke(this, new EventArgs<bool>(false));
return;
}
}
//console.log("dosync: SUCCESS. %i conflicted items", Object.keys(items).length);
using (ReadWriteLock.WriteLock())
{
if (items.Count > 0)
{
App.Database.SaveVariable("last_sync", 0L);
last_sync = 0;
DoSyncAsync(true);
return;
}
if (time > last_sync)
{
last_sync = time;
App.Database.SaveVariable("last_sync", time);
}
if (unsynced.Count > 0)
{
DoSyncAsync(true);
}
else
{
serversync = SyncState.Ready;
EndSyncEvent?.Invoke(this, new EventArgs<bool>(true));
}
}
}
}, TaskCreationOptions.PreferFairness | TaskCreationOptions.LongRunning);
}
public Task<IDictionary<long, WorkChapter>> GetWorkChaptersAsync(IEnumerable<long> works)
{
return Task.Run(() =>
{
using (ReadWriteLock.ReadLock())
{
IDictionary<long, WorkChapter> r = new Dictionary<long, WorkChapter>();
foreach (long w in works)
{
if (storage.TryGetValue(w, out Work work))
{
r[w] = new WorkChapter(work);
}
}
return r;
}
});
}
public Task SetWorkChaptersAsync(IDictionary<long, WorkChapter> works)
{
return Task.Run(() =>
{
using (ReadWriteLock.WriteLock())
{
long time = DateTime.UtcNow.ToUnixTime();
Dictionary<long, Work> newitems = new Dictionary<long, Work>();
bool do_delayed = false;
foreach (var work in works)
{
if (work.Value.workid == 0) work.Value.workid = work.Key;
else if (work.Value.workid != work.Key) throw new ArgumentException("Value.workid != Key", nameof(works));
if (!storage.TryGetValue(work.Key, out var old) || old.LessThan(work.Value))
{
var seq = work.Value.seq;
if (seq == null && old != null)
{
seq = old.Seq;
}
var w = new Work
{
workid = work.Key,
number = work.Value.number,
chapterid = work.Value.chapterid,
location = work.Value.location,
Timestamp = time,
Seq = seq ?? 0,
};
unsynced[work.Key] = newitems[work.Key] = storage[work.Key] = w;
// Do a delayed since if we finished a chapter, or started a new one
if (old == null || work.Value.location == null || work.Value.location == 0 || work.Value.number > old.number || work.Value.seq > old.Seq)
{
do_delayed = true;
WorkEvents.TryGetEvent(work.Key)?.OnChapterNumChanged(this, w);
}
else
{
WorkEvents.TryGetEvent(work.Key)?.OnLocationChanged(this, w);
}
}
}
if (newitems.Count > 0)
{
App.Database.SaveItems(newitems.Values.ToReadOnly());
if (serversync == SyncState.Ready || serversync == SyncState.Delayed)
{
if (do_delayed)
{
DelayedSyncAsync(10 * 1000);
}
else
{
DoSyncAsync();
}
}
}
}
});
}
public Task UserLogoutAsync()
{
return Task.Run(() =>
{
using (ReadWriteLock.WriteLock())
{
serversync = SyncState.Disabled;
HttpClient.DefaultRequestHeaders.Authorization = null;
last_sync = 0;
App.Database.SaveVariable("authorization.credential", "");
App.Database.SaveVariable("last_sync", last_sync);
}
}
);
}
public Task<Dictionary<string, string>> UserLoginAsync(string username, string password)
{
return UserLoginOrCreateAsync(username, password, null);
}
public Task<Dictionary<string, string>> UserCreateAsync(string username, string password, string email)
{
return UserLoginOrCreateAsync(username, password, email ?? "");
}
private Task<Dictionary<string, string>> UserLoginOrCreateAsync(string username, string password, string email)
{
return Task.Run(() =>
{
using (ReadWriteLock.WriteLock())
{
serversync = SyncState.Disabled;
HttpClient.DefaultRequestHeaders.Authorization = null;
App.Database.SaveVariable("authorization.credential", "");
Task<HttpResponseMessage> responseTask;
if (email == null)
{
var json = JsonConvert.SerializeObject(new
{
username = username,
password = password
});
var postBody = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
responseTask = HttpClient.PostAsync(new Uri(url_base, "User/Login"), postBody);
}
else
{
var json = JsonConvert.SerializeObject(new
{
username = username,
password = password,
email = email
});
var postBody = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
responseTask = HttpClient.PostAsync(new Uri(url_base, "User/Create"), postBody);
}
responseTask.TryWait();
if (responseTask.IsFaulted)
{
return new Dictionary<string, string> {
{ "exception", responseTask.Exception.Message }
};
}
var response = responseTask.Result;
if (!response.IsSuccessStatusCode)
{
return new Dictionary<string, string> {
{ "server", response.ReasonPhrase }
};
}
var contentTask = response.Content.ReadAsStringAsync();
contentTask.Wait();
var content = contentTask.Result;
try
{
if (content.StartsWith("{"))
{
return JsonConvert.DeserializeObject<Dictionary<string, string>>(content);
}
string cred = JsonConvert.DeserializeObject<string>(content);
Authorization authorization;
authorization.credential = cred;
authorization.username = username;
HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Ao3track", authorization.ToBase64());
last_sync = 0;
App.Database.SaveVariable("authorization.username", authorization.username);
App.Database.SaveVariable("authorization.credential", authorization.credential);
App.Database.SaveVariable("last_sync", last_sync);
serversync = SyncState.Syncing;
DoSyncAsync(true);
}
catch (Exception e)
{
App.Log(e);
return new Dictionary<string, string> {
{ "exception", e.Message }
};
}
return null;
}
});
}
public Task<Models.ServerReadingList> SyncReadingListAsync(Models.ServerReadingList srl)
{
return Task.Run(async () =>
{
if (serversync == SyncState.Disabled) return null;
var json = JsonConvert.SerializeObject(srl);
var postBody = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var responseTask = HttpClient.PostAsync(new Uri(url_base, "ReadingList"), postBody);
responseTask.TryWait();
if (responseTask.IsFaulted) return null;
var response = responseTask.Result;
if (!response.IsSuccessStatusCode) return null;
var content = await response.Content.ReadAsStringAsync();
try
{
return JsonConvert.DeserializeObject<Models.ServerReadingList>(content);
}
catch
{
return null;
}
});
}
public Task<Models.ServerListFilters> SyncListFiltersAsync(Models.ServerListFilters slf)
{
return Task.Run(async () =>
{
if (serversync == SyncState.Disabled) return null;
var json = JsonConvert.SerializeObject(slf);
var postBody = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var responseTask = HttpClient.PostAsync(new Uri(url_base, "ListFilters"), postBody);
responseTask.TryWait();
if (responseTask.IsFaulted) return null;
var response = responseTask.Result;
if (!response.IsSuccessStatusCode) return null;
var content = await response.Content.ReadAsStringAsync();
try
{
return JsonConvert.DeserializeObject<Models.ServerListFilters>(content);
}
catch
{
return null;
}
});
}
public Task<bool> SubmitErrorReport(string report)
{
return Task.Run(() =>
{
var json = JsonConvert.SerializeObject(report);
var postBody = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var responseTask = HttpClient.PostAsync(new Uri(url_base, "ErrorReport"), postBody);
responseTask.TryWait();
if (responseTask.IsFaulted) return false;
return responseTask.Result.IsSuccessStatusCode;
});
}
public async Task<string> FetchAsync(string path)
{
var request = await HttpClient.GetAsync(new Uri(url_base, "/ao3track/" + path));
if (!request.IsSuccessStatusCode) return null;
return await request.Content.ReadAsStringAsync();
}
}
}
| 40.706304
| 190
| 0.447718
|
a16543418271c494ee734f3e1c3b67fbc3f3fc9f
| 182
|
ts
|
TypeScript
|
src/app/models/WorkExperience.model.ts
|
Swaraj-Deep/Portfolio
|
9f88ee5429ef125a2ab1450609482f3286ae53ca
|
[
"MIT"
] | 2
|
2021-11-01T18:12:47.000Z
|
2021-11-06T10:20:21.000Z
|
src/app/models/WorkExperience.model.ts
|
Swaraj-Deep/Portfolio
|
9f88ee5429ef125a2ab1450609482f3286ae53ca
|
[
"MIT"
] | null | null | null |
src/app/models/WorkExperience.model.ts
|
Swaraj-Deep/Portfolio
|
9f88ee5429ef125a2ab1450609482f3286ae53ca
|
[
"MIT"
] | null | null | null |
export interface WorkExperience {
title: string;
description: string[];
organization: string;
location: string;
techStack: string[];
startDate: Date;
endDate?: Date;
}
| 18.2
| 33
| 0.703297
|
dd6b9aacf7705a55d48fc78a520b0bafcb501a6c
| 175
|
java
|
Java
|
src/main/java/block/event/separator/interfaces/mixin/IMinecraftServer.java
|
SpaceWalkerRS/block-event-separator
|
978ae1fa5abbdf9221e1b1fc5d23f83430d0cdeb
|
[
"MIT"
] | 1
|
2022-03-22T10:46:17.000Z
|
2022-03-22T10:46:17.000Z
|
src/main/java/block/event/separator/interfaces/mixin/IMinecraftServer.java
|
SpaceWalkerRS/block-event-separator
|
978ae1fa5abbdf9221e1b1fc5d23f83430d0cdeb
|
[
"MIT"
] | null | null | null |
src/main/java/block/event/separator/interfaces/mixin/IMinecraftServer.java
|
SpaceWalkerRS/block-event-separator
|
978ae1fa5abbdf9221e1b1fc5d23f83430d0cdeb
|
[
"MIT"
] | 1
|
2022-03-16T19:53:36.000Z
|
2022-03-16T19:53:36.000Z
|
package block.event.separator.interfaces.mixin;
public interface IMinecraftServer {
default boolean isPaused() {
return false;
}
public void postBlockEvents_bes();
}
| 14.583333
| 47
| 0.765714
|
312735cb21115510bfe1e1cf15af2f76c2d073ec
| 3,124
|
rb
|
Ruby
|
sli/bulk-extract/marker/marker.rb
|
jstokes/secure-data-service
|
94ae9df1c2a46b3555cdee5779929f48405f788d
|
[
"Apache-2.0"
] | null | null | null |
sli/bulk-extract/marker/marker.rb
|
jstokes/secure-data-service
|
94ae9df1c2a46b3555cdee5779929f48405f788d
|
[
"Apache-2.0"
] | null | null | null |
sli/bulk-extract/marker/marker.rb
|
jstokes/secure-data-service
|
94ae9df1c2a46b3555cdee5779929f48405f788d
|
[
"Apache-2.0"
] | null | null | null |
=begin
Copyright 2012 Shared Learning Collaborative, LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=end
require 'rbconfig'
require File.dirname(__FILE__) + '/lea_marker'
class PKFactory
def create_pk(doc)
return doc if doc[:_id]
doc.delete(:_id) # in case it exists but the value is nil
doc['_id'] ||= doc['sliId']
doc
end
end
def run_marker(tenant, lea)
connection = Mongo::MongoClient.new(@hp[0], @hp[1].to_i, :pool_size => 10, :pool_timeout => 25)
db = connection[tenant]
writeDb = connection.db("m_" + Digest::SHA1.hexdigest("#{tenant}_#{lea}"), :pk => PKFactory.new)
@log.info "Creating a new stamper for #{lea}"
fixer = LEAMarker.new(db, writeDb, tenant, lea, @log)
begin
fixer.start
connection.close
@log.error "Finished stamping tenant \'#{tenant}\'."
rescue Exception => e
#KILL THE THREADS
@log.error "#{e}"
@log.error "#{e.backtrace}"
Process.kill("HUP", Process.pid)
connection.close
end
end
def launch_marker
connection = Mongo::Connection.new(@hp[0], @hp[1].to_i, :pool_size => 10, :pool_timeout => 25, :w => 0)
@db = connection[@database]
#Get BE Apps
appIds = []
@db['application'].find({}) do |cur|
cur.each do |app|
if app['body'].include? 'isBulkExtract' and app['body']['isBulkExtract'] == true
if app['body']['registration']['status'] == 'APPROVED'
appIds.push app['_id']
end
end
end
end
return if appIds.empty?
@log.info "Searching for #{appIds}"
#Get the tenants out.
@log.info "Searching tenant collecitons"
@db['tenant'].find({}) do |cur|
cur.each do |tenant|
dbName = tenant['body']['dbName']
tenantDB = connection[dbName]
tenantDB['applicationAuthorization'].find({'body.applicationId' => {'$in' => appIds}}) do |cur|
cur.each {|auth| auth['body']['edorgs'].each {|lea| @pids << run_marker(dbName, lea) }}
end
end
end
connection.close
end
if ARGV.count < 1
puts "Usage: edorg_stamper <dbhost:port> <database> <terminates>"
puts "\t dbhost - hostname for mongo"
puts "\t port - port mongo is running on (27017 is common)"
puts "\t database - the name of the system database (Defaults to sli)"
puts "*** Note: These parameters must exist in the order they are presented ***"
exit
else
@pids = []
@tenants = Set.new
@terminates = (ARGV[2].nil? ? false : true)
@database = (ARGV[1].nil? ? 'sli' : ARGV[1])
@hp = ARGV[0].split(":")
@log = Logger.new(STDOUT)
@log.level = Logger::INFO
backoff = 2
begin
launch_marker
sleep(backoff)
backoff **= 2 if backoff < 600
end while @terminates
end
| 31.24
| 105
| 0.661652
|
f4621062b20fa8f76c3861c861490d452aab2522
| 1,389
|
ts
|
TypeScript
|
src/__tests__/with-query-hoc.spec.ts
|
kevinydhan/gatsby-with-query
|
adb74349217991b60b0289f3c468b27dff9b3557
|
[
"MIT"
] | null | null | null |
src/__tests__/with-query-hoc.spec.ts
|
kevinydhan/gatsby-with-query
|
adb74349217991b60b0289f3c468b27dff9b3557
|
[
"MIT"
] | 6
|
2020-12-17T19:05:55.000Z
|
2020-12-18T03:29:59.000Z
|
src/__tests__/with-query-hoc.spec.ts
|
kevinydhan/gatsby-with-query
|
adb74349217991b60b0289f3c468b27dff9b3557
|
[
"MIT"
] | null | null | null |
/**
* TypeScript linting is disabled to test for invalid arguments.
*/
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-nocheck
import { createElement } from 'react'
import withQuery from '../with-query'
const DivComponent = () => createElement('div')
const emptyQueryHook = () => ({})
describe('WithQueryHOC.displayName', () => {
it('is defined', () => {
const WithQueryHOC = withQuery(DivComponent, emptyQueryHook)
expect(WithQueryHOC.displayName).toBeDefined()
})
it('is a string', () => {
const WithQueryHOC = withQuery(DivComponent, emptyQueryHook)
expect(typeof WithQueryHOC.displayName).toBe('string')
})
it('contains Component.displayName', () => {
const NameTestComponent = () => createElement('div')
const WithQueryHOC = withQuery(NameTestComponent, emptyQueryHook)
const containsName = WithQueryHOC.displayName.includes('NameTestComponent')
expect(containsName).toBe(true)
})
it('creates higher-order components with different displayName values', () => {
const NameTestComponent1 = () => createElement('div')
const NameTestComponent2 = () => createElement('div')
const WithQueryHOC1 = withQuery(NameTestComponent1, emptyQueryHook)
const WithQueryHOC2 = withQuery(NameTestComponent2, emptyQueryHook)
expect(WithQueryHOC1.displayName === WithQueryHOC2.displayName).toBe(false)
})
})
| 35.615385
| 81
| 0.716343
|