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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d13fe64c5bc402e0340c4b2e8eb0eeae0d79c653 | 9,116 | swift | Swift | DataStructure/Queue.swift | ChenYalun/Project | 9734c3987676d61b8932973a82a578470e398e09 | [
"MIT"
] | 2 | 2019-05-31T02:17:02.000Z | 2020-02-19T13:54:41.000Z | DataStructure/Queue.swift | ChenYalun/Project | 9734c3987676d61b8932973a82a578470e398e09 | [
"MIT"
] | null | null | null | DataStructure/Queue.swift | ChenYalun/Project | 9734c3987676d61b8932973a82a578470e398e09 | [
"MIT"
] | null | null | null | //
// Queue.swift
// Le
//
// Created by Chen,Yalun on 2019/6/20.
// Copyright © 2019 Chen,Yalun. All rights reserved.
//
/// 队列
/*
因为频繁地在开头末尾添加删除元素所以使用链表实现
又因为双向链表有头指针和尾指针而单向链表只有头指针所以使用双向链表实现(减少遍历)
*/
class Queue<T: Equatable> {
private var list: TwoWayLinkedList<T> = TwoWayLinkedList()
// 元素数量
func size() -> Int {
return list.count
}
// 是否为空
func isEmpty() -> Bool {
return list.isEmpty()
}
// 入队
func enQueue(_ item: T) {
list.append(item)
}
// 出队
func deQueue() -> T {
return list.remove(0)
}
// 获取队头元素
func front() -> T? {
return list.first?.ele
}
// 清空所有元素
func clear() {
list.clear()
}
// 打印元素
func desc() {
list.desc()
}
}
/*
var queue = Queue<Int>()
queue.enQueue(1)
queue.enQueue(2)
queue.enQueue(3)
queue.deQueue()
print(queue.front())
queue.enQueue(3)
print(queue.front())
queue.desc()
*/
/// 使用栈实现队列
/*
原理:
1. 入队时, 把元素放入inStack中
2. 出队时, 如果outStack为空, 则把inStack中的全部栈顶元素依次放到outStack中, 返回outStack的栈顶元素, 否则, 直接返回outStack的栈顶元素
*/
class Queue_UseStack<T: Equatable> {
// 维护两个栈
private var inStack: Stack<T> = Stack()
private var outStack: Stack<T> = Stack()
// 元素数量
func size() -> Int {
return inStack.size() + outStack.size()
}
// 是否为空
func isEmpty() -> Bool {
return size() == 0
}
// 入队
func enQueue(_ item: T) {
inStack.push(item)
}
// 出队
func deQueue() -> T {
if outStack.isEmpty() {
while inStack.isEmpty() == false {
outStack.push(inStack.pop())
}
}
return outStack.pop()
}
// 获取队头元素
func front() -> T? {
if outStack.isEmpty() {
while inStack.isEmpty() == false {
outStack.push(inStack.pop())
}
}
return outStack.top()
}
// 清空所有元素
func clear() {
inStack.clear()
outStack.clear()
}
}
/*
let que = Queue_UseStack<Int>()
que.enQueue(1)
que.deQueue()
que.enQueue(2)
que.enQueue(3)
que.deQueue()
print(que.front())
*/
/// 循环队列
/*
使用动态数组实现, 且各接口优化到O(1)时间复杂度
要点:
1. 有一个指向队头元素的索引frontIndex, 必不可少
2. 接口索引与真实索引的互换: 真实索引 = (frontIndex + index) % elements.count
3. 入队
*/
class CircleQueue<T: Equatable> {
// 元素数量
private var count: Int = 0
// 指向队头的索引
private var frontIndex: Int = 0
// 使用nil作为占位
private var elements: [T?]
// 默认10个元素
private let DEFAULT_CAPACITY = 10
private let ELEMENT_NOT_FOUND = -1
// 构造器, 初始化容量为capaticy的数组
init(_ capaticy: Int) {
let capaticy = capaticy < DEFAULT_CAPACITY ? DEFAULT_CAPACITY : capaticy
elements = [T?](repeating: nil, count: capaticy)
}
// 元素数量
func size() -> Int {
return count
}
// 是否为空
func isEmpty() -> Bool {
return count == 0
}
// 入队
func enQueue(_ item: T) {
ensureCapacity(count + 1)
elements[index(count)] = item
count += 1
}
// 出队
func deQueue() -> T {
let ele = elements[frontIndex]
if ele == nil {
fatalError("队列为空")
}
elements[frontIndex] = nil
// 不是frontIndex += 1, 要考虑frontIndex == elements.count但是elements有空闲位置的情况
// 这时应该是frontIndex = (frontIndex + 1) % elements.count, 也就是index(1)
frontIndex = index(1)
count -= 1
return ele!
}
// 获取队头元素
func front() -> T? {
return elements[frontIndex]
}
// 清空所有元素
func clear() {
for idx in 0..<elements.count {
elements[idx] = nil
}
frontIndex = 0
count = 0
}
// 数组扩容
private func ensureCapacity(_ capacity: Int) {
// 不需要扩容
if elements.count >= capacity {
return
}
var elements = self.elements
// 扩容1.5倍
let newCapacity = elements.count + elements.count >> 1
var newElements = [T?](repeating: nil, count: newCapacity)
for idx in 0..<count {
newElements[idx] = elements[index(idx)]
}
self.elements = newElements
frontIndex = 0
}
// 获取索引对应真实索引
private func index(_ index: Int) -> Int {
return (frontIndex + index) % elements.count
}
// 打印元素
func desc() {
print("frontIndex: \(frontIndex)" + " eles: \(elements)")
}
}
/*
var cq = CircleQueue<Int>(10)
cq.enQueue(1)
cq.enQueue(2)
cq.enQueue(3)
cq.deQueue()
cq.deQueue()
cq.deQueue()
cq.desc()
cq.enQueue(11)
cq.enQueue(12)
cq.enQueue(13)
cq.enQueue(21)
cq.enQueue(22)
cq.enQueue(23)
cq.enQueue(33)
cq.enQueue(42)
cq.enQueue(43)
cq.enQueue(44)
cq.enQueue(54)
cq.desc()
cq.deQueue()
cq.deQueue()
cq.desc()
*/
/// 双端队列
/*
两端都可以入队和出队
*/
class DoubleEndedQueue<T: Equatable> {
private var list: TwoWayLinkedList<T> = TwoWayLinkedList()
// 元素数量
func size() -> Int {
return list.count
}
// 是否为空
func isEmpty() -> Bool {
return list.isEmpty()
}
// 从队头入队
func enQueueFront(_ item: T) {
list.insert(item, 0)
}
// 从队尾入队
func enQueueRear(_ item: T) {
list.append(item)
}
// 从队头出队
func deQueueFront() -> T {
return list.remove(0)
}
// 从队尾出队
func deQueueRear() -> T {
return list.remove(list.count - 1)
}
// 获取队头元素
func front() -> T? {
return list.first?.ele
}
// 获取队尾元素
func rear() -> T? {
return list.last?.ele
}
// 清空所有元素
func clear() {
list.clear()
}
// 打印元素
func desc() {
list.desc()
}
}
/*
let deq = DoubleEndedQueue<Int>()
deq.enQueueFront(1)
deq.enQueueFront(2)
deq.enQueueRear(8)
deq.enQueueRear(9)
deq.desc()
deq.clear()
deq.enQueueFront(1)
deq.enQueueFront(2)
deq.deQueueFront()
deq.enQueueRear(8)
deq.enQueueRear(9)
deq.deQueueRear()
deq.desc()
*/
// 循环双端队列
class CircleDoubleEndedQueue<T: Equatable> {
// 元素数量
private var count: Int = 0
// 指向队头的索引
private var frontIndex: Int = 0
// 使用nil作为占位
private var elements: [T?]
// 默认10个元素
private let DEFAULT_CAPACITY = 10
private let ELEMENT_NOT_FOUND = -1
// 构造器, 初始化容量为capaticy的数组
init(_ capaticy: Int) {
let capaticy = capaticy < DEFAULT_CAPACITY ? DEFAULT_CAPACITY : capaticy
elements = [T?](repeating: nil, count: capaticy)
}
// 元素数量
func size() -> Int {
return count
}
// 是否为空
func isEmpty() -> Bool {
return count == 0
}
// 从队头入队
func enQueueFront(_ item: T) {
ensureCapacity(count + 1)
frontIndex = index(-1)
elements[frontIndex] = item
count += 1
}
// 从队尾入队
func enQueueRear(_ item: T) {
ensureCapacity(count + 1)
elements[index(count)] = item
count += 1
}
// 从队头出队
func deQueueFront() -> T {
if count <= 0 {
fatalError("队列为空")
}
let ele = elements[frontIndex]
elements[frontIndex] = nil
frontIndex = index(1)
count -= 1
return ele!
}
// 从队尾出队
func deQueueRear() -> T {
if count <= 0 {
fatalError("队列为空")
}
let ele = elements[index(count - 1)]!
elements[index(count - 1)] = nil
count -= 1
return ele
}
// 获取队头元素
func front() -> T? {
return elements[frontIndex]
}
// 获取队尾元素
func rear() -> T? {
return elements[index(count - 1)]
}
// 清空所有元素
func clear() {
for idx in 0..<elements.count {
elements[idx] = nil
}
frontIndex = 0
count = 0
}
// 数组扩容
private func ensureCapacity(_ capacity: Int) {
// 不需要扩容
if elements.count >= capacity {
return
}
var elements = self.elements
// 扩容1.5倍
let newCapacity = elements.count + elements.count >> 1
var newElements = [T?](repeating: nil, count: newCapacity)
for idx in 0..<count {
newElements[idx] = elements[index(idx)]
}
self.elements = newElements
frontIndex = 0
}
// 获取索引对应真实索引
private func index(_ index: Int) -> Int {
var index = index
index += frontIndex
if index < 0 {
return index + elements.count
}
// return index % elements.count
return index - (index >= elements.count ? elements.count : 0)
}
// 打印元素
func desc() {
print("frontIndex: \(frontIndex)" + ",eles: \(elements)")
}
}
/*
var cdeq = CircleDoubleEndedQueue<Int>(10)
cdeq.clear()
cdeq.enQueueFront(1)
cdeq.deQueueFront()
cdeq.enQueueFront(1)
cdeq.enQueueFront(2)
cdeq.enQueueFront(3)
cdeq.deQueueFront()
cdeq.enQueueRear(9)
cdeq.enQueueRear(5)
cdeq.enQueueRear(4)
cdeq.deQueueRear()
cdeq.desc()
*/
| 19.191579 | 93 | 0.534774 |
06a36ca5ea176c6343a876da25c863b4c776a77a | 709 | cpp | C++ | MSVC/14.24.28314/crt/src/vcruntime/new_array.cpp | 825126369/UCRT | 8853304fdc2a5c216658d08b6dbbe716aa2a7b1f | [
"MIT"
] | 2 | 2021-01-27T10:19:30.000Z | 2021-02-09T06:24:30.000Z | MSVC/14.24.28314/crt/src/vcruntime/new_array.cpp | 825126369/UCRT | 8853304fdc2a5c216658d08b6dbbe716aa2a7b1f | [
"MIT"
] | null | null | null | MSVC/14.24.28314/crt/src/vcruntime/new_array.cpp | 825126369/UCRT | 8853304fdc2a5c216658d08b6dbbe716aa2a7b1f | [
"MIT"
] | 1 | 2021-01-27T10:19:36.000Z | 2021-01-27T10:19:36.000Z | //
// new_array.cpp
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Defines the array operator new.
//
#include <vcruntime_internal.h>
#include <vcruntime_new.h>
////////////////////////////////////
// new() Fallback Ordering
//
// +----------+
// |new_scalar<---------------+
// +----^-----+ |
// | |
// +----+-------------+ +----+----+
// |new_scalar_nothrow| |new_array|
// +------------------+ +----^----+
// |
// +------------+----+
// |new_array_nothrow|
// +-----------------+
void* __CRTDECL operator new[](size_t const size)
{
return operator new(size);
}
| 23.633333 | 65 | 0.373766 |
9654a08f007b875f53884560f65ed8ca8f903245 | 1,109 | php | PHP | src/Form/Type/UserRoleType.php | danilovl/final-work-system | ad17dd95966a6cfca6bd67cbb23ab2df2113707b | [
"MIT"
] | 8 | 2019-11-19T10:55:42.000Z | 2022-03-23T20:48:52.000Z | src/Form/Type/UserRoleType.php | danilovl/final-work-system | ad17dd95966a6cfca6bd67cbb23ab2df2113707b | [
"MIT"
] | 26 | 2020-10-23T20:23:59.000Z | 2022-02-11T21:34:31.000Z | src/Form/Type/UserRoleType.php | danilovl/final-work-system | ad17dd95966a6cfca6bd67cbb23ab2df2113707b | [
"MIT"
] | null | null | null | <?php declare(strict_types=1);
/**
*
* This file is part of the FinalWorkSystem project.
* (c) Vladimir Danilov
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
*/
namespace App\Form\Type;
use App\Constant\UserRoleConstant;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\OptionsResolver\OptionsResolver;
final class UserRoleType extends AbstractType
{
public const NAME = 'user_role_type';
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'choices' => [
'app.roles.student' => UserRoleConstant::STUDENT,
'app.roles.opponent' => UserRoleConstant::OPPONENT,
'app.roles.consultant' => UserRoleConstant::CONSULTANT
]
]);
}
public function getParent(): string
{
return ChoiceType::class;
}
public function getBlockPrefix(): string
{
return self::NAME;
}
}
| 24.644444 | 74 | 0.664563 |
626c1d0249cb06f7eb3f8e47e72b6159dde3c98e | 8,519 | dart | Dart | lib/events.dart | El-Gonno-Grande/beer_counter | e39a1b98d56ee361bbe59ec4a227715b2257fca3 | [
"Apache-2.0"
] | null | null | null | lib/events.dart | El-Gonno-Grande/beer_counter | e39a1b98d56ee361bbe59ec4a227715b2257fca3 | [
"Apache-2.0"
] | 15 | 2020-08-02T22:42:40.000Z | 2020-08-25T22:45:58.000Z | lib/events.dart | El-Gonno-Grande/beer_counter | e39a1b98d56ee361bbe59ec4a227715b2257fca3 | [
"Apache-2.0"
] | null | null | null | import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'beermap.dart';
import 'firebase/firebase_helper.dart';
import 'models.dart';
void openEventPage(context, FirebaseUser user, BeerEvent event) =>
Navigator.of(context).push(MaterialPageRoute<Null>(
builder: (BuildContext context) =>
EventPage(user: user, beerEventId: event.id)));
class EventPage extends StatefulWidget {
final FirebaseUser user;
final String beerEventId;
EventPage({this.user, this.beerEventId});
@override
State<StatefulWidget> createState() => _EventPageState();
}
class _EventPageState extends State<EventPage>
implements FirebaseHelperCallback {
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
BeerEvent event = BeerEvent();
List<BeerEvent> events = [];
List<Beer> beers = [];
List<User> users = [];
FirebaseHelper helper;
_EventPageState() {
helper = FirebaseHelper(callback: this);
}
void _sortDrinkers() => event.drinkers
.sort((d1, d2) => _getBeers(d1).length - _getBeers(d2).length);
@override
void initState() {
super.initState();
helper.initState();
}
@override
void dispose() {
super.dispose();
helper.dispose();
}
@override
void eventsChanged(List<BeerEvent> events) => setState(() {
this.events = events;
this.event = events.firstWhere((e) => e.id == widget.beerEventId);
});
@override
void beersChanged(List<Beer> beers) {
_sortDrinkers();
setState(() => {
this.beers =
beers.where((e) => e.eventId == widget.beerEventId).toList()
});
}
@override
void usersChanged(List<User> users) => setState(() => {this.users = users});
Future<void> _showPasswordDialog() async => showDialog<void>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Password'),
content: Text(
'The password to join ${event.name} is: ${widget.beerEventId}'),
actions: <Widget>[
FlatButton(
child: Text('OK'),
onPressed: () => Navigator.of(context).pop(),
),
],
);
},
);
String _getPhotoUrl(uid) {
List<User> _user = users.where((e) => e.uid == uid).toList();
return _user.isNotEmpty ? _user.first.photoUrl : '';
}
String _getUserName(uid) {
List<User> _user = users.where((e) => e.uid == uid).toList();
return _user.isNotEmpty ? _user.first.name : '';
}
List<Beer> _getBeers(uid) => beers.where((e) => e.uid == uid).toList();
Future<void> _askForBeerEventPassword() async {
int idx = events.indexOf(event);
TextEditingController controller = TextEditingController();
return showDialog<void>(
context: context,
barrierDismissible: false, // user must tap button!
builder: (BuildContext context) {
return AlertDialog(
title: Text('Enter Password'),
content: SingleChildScrollView(
child: ListBody(
children: <Widget>[
Text(
'Please ask a someone for the password to join ${event.name}.'),
TextField(
autofocus: true,
controller: controller,
decoration: InputDecoration(labelText: 'Password'),
),
],
),
),
actions: <Widget>[
FlatButton(
child: const Text('CANCEL'),
onPressed: () {
Navigator.pop(context);
}),
FlatButton(
child: const Text('OK'),
onPressed: () {
Navigator.pop(context);
SnackBar snackBar;
if (controller.text == widget.beerEventId) {
// password correct
helper.joinBeerEvent(widget.user.uid, idx);
snackBar = SnackBar(content: Text('Password correct!'));
} else {
snackBar = SnackBar(content: Text('Password incorrect!'));
}
_scaffoldKey.currentState..showSnackBar(snackBar);
})
],
);
},
);
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
bool isDrinker = event.drinkers.contains(widget.user.uid);
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(
title: Text(event.name),
actions: <Widget>[
Center(
child: Visibility(
child: OutlineButton(
child: Text('Join'),
onPressed: () => _askForBeerEventPassword(),
textColor: theme.accentColor,
color: theme.accentColor,
highlightedBorderColor: theme.accentColor,
),
visible: !isDrinker,
),
),
IconButton(
icon: Icon(Icons.map),
onPressed: () => openBeerMap(context, beers),
),
PopupMenuButton<String>(
onSelected: (String s) {
switch (s) {
case 'pwd':
_showPasswordDialog();
break;
default:
break;
}
},
itemBuilder: (BuildContext context) => [
PopupMenuItem<String>(
value: 'pwd',
child: Text('Show Password'),
)
],
),
],
),
body: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(
left: 8,
top: 16,
right: 8,
bottom: 8,
),
child: InkWell(
child: Text(
'Total Beer Count: ${beers.length}',
style: theme.textTheme.headline4,
),
onTap: () => {},
),
),
Flexible(
child: ListView.builder(
padding: const EdgeInsets.only(left: 16, right: 16),
itemCount: event.drinkers.length,
itemBuilder: (BuildContext context, int idx) {
String uid = event.drinkers[idx];
List<Beer> beers = _getBeers(uid);
return Container(
child: Padding(
padding: const EdgeInsets.only(top: 12, bottom: 12),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Row(
children: <Widget>[
Container(
child: CircleAvatar(
backgroundImage:
NetworkImage(_getPhotoUrl(uid)),
),
margin: EdgeInsets.only(right: 16.0),
),
Text(
_getUserName(uid),
style: theme.textTheme.headline6,
),
],
),
InkWell(
child: Text(
'${beers.length} Beers',
style: theme.textTheme.headline6
.apply(color: theme.accentColor),
),
onTap: () => openBeerMap(context, beers),
),
],
),
),
);
}),
),
],
));
}
}
| 33.14786 | 85 | 0.449583 |
39732cc741b27a8056eec671fdbc8ce43af0cc4b | 68,028 | html | HTML | lists.whatwg.org/pipermail/commit-watchers-whatwg.org/2011/013014.html | zcorpan/whatwg.org | 3374e69f013e5939abc5f3fffaae50bb6eaf0bd3 | [
"CC-BY-4.0"
] | 1 | 2022-02-14T23:44:51.000Z | 2022-02-14T23:44:51.000Z | lists.whatwg.org/pipermail/commit-watchers-whatwg.org/2011/013014.html | Seanpm2001-Google/whatwg.org | 33ad837c0dc53b68865f4a35ccdc1c68dc07fce6 | [
"BSD-3-Clause"
] | 1 | 2021-01-31T11:51:12.000Z | 2021-01-31T11:51:12.000Z | lists.whatwg.org/pipermail/commit-watchers-whatwg.org/2011/013014.html | Seanpm2001-Google/whatwg.org | 33ad837c0dc53b68865f4a35ccdc1c68dc07fce6 | [
"BSD-3-Clause"
] | null | null | null | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<TITLE> [html5] r6147 - [cgiow] (0) Change cross-origin='' to crossorigin='' since people don't seem to [...]
</TITLE>
<LINK REL="Index" HREF="index.html" >
<LINK REL="made" HREF="mailto:commit-watchers%40lists.whatwg.org?Subject=Re%3A%20%5Bhtml5%5D%20r6147%20-%20%5Bcgiow%5D%20%280%29%20Change%20cross-origin%3D%27%27%20to%0A%09crossorigin%3D%27%27%20since%20people%20don%27t%20seem%20to%20%5B...%5D&In-Reply-To=%3C20110523212915.5FEAF11C7C00B%40ps20323.dreamhostps.com%3E">
<META NAME="robots" CONTENT="index,nofollow">
<style type="text/css">
pre {
white-space: pre-wrap; /* css-2.1, curent FF, Opera, Safari */
}
</style>
<META http-equiv="Content-Type" content="text/html; charset=us-ascii">
<LINK REL="Previous" HREF="013013.html">
<LINK REL="Next" HREF="013015.html">
</HEAD>
<BODY BGCOLOR="#ffffff">
<H1>[html5] r6147 - [cgiow] (0) Change cross-origin='' to crossorigin='' since people don't seem to [...]</H1>
<!--htdig_noindex-->
<B>whatwg at whatwg.org</B>
<A HREF="mailto:commit-watchers%40lists.whatwg.org?Subject=Re%3A%20%5Bhtml5%5D%20r6147%20-%20%5Bcgiow%5D%20%280%29%20Change%20cross-origin%3D%27%27%20to%0A%09crossorigin%3D%27%27%20since%20people%20don%27t%20seem%20to%20%5B...%5D&In-Reply-To=%3C20110523212915.5FEAF11C7C00B%40ps20323.dreamhostps.com%3E"
TITLE="[html5] r6147 - [cgiow] (0) Change cross-origin='' to crossorigin='' since people don't seem to [...]">whatwg at whatwg.org
</A><BR>
<I>Mon May 23 14:29:15 PDT 2011</I>
<P><UL>
<LI>Previous message: <A HREF="013013.html">[html5] r6146 - [e] (0) remove pointless annotations
</A></li>
<LI>Next message: <A HREF="013015.html">[html5] r6148 - [giow] (0) Block redirects in WebSockets
</A></li>
<LI> <B>Messages sorted by:</B>
<a href="date.html#13014">[ date ]</a>
<a href="thread.html#13014">[ thread ]</a>
<a href="subject.html#13014">[ subject ]</a>
<a href="author.html#13014">[ author ]</a>
</LI>
</UL>
<HR>
<!--/htdig_noindex-->
<!--beginarticle-->
<PRE>Author: ianh
Date: 2011-05-23 14:29:13 -0700 (Mon, 23 May 2011)
New Revision: 6147
Modified:
complete.html
index
source
Log:
[cgiow] (0) Change cross-origin='' to crossorigin='' since people don't seem to like hyphens. Poor hyphens.
Fixing <A HREF="http://www.w3.org/Bugs/Public/show_bug.cgi?id=12679">http://www.w3.org/Bugs/Public/show_bug.cgi?id=12679</A>
Modified: complete.html
===================================================================
--- complete.html 2011-05-23 21:24:43 UTC (rev 6146)
+++ complete.html 2011-05-23 21:29:13 UTC (rev 6147)
@@ -7219,33 +7219,33 @@
<table><thead><tr><th> Keyword
<th> State
<th> Brief description
- <tbody><tr><td><dfn id=attr-cross-origin-anonymous-keyword title=attr-cross-origin-anonymous-keyword><code>anonymous</code></dfn>
- <td><dfn id=attr-cross-origin-anonymous title=attr-cross-origin-anonymous>Anonymous</dfn>
+ <tbody><tr><td><dfn id=attr-crossorigin-anonymous-keyword title=attr-crossorigin-anonymous-keyword><code>anonymous</code></dfn>
+ <td><dfn id=attr-crossorigin-anonymous title=attr-crossorigin-anonymous>Anonymous</dfn>
<td>Cross-origin CORS requests for the element will not have the <i>credentials flag</i> set.
- <tr><td><dfn id=attr-cross-origin-use-credentials-keyword title=attr-cross-origin-use-credentials-keyword><code>use-credentials</code></dfn>
- <td><dfn id=attr-cross-origin-use-credentials title=attr-cross-origin-use-credentials>Use Credentials</dfn>
+ <tr><td><dfn id=attr-crossorigin-use-credentials-keyword title=attr-crossorigin-use-credentials-keyword><code>use-credentials</code></dfn>
+ <td><dfn id=attr-crossorigin-use-credentials title=attr-crossorigin-use-credentials>Use Credentials</dfn>
<td>Cross-origin CORS requests for the element will have the <i>credentials flag</i> set.
- </table><p>The empty string is also a valid keyword, and maps to the <a href=#attr-cross-origin-anonymous title=attr-cross-origin-anonymous>Anonymous</a> state. The
- attribute's <i>invalid value default</i> is the <a href=#attr-cross-origin-anonymous title=attr-cross-origin-anonymous>Anonymous</a> state. The
+ </table><p>The empty string is also a valid keyword, and maps to the <a href=#attr-crossorigin-anonymous title=attr-crossorigin-anonymous>Anonymous</a> state. The
+ attribute's <i>invalid value default</i> is the <a href=#attr-crossorigin-anonymous title=attr-crossorigin-anonymous>Anonymous</a> state. The
<i>missing value default</i>, used when the attribute is omitted, is
- the <dfn id=attr-cross-origin-none title=attr-cross-origin-none>No CORS</dfn> state.</p>
+ the <dfn id=attr-crossorigin-none title=attr-crossorigin-none>No CORS</dfn> state.</p>
<h4 id=cors-enabled-fetch><span class=secno>2.7.6 </span>CORS-enabled fetch</h4>
<p>When the user agent is required to perform a <dfn id=potentially-cors-enabled-fetch>potentially
CORS-enabled fetch</dfn> of an <a href=#absolute-url>absolute URL</a> <var title="">URL</var>, with a mode <var title="">mode</var> that is
- either "<a href=#attr-cross-origin-none title=attr-cross-origin-none>No CORS</a>", "<a href=#attr-cross-origin-anonymous title=attr-cross-origin-anonymous>Anonymous</a>", or "<a href=#attr-cross-origin-use-credentials title=attr-cross-origin-use-credentials>Use Credentials</a>",
+ either "<a href=#attr-crossorigin-none title=attr-crossorigin-none>No CORS</a>", "<a href=#attr-crossorigin-anonymous title=attr-crossorigin-anonymous>Anonymous</a>", or "<a href=#attr-crossorigin-use-credentials title=attr-crossorigin-use-credentials>Use Credentials</a>",
an <a href=#origin>origin</a> <var title="">origin</var>, and a default
origin behaviour <var title="">default</var> which is either
"<i>taint</i>" or "<i>fail</i>", it must run the first applicable
set of steps from the following list. The default origin behaviour
- is only used if <var title="">mode</var> is "<a href=#attr-cross-origin-none title=attr-cross-origin-none>No CORS</a>". This algorithm wraps
+ is only used if <var title="">mode</var> is "<a href=#attr-crossorigin-none title=attr-crossorigin-none>No CORS</a>". This algorithm wraps
the <a href=#fetch>fetch</a> algorithm above, and labels the obtained
resource as either <dfn id=cors-same-origin>CORS-same-origin</dfn> or
<dfn id=cors-cross-origin>CORS-cross-origin</dfn>, or blocks the resource entirely.</p>
- <dl class=switch><dt>If <var title="">mode</var> is "<a href=#attr-cross-origin-none title=attr-cross-origin-none>No CORS</a>"</dt>
+ <dl class=switch><dt>If <var title="">mode</var> is "<a href=#attr-crossorigin-none title=attr-crossorigin-none>No CORS</a>"</dt>
<dd>
@@ -7338,7 +7338,7 @@
</ol></dd>
- <dt>If <var title="">mode</var> is "<a href=#attr-cross-origin-anonymous title=attr-cross-origin-anonymous>Anonymous</a>" or "<a href=#attr-cross-origin-use-credentials title=attr-cross-origin-use-credentials>Use
+ <dt>If <var title="">mode</var> is "<a href=#attr-crossorigin-anonymous title=attr-crossorigin-anonymous>Anonymous</a>" or "<a href=#attr-crossorigin-use-credentials title=attr-crossorigin-use-credentials>Use
Credentials</a>"</dt>
<dd>
@@ -7349,7 +7349,7 @@
<i>request URL</i> set to <var title="">URL</var>, the
<i>source origin</i> set to <var title="">origin</var>, and the
<i>credentials flag</i> set to true if <var title="">mode</var>
- is "<a href=#attr-cross-origin-use-credentials title=attr-cross-origin-use-credentials>Use
+ is "<a href=#attr-crossorigin-use-credentials title=attr-crossorigin-use-credentials>Use
Credentials</a>" and set to false otherwise. <a href=#refsCORS>[CORS]</a></li>
<li><p>Wait for the CORS <a href=#cross-origin-request-status>cross-origin request status</a>
@@ -22166,7 +22166,7 @@
<dd><a href=#global-attributes>Global attributes</a></dd>
<dd><code title=attr-img-alt><a href=#attr-img-alt>alt</a></code></dd>
<dd><code title=attr-img-src><a href=#attr-img-src>src</a></code></dd>
- <dd><code title=attr-img-cross-origin><a href=#attr-img-cross-origin>cross-origin</a></code></dd>
+ <dd><code title=attr-img-crossorigin><a href=#attr-img-crossorigin>crossorigin</a></code></dd>
<dd><code title=attr-hyperlink-usemap><a href=#attr-hyperlink-usemap>usemap</a></code></dd>
<dd><code title=attr-img-ismap><a href=#attr-img-ismap>ismap</a></code></dd>
<dd><code title=attr-dim-width><a href=#attr-dim-width>width</a></code></dd>
@@ -22202,7 +22202,7 @@
Slight hitch: their images are at a different origin, and we
don't want to allow arbitrary cross-origin inspection (privacy
- leak risk).
+ leak risk). So it will require them to do CORS opt-in.
* See note at rel=noreferrer.
@@ -22241,7 +22241,7 @@
display transparent images, as they rarely convey meaning and rarely
add anything useful to the document.</p>
- <p>The <dfn id=attr-img-cross-origin title=attr-img-cross-origin><code>cross-origin</code></dfn>
+ <p>The <dfn id=attr-img-crossorigin title=attr-img-crossorigin><code>crossorigin</code></dfn>
attribute is a <a href=#cors-settings-attribute>CORS settings attribute</a>.</p>
<div class=impl>
@@ -22319,7 +22319,7 @@
<p>Otherwise, do a <a href=#potentially-cors-enabled-fetch>potentially CORS-enabled fetch</a> of
the resulting <a href=#absolute-url>absolute URL</a>, with the <i>mode</i>
- being the state of the element's <code title=attr-img-cross-origin><a href=#attr-img-cross-origin>cross-origin</a></code> content
+ being the state of the element's <code title=attr-img-crossorigin><a href=#attr-img-crossorigin>crossorigin</a></code> content
attribute, the <i><a href=#origin>origin</a></i> being the <a href=#origin>origin</a> of the
<code><a href=#the-img-element>img</a></code> element's <code><a href=#document>Document</a></code>, and the
<i>default origin behaviour</i> set to <i>taint</i>.</p>
@@ -22341,8 +22341,9 @@
conjunction with scripting, though scripting isn't actually
necessary to carry out such an attack). User agents may implement
<a href=#origin title=origin>cross-origin</a> access control policies
- that mitigate this attack, but unfortunately such policies are
- typically not compatible with existing Web content.</p>
+ that are stricter than those described above to mitigate this
+ attack, but unfortunately such policies are typically not
+ compatible with existing Web content.</p>
</li>
@@ -22572,7 +22573,7 @@
name.</p>
<p>The <dfn id=dom-img-crossorigin title=dom-img-crossOrigin><code>crossOrigin</code></dfn> IDL
- attribute must <a href=#reflect>reflect</a> the <code title=attr-img-cross-origin><a href=#attr-img-cross-origin>cross-origin</a></code> content
+ attribute must <a href=#reflect>reflect</a> the <code title=attr-img-crossorigin><a href=#attr-img-crossorigin>crossorigin</a></code> content
attribute.</p>
<p>The <dfn id=dom-img-usemap title=dom-img-useMap><code>useMap</code></dfn> IDL
@@ -25622,7 +25623,7 @@
<dt>Content attributes:</dt>
<dd><a href=#global-attributes>Global attributes</a></dd>
<dd><code title=attr-media-src><a href=#attr-media-src>src</a></code></dd>
- <dd><code title=attr-media-cross-origin><a href=#attr-media-cross-origin>cross-origin</a></code></dd>
+ <dd><code title=attr-media-crossorigin><a href=#attr-media-crossorigin>crossorigin</a></code></dd>
<dd><code title=attr-video-poster><a href=#attr-video-poster>poster</a></code></dd>
<dd><code title=attr-media-preload><a href=#attr-media-preload>preload</a></code></dd>
<dd><code title=attr-media-autoplay><a href=#attr-media-autoplay>autoplay</a></code></dd>
@@ -25957,7 +25958,7 @@
<dt>Content attributes:</dt>
<dd><a href=#global-attributes>Global attributes</a></dd>
<dd><code title=attr-media-src><a href=#attr-media-src>src</a></code></dd>
- <dd><code title=attr-media-cross-origin><a href=#attr-media-cross-origin>cross-origin</a></code></dd>
+ <dd><code title=attr-media-crossorigin><a href=#attr-media-crossorigin>crossorigin</a></code></dd>
<dd><code title=attr-media-preload><a href=#attr-media-preload>preload</a></code></dd>
<dd><code title=attr-media-autoplay><a href=#attr-media-autoplay>autoplay</a></code></dd>
<dd><code title=attr-media-mediagroup><a href=#attr-media-mediagroup>mediagroup</a></code></dd>
@@ -26517,7 +26518,7 @@
<a href=#mutabletexttrack>MutableTextTrack</a> <a href=#dom-media-addtexttrack title=dom-media-addTextTrack>addTextTrack</a>(in DOMString kind, in optional DOMString label, in optional DOMString language);
};</pre>
- <p>The <dfn id=media-element-attributes>media element attributes</dfn>, <code title=attr-media-src><a href=#attr-media-src>src</a></code>, <code title=attr-media-cross-origin><a href=#attr-media-cross-origin>cross-origin</a></code>, <code title=attr-media-preload><a href=#attr-media-preload>preload</a></code>, <code title=attr-media-autoplay><a href=#attr-media-autoplay>autoplay</a></code>,
+ <p>The <dfn id=media-element-attributes>media element attributes</dfn>, <code title=attr-media-src><a href=#attr-media-src>src</a></code>, <code title=attr-media-crossorigin><a href=#attr-media-crossorigin>crossorigin</a></code>, <code title=attr-media-preload><a href=#attr-media-preload>preload</a></code>, <code title=attr-media-autoplay><a href=#attr-media-autoplay>autoplay</a></code>,
<code title=attr-media-mediagroup><a href=#attr-media-mediagroup>mediagroup</a></code>,
<code title=attr-media-loop><a href=#attr-media-loop>loop</a></code>,
<code title=attr-media-muted><a href=#attr-media-muted>muted</a></code>, and <code title=attr-media-controls><a href=#attr-media-controls>controls</a></code>, apply to all <a href=#media-element title="media element">media elements</a>. They are defined in
@@ -26672,7 +26673,7 @@
attribute, if present, must contain a <a href=#valid-non-empty-url-potentially-surrounded-by-spaces>valid non-empty
URL potentially surrounded by spaces</a>.</p>
- <p>The <dfn id=attr-media-cross-origin title=attr-media-cross-origin><code>cross-origin</code></dfn>
+ <p>The <dfn id=attr-media-crossorigin title=attr-media-crossorigin><code>crossorigin</code></dfn>
content attribute on <a href=#media-element title="media element">media
elements</a> is a <a href=#cors-settings-attribute>CORS settings attribute</a>.</p>
@@ -26689,7 +26690,7 @@
<a href=#reflect>reflect</a> the content attribute of the same name.</p>
<p>The <dfn id=dom-media-crossorigin title=dom-media-crossOrigin><code>crossOrigin</code></dfn> IDL
- attribute must <a href=#reflect>reflect</a> the <code title=attr-media-cross-origin><a href=#attr-media-cross-origin>cross-origin</a></code> content
+ attribute must <a href=#reflect>reflect</a> the <code title=attr-media-crossorigin><a href=#attr-media-crossorigin>crossorigin</a></code> content
attribute.</p>
</div>
@@ -27288,7 +27289,7 @@
<p>Perform a <a href=#potentially-cors-enabled-fetch>potentially CORS-enabled fetch</a> of the
<var title="">current media resource</var>'s <a href=#absolute-url>absolute
URL</a>, with the <i>mode</i> being the state of the
- <a href=#media-element>media element</a>'s <code title=attr-media-cross-origin><a href=#attr-media-cross-origin>cross-origin</a></code> content
+ <a href=#media-element>media element</a>'s <code title=attr-media-crossorigin><a href=#attr-media-crossorigin>crossorigin</a></code> content
attribute, the <i><a href=#origin>origin</a></i> being the <a href=#origin>origin</a> of the
<a href=#media-element>media element</a>'s <code><a href=#document>Document</a></code>, and the
<i>default origin behaviour</i> set to <i>taint</i>.</p>
@@ -30821,7 +30822,7 @@
<p>If <var title="">URL</var> is not the empty string, perform a
<a href=#potentially-cors-enabled-fetch>potentially CORS-enabled fetch</a> of <var title="">URL</var>, with the <i>mode</i> being the state of the
- <a href=#media-element>media element</a>'s <code title=attr-media-cross-origin><a href=#attr-media-cross-origin>cross-origin</a></code> content
+ <a href=#media-element>media element</a>'s <code title=attr-media-crossorigin><a href=#attr-media-crossorigin>crossorigin</a></code> content
attribute, the <i><a href=#origin>origin</a></i> being the <a href=#origin>origin</a> of the
<a href=#media-element>media element</a>'s <code><a href=#document>Document</a></code>, and the
<i>default origin behaviour</i> set to <i>fail</i>.</p>
@@ -33934,7 +33935,7 @@
obtained if the user agent further exposes metadata within the
content such as subtitles or chapter titles. Such information is
therefore only exposed if the video resource passes a CORS
- <a href=#resource-sharing-check>resource sharing check</a>. The <code title=attr-media-cross-origin><a href=#attr-media-cross-origin>cross-origin</a></code> attribute allows
+ <a href=#resource-sharing-check>resource sharing check</a>. The <code title=attr-media-crossorigin><a href=#attr-media-crossorigin>crossorigin</a></code> attribute allows
authors to control how this check is performed. <a href=#refsCORS>[CORS]</a></p>
<p class=example>Without this restriction, an attacker could trick
@@ -95702,7 +95703,7 @@
<a href=#transparent>transparent</a>*</td>
<td><a href=#global-attributes title="global attributes">globals</a>;
<code title=attr-media-src><a href=#attr-media-src>src</a></code>;
- <code title=attr-media-cross-origin><a href=#attr-media-cross-origin>cross-origin</a></code>;
+ <code title=attr-media-crossorigin><a href=#attr-media-crossorigin>crossorigin</a></code>;
<code title=attr-media-preload><a href=#attr-media-preload>preload</a></code>;
<code title=attr-media-autoplay><a href=#attr-media-autoplay>autoplay</a></code>;
<code title=attr-media-mediagroup><a href=#attr-media-mediagroup>mediagroup</a></code>;
@@ -96107,7 +96108,7 @@
<td><a href=#global-attributes title="global attributes">globals</a>;
<code title=attr-img-alt><a href=#attr-img-alt>alt</a></code>;
<code title=attr-img-src><a href=#attr-img-src>src</a></code>;
- <code title=attr-img-cross-origin><a href=#attr-img-cross-origin>cross-origin</a></code>;
+ <code title=attr-img-crossorigin><a href=#attr-img-crossorigin>crossorigin</a></code>;
<code title=attr-hyperlink-usemap><a href=#attr-hyperlink-usemap>usemap</a></code>;
<code title=attr-img-ismap><a href=#attr-img-ismap>ismap</a></code>;
<code title=attr-dim-width><a href=#attr-dim-width>width</a></code>;
@@ -96744,7 +96745,7 @@
<a href=#transparent>transparent</a>*</td>
<td><a href=#global-attributes title="global attributes">globals</a>;
<code title=attr-media-src><a href=#attr-media-src>src</a></code>;
- <code title=attr-media-cross-origin><a href=#attr-media-cross-origin>cross-origin</a></code>;
+ <code title=attr-media-crossorigin><a href=#attr-media-crossorigin>crossorigin</a></code>;
<code title=attr-video-poster><a href=#attr-video-poster>poster</a></code>;
<code title=attr-media-preload><a href=#attr-media-preload>preload</a></code>;
<code title=attr-media-autoplay><a href=#attr-media-autoplay>autoplay</a></code>;
@@ -97219,12 +97220,12 @@
<td> <code title=attr-area-coords><a href=#attr-area-coords>area</a></code>
<td> Coordinates for the shape to be created in an <a href=#image-map>image map</a>
<td> <a href=#valid-list-of-integers>Valid list of integers</a>*
- <tr><th> <code title="">cross-origin</code>
- <td> <code title=attr-media-cross-origin><a href=#attr-media-cross-origin>audio</a></code>;
- <code title=attr-img-cross-origin><a href=#attr-img-cross-origin>img</a></code>;
- <code title=attr-media-cross-origin><a href=#attr-media-cross-origin>video</a></code>
- <td> How the element handles cross-origin requests.
- <td> "<code title=attr-cross-origin-anonymous-keyword><a href=#attr-cross-origin-anonymous-keyword>anonymous</a></code>"; "<code title=attr-cross-origin-use-credentials-keyword><a href=#attr-cross-origin-use-credentials-keyword>use-credentials</a></code>"
+ <tr><th> <code title="">crossorigin</code>
+ <td> <code title=attr-media-crossorigin><a href=#attr-media-crossorigin>audio</a></code>;
+ <code title=attr-img-crossorigin><a href=#attr-img-crossorigin>img</a></code>;
+ <code title=attr-media-crossorigin><a href=#attr-media-crossorigin>video</a></code>
+ <td> How the element handles crossorigin requests.
+ <td> "<code title=attr-crossorigin-anonymous-keyword><a href=#attr-crossorigin-anonymous-keyword>anonymous</a></code>"; "<code title=attr-crossorigin-use-credentials-keyword><a href=#attr-crossorigin-use-credentials-keyword>use-credentials</a></code>"
<tr><th> <code title="">data</code>
<td> <code title=attr-object-data><a href=#attr-object-data>object</a></code>
<td> Address of the resource
Modified: index
===================================================================
--- index 2011-05-23 21:24:43 UTC (rev 6146)
+++ index 2011-05-23 21:29:13 UTC (rev 6147)
@@ -7236,33 +7236,33 @@
<table><thead><tr><th> Keyword
<th> State
<th> Brief description
- <tbody><tr><td><dfn id=attr-cross-origin-anonymous-keyword title=attr-cross-origin-anonymous-keyword><code>anonymous</code></dfn>
- <td><dfn id=attr-cross-origin-anonymous title=attr-cross-origin-anonymous>Anonymous</dfn>
+ <tbody><tr><td><dfn id=attr-crossorigin-anonymous-keyword title=attr-crossorigin-anonymous-keyword><code>anonymous</code></dfn>
+ <td><dfn id=attr-crossorigin-anonymous title=attr-crossorigin-anonymous>Anonymous</dfn>
<td>Cross-origin CORS requests for the element will not have the <i>credentials flag</i> set.
- <tr><td><dfn id=attr-cross-origin-use-credentials-keyword title=attr-cross-origin-use-credentials-keyword><code>use-credentials</code></dfn>
- <td><dfn id=attr-cross-origin-use-credentials title=attr-cross-origin-use-credentials>Use Credentials</dfn>
+ <tr><td><dfn id=attr-crossorigin-use-credentials-keyword title=attr-crossorigin-use-credentials-keyword><code>use-credentials</code></dfn>
+ <td><dfn id=attr-crossorigin-use-credentials title=attr-crossorigin-use-credentials>Use Credentials</dfn>
<td>Cross-origin CORS requests for the element will have the <i>credentials flag</i> set.
- </table><p>The empty string is also a valid keyword, and maps to the <a href=#attr-cross-origin-anonymous title=attr-cross-origin-anonymous>Anonymous</a> state. The
- attribute's <i>invalid value default</i> is the <a href=#attr-cross-origin-anonymous title=attr-cross-origin-anonymous>Anonymous</a> state. The
+ </table><p>The empty string is also a valid keyword, and maps to the <a href=#attr-crossorigin-anonymous title=attr-crossorigin-anonymous>Anonymous</a> state. The
+ attribute's <i>invalid value default</i> is the <a href=#attr-crossorigin-anonymous title=attr-crossorigin-anonymous>Anonymous</a> state. The
<i>missing value default</i>, used when the attribute is omitted, is
- the <dfn id=attr-cross-origin-none title=attr-cross-origin-none>No CORS</dfn> state.</p>
+ the <dfn id=attr-crossorigin-none title=attr-crossorigin-none>No CORS</dfn> state.</p>
<h4 id=cors-enabled-fetch><span class=secno>2.7.6 </span>CORS-enabled fetch</h4>
<p>When the user agent is required to perform a <dfn id=potentially-cors-enabled-fetch>potentially
CORS-enabled fetch</dfn> of an <a href=#absolute-url>absolute URL</a> <var title="">URL</var>, with a mode <var title="">mode</var> that is
- either "<a href=#attr-cross-origin-none title=attr-cross-origin-none>No CORS</a>", "<a href=#attr-cross-origin-anonymous title=attr-cross-origin-anonymous>Anonymous</a>", or "<a href=#attr-cross-origin-use-credentials title=attr-cross-origin-use-credentials>Use Credentials</a>",
+ either "<a href=#attr-crossorigin-none title=attr-crossorigin-none>No CORS</a>", "<a href=#attr-crossorigin-anonymous title=attr-crossorigin-anonymous>Anonymous</a>", or "<a href=#attr-crossorigin-use-credentials title=attr-crossorigin-use-credentials>Use Credentials</a>",
an <a href=#origin>origin</a> <var title="">origin</var>, and a default
origin behaviour <var title="">default</var> which is either
"<i>taint</i>" or "<i>fail</i>", it must run the first applicable
set of steps from the following list. The default origin behaviour
- is only used if <var title="">mode</var> is "<a href=#attr-cross-origin-none title=attr-cross-origin-none>No CORS</a>". This algorithm wraps
+ is only used if <var title="">mode</var> is "<a href=#attr-crossorigin-none title=attr-crossorigin-none>No CORS</a>". This algorithm wraps
the <a href=#fetch>fetch</a> algorithm above, and labels the obtained
resource as either <dfn id=cors-same-origin>CORS-same-origin</dfn> or
<dfn id=cors-cross-origin>CORS-cross-origin</dfn>, or blocks the resource entirely.</p>
- <dl class=switch><dt>If <var title="">mode</var> is "<a href=#attr-cross-origin-none title=attr-cross-origin-none>No CORS</a>"</dt>
+ <dl class=switch><dt>If <var title="">mode</var> is "<a href=#attr-crossorigin-none title=attr-crossorigin-none>No CORS</a>"</dt>
<dd>
@@ -7355,7 +7355,7 @@
</ol></dd>
- <dt>If <var title="">mode</var> is "<a href=#attr-cross-origin-anonymous title=attr-cross-origin-anonymous>Anonymous</a>" or "<a href=#attr-cross-origin-use-credentials title=attr-cross-origin-use-credentials>Use
+ <dt>If <var title="">mode</var> is "<a href=#attr-crossorigin-anonymous title=attr-crossorigin-anonymous>Anonymous</a>" or "<a href=#attr-crossorigin-use-credentials title=attr-crossorigin-use-credentials>Use
Credentials</a>"</dt>
<dd>
@@ -7366,7 +7366,7 @@
<i>request URL</i> set to <var title="">URL</var>, the
<i>source origin</i> set to <var title="">origin</var>, and the
<i>credentials flag</i> set to true if <var title="">mode</var>
- is "<a href=#attr-cross-origin-use-credentials title=attr-cross-origin-use-credentials>Use
+ is "<a href=#attr-crossorigin-use-credentials title=attr-crossorigin-use-credentials>Use
Credentials</a>" and set to false otherwise. <a href=#refsCORS>[CORS]</a></li>
<li><p>Wait for the CORS <a href=#cross-origin-request-status>cross-origin request status</a>
@@ -22183,7 +22183,7 @@
<dd><a href=#global-attributes>Global attributes</a></dd>
<dd><code title=attr-img-alt><a href=#attr-img-alt>alt</a></code></dd>
<dd><code title=attr-img-src><a href=#attr-img-src>src</a></code></dd>
- <dd><code title=attr-img-cross-origin><a href=#attr-img-cross-origin>cross-origin</a></code></dd>
+ <dd><code title=attr-img-crossorigin><a href=#attr-img-crossorigin>crossorigin</a></code></dd>
<dd><code title=attr-hyperlink-usemap><a href=#attr-hyperlink-usemap>usemap</a></code></dd>
<dd><code title=attr-img-ismap><a href=#attr-img-ismap>ismap</a></code></dd>
<dd><code title=attr-dim-width><a href=#attr-dim-width>width</a></code></dd>
@@ -22219,7 +22219,7 @@
Slight hitch: their images are at a different origin, and we
don't want to allow arbitrary cross-origin inspection (privacy
- leak risk).
+ leak risk). So it will require them to do CORS opt-in.
* See note at rel=noreferrer.
@@ -22258,7 +22258,7 @@
display transparent images, as they rarely convey meaning and rarely
add anything useful to the document.</p>
- <p>The <dfn id=attr-img-cross-origin title=attr-img-cross-origin><code>cross-origin</code></dfn>
+ <p>The <dfn id=attr-img-crossorigin title=attr-img-crossorigin><code>crossorigin</code></dfn>
attribute is a <a href=#cors-settings-attribute>CORS settings attribute</a>.</p>
<div class=impl>
@@ -22336,7 +22336,7 @@
<p>Otherwise, do a <a href=#potentially-cors-enabled-fetch>potentially CORS-enabled fetch</a> of
the resulting <a href=#absolute-url>absolute URL</a>, with the <i>mode</i>
- being the state of the element's <code title=attr-img-cross-origin><a href=#attr-img-cross-origin>cross-origin</a></code> content
+ being the state of the element's <code title=attr-img-crossorigin><a href=#attr-img-crossorigin>crossorigin</a></code> content
attribute, the <i><a href=#origin>origin</a></i> being the <a href=#origin>origin</a> of the
<code><a href=#the-img-element>img</a></code> element's <code><a href=#document>Document</a></code>, and the
<i>default origin behaviour</i> set to <i>taint</i>.</p>
@@ -22358,8 +22358,9 @@
conjunction with scripting, though scripting isn't actually
necessary to carry out such an attack). User agents may implement
<a href=#origin title=origin>cross-origin</a> access control policies
- that mitigate this attack, but unfortunately such policies are
- typically not compatible with existing Web content.</p>
+ that are stricter than those described above to mitigate this
+ attack, but unfortunately such policies are typically not
+ compatible with existing Web content.</p>
</li>
@@ -22589,7 +22590,7 @@
name.</p>
<p>The <dfn id=dom-img-crossorigin title=dom-img-crossOrigin><code>crossOrigin</code></dfn> IDL
- attribute must <a href=#reflect>reflect</a> the <code title=attr-img-cross-origin><a href=#attr-img-cross-origin>cross-origin</a></code> content
+ attribute must <a href=#reflect>reflect</a> the <code title=attr-img-crossorigin><a href=#attr-img-crossorigin>crossorigin</a></code> content
attribute.</p>
<p>The <dfn id=dom-img-usemap title=dom-img-useMap><code>useMap</code></dfn> IDL
@@ -25642,7 +25643,7 @@
<dt>Content attributes:</dt>
<dd><a href=#global-attributes>Global attributes</a></dd>
<dd><code title=attr-media-src><a href=#attr-media-src>src</a></code></dd>
- <dd><code title=attr-media-cross-origin><a href=#attr-media-cross-origin>cross-origin</a></code></dd>
+ <dd><code title=attr-media-crossorigin><a href=#attr-media-crossorigin>crossorigin</a></code></dd>
<dd><code title=attr-video-poster><a href=#attr-video-poster>poster</a></code></dd>
<dd><code title=attr-media-preload><a href=#attr-media-preload>preload</a></code></dd>
<dd><code title=attr-media-autoplay><a href=#attr-media-autoplay>autoplay</a></code></dd>
@@ -25977,7 +25978,7 @@
<dt>Content attributes:</dt>
<dd><a href=#global-attributes>Global attributes</a></dd>
<dd><code title=attr-media-src><a href=#attr-media-src>src</a></code></dd>
- <dd><code title=attr-media-cross-origin><a href=#attr-media-cross-origin>cross-origin</a></code></dd>
+ <dd><code title=attr-media-crossorigin><a href=#attr-media-crossorigin>crossorigin</a></code></dd>
<dd><code title=attr-media-preload><a href=#attr-media-preload>preload</a></code></dd>
<dd><code title=attr-media-autoplay><a href=#attr-media-autoplay>autoplay</a></code></dd>
<dd><code title=attr-media-mediagroup><a href=#attr-media-mediagroup>mediagroup</a></code></dd>
@@ -26537,7 +26538,7 @@
<a href=#mutabletexttrack>MutableTextTrack</a> <a href=#dom-media-addtexttrack title=dom-media-addTextTrack>addTextTrack</a>(in DOMString kind, in optional DOMString label, in optional DOMString language);
};</pre>
- <p>The <dfn id=media-element-attributes>media element attributes</dfn>, <code title=attr-media-src><a href=#attr-media-src>src</a></code>, <code title=attr-media-cross-origin><a href=#attr-media-cross-origin>cross-origin</a></code>, <code title=attr-media-preload><a href=#attr-media-preload>preload</a></code>, <code title=attr-media-autoplay><a href=#attr-media-autoplay>autoplay</a></code>,
+ <p>The <dfn id=media-element-attributes>media element attributes</dfn>, <code title=attr-media-src><a href=#attr-media-src>src</a></code>, <code title=attr-media-crossorigin><a href=#attr-media-crossorigin>crossorigin</a></code>, <code title=attr-media-preload><a href=#attr-media-preload>preload</a></code>, <code title=attr-media-autoplay><a href=#attr-media-autoplay>autoplay</a></code>,
<code title=attr-media-mediagroup><a href=#attr-media-mediagroup>mediagroup</a></code>,
<code title=attr-media-loop><a href=#attr-media-loop>loop</a></code>,
<code title=attr-media-muted><a href=#attr-media-muted>muted</a></code>, and <code title=attr-media-controls><a href=#attr-media-controls>controls</a></code>, apply to all <a href=#media-element title="media element">media elements</a>. They are defined in
@@ -26692,7 +26693,7 @@
attribute, if present, must contain a <a href=#valid-non-empty-url-potentially-surrounded-by-spaces>valid non-empty
URL potentially surrounded by spaces</a>.</p>
- <p>The <dfn id=attr-media-cross-origin title=attr-media-cross-origin><code>cross-origin</code></dfn>
+ <p>The <dfn id=attr-media-crossorigin title=attr-media-crossorigin><code>crossorigin</code></dfn>
content attribute on <a href=#media-element title="media element">media
elements</a> is a <a href=#cors-settings-attribute>CORS settings attribute</a>.</p>
@@ -26709,7 +26710,7 @@
<a href=#reflect>reflect</a> the content attribute of the same name.</p>
<p>The <dfn id=dom-media-crossorigin title=dom-media-crossOrigin><code>crossOrigin</code></dfn> IDL
- attribute must <a href=#reflect>reflect</a> the <code title=attr-media-cross-origin><a href=#attr-media-cross-origin>cross-origin</a></code> content
+ attribute must <a href=#reflect>reflect</a> the <code title=attr-media-crossorigin><a href=#attr-media-crossorigin>crossorigin</a></code> content
attribute.</p>
</div>
@@ -27308,7 +27309,7 @@
<p>Perform a <a href=#potentially-cors-enabled-fetch>potentially CORS-enabled fetch</a> of the
<var title="">current media resource</var>'s <a href=#absolute-url>absolute
URL</a>, with the <i>mode</i> being the state of the
- <a href=#media-element>media element</a>'s <code title=attr-media-cross-origin><a href=#attr-media-cross-origin>cross-origin</a></code> content
+ <a href=#media-element>media element</a>'s <code title=attr-media-crossorigin><a href=#attr-media-crossorigin>crossorigin</a></code> content
attribute, the <i><a href=#origin>origin</a></i> being the <a href=#origin>origin</a> of the
<a href=#media-element>media element</a>'s <code><a href=#document>Document</a></code>, and the
<i>default origin behaviour</i> set to <i>taint</i>.</p>
@@ -30841,7 +30842,7 @@
<p>If <var title="">URL</var> is not the empty string, perform a
<a href=#potentially-cors-enabled-fetch>potentially CORS-enabled fetch</a> of <var title="">URL</var>, with the <i>mode</i> being the state of the
- <a href=#media-element>media element</a>'s <code title=attr-media-cross-origin><a href=#attr-media-cross-origin>cross-origin</a></code> content
+ <a href=#media-element>media element</a>'s <code title=attr-media-crossorigin><a href=#attr-media-crossorigin>crossorigin</a></code> content
attribute, the <i><a href=#origin>origin</a></i> being the <a href=#origin>origin</a> of the
<a href=#media-element>media element</a>'s <code><a href=#document>Document</a></code>, and the
<i>default origin behaviour</i> set to <i>fail</i>.</p>
@@ -33954,7 +33955,7 @@
obtained if the user agent further exposes metadata within the
content such as subtitles or chapter titles. Such information is
therefore only exposed if the video resource passes a CORS
- <a href=#resource-sharing-check>resource sharing check</a>. The <code title=attr-media-cross-origin><a href=#attr-media-cross-origin>cross-origin</a></code> attribute allows
+ <a href=#resource-sharing-check>resource sharing check</a>. The <code title=attr-media-crossorigin><a href=#attr-media-crossorigin>crossorigin</a></code> attribute allows
authors to control how this check is performed. <a href=#refsCORS>[CORS]</a></p>
<p class=example>Without this restriction, an attacker could trick
@@ -91675,7 +91676,7 @@
<a href=#transparent>transparent</a>*</td>
<td><a href=#global-attributes title="global attributes">globals</a>;
<code title=attr-media-src><a href=#attr-media-src>src</a></code>;
- <code title=attr-media-cross-origin><a href=#attr-media-cross-origin>cross-origin</a></code>;
+ <code title=attr-media-crossorigin><a href=#attr-media-crossorigin>crossorigin</a></code>;
<code title=attr-media-preload><a href=#attr-media-preload>preload</a></code>;
<code title=attr-media-autoplay><a href=#attr-media-autoplay>autoplay</a></code>;
<code title=attr-media-mediagroup><a href=#attr-media-mediagroup>mediagroup</a></code>;
@@ -92080,7 +92081,7 @@
<td><a href=#global-attributes title="global attributes">globals</a>;
<code title=attr-img-alt><a href=#attr-img-alt>alt</a></code>;
<code title=attr-img-src><a href=#attr-img-src>src</a></code>;
- <code title=attr-img-cross-origin><a href=#attr-img-cross-origin>cross-origin</a></code>;
+ <code title=attr-img-crossorigin><a href=#attr-img-crossorigin>crossorigin</a></code>;
<code title=attr-hyperlink-usemap><a href=#attr-hyperlink-usemap>usemap</a></code>;
<code title=attr-img-ismap><a href=#attr-img-ismap>ismap</a></code>;
<code title=attr-dim-width><a href=#attr-dim-width>width</a></code>;
@@ -92717,7 +92718,7 @@
<a href=#transparent>transparent</a>*</td>
<td><a href=#global-attributes title="global attributes">globals</a>;
<code title=attr-media-src><a href=#attr-media-src>src</a></code>;
- <code title=attr-media-cross-origin><a href=#attr-media-cross-origin>cross-origin</a></code>;
+ <code title=attr-media-crossorigin><a href=#attr-media-crossorigin>crossorigin</a></code>;
<code title=attr-video-poster><a href=#attr-video-poster>poster</a></code>;
<code title=attr-media-preload><a href=#attr-media-preload>preload</a></code>;
<code title=attr-media-autoplay><a href=#attr-media-autoplay>autoplay</a></code>;
@@ -93192,12 +93193,12 @@
<td> <code title=attr-area-coords><a href=#attr-area-coords>area</a></code>
<td> Coordinates for the shape to be created in an <a href=#image-map>image map</a>
<td> <a href=#valid-list-of-integers>Valid list of integers</a>*
- <tr><th> <code title="">cross-origin</code>
- <td> <code title=attr-media-cross-origin><a href=#attr-media-cross-origin>audio</a></code>;
- <code title=attr-img-cross-origin><a href=#attr-img-cross-origin>img</a></code>;
- <code title=attr-media-cross-origin><a href=#attr-media-cross-origin>video</a></code>
- <td> How the element handles cross-origin requests.
- <td> "<code title=attr-cross-origin-anonymous-keyword><a href=#attr-cross-origin-anonymous-keyword>anonymous</a></code>"; "<code title=attr-cross-origin-use-credentials-keyword><a href=#attr-cross-origin-use-credentials-keyword>use-credentials</a></code>"
+ <tr><th> <code title="">crossorigin</code>
+ <td> <code title=attr-media-crossorigin><a href=#attr-media-crossorigin>audio</a></code>;
+ <code title=attr-img-crossorigin><a href=#attr-img-crossorigin>img</a></code>;
+ <code title=attr-media-crossorigin><a href=#attr-media-crossorigin>video</a></code>
+ <td> How the element handles crossorigin requests.
+ <td> "<code title=attr-crossorigin-anonymous-keyword><a href=#attr-crossorigin-anonymous-keyword>anonymous</a></code>"; "<code title=attr-crossorigin-use-credentials-keyword><a href=#attr-crossorigin-use-credentials-keyword>use-credentials</a></code>"
<tr><th> <code title="">data</code>
<td> <code title=attr-object-data><a href=#attr-object-data>object</a></code>
<td> Address of the resource
Modified: source
===================================================================
--- source 2011-05-23 21:24:43 UTC (rev 6146)
+++ source 2011-05-23 21:29:13 UTC (rev 6147)
@@ -7070,21 +7070,21 @@
<th> Brief description
<tbody>
<tr>
- <td><dfn title="attr-cross-origin-anonymous-keyword"><code>anonymous</code></dfn>
- <td><dfn title="attr-cross-origin-anonymous">Anonymous</dfn>
+ <td><dfn title="attr-crossorigin-anonymous-keyword"><code>anonymous</code></dfn>
+ <td><dfn title="attr-crossorigin-anonymous">Anonymous</dfn>
<td>Cross-origin CORS requests for the element will not have the <i>credentials flag</i> set.
<tr>
- <td><dfn title="attr-cross-origin-use-credentials-keyword"><code>use-credentials</code></dfn>
- <td><dfn title="attr-cross-origin-use-credentials">Use Credentials</dfn>
+ <td><dfn title="attr-crossorigin-use-credentials-keyword"><code>use-credentials</code></dfn>
+ <td><dfn title="attr-crossorigin-use-credentials">Use Credentials</dfn>
<td>Cross-origin CORS requests for the element will have the <i>credentials flag</i> set.
</table>
<p>The empty string is also a valid keyword, and maps to the <span
- title="attr-cross-origin-anonymous">Anonymous</span> state. The
+ title="attr-crossorigin-anonymous">Anonymous</span> state. The
attribute's <i>invalid value default</i> is the <span
- title="attr-cross-origin-anonymous">Anonymous</span> state. The
+ title="attr-crossorigin-anonymous">Anonymous</span> state. The
<i>missing value default</i>, used when the attribute is omitted, is
- the <dfn title="attr-cross-origin-none">No CORS</dfn> state.</p>
+ the <dfn title="attr-crossorigin-none">No CORS</dfn> state.</p>
<h4>CORS-enabled fetch</h4>
@@ -7092,15 +7092,15 @@
<p>When the user agent is required to perform a <dfn>potentially
CORS-enabled fetch</dfn> of an <span>absolute URL</span> <var
title="">URL</var>, with a mode <var title="">mode</var> that is
- either "<span title="attr-cross-origin-none">No CORS</span>", "<span
- title="attr-cross-origin-anonymous">Anonymous</span>", or "<span
- title="attr-cross-origin-use-credentials">Use Credentials</span>",
+ either "<span title="attr-crossorigin-none">No CORS</span>", "<span
+ title="attr-crossorigin-anonymous">Anonymous</span>", or "<span
+ title="attr-crossorigin-use-credentials">Use Credentials</span>",
an <span>origin</span> <var title="">origin</var>, and a default
origin behaviour <var title="">default</var> which is either
"<i>taint</i>" or "<i>fail</i>", it must run the first applicable
set of steps from the following list. The default origin behaviour
is only used if <var title="">mode</var> is "<span
- title="attr-cross-origin-none">No CORS</span>". This algorithm wraps
+ title="attr-crossorigin-none">No CORS</span>". This algorithm wraps
the <span>fetch</span> algorithm above, and labels the obtained
resource as either <dfn>CORS-same-origin</dfn> or
<dfn>CORS-cross-origin</dfn>, or blocks the resource entirely.</p>
@@ -7108,7 +7108,7 @@
<dl class="switch">
<dt>If <var title="">mode</var> is "<span
- title="attr-cross-origin-none">No CORS</span>"</dt>
+ title="attr-crossorigin-none">No CORS</span>"</dt>
<dd>
@@ -7214,8 +7214,8 @@
<dt>If <var title="">mode</var> is "<span
- title="attr-cross-origin-anonymous">Anonymous</span>" or "<span
- title="attr-cross-origin-use-credentials">Use
+ title="attr-crossorigin-anonymous">Anonymous</span>" or "<span
+ title="attr-crossorigin-use-credentials">Use
Credentials</span>"</dt>
<dd>
@@ -7228,7 +7228,7 @@
<i>request URL</i> set to <var title="">URL</var>, the
<i>source origin</i> set to <var title="">origin</var>, and the
<i>credentials flag</i> set to true if <var title="">mode</var>
- is "<span title="attr-cross-origin-use-credentials">Use
+ is "<span title="attr-crossorigin-use-credentials">Use
Credentials</span>" and set to false otherwise. <a
href="#refsCORS">[CORS]</a></p></li>
@@ -23895,7 +23895,7 @@
<dd><span>Global attributes</span></dd>
<dd><code title="attr-img-alt">alt</code></dd>
<dd><code title="attr-img-src">src</code></dd>
- <dd><code title="attr-img-cross-origin">cross-origin</code></dd>
+ <dd><code title="attr-img-crossorigin">crossorigin</code></dd>
<dd><code title="attr-hyperlink-usemap">usemap</code></dd>
<dd><code title="attr-img-ismap">ismap</code></dd>
<dd><code title="attr-dim-width">width</code></dd>
@@ -23933,7 +23933,7 @@
Slight hitch: their images are at a different origin, and we
don't want to allow arbitrary cross-origin inspection (privacy
- leak risk).
+ leak risk). So it will require them to do CORS opt-in.
* See note at rel=noreferrer.
@@ -23975,7 +23975,7 @@
add anything useful to the document.</p>
<p>The <dfn
- title="attr-img-cross-origin"><code>cross-origin</code></dfn>
+ title="attr-img-crossorigin"><code>crossorigin</code></dfn>
attribute is a <span>CORS settings attribute</span>.</p>
<div class="impl">
@@ -24071,7 +24071,7 @@
<p>Otherwise, do a <span>potentially CORS-enabled fetch</span> of
the resulting <span>absolute URL</span>, with the <i>mode</i>
being the state of the element's <code
- title="attr-img-cross-origin">cross-origin</code> content
+ title="attr-img-crossorigin">crossorigin</code> content
attribute, the <i>origin</i> being the <span>origin</span> of the
<code>img</code> element's <code>Document</code>, and the
<i>default origin behaviour</i> set to <i>taint</i>.</p>
@@ -24095,8 +24095,9 @@
conjunction with scripting, though scripting isn't actually
necessary to carry out such an attack). User agents may implement
<span title="origin">cross-origin</span> access control policies
- that mitigate this attack, but unfortunately such policies are
- typically not compatible with existing Web content.</p>
+ that are stricter than those described above to mitigate this
+ attack, but unfortunately such policies are typically not
+ compatible with existing Web content.</p>
</li>
@@ -24369,7 +24370,7 @@
<p>The <dfn
title="dom-img-crossOrigin"><code>crossOrigin</code></dfn> IDL
attribute must <span>reflect</span> the <code
- title="attr-img-cross-origin">cross-origin</code> content
+ title="attr-img-crossorigin">crossorigin</code> content
attribute.</p>
<p>The <dfn title="dom-img-useMap"><code>useMap</code></dfn> IDL
@@ -27735,7 +27736,7 @@
<dt>Content attributes:</dt>
<dd><span>Global attributes</span></dd>
<dd><code title="attr-media-src">src</code></dd>
- <dd><code title="attr-media-cross-origin">cross-origin</code></dd>
+ <dd><code title="attr-media-crossorigin">crossorigin</code></dd>
<dd><code title="attr-video-poster">poster</code></dd>
<dd><code title="attr-media-preload">preload</code></dd>
<dd><code title="attr-media-autoplay">autoplay</code></dd>
@@ -28110,7 +28111,7 @@
<dt>Content attributes:</dt>
<dd><span>Global attributes</span></dd>
<dd><code title="attr-media-src">src</code></dd>
- <dd><code title="attr-media-cross-origin">cross-origin</code></dd>
+ <dd><code title="attr-media-crossorigin">crossorigin</code></dd>
<dd><code title="attr-media-preload">preload</code></dd>
<dd><code title="attr-media-autoplay">autoplay</code></dd>
<dd><code title="attr-media-mediagroup">mediagroup</code></dd>
@@ -28741,7 +28742,7 @@
<p>The <dfn>media element attributes</dfn>, <code
title="attr-media-src">src</code>, <code
- title="attr-media-cross-origin">cross-origin</code>, <code
+ title="attr-media-crossorigin">crossorigin</code>, <code
title="attr-media-preload">preload</code>, <code
title="attr-media-autoplay">autoplay</code>,
<code title="attr-media-mediagroup">mediagroup</code>,
@@ -28919,7 +28920,7 @@
URL potentially surrounded by spaces</span>.</p>
<p>The <dfn
- title="attr-media-cross-origin"><code>cross-origin</code></dfn>
+ title="attr-media-crossorigin"><code>crossorigin</code></dfn>
content attribute on <span title="media element">media
elements</span> is a <span>CORS settings attribute</span>.</p>
@@ -28939,7 +28940,7 @@
<p>The <dfn
title="dom-media-crossOrigin"><code>crossOrigin</code></dfn> IDL
attribute must <span>reflect</span> the <code
- title="attr-media-cross-origin">cross-origin</code> content
+ title="attr-media-crossorigin">crossorigin</code> content
attribute.</p>
</div>
@@ -29671,7 +29672,7 @@
<var title="">current media resource</var>'s <span>absolute
URL</span>, with the <i>mode</i> being the state of the
<span>media element</span>'s <code
- title="attr-media-cross-origin">cross-origin</code> content
+ title="attr-media-crossorigin">crossorigin</code> content
attribute, the <i>origin</i> being the <span>origin</span> of the
<span>media element</span>'s <code>Document</code>, and the
<i>default origin behaviour</i> set to <i>taint</i>.</p>
@@ -33778,7 +33779,7 @@
<span>potentially CORS-enabled fetch</span> of <var
title="">URL</var>, with the <i>mode</i> being the state of the
<span>media element</span>'s <code
- title="attr-media-cross-origin">cross-origin</code> content
+ title="attr-media-crossorigin">crossorigin</code> content
attribute, the <i>origin</i> being the <span>origin</span> of the
<span>media element</span>'s <code>Document</code>, and the
<i>default origin behaviour</i> set to <i>fail</i>.</p>
@@ -37481,7 +37482,7 @@
content such as subtitles or chapter titles. Such information is
therefore only exposed if the video resource passes a CORS
<span>resource sharing check</span>. The <code
- title="attr-media-cross-origin">cross-origin</code> attribute allows
+ title="attr-media-crossorigin">crossorigin</code> attribute allows
authors to control how this check is performed. <a
href="#refsCORS">[CORS]</a></p>
@@ -108806,7 +108807,7 @@
<span>transparent</span>*</td>
<td><span title="global attributes">globals</span>;
<code title="attr-media-src">src</code>;
- <code title="attr-media-cross-origin">cross-origin</code>;
+ <code title="attr-media-crossorigin">crossorigin</code>;
<code title="attr-media-preload">preload</code>;
<code title="attr-media-autoplay">autoplay</code>;
<code title="attr-media-mediagroup">mediagroup</code>;
@@ -109328,7 +109329,7 @@
<td><span title="global attributes">globals</span>;
<code title="attr-img-alt">alt</code>;
<code title="attr-img-src">src</code>;
- <code title="attr-img-cross-origin">cross-origin</code>;
+ <code title="attr-img-crossorigin">crossorigin</code>;
<code title="attr-hyperlink-usemap">usemap</code>;
<code title="attr-img-ismap">ismap</code>;
<code title="attr-dim-width">width</code>;
@@ -110133,7 +110134,7 @@
<span>transparent</span>*</td>
<td><span title="global attributes">globals</span>;
<code title="attr-media-src">src</code>;
- <code title="attr-media-cross-origin">cross-origin</code>;
+ <code title="attr-media-crossorigin">crossorigin</code>;
<code title="attr-video-poster">poster</code>;
<code title="attr-media-preload">preload</code>;
<code title="attr-media-autoplay">autoplay</code>;
@@ -110664,12 +110665,12 @@
<td> Coordinates for the shape to be created in an <span>image map</span>
<td> <span>Valid list of integers</span>*
<tr>
- <th> <code title="">cross-origin</code>
- <td> <code title="attr-media-cross-origin">audio</code>;
- <code title="attr-img-cross-origin">img</code>;
- <code title="attr-media-cross-origin">video</code>
- <td> How the element handles cross-origin requests.
- <td> "<code title="attr-cross-origin-anonymous-keyword">anonymous</code>"; "<code title="attr-cross-origin-use-credentials-keyword">use-credentials</code>"
+ <th> <code title="">crossorigin</code>
+ <td> <code title="attr-media-crossorigin">audio</code>;
+ <code title="attr-img-crossorigin">img</code>;
+ <code title="attr-media-crossorigin">video</code>
+ <td> How the element handles crossorigin requests.
+ <td> "<code title="attr-crossorigin-anonymous-keyword">anonymous</code>"; "<code title="attr-crossorigin-use-credentials-keyword">use-credentials</code>"
<tr>
<th> <code title="">data</code>
<td> <code title="attr-object-data">object</code>
</PRE>
<!--endarticle-->
<!--htdig_noindex-->
<HR>
<P><UL>
<!--threads-->
<LI>Previous message: <A HREF="013013.html">[html5] r6146 - [e] (0) remove pointless annotations
</A></li>
<LI>Next message: <A HREF="013015.html">[html5] r6148 - [giow] (0) Block redirects in WebSockets
</A></li>
<LI> <B>Messages sorted by:</B>
<a href="date.html#13014">[ date ]</a>
<a href="thread.html#13014">[ thread ]</a>
<a href="subject.html#13014">[ subject ]</a>
<a href="author.html#13014">[ author ]</a>
</LI>
</UL>
<hr>
<a href="http://lists.whatwg.org/listinfo.cgi/commit-watchers-whatwg.org">More information about the Commit-Watchers
mailing list</a><br>
<!--/htdig_noindex-->
</body></html>
| 82.960976 | 511 | 0.683557 |
04b88999147a534e799a9aef02fe0df0e155f9c1 | 1,994 | java | Java | treebase-web/src/main/java/org/cipres/treebase/web/controllers/RegisterUserController.java | TreeBASE/treebasetest | 12e0c9c30b8269891318140714a06b9fccdc723f | [
"BSD-3-Clause"
] | 6 | 2018-04-18T11:28:45.000Z | 2021-12-08T05:22:27.000Z | treebase-web/src/main/java/org/cipres/treebase/web/controllers/RegisterUserController.java | TreeBASE/treebasetest | 12e0c9c30b8269891318140714a06b9fccdc723f | [
"BSD-3-Clause"
] | 38 | 2015-10-23T09:57:03.000Z | 2022-03-15T13:07:45.000Z | treebase-web/src/main/java/org/cipres/treebase/web/controllers/RegisterUserController.java | TreeBASE/treebase | ebb437aece0f3feeb0491cc3c3b459f10e376978 | [
"BSD-3-Clause"
] | null | null | null |
package org.cipres.treebase.web.controllers;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.cipres.treebase.domain.admin.User;
import org.cipres.treebase.framework.ExecutionResult;
import org.cipres.treebase.web.Constants;
import org.cipres.treebase.web.util.StringUtil;
/**
* RegisterUserController.java
*
* Controller to sign up for user-related functions
*
* Created on May 1, 2006
*
* @author lcchan
*
*/
public class RegisterUserController extends AbstractUserController {
private static final Logger LOGGER = Logger.getLogger(RegisterUserController.class);
/**
*
* Creation date: May 8, 2006 5:18:08 PM
*/
public ModelAndView onSubmit(
HttpServletRequest request,
HttpServletResponse response,
Object command,
BindException bindExp) throws Exception {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Entering RegisterUserController:onsubmit()...");
}
User user = (User) command;
if (!checkPasswords(request, user)) {
return setAttributeAndShowForm(
request,
response,
bindExp,
"errors",
"Passwords, you typed are not identical.");
}
if (request.getParameter(ACTION_SUBMIT) != null) {
// TODO: need code to encrypt and decrypt password
// user.setPassword(StringUtil.encodePassword(user.getPassword(),Constants.ENCRYPTION_ALGORITHM));
StringUtil.encodePassword(user.getPassword(), Constants.ENCRYPTION_ALGORITHM);
ExecutionResult execResult = getUserService().createUser(user);
if (!execResult.isSuccessful()) {
// possible reason: e.g. the username or the email address is already taken.
return setAttributeAndShowForm(request, response, bindExp, "messages", execResult
.getErrorMessage());
}
}
String successView = getSuccessView();
return new ModelAndView(successView);
}
} | 27.694444 | 101 | 0.750752 |
9eed439bbddb61d8a18bb8cf5b6873231ec248c3 | 8,691 | lua | Lua | ConsolePortBar/Custom/Blizzard.lua | anton-bozhina/ConsolePort | 7211a1fb7af448c35e9ea8df3e1ba101c34fab22 | [
"Artistic-2.0"
] | null | null | null | ConsolePortBar/Custom/Blizzard.lua | anton-bozhina/ConsolePort | 7211a1fb7af448c35e9ea8df3e1ba101c34fab22 | [
"Artistic-2.0"
] | null | null | null | ConsolePortBar/Custom/Blizzard.lua | anton-bozhina/ConsolePort | 7211a1fb7af448c35e9ea8df3e1ba101c34fab22 | [
"Artistic-2.0"
] | null | null | null | -- This was mostly stolen from Bartender4.
-- This code snippet hides and modifies the default action bars.
local _, ab = ...
local Bar = ab.bar
local red, green, blue = ab.data.Atlas.GetCC()
do
-- Hidden parent frame
local UIHider = CreateFrame('Frame')
local FadeIn, FadeOut = ab.data.UIFrameFadeIn, ab.data.UIFrameFadeOut
-------------------------------------------
--- UI hider -> dispose of blizzbars
-------------------------------------------
UIHider:Hide()
Bar.UIHider = UIHider
for _, bar in pairs({
MainMenuBarArtFrame,
-- MultiBarLeft,
-- MultiBarRight,
MultiBarBottomLeft,
MultiBarBottomRight }) do
bar:SetParent(UIHider)
end
MainMenuBarArtFrame:Hide()
-- Hide MultiBar Buttons, but keep the bars alive
for _, n in pairs({
'ActionButton',
-- 'MultiBarLeftButton',
-- 'MultiBarRightButton',
'MultiBarBottomLeftButton',
'MultiBarBottomRightButton' }) do
for i=1, 12 do
local b = _G[n .. i]
b:Hide()
b:UnregisterAllEvents()
b:SetAttribute('statehidden', true)
end
end
UIPARENT_MANAGED_FRAME_POSITIONS['MainMenuBar'] = nil
UIPARENT_MANAGED_FRAME_POSITIONS['StanceBarFrame'] = nil
UIPARENT_MANAGED_FRAME_POSITIONS['PossessBarFrame'] = nil
UIPARENT_MANAGED_FRAME_POSITIONS['PETACTIONBAR_YPOS'] = nil
MainMenuBar:EnableMouse(false)
MicroButtonAndBagsBar:Hide()
StatusTrackingBarManager:Hide()
local animations = {MainMenuBar.slideOut:GetAnimations()}
animations[1]:SetOffset(0,0)
-------------------------------------------
--- Watch bar container
-------------------------------------------
function Bar:OnStatusBarsUpdated()
end
local WBC = CreateFrame('Frame', '$parentWatchBars', Bar, 'StatusTrackingBarManagerTemplate')
WBC:SetPoint('BOTTOMLEFT', 90, 0)
WBC:SetPoint('BOTTOMRIGHT',-90, 0)
WBC:SetHeight(16)
WBC:SetFrameStrata('LOW')
for i, region in pairs({WBC:GetRegions()}) do
region:SetTexture(nil)
end
WBC.BGLeft = WBC:CreateTexture(nil, 'BACKGROUND')
WBC.BGLeft:SetPoint('TOPLEFT')
WBC.BGLeft:SetPoint('BOTTOMRIGHT', WBC, 'BOTTOM', 0, 0)
WBC.BGLeft:SetColorTexture(0, 0, 0, 1)
WBC.BGLeft:SetGradientAlpha('HORIZONTAL', 0, 0, 0, 0, 0, 0, 0, 1)
WBC.BGRight = WBC:CreateTexture(nil, 'BACKGROUND')
WBC.BGRight:SetColorTexture(0, 0, 0, 1)
WBC.BGRight:SetPoint('TOPRIGHT')
WBC.BGRight:SetPoint('BOTTOMLEFT', WBC, 'BOTTOM', 0, 0)
WBC.BGRight:SetGradientAlpha('HORIZONTAL', 0, 0, 0, 1, 0, 0, 0, 0)
Bar.WatchBarContainer = WBC
local function BarColorOverride(self)
if (ab.cfg and ab.cfg.expRGB) and (WBC.mainBar == self) then
self:SetBarColorRaw(unpack(ab.cfg.expRGB))
end
end
function WBC:AddBarFromTemplate(frameType, template)
local bar = CreateFrame(frameType, nil, self, template)
table.insert(self.bars, bar)
bar.StatusBar.Background:Hide()
bar.StatusBar.BarTexture:SetTexture([[Interface\AddOns\ConsolePortBar\Textures\XPBar]])
bar.SetBarColorRaw = bar.SetBarColor
bar:HookScript('OnEnter', function()
FadeIn(self, 0.2, self:GetAlpha(), 1)
end)
bar:HookScript('OnLeave', function()
if (ab.cfg and not ab.cfg.watchbars) or not ab.cfg then
FadeOut(self, 0.2, self:GetAlpha(), 0)
end
end)
bar:HookScript('OnShow', BarColorOverride)
hooksecurefunc(bar, 'SetBarColor', BarColorOverride)
self:UpdateBarsShown()
return bar
end
function WBC:LayoutBar(bar, barWidth, isTopBar, isDouble)
bar:Update()
bar:Show()
bar:ClearAllPoints()
if ( isDouble ) then
if ( isTopBar ) then
bar:SetPoint("BOTTOM", self:GetParent(), 0, 14)
else
bar:SetPoint("BOTTOM", self:GetParent(), 0, 2)
end
self:SetDoubleBarSize(bar, barWidth)
else
bar:SetPoint("BOTTOM", self:GetParent(), 0, 0)
self:SetSingleBarSize(bar, barWidth)
end
end
function WBC:SetMainBarColor(r, g, b)
if self.mainBar then
self.mainBar:SetBarColorRaw(r, g, b)
end
end
function WBC:LayoutBars(visBars)
local width = self:GetWidth()
self:HideStatusBars()
local TOP_BAR, IS_DOUBLE = true, true
if ( #visBars > 1 ) then
self:LayoutBar(visBars[1], width, not TOP_BAR, IS_DOUBLE)
self:LayoutBar(visBars[2], width, TOP_BAR, IS_DOUBLE)
elseif( #visBars == 1 ) then
self:LayoutBar(visBars[1], width, TOP_BAR, not IS_DOUBLE)
end
self.mainBar = visBars and visBars[1]
self:GetParent():OnStatusBarsUpdated()
self:UpdateBarTicks()
end
WBC:AddBarFromTemplate('FRAME', 'ReputationStatusBarTemplate')
WBC:AddBarFromTemplate('FRAME', 'HonorStatusBarTemplate')
WBC:AddBarFromTemplate('FRAME', 'ArtifactStatusBarTemplate')
WBC:AddBarFromTemplate('FRAME', 'AzeriteBarTemplate')
local xpBar = WBC:AddBarFromTemplate('FRAME', 'ExpStatusBarTemplate')
xpBar.ExhaustionLevelFillBar:SetTexture([[Interface\AddOns\ConsolePortBar\Textures\XPBar]])
WBC:SetScript('OnShow', function(self)
if ab.cfg and ab.cfg.watchbars then
FadeIn(self, 0.2, self:GetAlpha(), 1)
else
self:SetAlpha(0)
end
end)
-------------------------------------------
--- Special action bars
-------------------------------------------
for _, bar in pairs({
StanceBarFrame,
PossessBarFrame,
PetActionBarFrame }) do
bar:UnregisterAllEvents()
bar:SetParent(UIHider)
bar:Hide()
end
-------------------------------------------
--- Casting bar modified
-------------------------------------------
local castBar, overrideCastBarPos = CastingBarFrame
local castBarAnchor = {'BOTTOM', Bar, 'BOTTOM', 0, 0}
hooksecurefunc(castBar, 'SetPoint', function(self, point, region, relPoint, x, y)
if overrideCastBarPos and region ~= castBarAnchor[2] then
self:SetPoint(unpack(castBarAnchor))
end
end)
local function ModifyCastingBarFrame(self, isOverrideBar)
CastingBarFrame_SetLook(self, isOverrideBar and 'CLASSIC' or 'UNITFRAME')
self.Border:SetShown(isOverrideBar)
if isOverrideBar then
return
end
-- Text anchor
self.Text:SetPoint('TOPLEFT', 0, 0)
self.Text:SetPoint('TOPRIGHT', 0, 0)
-- Flash at the end of a cast
self.Flash:SetTexture('Interface\\QUESTFRAME\\UI-QuestLogTitleHighlight')
self.Flash:SetAllPoints()
-- Border shield for uninterruptible casts
self.BorderShield:ClearAllPoints()
self.BorderShield:SetTexture('Interface\\CastingBar\\UI-CastingBar-Arena-Shield')
self.BorderShield:SetPoint('CENTER', self.Icon, 'CENTER', 10, 0)
self.BorderShield:SetSize(49, 49)
local r, g, b = ab:GetRGBColorFor('exp')
CastingBarFrame_SetStartCastColor(self, r or 1.0, g or 0.7, b or 0.0)
end
local function MoveCastingBarFrame()
local cfg = ab.cfg
if cfg and cfg.disableCastBarHook then
overrideCastBarPos = false
elseif OverrideActionBar:IsShown() or (cfg and cfg.defaultCastBar) then
ModifyCastingBarFrame(castBar, true)
overrideCastBarPos = false
else
castBarAnchor[4] = ( cfg and cfg.castbarxoffset or 0 )
castBarAnchor[5] = ( cfg and cfg.castbaryoffset or 0 )
ModifyCastingBarFrame(castBar, false)
castBar:ClearAllPoints()
castBar:SetPoint(unpack(castBarAnchor))
castBar:SetSize(
(cfg and cfg.castbarwidth) or (Bar:GetWidth() - 280),
(cfg and cfg.castbarheight) or 14)
overrideCastBarPos = true
end
end
Bar:HookScript('OnSizeChanged', MoveCastingBarFrame)
Bar:HookScript('OnShow', MoveCastingBarFrame)
Bar:HookScript('OnHide', MoveCastingBarFrame)
OverrideActionBar:HookScript('OnShow', MoveCastingBarFrame)
OverrideActionBar:HookScript('OnHide', MoveCastingBarFrame)
-------------------------------------------
--- Misc changes
-------------------------------------------
ObjectiveTrackerFrame:SetPoint('TOPRIGHT', MinimapCluster, 'BOTTOMRIGHT', -100, -132)
AlertFrame:SetPoint('BOTTOM', UIParent, 'BOTTOM', 0, 200)
if PlayerTalentFrame then
PlayerTalentFrame:UnregisterEvent('ACTIVE_TALENT_GROUP_CHANGED')
else
hooksecurefunc('TalentFrame_LoadUI', function() PlayerTalentFrame:UnregisterEvent('ACTIVE_TALENT_GROUP_CHANGED') end)
end
-- Replace spell push animations.
IconIntroTracker:HookScript('OnEvent', function(self, event, ...)
local anim = ConsolePortSpellHelperFrame
if anim and event == 'SPELL_PUSHED_TO_ACTIONBAR' then
for _, icon in pairs(self.iconList) do
icon:ClearAllPoints()
icon:SetAlpha(0)
end
local spellID, slotIndex, slotPos = ...
local page = math.floor((slotIndex - 1) / NUM_ACTIONBAR_BUTTONS) + 1
local currentPage = GetActionBarPage()
local bonusBarIndex = GetBonusBarIndex()
if (HasBonusActionBar() and bonusBarIndex ~= 0) then
currentPage = bonusBarIndex
end
if (page ~= currentPage and page ~= MULTIBOTTOMLEFTINDEX) then
return
end
local _, _, icon = GetSpellInfo(spellID)
local actionID = ((page - 1) * NUM_ACTIONBAR_BUTTONS) + slotPos
anim:OnActionPlaced(actionID, icon)
end
end)
end | 30.072664 | 119 | 0.695432 |
b2e92be3c0534e16199e949b149cd8bfd11ccfbb | 1,382 | asm | Assembly | u7-common/patch-eop-findPartyItem.asm | JohnGlassmyer/UltimaHacks | f9a114e00c4a1edf1ac7792b465feff2c9b88ced | [
"MIT"
] | 68 | 2018-03-04T22:34:22.000Z | 2022-03-10T15:18:32.000Z | u7-common/patch-eop-findPartyItem.asm | ptrie/UltimaHacks | 2c3557a86d94ad8b54b26bc395b9aed1604f8be1 | [
"MIT"
] | 19 | 2018-11-20T04:06:49.000Z | 2021-11-08T16:37:10.000Z | u7-common/patch-eop-findPartyItem.asm | ptrie/UltimaHacks | 2c3557a86d94ad8b54b26bc395b9aed1604f8be1 | [
"MIT"
] | 4 | 2020-09-01T17:57:36.000Z | 2022-01-04T20:51:11.000Z | ; Returns ibo of first found matching item held by any party member, or zero.
[bits 16]
startPatch EXE_LENGTH, eop-findPartyItem
startBlockAt addr_eop_findPartyItem
push bp
mov bp, sp
; bp-based stack frame:
%assign arg_itemFrame 0x08
%assign arg_itemQuality 0x06
%assign arg_itemType 0x04
%assign ____callerIp 0x02
%assign ____callerBp 0x00
%assign var_iPartyMember -0x02
%assign var_findItemQuery -0x30
add sp, var_findItemQuery
push si
push di
mov word [bp+var_iPartyMember], 0
tryPartyMember:
mov al, byte [dseg_partySize]
cbw
cmp ax, [bp+var_iPartyMember]
jle noMorePartyMembers
mov bx, [bp+var_iPartyMember]
push word [bp+arg_itemFrame]
push word [bp+arg_itemQuality]
push word [bp+arg_itemType]
push word 0 ; queryFlags
shl bx, 1
lea ax, [dseg_partyMemberIbos+bx]
push ax
lea ax, [bp+var_findItemQuery]
push ax
callFromOverlay findItemInContainer
add sp, 12
mov ax, [bp+var_findItemQuery]
test ax, ax
jnz foundItem
inc word [bp+var_iPartyMember]
jmp tryPartyMember
foundItem:
jmp endProc
noMorePartyMembers:
mov ax, 0
jmp endProc
endProc:
; ax == foundItemIbo or 0
pop di
pop si
mov sp, bp
pop bp
retn
endBlockAt off_eop_findPartyItem_end
endPatch
| 20.323529 | 77 | 0.673661 |
5d4a7a9afae5d519bf2f71e4684545da0dc04cbb | 115 | dart | Dart | lib/src/info/search_conversation_result.dart | drewzhao/rongcloud-im-flutter-sdk | 86c6f97f12587da8c86d12423ff67890c2d63450 | [
"MIT"
] | 203 | 2019-07-22T00:51:20.000Z | 2022-03-22T07:09:23.000Z | lib/src/info/search_conversation_result.dart | drewzhao/rongcloud-im-flutter-sdk | 86c6f97f12587da8c86d12423ff67890c2d63450 | [
"MIT"
] | 208 | 2019-07-15T13:25:20.000Z | 2021-12-16T03:04:03.000Z | lib/src/info/search_conversation_result.dart | drewzhao/rongcloud-im-flutter-sdk | 86c6f97f12587da8c86d12423ff67890c2d63450 | [
"MIT"
] | 60 | 2019-07-24T07:00:59.000Z | 2022-03-22T07:45:57.000Z | import 'conversation.dart';
class SearchConversationResult {
Conversation? mConversation;
int? mMatchCount;
}
| 16.428571 | 32 | 0.782609 |
80d61a4aa878c0641ba8d56488bc41e79dd88bd1 | 2,206 | java | Java | src/main/java/org/bian/dto/SDRegulatoryAndLegalAuthorityConfigureInputModelRegulatoryAndLegalAuthorityServiceConfigurationRecordRegulatoryAndLegalAuthorityServiceSubscription.java | bianapis/sd-regulatoryand-legal-authority-v3 | e562ee85319a22850e69a89985d136d21cb643ad | [
"Apache-2.0"
] | null | null | null | src/main/java/org/bian/dto/SDRegulatoryAndLegalAuthorityConfigureInputModelRegulatoryAndLegalAuthorityServiceConfigurationRecordRegulatoryAndLegalAuthorityServiceSubscription.java | bianapis/sd-regulatoryand-legal-authority-v3 | e562ee85319a22850e69a89985d136d21cb643ad | [
"Apache-2.0"
] | null | null | null | src/main/java/org/bian/dto/SDRegulatoryAndLegalAuthorityConfigureInputModelRegulatoryAndLegalAuthorityServiceConfigurationRecordRegulatoryAndLegalAuthorityServiceSubscription.java | bianapis/sd-regulatoryand-legal-authority-v3 | e562ee85319a22850e69a89985d136d21cb643ad | [
"Apache-2.0"
] | null | null | null | package org.bian.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import javax.validation.Valid;
/**
* SDRegulatoryAndLegalAuthorityConfigureInputModelRegulatoryAndLegalAuthorityServiceConfigurationRecordRegulatoryAndLegalAuthorityServiceSubscription
*/
public class SDRegulatoryAndLegalAuthorityConfigureInputModelRegulatoryAndLegalAuthorityServiceConfigurationRecordRegulatoryAndLegalAuthorityServiceSubscription {
private String regulatoryAndLegalAuthorityServiceSubscriberReference = null;
private String regulatoryAndLegalAuthorityServiceSubscriberAccessProfile = null;
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Maintains reference to allowed users or subscribers to the service which can be any known party
* @return regulatoryAndLegalAuthorityServiceSubscriberReference
**/
public String getRegulatoryAndLegalAuthorityServiceSubscriberReference() {
return regulatoryAndLegalAuthorityServiceSubscriberReference;
}
public void setRegulatoryAndLegalAuthorityServiceSubscriberReference(String regulatoryAndLegalAuthorityServiceSubscriberReference) {
this.regulatoryAndLegalAuthorityServiceSubscriberReference = regulatoryAndLegalAuthorityServiceSubscriberReference;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: The allowed service access for a user or subscriber to the service which can be any known party
* @return regulatoryAndLegalAuthorityServiceSubscriberAccessProfile
**/
public String getRegulatoryAndLegalAuthorityServiceSubscriberAccessProfile() {
return regulatoryAndLegalAuthorityServiceSubscriberAccessProfile;
}
public void setRegulatoryAndLegalAuthorityServiceSubscriberAccessProfile(String regulatoryAndLegalAuthorityServiceSubscriberAccessProfile) {
this.regulatoryAndLegalAuthorityServiceSubscriberAccessProfile = regulatoryAndLegalAuthorityServiceSubscriberAccessProfile;
}
}
| 45.020408 | 235 | 0.856754 |
c4446d272b0463c2a2c5c65cfc58d5b41e852654 | 256 | kt | Kotlin | tmp/arrays/youTrackTests/10385.kt | vitekkor/bbfgradle | b4ec701a7a3b7523db97631fa0ed6484149ca9cd | [
"Apache-2.0"
] | 1 | 2021-04-06T16:59:24.000Z | 2021-04-06T16:59:24.000Z | tmp/arrays/youTrackTests/10385.kt | vitekkor/bbfgradle | b4ec701a7a3b7523db97631fa0ed6484149ca9cd | [
"Apache-2.0"
] | null | null | null | tmp/arrays/youTrackTests/10385.kt | vitekkor/bbfgradle | b4ec701a7a3b7523db97631fa0ed6484149ca9cd | [
"Apache-2.0"
] | 11 | 2020-03-23T08:28:36.000Z | 2022-03-22T07:04:42.000Z | // Original bug: KT-6202
fun createPage(pageNum: Int, position: String): String? {
var pageView: String? = "123"
if (pageView == null) {
pageView = ""
} else {
pageView.toString()
}
print(pageNum)
return pageView
}
| 19.692308 | 57 | 0.578125 |
90e9d67bee168d14a2d55cd10fdc902c536cc2d5 | 313 | sql | SQL | openGaussBase/testcase/SQL/DDL/table/Opengauss_Function_DDL_Table_Case0102.sql | opengauss-mirror/Yat | aef107a8304b94e5d99b4f1f36eb46755eb8919e | [
"MulanPSL-1.0"
] | null | null | null | openGaussBase/testcase/SQL/DDL/table/Opengauss_Function_DDL_Table_Case0102.sql | opengauss-mirror/Yat | aef107a8304b94e5d99b4f1f36eb46755eb8919e | [
"MulanPSL-1.0"
] | null | null | null | openGaussBase/testcase/SQL/DDL/table/Opengauss_Function_DDL_Table_Case0102.sql | opengauss-mirror/Yat | aef107a8304b94e5d99b4f1f36eb46755eb8919e | [
"MulanPSL-1.0"
] | null | null | null | -- @testpoint: 测试列名长度超过63字节,实际列名为前63字节
drop table if exists table_1;
create table table_1(qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq int);
insert into table_1 values(1);
insert into table_1 values(2);
insert into table_1 values(3);
select * from table_1;
drop table if exists table_1;
| 34.777778 | 97 | 0.827476 |
cb48449c2ae2cfe279a4a154b44934da60710838 | 291 | h | C | mmu.h | Seteeri/pilos-risc | 63a01c9ce1d12f157ea9e3bb87108d5e83d14158 | [
"Apache-2.0"
] | null | null | null | mmu.h | Seteeri/pilos-risc | 63a01c9ce1d12f157ea9e3bb87108d5e83d14158 | [
"Apache-2.0"
] | null | null | null | mmu.h | Seteeri/pilos-risc | 63a01c9ce1d12f157ea9e3bb87108d5e83d14158 | [
"Apache-2.0"
] | null | null | null | void mmu_mair(void);
void mmu_tcr(long long int TG1,
long long int T1SZ,
long long int TG0,
long long int T0SZ);
void mmu_ttrbr0(unsigned long r);
void mmu_sctrlr(void);
void mmu_map_stage1(void);
void mmu_map_stage2(void);
void mmu_map_stage3(void);
| 24.25 | 33 | 0.67354 |
7a68742d27bfbbb36cbf9c58587d13b1628c5c1e | 1,697 | sql | SQL | SQL TABLES/story_list.sql | calebdenby/StoryBlend | 96b0ae55fef31be416582eae66b167792b0b9848 | [
"MIT"
] | null | null | null | SQL TABLES/story_list.sql | calebdenby/StoryBlend | 96b0ae55fef31be416582eae66b167792b0b9848 | [
"MIT"
] | null | null | null | SQL TABLES/story_list.sql | calebdenby/StoryBlend | 96b0ae55fef31be416582eae66b167792b0b9848 | [
"MIT"
] | null | null | null | -- phpMyAdmin SQL Dump
-- version 4.5.1
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Feb 14, 2017 at 06:09 PM
-- Server version: 10.1.19-MariaDB
-- PHP Version: 5.5.38
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `id695241_storyblenddb`
--
-- --------------------------------------------------------
--
-- Table structure for table `story_list`
--
CREATE TABLE `story_list` (
`id` int(50) NOT NULL,
`created_by_id` int(50) NOT NULL,
`story_name` varchar(100) NOT NULL,
`story_description` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `story_list`
--
INSERT INTO `story_list` (`id`, `created_by_id`, `story_name`, `story_description`) VALUES
(9, 1, 'fgfdddgd', 'dfsfdsfsdfs'),
(10, 1, 'fdgfrtet3rtrtrert43rt', 't5432ty5434554356545'),
(11, 2, 'look at me', 'A story about corbin'),
(12, 2, 'dsfghj', 'dfghj'),
(13, 2, 'adsfgh', 'asdfhg');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `story_list`
--
ALTER TABLE `story_list`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `story_list`
--
ALTER TABLE `story_list`
MODIFY `id` int(50) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| 24.594203 | 90 | 0.680613 |
988ba90d49fbf3c732183d48764a621e7506d06b | 1,215 | html | HTML | Site/angular-src/src/app/components/profile/profile.component.html | KyrXtz/HexiwearMeanStack | fd92555fee4b58cd802b4dcf3bd78623c3c8e1ff | [
"MIT"
] | 7 | 2019-05-15T12:29:00.000Z | 2020-12-08T15:00:24.000Z | Site/angular-src/src/app/components/profile/profile.component.html | fotioudim/HexiwearMeanStack | 43075ab0b065b74a9478fc462327cbe18f861722 | [
"MIT"
] | null | null | null | Site/angular-src/src/app/components/profile/profile.component.html | fotioudim/HexiwearMeanStack | 43075ab0b065b74a9478fc462327cbe18f861722 | [
"MIT"
] | 2 | 2019-06-20T12:17:22.000Z | 2020-12-08T15:00:27.000Z | <div *ngIf="user">
<h2 class="page-header">Greetings {{user.name}} !!</h2>
<ul class="list-group">
<li class="list-group-item">Username : {{user.username}}</li>
<li class="list-group-item">Email : {{user.email}}</li>
<li class="list-group-item">Role : {{user.role}}</li>
<div *ngIf="user.role == 'Patient'">
<li class="list-group-item">Device : {{user.device}}</li>
</div>
</ul>
</div>
<div>
<form (submit)="onChangeSubmit()" >
<div class="form-group">
<label for="oldpass">Old Password</label>
<input type="password" [(ngModel)]="oldpass" name="oldpass" class="form-control" id="oldpass" placeholder=" Enter Password">
</div>
<div class="form-group">
<label for="newpass">New Password</label>
<input type="password" [(ngModel)]="newpass" name="newpass" class="form-control" id="newpass" placeholder=" Enter New Password">
</div>
<div class="form-group">
<label for="newpasscheck">Re-enter New Password</label>
<input type="password" [(ngModel)]="newpasscheck" name="newpasscheck" class="form-control" id="newpasscheck" placeholder=" Re-Enter New Password">
</div>
<input type="submit" class="btn btn-primary" value="Submit">
</form>
</div>
| 36.818182 | 150 | 0.643621 |
987b35519c707d89c878d263c085698bdf14a003 | 812 | swift | Swift | Sources/Solana/Models/Requests and Responses/GetConfirmedTransaction.swift | ajamaica/solana-swift | 29470a4273ab23055467b0ad68eff0e4a0f89138 | [
"MIT"
] | null | null | null | Sources/Solana/Models/Requests and Responses/GetConfirmedTransaction.swift | ajamaica/solana-swift | 29470a4273ab23055467b0ad68eff0e4a0f89138 | [
"MIT"
] | null | null | null | Sources/Solana/Models/Requests and Responses/GetConfirmedTransaction.swift | ajamaica/solana-swift | 29470a4273ab23055467b0ad68eff0e4a0f89138 | [
"MIT"
] | null | null | null | //
// GetConfirmedTransaction.swift
// SolanaDemoApp
//
// Created by Gene Crucean on 3/11/21.
//
import Foundation
// MARK: - Response
public struct GetConfirmedTransactionResponse: Codable {
let jsonrpc: String
let result: GetConfirmedTransactionResult?
let id: Int
let error: RpcError?
}
public struct GetConfirmedTransactionResult: Codable {
let slot: UInt64
let transaction: Transaction
let blockTime: Int64?
let meta: GetConfirmedTransactionMeta?
}
public struct GetConfirmedTransactionMeta: Codable {
let err: TransactionError?
let fee: UInt64
let preBalances: [UInt64]
let postBalances: [UInt64]
let innerInstructions: [BlockInstruction]?
let preTokenBalances: [UInt64]?
let postTokenBalances: [UInt64]?
let logMessages: [String]?
}
| 23.2 | 56 | 0.725369 |
dc902ebfc0fc0b22b6952c56e6e02d9b535ef9ba | 61 | dart | Dart | lib/src/services/remote/rest/rest.dart | sibvisions/flutterclient | ee04222b585cc705a52e2ac65aeebf8c649c5d45 | [
"Apache-2.0"
] | 1 | 2022-02-28T14:36:24.000Z | 2022-02-28T14:36:24.000Z | lib/src/services/remote/rest/rest.dart | sibvisions/flutterclient | ee04222b585cc705a52e2ac65aeebf8c649c5d45 | [
"Apache-2.0"
] | null | null | null | lib/src/services/remote/rest/rest.dart | sibvisions/flutterclient | ee04222b585cc705a52e2ac65aeebf8c649c5d45 | [
"Apache-2.0"
] | null | null | null | export 'rest_client.dart';
export 'cert_http_overrides.dart'; | 30.5 | 34 | 0.819672 |
46aeb4000914843606b44f3e356d9293f6603ce1 | 876 | html | HTML | ex007/index.html | delima75/Aulas-HTML | 55aa6e792fa654291591ffc548b03d018a2e3a38 | [
"MIT"
] | null | null | null | ex007/index.html | delima75/Aulas-HTML | 55aa6e792fa654291591ffc548b03d018a2e3a38 | [
"MIT"
] | null | null | null | ex007/index.html | delima75/Aulas-HTML | 55aa6e792fa654291591ffc548b03d018a2e3a38 | [
"MIT"
] | null | null | null | <html>
<head>
<title>Meu Site em HTML4</title>
</head>
<body bgcolor="blue">
<h1>Exercício de site em HTML4</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolorum, reprehenderit voluptate? Quam inventore odio quos provident voluptate dolorum! Sed blanditiis, dolores doloribus placeat consequuntur maxime eligendi! Nulla deserunt ab blanditiis.</p>
<p><font color="white">Teste de Pararafo</font></p> <!-- tags que aparecem em vermelho cairam em desuso-->
<p><font color="white">Exemplo de tag u Eu <u>moro na rua tal, 15</u>.</font> </p>
<p><font color="white">Nova forma usando address Eu noro na <address>rua bla bla blá</address></font></p>
<marquee behavior="" direction="rigth"><font color="white">teste de marquee</font></font></marquee>
</body>
</html>
| 48.666667 | 261 | 0.650685 |
fb245b1e5724ea1e3b80c413d42ec2180dd238c7 | 1,447 | go | Go | pkg/backend/mock/api/server/backend/v1/system/teardown.go | mlab-lattice/lattice | 8ad7070f7c0c5d2a24373b59567797afd669201f | [
"Apache-2.0"
] | 1 | 2018-10-01T17:33:36.000Z | 2018-10-01T17:33:36.000Z | pkg/backend/mock/api/server/backend/v1/system/teardown.go | mlab-lattice/lattice | 8ad7070f7c0c5d2a24373b59567797afd669201f | [
"Apache-2.0"
] | 59 | 2018-08-23T17:07:35.000Z | 2018-10-09T15:55:05.000Z | pkg/backend/mock/api/server/backend/v1/system/teardown.go | mlab-lattice/lattice | 8ad7070f7c0c5d2a24373b59567797afd669201f | [
"Apache-2.0"
] | 3 | 2018-10-09T05:38:16.000Z | 2018-10-10T16:58:57.000Z | package system
import (
"github.com/mlab-lattice/lattice/pkg/api/v1"
"github.com/satori/go.uuid"
)
type TeardownBackend struct {
systemID v1.SystemID
backend *Backend
}
func (b *TeardownBackend) Create() (*v1.Teardown, error) {
b.backend.registry.Lock()
defer b.backend.registry.Unlock()
record, err := b.backend.systemRecordInitialized(b.systemID)
if err != nil {
return nil, err
}
teardown := &v1.Teardown{
ID: v1.TeardownID(uuid.NewV4().String()),
Status: v1.TeardownStatus{
State: v1.TeardownStatePending,
},
}
record.Teardowns[teardown.ID] = teardown
// run the teardown
b.backend.controller.RunTeardown(teardown, record)
return teardown.DeepCopy(), nil
}
func (b *TeardownBackend) List() ([]v1.Teardown, error) {
b.backend.registry.Lock()
defer b.backend.registry.Unlock()
record, err := b.backend.systemRecordInitialized(b.systemID)
if err != nil {
return nil, err
}
var teardowns []v1.Teardown
for _, teardown := range record.Teardowns {
teardowns = append(teardowns, *teardown.DeepCopy())
}
return teardowns, nil
}
func (b *TeardownBackend) Get(id v1.TeardownID) (*v1.Teardown, error) {
b.backend.registry.Lock()
defer b.backend.registry.Unlock()
record, err := b.backend.systemRecordInitialized(b.systemID)
if err != nil {
return nil, err
}
teardown, ok := record.Teardowns[id]
if !ok {
return nil, v1.NewInvalidTeardownIDError()
}
return teardown.DeepCopy(), nil
}
| 20.097222 | 71 | 0.709744 |
2fa29c33fb3d85c13efe31afaa1fae244db3a22a | 47 | sql | SQL | db/migrations/20190206204219_add_url_nonce_to_payments/down.sql | taritom/bn-api | 6fbf05bf426c4ddd3d5f50378ac9b51f3ebf2a3f | [
"BSD-3-Clause"
] | null | null | null | db/migrations/20190206204219_add_url_nonce_to_payments/down.sql | taritom/bn-api | 6fbf05bf426c4ddd3d5f50378ac9b51f3ebf2a3f | [
"BSD-3-Clause"
] | null | null | null | db/migrations/20190206204219_add_url_nonce_to_payments/down.sql | taritom/bn-api | 6fbf05bf426c4ddd3d5f50378ac9b51f3ebf2a3f | [
"BSD-3-Clause"
] | null | null | null | ALTER TABLE payments
drop column url_nonce
| 15.666667 | 25 | 0.787234 |
80a0792e89b14483bfc778bcb44926e963d521cf | 568 | java | Java | The 5zig Mod/src/eu/the5zig/mod/modules/items/server/timolia/DNAHeight.java | TurTalhi/The-5zig-Mod | efce66b2cec83e76f40e4e18e96a2013a89e0a42 | [
"MIT"
] | 105 | 2019-05-28T16:53:31.000Z | 2022-03-11T06:41:04.000Z | The 5zig Mod/src/eu/the5zig/mod/modules/items/server/timolia/DNAHeight.java | TurTalhi/The-5zig-Mod | efce66b2cec83e76f40e4e18e96a2013a89e0a42 | [
"MIT"
] | 33 | 2019-06-12T14:52:32.000Z | 2021-11-07T15:09:38.000Z | The 5zig Mod/src/eu/the5zig/mod/modules/items/server/timolia/DNAHeight.java | TurTalhi/The-5zig-Mod | efce66b2cec83e76f40e4e18e96a2013a89e0a42 | [
"MIT"
] | 68 | 2019-05-30T22:40:20.000Z | 2022-03-29T00:58:25.000Z | package eu.the5zig.mod.modules.items.server.timolia;
import eu.the5zig.mod.modules.GameModeItem;
import eu.the5zig.mod.server.GameState;
import eu.the5zig.mod.server.timolia.ServerTimolia;
public class DNAHeight extends GameModeItem<ServerTimolia.DNA> {
public DNAHeight() {
super(ServerTimolia.DNA.class, GameState.GAME);
}
@Override
protected Object getValue(boolean dummy) {
if (dummy) {
return 16;
}
return shorten(getGameMode().getHeight()) + "/" + shorten(32.0);
}
@Override
public String getTranslation() {
return "ingame.height";
}
}
| 21.846154 | 66 | 0.739437 |
d9936a4a644ce10ef5415164adee73df061d4c40 | 2,959 | rs | Rust | src/game/game.rs | samhippie/rust_mc_cfr | 38baf84ec84dfdf26fd2e82e6586dbfec0bdcf8f | [
"MIT"
] | null | null | null | src/game/game.rs | samhippie/rust_mc_cfr | 38baf84ec84dfdf26fd2e82e6586dbfec0bdcf8f | [
"MIT"
] | null | null | null | src/game/game.rs | samhippie/rust_mc_cfr | 38baf84ec84dfdf26fd2e82e6586dbfec0bdcf8f | [
"MIT"
] | null | null | null | use std::fmt;
use std::hash::{Hash, Hasher};
use fasthash::{MetroHasher};
#[derive(PartialEq, Copy, Clone, Debug, Hash)]
pub enum Player {
P1,
P2,
}
impl Player {
/// Gets the opposite player
pub fn other(self) -> Player {
match self {
Player::P1 => Player::P2,
Player::P2 => Player::P1,
}
}
/// Returns a mutable reference to either member of a 2-tuple
///
/// This allows you to use tuples for P1 and P2 instead of p1_val, p2_val everywhere
pub fn lens_mut<'a, T>(&self, tuple: &'a mut (T,T)) -> &'a mut T {
match self {
Player::P1 => &mut tuple.0,
Player::P2 => &mut tuple.1,
}
}
/// Returns a reference to either member of a 2-tuple
///
/// This allows you to use tuples for P1 and P2 instead of p1_val, p2_val everywhere
pub fn lens<'a, T>(&self, tuple: &'a (T,T)) -> &'a T {
match self {
Player::P1 => &tuple.0,
Player::P2 => &tuple.1,
}
}
/// Returns P1 if the given player matches the current player, P2 otherwise
///
/// This is for when you want a player to see themself as P1
pub fn view(self, other: Player) -> Player {
if self == other {
Player::P1
} else {
Player::P2
}
}
}
impl fmt::Display for Player {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result {
let s = match self {
Player::P1 => "P1",
Player::P2 => "P2",
};
write!(f, "{}", s)
}
}
pub struct Infoset {
pub hash: u64,
}
impl Infoset {
pub fn new<T: Hash>(infoset: T) -> Infoset {
let mut hasher: MetroHasher = Default::default();
infoset.hash(&mut hasher);
let hash = hasher.finish();
Infoset {
hash,
}
}
}
/// 2 player zero sum game
///
/// Game is over when get_reward returns Some(reward) for player 1
pub trait Game: fmt::Display {
type Action: fmt::Display + fmt::Debug;
/// Returns player to move and all legal actions
fn get_turn(&self) -> (Player, Vec<Self::Action>);
/// The given player does the given action for their turn
/// # Panics
/// This may panic if the player cannot move or the action is invalid
fn take_turn(&mut self, player: Player, action: &Self::Action);
/// Returns None if the game is not over
///
/// Otherwise returns the reward for Player 1
fn get_reward(&self) -> Option<f32>;
/// Returns a player's infoset as a vector of hashes
///
/// Earlier parts of the infoset should come first, so an early infoset
/// is a prefix of a later infoset
fn get_infoset(&self, player: Player) -> Infoset;
/// Returns a human-readable summary of the game for the given player
fn get_summary_string(&self, _player: Player) -> String {
String::from("Player summary not available")
}
} | 27.654206 | 88 | 0.567759 |
409ee4439c5e2beef5d84d0609d9d97498d8be26 | 3,831 | py | Python | python/en/_numpy/python_numpy_tutorial/python_numpy_tutorial-numpy_array_indexing.py | aimldl/coding | 70ddbfaa454ab92fd072ee8dc614ecc330b34a70 | [
"MIT"
] | null | null | null | python/en/_numpy/python_numpy_tutorial/python_numpy_tutorial-numpy_array_indexing.py | aimldl/coding | 70ddbfaa454ab92fd072ee8dc614ecc330b34a70 | [
"MIT"
] | null | null | null | python/en/_numpy/python_numpy_tutorial/python_numpy_tutorial-numpy_array_indexing.py | aimldl/coding | 70ddbfaa454ab92fd072ee8dc614ecc330b34a70 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
CS231n Convolutional Neural Networks for Visual Recognition
http://cs231n.github.io/
Python Numpy Tutorial
http://cs231n.github.io/python-numpy-tutorial/
Numpy Reference
https://docs.scipy.org/doc/numpy/reference/
 ̄
python_numpy_tutorial-numpy_array_indexing.py
2019-07-02 (Tue)
"""
# Python Numpy Tutorial > Numpy > Array indexing
# Numpy offers several ways to index into arrays.
#
# This examples cover:
# Slicing
# Integer array indexing
# Boolean array indexing
#############
# Slicing #
#############
# Similar to Python lists, numpy arrays can be sliced.
# Since arrays may be multidimensional,
# you must specify a slice for each dimension of the array.
import numpy as np
# Create a new array
a = np.array( [[1,2,3,4],[5,6,7,8],[9,10,11,12]])
print(a)
#[[ 1 2 3 4]
# [ 5 6 7 8]
# [ 9 10 11 12]]
b = a[:2,1:3]
print(b)
#[[2 3]
# [6 7]]
print( a[0,1] )
#2
b[0,0] = 77
print( a[0,1] )
#77
print(a)
#[[ 1 77 3 4]
# [ 5 6 7 8]
# [ 9 10 11 12]]
print(b)
#[[77 3]
# [ 6 7]]
# You can also mix integer indexing with slice indexing.
# However, doing so will yield an array of lower rank than the original array.
# Note this is different from the way MATLAB handles array slicing.
# Create a new array # NOTE
a = np.array( [[1,2,3,4],[5,6,7,8],[9,10,11,12]]) # NOTE
print(a) # NOTE
#[[ 1 2 3 4] # NOTE
# [ 5 6 7 8] # NOTE
# [ 9 10 11 12]] # NOTE
row_r1 = a[1,:]
print( row_r1, row_r1.shape )
#[5 6 7 8] (4,)
row_r2 = a[1:2,:] # NOTE
print( row_r2,row_r2.shape ) # NOTE: Review this again
#[[5 6 7 8]] (1, 4) # NOTE
col_r1 = a[:,1] # NOTE
print( col_r1,col_r1.shape ) # NOTE
# [ 2 6 10] (3,) # NOTE
col_r2 = a[:,1:2] # NOTE
print( col_r2,col_r2.shape ) # NOTE: Review this again
#[[ 2] # NOTE
# [ 6] # NOTE
# [10]] (3, 1) # NOTE
############################
# Integer array indexing #
############################
# When you index into numpy arrays using slicing,
# the resulting array view will always be a subarray of the original array.
# In contrast, integer array indexing allows you to construct arbitrary arrays using the data from another array.
a = np.array( [[1,2],[3,4],[5,6]])
print(a)
#[[1 2]
# [3 4]
# [5 6]]
# An example of integer array indexing
print( a[[0,1,2],[0,1,0]] )
# [1 4 5]
# Identical to [a[0,0], a[1,1], a[2,0]]
print( np.array( [ a[0,0], a[1,1], a[2,0] ]) )
# [1 4 5]
# The same element from the source array can be used.
# in this case a[0,1] is repeated.
print( a[[0,0],[1,1]] )
# [2,2]
print( np.array( [a[0,1],a[0,1]]) )
# [2,2]
# One useful trick with integer array indexing is
# selecting or mutating one element from each row of a matrix:
# Create a new array
a = np.array( [[1,2,3], [4,5,6], [7,8,9], [10,11,12]])
print(a)
#[[ 1 2 3]
# [ 4 5 6]
# [ 7 8 9]
# [10 11 12]]
# Create an array of indices
b = np.array( [0,2,0,1] )
print( a[ np.arange(4), b] )
# [ 1 6 7 11]
# [np.arange(4), b] means
# [ [0,1,2,3],[0,2,0,1] ]
# => a[0,0], a[1,2], a[2,0], a[3,1]
# Mutate one element from each row of a using the indices in b
a[np.arange(4),b] += 10
print(a)
#[[11 2 3]
# [ 4 5 16]
# [17 8 9]
# [10 21 12]]
# Add 10 to the indices
############################
# Boolean array indexing #
############################
# Boolean array indexing lets you pick out arbitrary elements of an array.
# Frequently this type of indexing is used to select the elements of an array
# that satisfy some condition.
a = np.array( [[1,2],[3,4],[5,6]] )
print(a)
#[[1 2]
# [3 4]
# [5 6]]
bool_idx = (a > 2)
print( bool_idx )
#[[False False]
# [ True True]
# [ True True]]
print( a[bool_idx] )
#[3 4 5 6]
print( a[ a>2] )
#[3 4 5 6]
print( a[ a>4] )
#[5 6] | 22.273256 | 114 | 0.567476 |
664aec69f908ceb5469acbc6782e2ded6f635666 | 14,171 | hpp | C++ | samples/cpp/speech_sample/utils.hpp | pazamelin/openvino | b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48 | [
"Apache-2.0"
] | 1 | 2019-09-22T01:05:07.000Z | 2019-09-22T01:05:07.000Z | samples/cpp/speech_sample/utils.hpp | pazamelin/openvino | b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48 | [
"Apache-2.0"
] | 58 | 2020-11-06T12:13:45.000Z | 2022-03-28T13:20:11.000Z | samples/cpp/speech_sample/utils.hpp | pazamelin/openvino | b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48 | [
"Apache-2.0"
] | 2 | 2019-09-20T01:33:37.000Z | 2019-09-20T08:42:11.000Z | // Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include <cnpy.h>
#include <samples/common.hpp>
#define MAX_SCORE_DIFFERENCE 0.0001f // max score difference for frame error threshold
#define MAX_VAL_2B_FEAT 16384 // max to find scale factor
typedef std::chrono::high_resolution_clock Time;
typedef std::chrono::duration<double, std::ratio<1, 1000>> ms;
typedef std::chrono::duration<float> fsec;
/**
* @brief struct to store score error
*/
struct ScoreErrorT {
uint32_t numScores;
uint32_t numErrors;
float threshold;
float maxError;
float rmsError;
float sumError;
float sumRmsError;
float sumSquaredError;
float maxRelError;
float sumRelError;
float sumSquaredRelError;
};
/**
* @brief struct to store infer request data per frame
*/
struct InferRequestStruct {
ov::runtime::InferRequest inferRequest;
int frameIndex;
uint32_t numFramesThisBatch;
};
/**
* @brief Check number of input files and model network inputs
* @param numInputs number model inputs
* @param numInputFiles number of input files
* @return none.
*/
void check_number_of_inputs(size_t numInputs, size_t numInputFiles) {
if (numInputs != numInputFiles) {
throw std::logic_error("Number of network inputs (" + std::to_string(numInputs) +
")"
" is not equal to number of input files (" +
std::to_string(numInputFiles) + ")");
}
}
/**
* @brief Get scale factor for quantization
* @param ptrFloatMemory pointer to float memory with speech feature vector
* @param targetMax max scale factor
* @param numElements number of elements in speech feature vector
* @return scale factor
*/
float scale_factor_for_quantization(void* ptrFloatMemory, float targetMax, uint32_t numElements) {
float* ptrFloatFeat = reinterpret_cast<float*>(ptrFloatMemory);
float max = 0.0;
float scaleFactor;
for (uint32_t i = 0; i < numElements; i++) {
if (fabs(ptrFloatFeat[i]) > max) {
max = fabs(ptrFloatFeat[i]);
}
}
if (max == 0) {
scaleFactor = 1.0;
} else {
scaleFactor = targetMax / max;
}
return (scaleFactor);
}
/**
* @brief Clean score error
* @param error pointer to score error struct
* @return none.
*/
void clear_score_error(ScoreErrorT* error) {
error->numScores = 0;
error->numErrors = 0;
error->maxError = 0.0;
error->rmsError = 0.0;
error->sumError = 0.0;
error->sumRmsError = 0.0;
error->sumSquaredError = 0.0;
error->maxRelError = 0.0;
error->sumRelError = 0.0;
error->sumSquaredRelError = 0.0;
}
/**
* @brief Update total score error
* @param error pointer to score error struct
* @param totalError pointer to total score error struct
* @return none.
*/
void update_score_error(ScoreErrorT* error, ScoreErrorT* totalError) {
totalError->numErrors += error->numErrors;
totalError->numScores += error->numScores;
totalError->sumRmsError += error->rmsError;
totalError->sumError += error->sumError;
totalError->sumSquaredError += error->sumSquaredError;
if (error->maxError > totalError->maxError) {
totalError->maxError = error->maxError;
}
totalError->sumRelError += error->sumRelError;
totalError->sumSquaredRelError += error->sumSquaredRelError;
if (error->maxRelError > totalError->maxRelError) {
totalError->maxRelError = error->maxRelError;
}
}
/**
* @brief Compare score errors, array should be the same length
* @param ptrScoreArray - pointer to score error struct array
* @param ptrRefScoreArray - pointer to score error struct array to compare
* @param scoreError - pointer to score error struct to save a new error
* @param numRows - number rows in score error arrays
* @param numColumns - number columns in score error arrays
* @return none.
*/
void compare_scores(float* ptrScoreArray,
void* ptrRefScoreArray,
ScoreErrorT* scoreError,
uint32_t numRows,
uint32_t numColumns) {
uint32_t numErrors = 0;
clear_score_error(scoreError);
float* A = ptrScoreArray;
float* B = reinterpret_cast<float*>(ptrRefScoreArray);
for (uint32_t i = 0; i < numRows; i++) {
for (uint32_t j = 0; j < numColumns; j++) {
float score = A[i * numColumns + j];
// std::cout << "score" << score << std::endl;
float refscore = B[i * numColumns + j];
float error = fabs(refscore - score);
float rel_error = error / (static_cast<float>(fabs(refscore)) + 1e-20f);
float squared_error = error * error;
float squared_rel_error = rel_error * rel_error;
scoreError->numScores++;
scoreError->sumError += error;
scoreError->sumSquaredError += squared_error;
if (error > scoreError->maxError) {
scoreError->maxError = error;
}
scoreError->sumRelError += rel_error;
scoreError->sumSquaredRelError += squared_rel_error;
if (rel_error > scoreError->maxRelError) {
scoreError->maxRelError = rel_error;
}
if (error > scoreError->threshold) {
numErrors++;
}
}
}
scoreError->rmsError = sqrt(scoreError->sumSquaredError / (numRows * numColumns));
scoreError->sumRmsError += scoreError->rmsError;
scoreError->numErrors = numErrors;
// std::cout << "rmsError=" << scoreError->rmsError << "sumRmsError="<<scoreError->sumRmsError;
}
/**
* @brief Get total stdev error
* @param error pointer to score error struct
* @return error
*/
float std_dev_error(ScoreErrorT error) {
return (sqrt(error.sumSquaredError / error.numScores -
(error.sumError / error.numScores) * (error.sumError / error.numScores)));
}
#if !defined(__arm__) && !defined(_M_ARM) && !defined(__aarch64__) && !defined(_M_ARM64)
# ifdef _WIN32
# include <intrin.h>
# include <windows.h>
# else
# include <cpuid.h>
# endif
inline void native_cpuid(unsigned int* eax, unsigned int* ebx, unsigned int* ecx, unsigned int* edx) {
size_t level = *eax;
# ifdef _WIN32
int regs[4] = {static_cast<int>(*eax), static_cast<int>(*ebx), static_cast<int>(*ecx), static_cast<int>(*edx)};
__cpuid(regs, level);
*eax = static_cast<uint32_t>(regs[0]);
*ebx = static_cast<uint32_t>(regs[1]);
*ecx = static_cast<uint32_t>(regs[2]);
*edx = static_cast<uint32_t>(regs[3]);
# else
__get_cpuid(level, eax, ebx, ecx, edx);
# endif
}
/**
* @brief Get GNA module frequency
* @return GNA module frequency in MHz
*/
float get_gna_frequency_mHz() {
uint32_t eax = 1;
uint32_t ebx = 0;
uint32_t ecx = 0;
uint32_t edx = 0;
uint32_t family = 0;
uint32_t model = 0;
const uint8_t sixth_family = 6;
const uint8_t cannon_lake_model = 102;
const uint8_t gemini_lake_model = 122;
const uint8_t ice_lake_model = 126;
const uint8_t tgl_model = 140;
const uint8_t next_model = 151;
native_cpuid(&eax, &ebx, &ecx, &edx);
family = (eax >> 8) & 0xF;
// model is the concatenation of two fields
// | extended model | model |
// copy extended model data
model = (eax >> 16) & 0xF;
// shift
model <<= 4;
// copy model data
model += (eax >> 4) & 0xF;
if (family == sixth_family) {
switch (model) {
case cannon_lake_model:
case ice_lake_model:
case tgl_model:
case next_model:
return 400;
case gemini_lake_model:
return 200;
default:
return 1;
}
} else {
// counters not supported and we returns just default value
return 1;
}
}
#endif // if not ARM
/**
* @brief Print a report on the statistical score error
* @param totalError reference to a total score error struct
* @param framesNum number of frames in utterance
* @param stream output stream
* @return none.
*/
void print_reference_compare_results(ScoreErrorT const& totalError, size_t framesNum, std::ostream& stream) {
stream << " max error: " << totalError.maxError << std::endl;
stream << " avg error: " << totalError.sumError / totalError.numScores << std::endl;
stream << " avg rms error: " << totalError.sumRmsError / framesNum << std::endl;
stream << " stdev error: " << std_dev_error(totalError) << std::endl << std::endl;
stream << std::endl;
}
/**
* @brief Print a report on the performance counts
* @param utterancePerfMap reference to a map to store performance counters
* @param numberOfFrames number of frames
* @param stream output stream
* @param fullDeviceName full device name string
* @param numberOfFramesOnHw number of frames delivered to GNA HW
* @param FLAGS_d flag of device
* @return none.
*/
void print_performance_counters(std::map<std::string, ov::runtime::ProfilingInfo> const& utterancePerfMap,
size_t numberOfFrames,
std::ostream& stream,
std::string fullDeviceName,
const uint64_t numberOfFramesOnHw,
std::string FLAGS_d) {
#if !defined(__arm__) && !defined(_M_ARM) && !defined(__aarch64__) && !defined(_M_ARM64)
stream << std::endl << "Performance counts:" << std::endl;
stream << std::setw(10) << std::right << ""
<< "Counter descriptions";
stream << std::setw(22) << "Utt scoring time";
stream << std::setw(18) << "Avg infer time";
stream << std::endl;
stream << std::setw(46) << "(ms)";
stream << std::setw(24) << "(us per call)";
stream << std::endl;
// if GNA HW counters
// get frequency of GNA module
float freq = get_gna_frequency_mHz();
for (const auto& it : utterancePerfMap) {
std::string const& counter_name = it.first;
float current_units_us = static_cast<float>(it.second.real_time.count()) / freq;
float call_units_us = current_units_us / numberOfFrames;
if (FLAGS_d.find("GNA") != std::string::npos) {
stream << std::setw(30) << std::left << counter_name.substr(4, counter_name.size() - 1);
} else {
stream << std::setw(30) << std::left << counter_name;
}
stream << std::setw(16) << std::right << current_units_us / 1000;
stream << std::setw(21) << std::right << call_units_us;
stream << std::endl;
}
stream << std::endl;
std::cout << std::endl;
std::cout << "Full device name: " << fullDeviceName << std::endl;
std::cout << std::endl;
stream << "Number of frames delivered to GNA HW: " << numberOfFramesOnHw;
stream << "/" << numberOfFrames;
stream << std::endl;
#endif
}
/**
* @brief Get performance counts
* @param request reference to infer request
* @param perfCounters reference to a map to save performance counters
* @return none.
*/
void get_performance_counters(ov::runtime::InferRequest& request,
std::map<std::string, ov::runtime::ProfilingInfo>& perfCounters) {
auto retPerfCounters = request.get_profiling_info();
for (const auto& element : retPerfCounters) {
perfCounters[element.node_name] = element;
}
}
/**
* @brief Summarize performance counts and total number of frames executed on the GNA HW device
* @param perfCounters reference to a map to get performance counters
* @param totalPerfCounters reference to a map to save total performance counters
* @param totalRunsOnHw reference to a total number of frames computed on GNA HW
* @return none.
*/
void sum_performance_counters(std::map<std::string, ov::runtime::ProfilingInfo> const& perfCounters,
std::map<std::string, ov::runtime::ProfilingInfo>& totalPerfCounters,
uint64_t& totalRunsOnHw) {
auto runOnHw = false;
for (const auto& pair : perfCounters) {
totalPerfCounters[pair.first].real_time += pair.second.real_time;
runOnHw |= pair.second.real_time > std::chrono::microseconds(0); // if realTime is above zero, that means that
// a primitive was executed on the device
}
totalRunsOnHw += runOnHw;
}
/**
* @brief Parse scale factors
* @param str reference to user-specified input scale factor for quantization, can be separated by comma
* @return vector scale factors
*/
std::vector<std::string> parse_scale_factors(const std::string& str) {
std::vector<std::string> scaleFactorInput;
if (!str.empty()) {
std::string outStr;
std::istringstream stream(str);
int i = 0;
while (getline(stream, outStr, ',')) {
auto floatScaleFactor = std::stof(outStr);
if (floatScaleFactor <= 0.0f) {
throw std::logic_error("Scale factor for input #" + std::to_string(i) +
" (counting from zero) is out of range (must be positive).");
}
scaleFactorInput.push_back(outStr);
i++;
}
} else {
throw std::logic_error("Scale factor need to be specified via -sf option if you are using -q user");
}
return scaleFactorInput;
}
/**
* @brief Parse string of file names separated by comma to save it to vector of file names
* @param str file names separated by comma
* @return vector of file names
*/
std::vector<std::string> convert_str_to_vector(std::string str) {
std::vector<std::string> blobName;
if (!str.empty()) {
size_t pos_last = 0;
size_t pos_next = 0;
while ((pos_next = str.find(",", pos_last)) != std::string::npos) {
blobName.push_back(str.substr(pos_last, pos_next - pos_last));
pos_last = pos_next + 1;
}
blobName.push_back(str.substr(pos_last));
}
return blobName;
}
| 34.818182 | 119 | 0.625785 |
d5d671096613999c8361fe4ffe4bb6205b5e5b3f | 270 | c | C | C language/class/last/large than ever.c | Yibotian-true/Fanta-sea | 52fc3fb8e6ce4591d07ba21b2456f8472d3c5b3c | [
"MIT"
] | null | null | null | C language/class/last/large than ever.c | Yibotian-true/Fanta-sea | 52fc3fb8e6ce4591d07ba21b2456f8472d3c5b3c | [
"MIT"
] | null | null | null | C language/class/last/large than ever.c | Yibotian-true/Fanta-sea | 52fc3fb8e6ce4591d07ba21b2456f8472d3c5b3c | [
"MIT"
] | null | null | null | //超长数(近百位数字)的处理
//非十进制数的处理--存到数组里面按竖式运算一样一位一位处理
//链表与数组是使用指针存放数据的不同方式 各有利弊
//桶排序:利用数组下标排列数据的方式,典型的以空间换时间,数字有多大,数组就要多大(用下标的数组还是声明成char吧)
//处理文件需要用到很多函数,需要的时候再翻吧,但是要知道一个特定的的功能可以用一个标准库里的函数来实现
//指针的更多使用方式:malloc与free,更面向内存
// C primer plus 的结束只是C语言的开始,溯洄从之,道阻且长
// C++? C++! | 33.75 | 60 | 0.807407 |
476d791e50110e17326cb9d11db01612f6991ba6 | 50 | sql | SQL | src/main/resources/org/support/project/web/dao/sql/RolesDao/RolesDao_select_count_all.sql | kuro-channel/knowledge-1 | 6f74162ad54af961fb5069a27f49959b9e9a8048 | [
"Apache-2.0"
] | 742 | 2015-02-03T02:02:15.000Z | 2022-03-15T16:54:25.000Z | src/main/resources/org/support/project/web/dao/sql/RolesDao/RolesDao_select_count_all.sql | kuro-channel/knowledge-1 | 6f74162ad54af961fb5069a27f49959b9e9a8048 | [
"Apache-2.0"
] | 760 | 2015-02-01T11:40:05.000Z | 2022-01-21T23:22:06.000Z | src/main/resources/org/support/project/web/dao/sql/RolesDao/RolesDao_select_count_all.sql | kuro-channel/knowledge-1 | 6f74162ad54af961fb5069a27f49959b9e9a8048 | [
"Apache-2.0"
] | 285 | 2015-02-23T08:02:29.000Z | 2022-03-25T02:48:31.000Z | SELECT COUNT(*) FROM ROLES
WHERE DELETE_FLAG = 0;
| 16.666667 | 26 | 0.74 |
69cdc2b37af8cbf984cb48265efd0fdbc6d636c4 | 5,123 | swift | Swift | SexyColor.Swift/Classes/Mall/Controller/Goods/CommodityDetailsCommentViewController.swift | lxkbest/SexyColor.Swift | b32eed4b5939f8846d372ea63e679d68acff17fe | [
"Apache-2.0"
] | 3 | 2018-06-09T10:38:49.000Z | 2020-06-26T10:07:29.000Z | SexyColor.Swift/Classes/Mall/Controller/Goods/CommodityDetailsCommentViewController.swift | lxkbest/SexyColor.Swift | b32eed4b5939f8846d372ea63e679d68acff17fe | [
"Apache-2.0"
] | null | null | null | SexyColor.Swift/Classes/Mall/Controller/Goods/CommodityDetailsCommentViewController.swift | lxkbest/SexyColor.Swift | b32eed4b5939f8846d372ea63e679d68acff17fe | [
"Apache-2.0"
] | null | null | null | //
// CommodityDetailsCommentViewController.swift
// SexyColor.Swift
//
// Created by kayzhang on 2017/8/31.
// Copyright © 2017年 薛凯凯圆滚滚. All rights reserved.
//商品详情-评论
import UIKit
import MJRefresh
class CommodityDetailsCommentViewController: BaseViewController {
fileprivate var tableView : UITableView!
fileprivate var model : GoodsCommentModel?
override func viewDidLoad() {
super.viewDidLoad()
InitUI()
loadNewData()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func InitUI() {
tableView = UITableView(frame: CGRect.zero, style: .plain)
tableView.register(CommodityDetailsCommodityEvaluationCell.self, forCellReuseIdentifier: "CommodityDetailsCommodityEvaluationCell")
tableView.dataSource = self
tableView.delegate = self
tableView.showsVerticalScrollIndicator = false
tableView.backgroundColor = GlobalColor
tableView.separatorColor = UIColor.colorWithHexString(hex: "FAF0E6")
tableView.separatorInset = UIEdgeInsetsMake(-ScreenHeight, 0, 0, 0)
tableView.estimatedRowHeight = 80
tableView.rowHeight = UITableViewAutomaticDimension
view.addSubview(tableView)
tableView.snp.makeConstraints { (make) in
make.top.equalTo(view)
make.leading.equalTo(view)
make.trailing.equalTo(view)
make.bottom.equalTo(view).offset(-NavigationH - 45)
}
let header = MJRefreshGifHeader()
header.setRefreshingTarget(self, refreshingAction: #selector(headerRefresh))
var idleImages = [UIImage]()
idleImages.append(UIImage(named:"loading_10")!)
for i in 1...7 {
idleImages.append(UIImage(named:"loading_\(i)")!)
}
header.setImages(idleImages, for: .idle)
var pullingImages = [UIImage]()
for i in 7...8 {
pullingImages.append(UIImage(named:"loading_\(i)")!)
}
header.setImages(pullingImages, for: .pulling)
//刷新状态下的图片集合(定时自动改变)
var refreshingImages = [UIImage]()
for i in 9...10 {
refreshingImages.append(UIImage(named:"loading_\(i)")!)
}
header.setImages(refreshingImages, for: .refreshing)
header.lastUpdatedTimeLabel.isHidden = true
header.stateLabel.isHidden = true
tableView.mj_header = header
tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(footerRefresh))
tableView.mj_footer.isHidden = true
}
func loadNewData() {
ProgressHUD.show()
if AppDelegate.netWorkState == .notReachable {
ProgressHUD.dismiss()
showBaseView()
return
}
let delay = DispatchTime.now() + .seconds(1)
DispatchQueue.main.asyncAfter(deadline: delay) {
ProgressHUD.dismiss()
GoodsCommentData.loadCommodity(completion: { [weak self] (model) in
self!.model = model.data
self?.tableView.reloadData()
self?.tableView.mj_footer.isHidden = false
})
}
}
func footerRefresh() {
ProgressHUD.show()
if AppDelegate.netWorkState == .notReachable {
ProgressHUD.dismiss()
showBaseView()
return
}
let delay = DispatchTime.now() + .seconds(1)
DispatchQueue.main.asyncAfter(deadline: delay) {
ProgressHUD.dismiss()
GoodsCommentData.loadCommodity(completion: { [weak self] (model) in
for item in model.data!.comment_list! {
self!.model?.comment_list?.append(item)
}
self?.tableView.reloadData()
self?.tableView.mj_footer.endRefreshing()
})
}
}
// 顶部刷新
func headerRefresh(){
print("下拉刷新")
// 结束刷新
tableView.mj_header.endRefreshing()
}
}
extension CommodityDetailsCommentViewController : UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if model != nil {
return (model?.comment_list!.count)!
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell?
cell = tableView.dequeueReusableCell(withIdentifier: "CommodityDetailsCommodityEvaluationCell", for: indexPath) as? CommodityDetailsCommodityEvaluationCell
(cell as! CommodityDetailsCommodityEvaluationCell).CommodityEvaluationData = model?.comment_list![indexPath.row]
return cell!
}
}
| 32.839744 | 163 | 0.618192 |
2e2558f3c6cefddeaf054fdb31c2b053348bdfe1 | 1,181 | sql | SQL | tables/table-create-alter/script_table_creation1.sql | dit-mark-team/mssql-server-standards | 3a5d6e9fff5b046671d14ada445889987755fda0 | [
"MIT"
] | 1 | 2020-02-12T16:49:30.000Z | 2020-02-12T16:49:30.000Z | tables/table-create-alter/script_table_creation1.sql | dit-mark-team/mssql-server-standards | 3a5d6e9fff5b046671d14ada445889987755fda0 | [
"MIT"
] | null | null | null | tables/table-create-alter/script_table_creation1.sql | dit-mark-team/mssql-server-standards | 3a5d6e9fff5b046671d14ada445889987755fda0 | [
"MIT"
] | null | null | null | --================================================================
-- Tabela.........: table_name
-- Modulo(s)......: nome_modulo(s)
-- Programador....: nome_programador
-- Descritivo.....: descricao_tabela
--================================================================
use master
go
use database_name
go
if object_id('table_name') is null
create table dbo.table_name(campo_tabela int)
go
if not exists(select 1 from sys.columns s where s.object_id=OBJECT_ID('table_name')and s.name='campo_tabela')
alter table table_name add campo_tabela varchar(50) --descritivo_do_campo
go
if not exists(select 1 from sys.columns s where s.object_id=OBJECT_ID('table_name')and s.name='campo_tabela')
alter table table_name add campo_tabela int --descritivo_do_campo
go
if not exists(select 1 from sys.columns s where s.object_id=OBJECT_ID('table_name')and s.name='campo_tabela')
alter table table_name add campo_tabela int --descritivo_do_campo
go
--//criacao de indices clusters
if exists(select 1 from sys.indexes s where s.name='id_index_000')
drop index id_index_000 on table_name
go
create unique clustered index id_index_000 on table_name(campo_tabela);
go
| 36.90625 | 109 | 0.680779 |
904ba8eccbda391a00dbef97b00866cf27e8e36e | 1,209 | py | Python | wikilabels/utilities/task_inserts.py | aryan040501/wikilabels | ea110da2b969cc978a0f288c4da6250dc9d67e72 | [
"MIT"
] | 15 | 2015-07-16T17:56:43.000Z | 2018-08-20T14:59:16.000Z | wikilabels/utilities/task_inserts.py | aryan040501/wikilabels | ea110da2b969cc978a0f288c4da6250dc9d67e72 | [
"MIT"
] | 122 | 2015-06-10T15:58:11.000Z | 2018-08-16T14:56:23.000Z | wikilabels/utilities/task_inserts.py | aryan040501/wikilabels | ea110da2b969cc978a0f288c4da6250dc9d67e72 | [
"MIT"
] | 27 | 2015-07-15T22:12:35.000Z | 2018-08-06T23:10:28.000Z | """
Inserts a set of tasks into a campaign
Usage:
load_tasks -h | --help
load_tasks <campaign-id> [--config=<path>]
Arguments:
<campaign-id> The campaign that the tasks should be associated with
Options:
-h --help Prints this documentation
--config=<path> Path to a config directory to use when connecting
to the database [default: config/]
"""
import glob
import json
import logging
import os
import sys
import docopt
import yamlconf
from ..database import DB, NotFoundError
logger = logging.getLogger(__name__)
def main(argv=None):
args = docopt.docopt(__doc__, argv=argv)
campaign_id = int(args['<campaign-id>'])
tasks = (json.loads(line) for line in sys.stdin)
config_paths = os.path.join(args['--config'], "*.yaml")
config = yamlconf.load(
*(open(p) for p in sorted(glob.glob(config_paths))))
db = DB.from_config(config)
run(db, campaign_id, tasks)
def run(db, campaign_id, tasks):
# Confirm that campaign exists
try:
db.campaigns.get(campaign_id)
except NotFoundError as e:
logger.error(e)
return
# Load tasks into campaign
db.tasks.load(tasks, campaign_id)
| 21.981818 | 72 | 0.664185 |
22e1ec2bd3b3df529b54a428cb835a7528daa1d8 | 783 | c | C | Set Matrix Zeroes /setZeroes.c | somnusfish/leetcode | eae387efd76159bc63948235fd1cb7d56f45335e | [
"MIT"
] | 3 | 2015-07-29T08:28:33.000Z | 2016-04-23T11:35:33.000Z | Set Matrix Zeroes /setZeroes.c | somnusfish/leetcode | eae387efd76159bc63948235fd1cb7d56f45335e | [
"MIT"
] | null | null | null | Set Matrix Zeroes /setZeroes.c | somnusfish/leetcode | eae387efd76159bc63948235fd1cb7d56f45335e | [
"MIT"
] | null | null | null | void setZeroes(int **matrix, int m, int n) {
bool *rowm;
bool *coln;
int i;
int j;
rowm = (bool *)malloc(sizeof(bool)*m);
coln = (bool *)malloc(sizeof(bool)*n);
for(i=0; i<m; i++){
rowm[i] = false;
}
for(i=0; i<n; i++){
coln[i] = false;
}
for(i=0; i<m; i++){
for(j=0; j<n; j++){
if(matrix[i][j]==0){
rowm[i] = true;
coln[j] = true;
}
}
}
for(i=0; i<m; i++){
if(rowm[i]){
for(j=0; j<n; j++){
matrix[i][j] = 0;
}
}
}
for(j=0; j<n; j++){
if(coln[j]){
for(i=0; i<m; i++){
matrix[i][j] = 0;
}
}
}
}
| 18.642857 | 44 | 0.318008 |
c171c4656f8f2933de27369002c283df7eb40ef2 | 9,901 | rs | Rust | r528-pac/src/uart0/lsr.rs | duskmoon314/aw-pac | b6ac4bbfdcf671dc2512281e226094b7be933ebe | [
"Apache-2.0",
"MIT"
] | 7 | 2021-12-21T10:15:37.000Z | 2022-02-20T14:16:47.000Z | r528-pac/src/uart3/lsr.rs | duskmoon314/d1-pac | 30db8b83ceeaf5c1b4fd331c2ad6e0697cbd7c76 | [
"Apache-2.0",
"MIT"
] | 1 | 2022-03-08T01:52:26.000Z | 2022-03-08T01:52:26.000Z | xr806-pac/src/uart2/lsr.rs | duskmoon314/aw-pac | b6ac4bbfdcf671dc2512281e226094b7be933ebe | [
"Apache-2.0",
"MIT"
] | 2 | 2022-01-16T23:05:17.000Z | 2022-02-13T11:43:01.000Z | #[doc = "Register `LSR` reader"]
pub struct R(crate::R<LSR_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<LSR_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<LSR_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<LSR_SPEC>) -> Self {
R(reader)
}
}
#[doc = "RX Data Error in FIFO\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FIFOERR_A {
#[doc = "1: `1`"]
ERROR = 1,
}
impl From<FIFOERR_A> for bool {
#[inline(always)]
fn from(variant: FIFOERR_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `fifoerr` reader - RX Data Error in FIFO"]
pub struct FIFOERR_R(crate::FieldReader<bool, FIFOERR_A>);
impl FIFOERR_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
FIFOERR_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<FIFOERR_A> {
match self.bits {
true => Some(FIFOERR_A::ERROR),
_ => None,
}
}
#[doc = "Checks if the value of the field is `ERROR`"]
#[inline(always)]
pub fn is_error(&self) -> bool {
**self == FIFOERR_A::ERROR
}
}
impl core::ops::Deref for FIFOERR_R {
type Target = crate::FieldReader<bool, FIFOERR_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Transmitter Empty\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TEMT_A {
#[doc = "1: `1`"]
EMPTY = 1,
}
impl From<TEMT_A> for bool {
#[inline(always)]
fn from(variant: TEMT_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `temt` reader - Transmitter Empty"]
pub struct TEMT_R(crate::FieldReader<bool, TEMT_A>);
impl TEMT_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
TEMT_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<TEMT_A> {
match self.bits {
true => Some(TEMT_A::EMPTY),
_ => None,
}
}
#[doc = "Checks if the value of the field is `EMPTY`"]
#[inline(always)]
pub fn is_empty(&self) -> bool {
**self == TEMT_A::EMPTY
}
}
impl core::ops::Deref for TEMT_R {
type Target = crate::FieldReader<bool, TEMT_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "TX Holding Register Empty\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum THRE_A {
#[doc = "1: `1`"]
EMPTY = 1,
}
impl From<THRE_A> for bool {
#[inline(always)]
fn from(variant: THRE_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `thre` reader - TX Holding Register Empty"]
pub struct THRE_R(crate::FieldReader<bool, THRE_A>);
impl THRE_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
THRE_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<THRE_A> {
match self.bits {
true => Some(THRE_A::EMPTY),
_ => None,
}
}
#[doc = "Checks if the value of the field is `EMPTY`"]
#[inline(always)]
pub fn is_empty(&self) -> bool {
**self == THRE_A::EMPTY
}
}
impl core::ops::Deref for THRE_R {
type Target = crate::FieldReader<bool, THRE_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `bi` reader - Break Interrupt"]
pub struct BI_R(crate::FieldReader<bool, bool>);
impl BI_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
BI_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for BI_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Framing Error\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FE_A {
#[doc = "1: `1`"]
ERROR = 1,
}
impl From<FE_A> for bool {
#[inline(always)]
fn from(variant: FE_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `fe` reader - Framing Error"]
pub struct FE_R(crate::FieldReader<bool, FE_A>);
impl FE_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
FE_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<FE_A> {
match self.bits {
true => Some(FE_A::ERROR),
_ => None,
}
}
#[doc = "Checks if the value of the field is `ERROR`"]
#[inline(always)]
pub fn is_error(&self) -> bool {
**self == FE_A::ERROR
}
}
impl core::ops::Deref for FE_R {
type Target = crate::FieldReader<bool, FE_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Parity Error\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PE_A {
#[doc = "1: `1`"]
ERROR = 1,
}
impl From<PE_A> for bool {
#[inline(always)]
fn from(variant: PE_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `pe` reader - Parity Error"]
pub struct PE_R(crate::FieldReader<bool, PE_A>);
impl PE_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
PE_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<PE_A> {
match self.bits {
true => Some(PE_A::ERROR),
_ => None,
}
}
#[doc = "Checks if the value of the field is `ERROR`"]
#[inline(always)]
pub fn is_error(&self) -> bool {
**self == PE_A::ERROR
}
}
impl core::ops::Deref for PE_R {
type Target = crate::FieldReader<bool, PE_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Overrun Error\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum OE_A {
#[doc = "1: `1`"]
ERROR = 1,
}
impl From<OE_A> for bool {
#[inline(always)]
fn from(variant: OE_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `oe` reader - Overrun Error"]
pub struct OE_R(crate::FieldReader<bool, OE_A>);
impl OE_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
OE_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<OE_A> {
match self.bits {
true => Some(OE_A::ERROR),
_ => None,
}
}
#[doc = "Checks if the value of the field is `ERROR`"]
#[inline(always)]
pub fn is_error(&self) -> bool {
**self == OE_A::ERROR
}
}
impl core::ops::Deref for OE_R {
type Target = crate::FieldReader<bool, OE_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Data Ready\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum DR_A {
#[doc = "1: `1`"]
READY = 1,
}
impl From<DR_A> for bool {
#[inline(always)]
fn from(variant: DR_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `dr` reader - Data Ready"]
pub struct DR_R(crate::FieldReader<bool, DR_A>);
impl DR_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
DR_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<DR_A> {
match self.bits {
true => Some(DR_A::READY),
_ => None,
}
}
#[doc = "Checks if the value of the field is `READY`"]
#[inline(always)]
pub fn is_ready(&self) -> bool {
**self == DR_A::READY
}
}
impl core::ops::Deref for DR_R {
type Target = crate::FieldReader<bool, DR_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl R {
#[doc = "Bit 7 - RX Data Error in FIFO"]
#[inline(always)]
pub fn fifoerr(&self) -> FIFOERR_R {
FIFOERR_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 6 - Transmitter Empty"]
#[inline(always)]
pub fn temt(&self) -> TEMT_R {
TEMT_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 5 - TX Holding Register Empty"]
#[inline(always)]
pub fn thre(&self) -> THRE_R {
THRE_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 4 - Break Interrupt"]
#[inline(always)]
pub fn bi(&self) -> BI_R {
BI_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 3 - Framing Error"]
#[inline(always)]
pub fn fe(&self) -> FE_R {
FE_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 2 - Parity Error"]
#[inline(always)]
pub fn pe(&self) -> PE_R {
PE_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 1 - Overrun Error"]
#[inline(always)]
pub fn oe(&self) -> OE_R {
OE_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 0 - Data Ready"]
#[inline(always)]
pub fn dr(&self) -> DR_R {
DR_R::new((self.bits & 0x01) != 0)
}
}
#[doc = "UART Line Status Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [lsr](index.html) module"]
pub struct LSR_SPEC;
impl crate::RegisterSpec for LSR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [lsr::R](R) reader structure"]
impl crate::Readable for LSR_SPEC {
type Reader = R;
}
#[doc = "`reset()` method sets LSR to value 0"]
impl crate::Resettable for LSR_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| 26.831978 | 231 | 0.555095 |
e8403f9b46c274c3536681d32289a1ec6cc42512 | 4,458 | cpp | C++ | Client/CCrashHandler.cpp | LHMPTeam/lhmp-old | 84dd379ab8ae59418135c940e700f3022339e136 | [
"Apache-2.0"
] | 8 | 2017-02-13T13:29:39.000Z | 2022-01-12T17:12:04.000Z | Client/CCrashHandler.cpp | LHMPTeam/lhmp-old | 84dd379ab8ae59418135c940e700f3022339e136 | [
"Apache-2.0"
] | null | null | null | Client/CCrashHandler.cpp | LHMPTeam/lhmp-old | 84dd379ab8ae59418135c940e700f3022339e136 | [
"Apache-2.0"
] | 10 | 2017-01-14T09:41:06.000Z | 2021-10-10T00:02:32.000Z | // (C) LHMP Team 2013-2016; Licensed under Apache 2; See LICENSE;;
#include "CCrashHandler.h"
#include "CCore.h"
#include <psapi.h>
#include <Windows.h>
#include "../shared/version.h"
#include <fstream>
#include <iostream>
extern CCore* g_CCore;
void GetAdressAsModule(DWORD addr, char* outbuffer)
{
HMODULE hMods[512];
HANDLE hProcess = GetCurrentProcess();
DWORD cbNeeded;
unsigned int i;
DWORD close = 0x0;
if (EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded))
{
for (i = 0; i < (cbNeeded / sizeof(HMODULE)); i++)
{
if (addr - (DWORD)hMods[i] < addr - close)
close = (DWORD)hMods[i];
}
if (close != NULL)
{
TCHAR szModName[MAX_PATH];
if (GetModuleBaseName(hProcess, (HMODULE)close, szModName,
sizeof(szModName) / sizeof(TCHAR)))
{
sprintf(outbuffer, "%s+0x%p", szModName, (addr - close));
return;
}
}
else {
sprintf(outbuffer, "UNKNOWN");
}
}
}
/**
Handles exception call.
Saves register information on disk and run CrashHandler.exe,
* which sends crash report to our server
*/
LONG HandleIt(struct _EXCEPTION_POINTERS * ExceptionInfo)
{
char buff[500];
char address[100];
GetAdressAsModule((DWORD)ExceptionInfo->ExceptionRecord->ExceptionAddress, address);
sprintf(buff, "Crash occured at address: %p Code: %x \nRegisters: \n"
"EAX: %p \tECX: %p \n"
"EDX: %p \tEBX: %p \n"
"ESP: %p \tEBP: %p \n"
"ESI: %p \tEDI : %p \n"
"Module: %s\n"
"You will find these information in lhmp/crashdump.txt",ExceptionInfo->ExceptionRecord->ExceptionAddress,
ExceptionInfo->ExceptionRecord->ExceptionCode, ExceptionInfo->ContextRecord->Eax,
ExceptionInfo->ContextRecord->Ecx, ExceptionInfo->ContextRecord->Edx, ExceptionInfo->ContextRecord->Ebx,
ExceptionInfo->ContextRecord->Esp, ExceptionInfo->ContextRecord->Ebp, ExceptionInfo->ContextRecord->Esi,
ExceptionInfo->ContextRecord->Edi,address);
//g_CCore->GetCrashHandler()->SaveDumpOnDisk(buff);
STARTUPINFOA siStartupInfo;
PROCESS_INFORMATION piProcessInfo;
memset(&siStartupInfo, 0, sizeof(siStartupInfo));
memset(&piProcessInfo, 0, sizeof(piProcessInfo));
siStartupInfo.cb = sizeof(siStartupInfo);
sprintf(buff, "CrashHandler.exe %p|%p@%p@%p@%p@%p@%p@%p@%p|%s|%s",
ExceptionInfo->ExceptionRecord->ExceptionAddress,
ExceptionInfo->ContextRecord->Eax,
ExceptionInfo->ContextRecord->Ecx, ExceptionInfo->ContextRecord->Edx, ExceptionInfo->ContextRecord->Ebx,
ExceptionInfo->ContextRecord->Esp, ExceptionInfo->ContextRecord->Ebp, ExceptionInfo->ContextRecord->Esi,
ExceptionInfo->ContextRecord->Edi, address,LHMP_VERSION_TEST_HASH);
if (!CreateProcessA(NULL,
buff, 0, 0, false,
CREATE_SUSPENDED, 0, 0,
&siStartupInfo, &piProcessInfo)) {
MessageBoxA(NULL, "Creating proccess failed !", "Error", MB_OK);
}
DWORD pId = piProcessInfo.dwProcessId;
ResumeThread(piProcessInfo.hThread);
return 0;
}
LONG WINAPI CrashExceptionFilter(struct _EXCEPTION_POINTERS *ExceptionInfo)
{
HandleIt(ExceptionInfo);
return EXCEPTION_EXECUTE_HANDLER;
}
void CCrashHandler::Prepare()
{
SetUnhandledExceptionFilter(CrashExceptionFilter);
}
void CCrashHandler::SaveDumpOnDisk(char* str)
{
FILE* log = fopen("lhmp/crashdump.txt", "a");
if (log)
{
fprintf(log, "---\nMINIDUMP\n%s\n",str);
fclose(log);
}
}
void CCrashHandler::SendReport(char* report){
TCPInterface TCP;
if (TCP.Start(0, 0) == false)
return;
SystemAddress server;
server = TCP.Connect("lh-mp.eu", 80, true);
if (server != UNASSIGNED_SYSTEM_ADDRESS) // if we are connected
{
std::string mod = report;
for (size_t pos = mod.find(' ');
pos != std::string::npos;
pos = mod.find(' ', pos))
{
mod.replace(pos, 1, "+");
}
std::string nick = g_CCore->GetLocalPlayer()->GetNickname();
for (size_t pos = nick.find(' ');
pos != std::string::npos;
pos = nick.find(' ', pos))
{
nick.replace(pos, 1, "+");
}
char postRequest[2048] = "";
RakNet::TimeMS TS = RakNet::GetTimeMS();
char data[1024] = "";
sprintf_s(data, "hash=%s&time=%d&dump=%s&nick=%s", LHMP_VERSION_TEST_HASH, (int)TS, mod.c_str(),nick.c_str());
sprintf_s(postRequest,
"POST /query/crash.php HTTP/1.1\r\n"
"Content-Type: application/x-www-form-urlencoded\r\n"
"Content-Length: %d\r\n"
"Host: lh-mp.eu\r\n\r\n"
"%s\r\n", strlen(data), data);
TCP.Send(postRequest, strlen(postRequest), server, false);
while (TCP.ReceiveHasPackets() == false)
RakSleep(10);
RakNet::Packet* pack = TCP.Receive();
}
} | 29.328947 | 112 | 0.696725 |
97cb58416bbafda8e02f00d7746545445fdef4c3 | 4,780 | swift | Swift | Provenance/Sources/CollectionViewCells/TransactionCell.swift | themuzzleflare/Provenance | f356e598107b3a5ac0beb890d5a5807bd84444be | [
"MIT"
] | null | null | null | Provenance/Sources/CollectionViewCells/TransactionCell.swift | themuzzleflare/Provenance | f356e598107b3a5ac0beb890d5a5807bd84444be | [
"MIT"
] | null | null | null | Provenance/Sources/CollectionViewCells/TransactionCell.swift | themuzzleflare/Provenance | f356e598107b3a5ac0beb890d5a5807bd84444be | [
"MIT"
] | null | null | null | import SnapKit
import IGListKit
import UIKit
final class TransactionCell: UICollectionViewCell {
// MARK: - Properties
private let transactionDescriptionLabel = UILabel()
private let transactionCreationDateLabel = UILabel()
private let transactionAmountLabel = UILabel()
private let verticalStack = UIStackView()
private let horizontalStack = UIStackView()
private let separator = CALayer.separator
private(set) var transactionDescription: String? {
get {
return transactionDescriptionLabel.text
}
set {
transactionDescriptionLabel.text = newValue
}
}
private(set) var transactionCreationDate: String? {
get {
return transactionCreationDateLabel.text
}
set {
transactionCreationDateLabel.text = newValue
}
}
private(set) var transactionAmount: String? {
get {
return transactionAmountLabel.text
}
set {
transactionAmountLabel.text = newValue
}
}
private(set) var transactionAmountColour: UIColor? {
get {
return transactionAmountLabel.textColor
}
set {
transactionAmountLabel.textColor = newValue
}
}
// MARK: - Life Cycle
override func layoutSubviews() {
super.layoutSubviews()
separator.frame = CGRect(x: 0, y: contentView.bounds.height - 0.5, width: contentView.bounds.width, height: 0.5)
}
override var isSelected: Bool {
didSet {
contentView.backgroundColor = isSelected ? .gray.withAlphaComponent(0.3) : .clear
}
}
override var isHighlighted: Bool {
didSet {
contentView.backgroundColor = isHighlighted ? .gray.withAlphaComponent(0.3) : .clear
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
guard previousTraitCollection?.userInterfaceStyle != traitCollection.userInterfaceStyle else { return }
separator.backgroundColor = .separator
}
}
// MARK: - Configuration
extension TransactionCell {
private func configureContentView() {
contentView.addSubview(horizontalStack)
contentView.layer.addSublayer(separator)
}
private func configureTransactionDescription() {
transactionDescriptionLabel.font = .circularStdBold(size: .labelFontSize)
transactionDescriptionLabel.textAlignment = .left
transactionDescriptionLabel.numberOfLines = 0
}
private func configureTransactionCreationDate() {
transactionCreationDateLabel.font = .circularStdBook(size: .smallSystemFontSize)
transactionCreationDateLabel.textAlignment = .left
transactionCreationDateLabel.numberOfLines = 0
transactionCreationDateLabel.textColor = .secondaryLabel
}
private func configureTransactionAmount() {
transactionAmountLabel.font = .circularStdBook(size: .labelFontSize)
transactionAmountLabel.textAlignment = .right
transactionAmountLabel.numberOfLines = 0
}
private func configureVerticalStackView() {
verticalStack.addArrangedSubview(transactionDescriptionLabel)
verticalStack.addArrangedSubview(transactionCreationDateLabel)
verticalStack.axis = .vertical
verticalStack.alignment = .leading
}
private func configureHorizontalStackView() {
horizontalStack.snp.makeConstraints { (make) in
make.edges.equalToSuperview().inset(UIEdgeInsets.cellNode)
}
horizontalStack.addArrangedSubview(verticalStack)
horizontalStack.addArrangedSubview(transactionAmountLabel)
horizontalStack.alignment = .center
horizontalStack.distribution = .equalSpacing
}
}
// MARK: - ListBindable
extension TransactionCell: ListBindable {
func bindViewModel(_ viewModel: Any) {
guard let viewModel = viewModel as? TransactionCellModel else { return }
configureContentView()
configureTransactionDescription()
configureTransactionCreationDate()
configureTransactionAmount()
configureVerticalStackView()
configureHorizontalStackView()
transactionDescription = viewModel.transactionDescription
transactionCreationDate = viewModel.creationDate
transactionAmount = viewModel.amount
transactionAmountColour = viewModel.colour.uiColour
addInteraction(UIContextMenuInteraction(delegate: self))
}
}
// MARK: - UIContextMenuInteractionDelegate
extension TransactionCell: UIContextMenuInteractionDelegate {
func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
return UIContextMenuConfiguration(elements: [
.copyTransactionDescription(transaction: transactionDescription ?? ""),
.copyTransactionCreationDate(transaction: transactionCreationDate ?? ""),
.copyTransactionAmount(transaction: transactionAmount ?? "")
])
}
}
| 31.447368 | 153 | 0.758787 |
6c1487cd0af3ff76b11945a37813c10e288aa798 | 947 | go | Go | search.go | Sixeight/alfred-workflow-search-rubygems | dffe981f66444de1b0a048998c7b2faf14895dee | [
"MIT"
] | null | null | null | search.go | Sixeight/alfred-workflow-search-rubygems | dffe981f66444de1b0a048998c7b2faf14895dee | [
"MIT"
] | null | null | null | search.go | Sixeight/alfred-workflow-search-rubygems | dffe981f66444de1b0a048998c7b2faf14895dee | [
"MIT"
] | null | null | null | package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
)
type searchResult struct {
Name string `json:"name"`
Version string `json:"version"`
Info string `json:"info"`
ProjectURI string `json:"project_uri"`
HomePageURI string `json:"homepage_uri"`
DocumentationURI string `json:"documentation_uri"`
SourceCodeURI string `json:"source_code_uri"`
}
func search(query string) ([]*searchResult, error) {
escapedQuery := url.QueryEscape(query)
url := fmt.Sprintf("https://rubygems.org/api/v1/search.json?query=%s", escapedQuery)
resp, err := http.Get(url)
if err != nil {
log.Fatal(err)
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
return nil, err
}
var results []*searchResult
err = json.Unmarshal(body, &results)
if err != nil {
log.Fatal(err)
}
return results, nil
}
| 22.023256 | 85 | 0.657867 |
4431ea29c0153049502ab57433aba00f393ba5cc | 3,430 | dart | Dart | lib/src/model/generated/Id4meIdentity.g.dart | InterNetX/dart-domainrobot-sdk | 5d27966d9b124117250bf4c8d586679b6653b261 | [
"MIT"
] | 1 | 2020-03-13T08:57:26.000Z | 2020-03-13T08:57:26.000Z | lib/src/model/generated/Id4meIdentity.g.dart | InterNetX/dart-domainrobot-sdk | 5d27966d9b124117250bf4c8d586679b6653b261 | [
"MIT"
] | 4 | 2019-11-21T10:33:37.000Z | 2020-06-05T08:19:58.000Z | lib/src/model/generated/Id4meIdentity.g.dart | InterNetX/dart-domainrobot-sdk | 5d27966d9b124117250bf4c8d586679b6653b261 | [
"MIT"
] | 3 | 2019-11-21T20:35:02.000Z | 2020-03-19T11:24:36.000Z | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'Id4meIdentity.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
Id4meIdentity _$Id4meIdentityFromJson(Map<String, dynamic> json) {
return Id4meIdentity(
created: json['created'] == null
? null
: DateTime.parse(json['created'] as String),
updated: json['updated'] == null
? null
: DateTime.parse(json['updated'] as String),
owner: json['owner'] == null
? null
: BasicUser.fromJson(json['owner'] as Map<String, dynamic>),
updater: json['updater'] == null
? null
: BasicUser.fromJson(json['updater'] as Map<String, dynamic>),
agent: json['agent'] == null
? null
: Id4MeAgent.fromJson(json['agent'] as Map<String, dynamic>),
verifyExpire: json['verifyExpire'] == null
? null
: DateTime.parse(json['verifyExpire'] as String),
addons: json['addons'] == null
? null
: Configuration.fromJson(json['addons'] as Map<String, dynamic>),
magicLink: json['magicLink'] as String,
claims: json['claims'] == null
? null
: Claims.fromJson(json['claims'] as Map<String, dynamic>),
showClaims: json['showClaims'] as bool,
resetUrl: json['resetUrl'] as String,
resetUrlExpire: json['resetUrlExpire'] == null
? null
: DateTime.parse(json['resetUrlExpire'] as String),
name: json['name'] as String,
status: _$enumDecodeNullable(_$IdentityStatusEnumMap, json['status']),
language: json['language'] as String,
record: (json['record'] as List)?.map((e) => e as String)?.toList(),
);
}
Map<String, dynamic> _$Id4meIdentityToJson(Id4meIdentity instance) =>
<String, dynamic>{
'created': instance.created?.toIso8601String(),
'updated': instance.updated?.toIso8601String(),
'owner': instance.owner,
'updater': instance.updater,
'agent': instance.agent,
'verifyExpire': instance.verifyExpire?.toIso8601String(),
'addons': instance.addons,
'magicLink': instance.magicLink,
'claims': instance.claims,
'showClaims': instance.showClaims,
'resetUrl': instance.resetUrl,
'resetUrlExpire': instance.resetUrlExpire?.toIso8601String(),
'name': instance.name,
'status': _$IdentityStatusEnumMap[instance.status],
'language': instance.language,
'record': instance.record,
};
T _$enumDecode<T>(
Map<T, dynamic> enumValues,
dynamic source, {
T unknownValue,
}) {
if (source == null) {
throw ArgumentError('A value must be provided. Supported values: '
'${enumValues.values.join(', ')}');
}
final value = enumValues.entries
.singleWhere((e) => e.value == source, orElse: () => null)
?.key;
if (value == null && unknownValue == null) {
throw ArgumentError('`$source` is not one of the supported values: '
'${enumValues.values.join(', ')}');
}
return value ?? unknownValue;
}
T _$enumDecodeNullable<T>(
Map<T, dynamic> enumValues,
dynamic source, {
T unknownValue,
}) {
if (source == null) {
return null;
}
return _$enumDecode<T>(enumValues, source, unknownValue: unknownValue);
}
const _$IdentityStatusEnumMap = {
IdentityStatus.VERIFY: 'VERIFY',
IdentityStatus.SUCCESS: 'SUCCESS',
};
| 32.980769 | 77 | 0.605831 |
fe3b37bd12300413ff3b911bae69431f5d961c1a | 2,658 | cpp | C++ | Utility/WinAPI/StringUtils_WinAPI.cpp | yorung/XLE | 083ce4c9d3fe32002ff5168e571cada2715bece4 | [
"MIT"
] | 1 | 2016-06-01T10:41:12.000Z | 2016-06-01T10:41:12.000Z | Utility/WinAPI/StringUtils_WinAPI.cpp | yorung/XLE | 083ce4c9d3fe32002ff5168e571cada2715bece4 | [
"MIT"
] | null | null | null | Utility/WinAPI/StringUtils_WinAPI.cpp | yorung/XLE | 083ce4c9d3fe32002ff5168e571cada2715bece4 | [
"MIT"
] | null | null | null | // Copyright 2015 XLGAMES Inc.
//
// Distributed under the MIT License (See
// accompanying file "LICENSE" or the website
// http://www.opensource.org/licenses/mit-license.php)
#include "../StringUtils.h"
#include "../../Core/WinAPI/IncludeWindows.h"
namespace Utility
{
#if 0
size_t XlUtf8To16(ucs2* utf16, size_t count, const utf8* utf8)
{
return MultiByteToWideChar(CP_UTF8, 0, (LPCCH)utf8, -1, (wchar_t*)utf16, int(count));
}
size_t XlUtf16To8(utf8* utf8, size_t count, const ucs2* utf16)
{
return WideCharToMultiByte(CP_UTF8, 0, (const wchar_t*)utf16, -1, (LPSTR)utf8, int(count), 0, 0);
}
size_t XlMultiToCp(unsigned int codePage, char* dst, size_t count, const char* src)
{
static const int MAX_MULTI_TO_ACP_BUF_LEN = 512*7; // same as MAX_WARNING_LENGTH
wchar_t tmp[MAX_MULTI_TO_ACP_BUF_LEN];
MultiByteToWideChar(CP_UTF8, 0, src, -1, tmp, MAX_MULTI_TO_ACP_BUF_LEN);
return WideCharToMultiByte(codePage, 0, tmp, -1, dst, int(count), 0, 0);
}
size_t XlCpToMulti(unsigned int codePage, char* dst, size_t count, const char* src)
{
wchar_t tmp[4096];
if (count >= dimof(tmp)) {
return 0;
}
MultiByteToWideChar(codePage, 0, src, -1, tmp, int(count));
return WideCharToMultiByte(CP_UTF8, 0, tmp, -1, dst, int(count), 0, 0);
}
size_t XlMultiToAcp(char* dst, size_t count, const char* src)
{
static const int MAX_MULTI_TO_ACP_BUF_LEN = 512*7; // same as MAX_WARNING_LENGTH
wchar_t tmp[MAX_MULTI_TO_ACP_BUF_LEN];
MultiByteToWideChar(CP_UTF8, 0, src, -1, tmp, MAX_MULTI_TO_ACP_BUF_LEN);
return WideCharToMultiByte(CP_ACP, 0, tmp, -1, dst, int(count), 0, 0);
}
size_t XlAcpToMulti(char* dst, size_t count, const char* src)
{
wchar_t tmp[4096];
if (count >= dimof(tmp)) {
return 0;
}
MultiByteToWideChar(CP_ACP, 0, src, -1, tmp, int(count));
return WideCharToMultiByte(CP_UTF8, 0, tmp, -1, dst, int(count), 0, 0);
}
size_t XlMultiToWide2(wchar_t* dst, size_t count, const char* src)
{
return MultiByteToWideChar(CP_ACP, 0, src, -1, dst, int(count));
}
size_t XlWideToAcp(char* dst, size_t count, const unsigned* src)
{
// if we have ucs4 -> utf16 function, can skip one step
utf8 tmp[4096];
if (count >= dimof(tmp)) {
return 0;
}
XlWideToMulti(tmp, int(count), src);
return XlMultiToAcp(dst, int(count), (char*)tmp);
}
size_t XlWide2ToAcp(char* dst, size_t count, const wchar_t* src)
{
return WideCharToMultiByte(CP_ACP, 0, src, -1, dst, int(count), NULL, NULL);
}
size_t XlAcpToWide2(wchar_t* dst, size_t count, const char* src)
{
return MultiByteToWideChar(CP_ACP, 0, src, -1, dst, int(count));
}
#endif
}
| 29.533333 | 101 | 0.687359 |
500ea74071b6ee9ce101b7ab95761afad059d2e0 | 1,935 | kts | Kotlin | library/build.gradle.kts | averagehuman/okhttp-client-mock | 0d8a801a6d0033fd62e3efa731c86dbe1a709c8e | [
"MIT"
] | null | null | null | library/build.gradle.kts | averagehuman/okhttp-client-mock | 0d8a801a6d0033fd62e3efa731c86dbe1a709c8e | [
"MIT"
] | null | null | null | library/build.gradle.kts | averagehuman/okhttp-client-mock | 0d8a801a6d0033fd62e3efa731c86dbe1a709c8e | [
"MIT"
] | null | null | null | plugins {
id("java")
id("jacoco")
id("maven-publish")
id("org.jetbrains.kotlin.jvm") version "1.3.21"
}
base.archivesBaseName = "okhttp-mock"
java {
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
}
dependencies {
compileOnly("com.squareup.okhttp3:okhttp:3.8.1")
compileOnly("org.robolectric:robolectric:3.4.2")
compileOnly("com.android.support:support-annotations:25.3.1")
compileOnly("com.google.android:android:2.2.1")
implementation(kotlin("stdlib"))
testImplementation(configurations.compileOnly)
testImplementation("junit:junit:4.12")
}
tasks.withType(JacocoReport::class.java) {
reports {
xml.isEnabled = true
html.isEnabled = true
}
tasks["check"].dependsOn(this)
}
val sourcesJar by tasks.creating(Jar::class) {
dependsOn(JavaPlugin.CLASSES_TASK_NAME)
classifier = "sources"
from(sourceSets["main"].allSource)
}
val javadocJar by tasks.creating(Jar::class) {
dependsOn(JavaPlugin.JAVADOC_TASK_NAME)
classifier = "javadoc"
from(sourceSets["main"].allSource)
}
publishing {
val bintrayPackage = "okhttp-client-mock"
val bintrayUser = System.getenv("BINTRAY_USER")
val bintrayKey = System.getenv("BINTRAY_KEY")
publications {
create<MavenPublication>("default") {
artifactId = base.archivesBaseName
from(components["java"])
artifact(sourcesJar)
artifact(javadocJar)
}
}
repositories {
maven {
name = "local"
url = file("${rootProject.buildDir}/repo").toURI()
}
maven {
name = "bintray"
url = uri("https://api.bintray.com/content/$bintrayUser/maven/$bintrayPackage/$version")
credentials {
username = bintrayUser
password = bintrayKey
}
}
}
}
| 25.460526 | 100 | 0.633075 |
48fb6ff9ec5e385020b6f915b818cd744685ba3b | 133 | h | C | compat-headers/stdnoreturn.h | mikesmiffy128/lumpystuff | cb726d66e8848ddbd69009033de7d7c436758d30 | [
"ISC"
] | 2 | 2018-08-07T09:54:09.000Z | 2021-03-25T17:48:41.000Z | compat-headers/stdnoreturn.h | mikesmiffy128/lumpystuff | cb726d66e8848ddbd69009033de7d7c436758d30 | [
"ISC"
] | null | null | null | compat-headers/stdnoreturn.h | mikesmiffy128/lumpystuff | cb726d66e8848ddbd69009033de7d7c436758d30 | [
"ISC"
] | null | null | null | #pragma once
#if defined(_MSC_VER) && !defined(__clang__)
#define _Noreturn __declspec(noreturn)
#endif
#define noreturn _Noreturn
| 19 | 44 | 0.781955 |
4a0b14ab1baa5def218b0172c1fa45e01ce3a9ae | 1,069 | kt | Kotlin | app/src/androidTest/java/shvyn22/flexingfinalspace/util/ImageViewAssertion.kt | shvyn22/FlexingFinalSpace | bbc57adeab66926b694af7f2e5b26a34bb7347ca | [
"MIT"
] | null | null | null | app/src/androidTest/java/shvyn22/flexingfinalspace/util/ImageViewAssertion.kt | shvyn22/FlexingFinalSpace | bbc57adeab66926b694af7f2e5b26a34bb7347ca | [
"MIT"
] | null | null | null | app/src/androidTest/java/shvyn22/flexingfinalspace/util/ImageViewAssertion.kt | shvyn22/FlexingFinalSpace | bbc57adeab66926b694af7f2e5b26a34bb7347ca | [
"MIT"
] | null | null | null | package shvyn22.flexingfinalspace.util
import android.view.View
import android.widget.ImageView
import androidx.core.graphics.drawable.toBitmap
import org.hamcrest.Description
import org.hamcrest.TypeSafeMatcher
fun withImageDrawable(
expectedId: Int
) = object : TypeSafeMatcher<View>() {
private var resourceName: String = ""
override fun describeTo(description: Description?) {
description?.appendText("with drawable from resource id: $expectedId")
if (resourceName.isNotEmpty()) {
description?.appendText("[$resourceName]")
}
}
override fun matchesSafely(item: View?): Boolean {
if (item !is ImageView) return false
val resources = item.context.resources
val drawable = resources.getDrawable(expectedId, item.context.theme)
resourceName = resources.getResourceName(expectedId)
if (drawable == null) return false
val bitmap = item.drawable.toBitmap()
val expectedBitmap = drawable.toBitmap()
return bitmap.sameAs(expectedBitmap)
}
}
| 28.891892 | 78 | 0.70159 |
d234f9a14d6788e535444e939a10df82301919b5 | 318 | ps1 | PowerShell | New-Post.ps1 | raveling/aaronpowell.github.io | f71f50e72378dc3dc8698261c3d6de805c5e5696 | [
"Apache-2.0"
] | 10 | 2015-02-28T14:14:10.000Z | 2021-03-28T02:09:07.000Z | New-Post.ps1 | raveling/aaronpowell.github.io | f71f50e72378dc3dc8698261c3d6de805c5e5696 | [
"Apache-2.0"
] | 13 | 2016-11-14T06:17:56.000Z | 2020-03-09T03:24:10.000Z | New-Post.ps1 | raveling/aaronpowell.github.io | f71f50e72378dc3dc8698261c3d6de805c5e5696 | [
"Apache-2.0"
] | 15 | 2016-10-10T20:59:13.000Z | 2022-01-19T03:13:41.000Z | #requires -version 3.0
[CmdletBinding()]
param(
# Blog post name
[Parameter(Mandatory=$true)]
[string]
$Title
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
Push-Location (Join-Path $PSScriptRoot src)
../hugo.exe new "posts/$(Get-Date -Format 'yyyy-MM-dd')-$Title.md"
Pop-Location
| 18.705882 | 66 | 0.691824 |
a0d6125e83971bee232d8fa3134cd159ea203f9f | 518 | asm | Assembly | programs/oeis/230/A230775.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 22 | 2018-02-06T19:19:31.000Z | 2022-01-17T21:53:31.000Z | programs/oeis/230/A230775.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 41 | 2021-02-22T19:00:34.000Z | 2021-08-28T10:47:47.000Z | programs/oeis/230/A230775.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 5 | 2021-02-24T21:14:16.000Z | 2021-08-09T19:48:05.000Z | ; A230775: Smallest prime number greater than or equal to the square root of n.
; 2,2,2,2,3,3,3,3,3,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11
seq $0,196 ; Integer part of square root of n. Or, number of positive squares <= n. Or, n appears 2n+1 times.
seq $0,151800 ; Least prime > n (version 2 of the "next prime" function).
| 86.333333 | 252 | 0.658301 |
08f41f7803dd89f93b081beb82e4f56939e6cd03 | 1,611 | lua | Lua | config/nvim/pack/benferse/opt/toggleterm.nvim/tests/commandline_spec.lua | benferse/dotfiles | da500616ad755f391bde6b99087b0d925b728aa4 | [
"MIT"
] | 4 | 2020-07-10T17:50:47.000Z | 2021-08-12T23:55:38.000Z | config/nvim/pack/benferse/opt/toggleterm.nvim/tests/commandline_spec.lua | benferse/dotfiles | da500616ad755f391bde6b99087b0d925b728aa4 | [
"MIT"
] | null | null | null | config/nvim/pack/benferse/opt/toggleterm.nvim/tests/commandline_spec.lua | benferse/dotfiles | da500616ad755f391bde6b99087b0d925b728aa4 | [
"MIT"
] | null | null | null | local fmt = string.format
describe("Commandline tests:", function()
local parser = require("toggleterm.commandline")
it("should return a table containg correct arguments", function()
local file = vim.fn.tempname() .. ".txt"
vim.cmd(fmt("e %s", file))
local result = parser.parse("cmd='echo %' dir='/test dir/file.txt'")
assert.is_truthy(result.cmd)
assert.is_truthy(result.dir)
assert.equal(fmt("echo %s", file), result.cmd)
assert.equal("/test dir/file.txt", result.dir)
end)
it("should handle double quotes", function()
local result = parser.parse('cmd="git status"')
assert.truthy(result.cmd)
assert.equal("git status", result.cmd)
end)
it("should handle non-quoted arguments", function()
local result = parser.parse("direction=horizontal dir=/test/file.txt")
assert.is_truthy(result.dir)
assert.is_truthy(result.direction)
assert.equal("/test/file.txt", result.dir)
assert.equal("horizontal", result.direction)
end)
it("should handle size args correctly", function()
local result = parser.parse("size=34")
assert.is_truthy(result.size)
assert.is_true(type(result.size) == "number")
assert.equal(34, result.size)
end)
it("should handle go_back args correctly", function()
local result = parser.parse("go_back=0")
assert.is_true(type(result.go_back) == "boolean")
assert.is_false(result.go_back)
end)
it("should handle open args correctly", function()
local result = parser.parse("open=0")
assert.is_true(type(result.open) == "boolean")
assert.is_false(result.open)
end)
end)
| 32.877551 | 74 | 0.68653 |
66268ae0ab31b90805e06da45371862cb5ef9834 | 4,438 | cpp | C++ | src/selector.cpp | mugiseyebrows/mugi-ffmpeg | e7c3a5aeab3ee6ba5d3000f912491e42f32facbd | [
"MIT"
] | 3 | 2019-10-08T13:33:48.000Z | 2020-06-14T01:10:04.000Z | src/selector.cpp | mugiseyebrows/mugi-ffmpeg | e7c3a5aeab3ee6ba5d3000f912491e42f32facbd | [
"MIT"
] | null | null | null | src/selector.cpp | mugiseyebrows/mugi-ffmpeg | e7c3a5aeab3ee6ba5d3000f912491e42f32facbd | [
"MIT"
] | 3 | 2020-06-14T01:10:09.000Z | 2021-12-30T01:36:49.000Z | #include "selector.h"
#include <QFile>
#include <QDir>
Selector::Selector(QObject* parent) : QObject(parent)
{
}
QStringList stringList(const QString& item1) {
QStringList result;
result << item1;
return result;
}
QStringList stringList(const QString& item1, const QString& item2) {
QStringList result;
result << item1 << item2;
return result;
}
QStringList findFiles(const QString& path, const QStringList& exts) {
QDir dir(path);
QStringList entryList = dir.entryList();
QStringList result;
QString file;
QString ext;
foreach(file,entryList) {
QString file_ = file.toLower();
foreach(ext,exts) {
if (file_.endsWith(ext)) {
result << dir.filePath(file);
break;
}
}
}
return result;
}
bool Selector::setInputs(const QString &input1, const QString &input2)
{
mNames.clear();
mInputs.clear();
mOutputs.clear();
if (input1.isEmpty())
return false;
QStringList videoExts;
QStringList audioExts;
videoExts << ".mkv" << ".mp4" << ".ts" << ".avi";
audioExts << ".mka";
if (QDir(input1).exists()) {
// directory mode
QStringList videoFiles = findFiles(input1,videoExts);
if (!input2.isEmpty() && QDir(input2).exists()) {
// two inputs for each task
QStringList audioFiles = findFiles(input2,audioExts);
QString path;
QStringList videoFiles_;
QStringList audioFiles_;
foreach(path,videoFiles) {
videoFiles_ << QFileInfo(path).completeBaseName();
}
foreach(path,audioFiles) {
audioFiles_ << QFileInfo(path).completeBaseName();
}
for (int i=0;i<videoFiles_.size();i++) {
for (int j=0;j<audioFiles_.size();j++) {
if (videoFiles_[i] == audioFiles_[j]) {
mInputs << stringList(videoFiles[i],audioFiles[j]);
}
}
}
QStringList paths;
foreach(paths,mInputs) {
mNames << QFileInfo(paths[0]).completeBaseName();
}
} else {
// one input for each task
QString path;
foreach(path,videoFiles) {
mInputs << stringList(path);
}
QStringList paths;
foreach(paths,mInputs) {
mNames << QFileInfo(paths[0]).fileName();
}
}
} else if (QFile::exists(input1)) {
// file mode
if (!input2.isEmpty() && QFile::exists(input2)) {
// two inputs for each task
mInputs << stringList(input1,input2);
mNames << QFileInfo(input1).completeBaseName();
} else {
// one input for each task
mInputs << stringList(input1);
mNames << QFileInfo(input1).fileName();
}
}
return mInputs.size() > 0;
}
void Selector::setOutput(const QString &output)
{
mOutputs.clear();
QStringList paths;
QFileInfo fileInfo(output);
QDir dir = fileInfo.dir();
QString fileMask = fileInfo.fileName();
foreach(paths,mInputs) {
QString fileName = fileMask;
fileName.replace("%name%", QFileInfo(paths[0]).completeBaseName());
QString path = dir.filePath(fileName);
mOutputs << path;
}
}
bool Selector::isEmpty() const {
return mInputs.isEmpty();
}
QString Selector::quoted(const QStringList& task) const {
QStringList res;
QString e;
res << "ffmpeg";
foreach(e,task) {
if (e.indexOf(" ") > -1)
res << "\"" + e + "\"";
else
res << e;
}
return res.join(" ");
}
void Selector::tasks(const QStringList& options, const QList<bool>& checkList, QList<QStringList>& args, QStringList& quoted) const
{
for (int i=0;i<mInputs.size();i++) {
if (!checkList[i])
continue;
QStringList args_;
QString e;
foreach(e,mInputs[i])
args_ << "-i" << e;
args_.append(options);
args_ << mOutputs[i];
args << args_;
quoted.append( this->quoted(args_) );
}
}
QStringList Selector::names() const
{
return mNames;
}
bool Selector::twoInputs() const
{
if (isEmpty())
return false;
return mInputs[0].size() > 1;
}
| 25.802326 | 131 | 0.547093 |
5bfae0313334900ebaf35e74709ac07861d60c72 | 7,708 | swift | Swift | MobileApplicationDevelopment2018-2019-master/Knowledge of FBLA_CenturaFBLA_SeeversJacobsenStates_2019/Knowledge of FBLA/Ribbons.swift | TechWizard12/MobileApplicationDevelopmentCentura2019 | c132332addb9e0c89b3ecb34d3bf6bf361271a39 | [
"AML"
] | null | null | null | MobileApplicationDevelopment2018-2019-master/Knowledge of FBLA_CenturaFBLA_SeeversJacobsenStates_2019/Knowledge of FBLA/Ribbons.swift | TechWizard12/MobileApplicationDevelopmentCentura2019 | c132332addb9e0c89b3ecb34d3bf6bf361271a39 | [
"AML"
] | null | null | null | MobileApplicationDevelopment2018-2019-master/Knowledge of FBLA_CenturaFBLA_SeeversJacobsenStates_2019/Knowledge of FBLA/Ribbons.swift | TechWizard12/MobileApplicationDevelopmentCentura2019 | c132332addb9e0c89b3ecb34d3bf6bf361271a39 | [
"AML"
] | null | null | null | //
// Ribbons.swift
// KIn the Know FBLA
//
// Created by Created by Colten Seevers, Jayden Jacobsen, Caitlin States on 12/28/18.
// Copyright © 2019 Centura FBLA. All rights reserved.
//
import UIKit
class Ribbons: UIViewController{
@IBOutlet var Ribbonlabel: UILabel!
@IBOutlet var Ribbonb1: UIButton!
@IBOutlet var Ribbonb2: UIButton!
@IBOutlet var Ribbonb3: UIButton!
@IBOutlet var Ribbonb4: UIButton!
@IBOutlet var Next: UIButton!
@IBOutlet var LabelEnd: UILabel!
var CorrectAnswer = String()
override func viewDidLoad() {
super.viewDidLoad()
RandomRibbonQuestions()
Hideall()
}
func RandomRibbonQuestions () {
var RandomNumber = arc4random() % 10
RandomNumber += 1
switch(RandomNumber) {
case 1:
Ribbonlabel.text = "Unless otherwise stated the Nebraskas individual ribbon awards deadline is"
Ribbonb1.setTitle("March 1", for: UIControlState.normal)
Ribbonb2.setTitle("March 8", for: UIControlState.normal)
Ribbonb3.setTitle("April 10", for: UIControlState.normal)
Ribbonb4.setTitle("April 21", for: UIControlState.normal)
CorrectAnswer = "1"
break
case 2:
Ribbonlabel.text = "The Seven Up Ribbon requires chapters to increase their membership over the previous year by"
Ribbonb1.setTitle("5", for: UIControlState.normal)
Ribbonb2.setTitle("7", for: UIControlState.normal)
Ribbonb3.setTitle("10", for: UIControlState.normal)
Ribbonb4.setTitle("12", for: UIControlState.normal)
CorrectAnswer = "2"
break
case 3:
Ribbonlabel.text = "One of the required activities to compete for a StepUp2Tech Ribbon is to:"
Ribbonb1.setTitle("Implement a chapter social media committee", for: UIControlState.normal)
Ribbonb2.setTitle("Register a member for broadcast journalism event", for: UIControlState.normal)
Ribbonb3.setTitle("Utilize social media to promote your chapter each month", for: UIControlState.normal)
Ribbonb4.setTitle("Create or maintain an FBLA Chapter Website", for: UIControlState.normal)
CorrectAnswer = "3"
break
case 4:
Ribbonlabel.text = "For the Connect with Bussiness Ribbon, the form should be emailed to the :"
Ribbonb1.setTitle("Nebraska State FBLA Vice President", for: UIControlState.normal)
Ribbonb2.setTitle("Nebraska State FBLA Secretary", for: UIControlState.normal)
Ribbonb3.setTitle("Nebraska State FBLA President", for: UIControlState.normal)
Ribbonb4.setTitle("Nebraska State FBLA Treasurer", for: UIControlState.normal)
CorrectAnswer = "1"
break
case 5:
Ribbonlabel.text = "If a chapter gives between $100-$499 to Nebraska FBLA Foundation Trust, they are considered a(n) ________ member:"
Ribbonb1.setTitle("Associate", for: UIControlState.normal)
Ribbonb2.setTitle("Director", for: UIControlState.normal)
Ribbonb3.setTitle("President", for: UIControlState.normal)
Ribbonb4.setTitle("Manager", for: UIControlState.normal)
CorrectAnswer = "4"
break
case 6:
Ribbonlabel.text = "To qualify for recognition for the Go Green Challenge, a chapter must complete ___________ activities in each of the categories provided."
Ribbonb1.setTitle("1", for: UIControlState.normal)
Ribbonb2.setTitle("2", for: UIControlState.normal)
Ribbonb3.setTitle("3", for: UIControlState.normal)
Ribbonb4.setTitle("4", for: UIControlState.normal)
CorrectAnswer = "2"
break
case 7:
Ribbonlabel.text = "How many reports must be completed in order to recieve recognition for a Sweepstakes Award?"
Ribbonb1.setTitle("1", for: UIControlState.normal)
Ribbonb2.setTitle("2", for: UIControlState.normal)
Ribbonb3.setTitle("3", for: UIControlState.normal)
Ribbonb4.setTitle("4", for: UIControlState.normal)
CorrectAnswer = "2"
break
case 8:
Ribbonlabel.text = "One section of the All State Quality Member section requires attendance at a mininume of ___ chapter meeetings for a total of three points."
Ribbonb1.setTitle("4", for: UIControlState.normal)
Ribbonb2.setTitle("5", for: UIControlState.normal)
Ribbonb3.setTitle("6", for: UIControlState.normal)
Ribbonb4.setTitle("7", for: UIControlState.normal)
CorrectAnswer = "2"
break
case 9:
Ribbonlabel.text = "To receive an All State Quality Member Award, the applicant must have a point total of:"
Ribbonb1.setTitle("50", for: UIControlState.normal)
Ribbonb2.setTitle("75", for: UIControlState.normal)
Ribbonb3.setTitle("100", for: UIControlState.normal)
Ribbonb4.setTitle("125", for: UIControlState.normal)
CorrectAnswer = "3"
break
case 10:
Ribbonlabel.text = "Those deserving of the Community Service Award receive recognition at the:"
Ribbonb1.setTitle("FLC", for: UIControlState.normal)
Ribbonb2.setTitle("NFLC", for: UIControlState.normal)
Ribbonb3.setTitle("SLC", for: UIControlState.normal)
Ribbonb4.setTitle("NLC", for: UIControlState.normal)
CorrectAnswer = "4"
break
default:
break
}
}
func HideLabel(){
LabelEnd.isHidden = true
}
//Hide the label only
func HideNext(){
Next.isHidden = true
}
//Hide the button only
func UnhideLabel(){
LabelEnd.isHidden = false
}
//Unhide the label only
func UnhideNext(){
Next.isHidden = false
}
//Unhide the button only
func Hideall(){
LabelEnd.isHidden = true
Next.isHidden = true
}
//Hide both
func Unhideall(){
LabelEnd.isHidden = false
Next.isHidden = false
}
//Unhide both
@IBAction func Ribbonb1action(_ sender: Any) {UnhideLabel()
if (CorrectAnswer == "1"){
LabelEnd.text = "You Are Correct"
UnhideNext()
}
else{
LabelEnd.text = "You Are Wrong"
HideNext()
}
}
@IBAction func Ribbonb2action(_ sender: Any) {UnhideLabel()
if (CorrectAnswer == "2"){
LabelEnd.text = "You Are Correct"
UnhideNext()
}
else{
LabelEnd.text = "You Are Wrong"
HideNext()
}
}
@IBAction func Ribbonb3action(_ sender: Any) {UnhideLabel()
if (CorrectAnswer == "3"){
LabelEnd.text = "You Are Correct"
UnhideNext()
}
else{
LabelEnd.text = "You Are Wrong"
HideNext()
}
}
@IBAction func Ribbonb4action(_ sender: Any) {UnhideLabel()
if (CorrectAnswer == "4"){
LabelEnd.text = "You Are Correct"
UnhideNext()
}
else{
LabelEnd.text = "You Are Wrong"
HideNext()
}
}
@IBAction func Next(_ sender: Any) {
RandomRibbonQuestions()
Hideall()
}
}
| 36.704762 | 172 | 0.590815 |
4a6b5384a133df444d14865b6a1f23a4f9ea4d8b | 30,352 | html | HTML | _site/2021/01/28/bcaitech-ustage-day9.html | Heeseok-Jeong/Heeseok-Jeong.github.io | ec463c4ffd6d9afe12a6ee1a949979da4b6ee2bf | [
"MIT"
] | null | null | null | _site/2021/01/28/bcaitech-ustage-day9.html | Heeseok-Jeong/Heeseok-Jeong.github.io | ec463c4ffd6d9afe12a6ee1a949979da4b6ee2bf | [
"MIT"
] | null | null | null | _site/2021/01/28/bcaitech-ustage-day9.html | Heeseok-Jeong/Heeseok-Jeong.github.io | ec463c4ffd6d9afe12a6ee1a949979da4b6ee2bf | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!--Favicon-->
<link rel="shortcut icon" href="/assets/favicon.ico" type="image/x-icon">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.9.0/css/all.css"
integrity="sha384-i1LQnF23gykqWXg6jxC2ZbCbUMxyw5gLZY6UiUS98LYV5unm8GWmfkIS6jqJfb4E" crossorigin="anonymous">
<!-- Spoqa Han Sans -->
<link href='//spoqa.github.io/spoqa-han-sans/css/SpoqaHanSans-kr.css' rel='stylesheet' type='text/css'>
<!-- CSS -->
<link rel="stylesheet" href="/assets/css/main.css">
<!-- OG Tag -->
<meta name="title" content="Heeseok Jeong-Ustage Day 9" />
<meta name="author" content="Heeseok Jeong" />
<meta name="keywords" content="BoostCamp AI Tech" />
<meta name="description" content="Pandas(2)|확률론 맛보기" />
<meta name="robots" content="index,follow" />
<meta property="og:title" content="Heeseok Jeong-Ustage Day 9" />
<meta property="og:description" content="Pandas(2)|확률론 맛보기" />
<meta property="og:type" content="website, blog" />
<meta property="og:image"
content="http://localhost:4000/assets/img/smile.png" />
<meta property="og:site_name" content="Heeseok Jeong" />
<meta property="og:url" content="http://localhost:4000/2021/01/28/bcaitech-ustage-day9.html" />
<meta name="twitter:card" content="summary" />
<meta name="twitter:title" content="Heeseok Jeong-Ustage Day 9" />
<meta name="twitter:description" content="Pandas(2)|확률론 맛보기" />
<meta name="twitter:image"
content="http://localhost:4000/assets/img/smile.png" />
<title>Heeseok Jeong-Ustage Day 9</title>
</head>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
TeX: {
equationNumbers: {
autoNumber: "AMS"
}
},
tex2jax: {
inlineMath: [ ['$', '$'] ],
displayMath: [ ['$$', '$$'] ],
processEscapes: true,
}
});
MathJax.Hub.Register.MessageHook("Math Processing Error",function (message) {
alert("Math Processing Error: "+message[1]);
});
MathJax.Hub.Register.MessageHook("TeX Jax - parse error",function (message) {
alert("Math Processing Error: "+message[1]);
});
</script>
<script type="text/javascript" async
src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-MML-AM_CHTML">
</script>
<body>
<div class="container">
<header>
<nav>
<ul>
<!-- others -->
<a href="http://localhost:4000">
<li class="current btn-nav">Blog</li>
</a>
<a href="http://localhost:4000/tags">
<li class="btn-nav">Tags</li>
</a>
<a href="http://localhost:4000/portfolio">
<li class="btn-nav">Portfolio</li>
</a>
</ul>
</nav>
</header>
<div id="post">
<section class="post-header">
<h1 class="title">Ustage Day 9</h1>
<p class="subtitle">Pandas(2)|확률론 맛보기</p>
<p class="meta">
January 28, 2021
</p>
</section>
<section class="post-content">
<h1 id="목차">목차</h1>
<p><br /></p>
<ul>
<li><a href="#pandas-2-">Pandas(2)</a></li>
<li><a href="#확률론-맛보기">확률론 맛보기</a></li>
<li><a href="#피어-세션">피어 세션</a></li>
<li><a href="#today-i-felt">Today I Felt</a></li>
</ul>
<p><br /></p>
<hr />
<p><br /></p>
<h1 id="pandas2">Pandas(2)</h1>
<p><br /></p>
<h2 id="groupby">Groupby</h2>
<ul>
<li>SQL groupby 명령어와 같음</li>
<li>
<p>split → apply → combine</p>
<p><img src="/assets/img/ustage_day9/1.png" alt="image1" /></p>
</li>
<li>문법
<ul>
<li>df.groupby(“Team”)[‘Point’].sum()</li>
<li>df 데이터에서 팀별로 점수를 합산해서 구분해라.</li>
</ul>
</li>
</ul>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">pandas</span> <span class="k">as</span> <span class="n">pd</span>
<span class="n">ipl_data</span> <span class="o">=</span> <span class="p">{</span><span class="s">'Team'</span><span class="p">:</span> <span class="p">[</span><span class="s">'Riders'</span><span class="p">,</span> <span class="s">'Riders'</span><span class="p">,</span> <span class="s">'Devils'</span><span class="p">,</span> <span class="s">'Devils'</span><span class="p">,</span> <span class="s">'Kings'</span><span class="p">,</span>
<span class="s">'kings'</span><span class="p">,</span> <span class="s">'Kings'</span><span class="p">,</span> <span class="s">'Kings'</span><span class="p">,</span> <span class="s">'Riders'</span><span class="p">,</span> <span class="s">'Royals'</span><span class="p">,</span> <span class="s">'Royals'</span><span class="p">,</span> <span class="s">'Riders'</span><span class="p">],</span>
<span class="s">'Rank'</span><span class="p">:</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span><span class="mi">4</span> <span class="p">,</span><span class="mi">1</span> <span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span> <span class="p">,</span> <span class="mi">4</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">],</span>
<span class="s">'Year'</span><span class="p">:</span> <span class="p">[</span><span class="mi">2014</span><span class="p">,</span><span class="mi">2015</span><span class="p">,</span><span class="mi">2014</span><span class="p">,</span><span class="mi">2015</span><span class="p">,</span><span class="mi">2014</span><span class="p">,</span><span class="mi">2015</span><span class="p">,</span><span class="mi">2016</span><span class="p">,</span><span class="mi">2017</span><span class="p">,</span><span class="mi">2016</span><span class="p">,</span><span class="mi">2014</span><span class="p">,</span><span class="mi">2015</span><span class="p">,</span><span class="mi">2017</span><span class="p">],</span>
<span class="s">'Points'</span><span class="p">:[</span><span class="mi">876</span><span class="p">,</span><span class="mi">789</span><span class="p">,</span><span class="mi">863</span><span class="p">,</span><span class="mi">673</span><span class="p">,</span><span class="mi">741</span><span class="p">,</span><span class="mi">812</span><span class="p">,</span><span class="mi">756</span><span class="p">,</span><span class="mi">788</span><span class="p">,</span><span class="mi">694</span><span class="p">,</span><span class="mi">701</span><span class="p">,</span><span class="mi">804</span><span class="p">,</span><span class="mi">690</span><span class="p">]}</span>
<span class="n">df</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">DataFrame</span><span class="p">(</span><span class="n">ipl_data</span><span class="p">)</span>
<span class="n">df</span>
<span class="s">'''
Team Rank Year Points
0 Riders 1 2014 876
1 Riders 2 2015 789
2 Devils 2 2014 863
3 Devils 3 2015 673
4 Kings 3 2014 741
5 kings 4 2015 812
6 Kings 1 2016 756
7 Kings 1 2017 788
8 Riders 2 2016 694
9 Royals 4 2014 701
10 Royals 1 2015 804
11 Riders 2 2017 690
'''</span>
<span class="n">df</span><span class="p">.</span><span class="n">groupby</span><span class="p">(</span><span class="s">"Team"</span><span class="p">)[</span><span class="s">"Points"</span><span class="p">].</span><span class="nb">sum</span><span class="p">()</span>
<span class="s">'''
Team
Devils 1536
Kings 2285
Riders 3049
Royals 1505
kings 812
Name: Points, dtype: int64
'''</span>
<span class="n">df</span> <span class="o">=</span> <span class="n">df</span><span class="p">.</span><span class="n">groupby</span><span class="p">([</span><span class="s">"Team"</span><span class="p">,</span> <span class="s">"Year"</span><span class="p">])[</span><span class="s">"Points"</span><span class="p">].</span><span class="nb">sum</span><span class="p">()</span>
<span class="n">df</span>
<span class="s">'''
Team Year
Devils 2014 863
2015 673
Kings 2014 741
2016 756
2017 788
Riders 2014 876
2015 789
2016 694
2017 690
Royals 2014 701
2015 804
kings 2015 812
Name: Points, dtype: int64
'''</span>
</code></pre></div></div>
<ul>
<li>엑셀의 피벗테이블로도 할 수 있음</li>
</ul>
<h3 id="hierarchical-index">Hierarchical index</h3>
<ul>
<li>여러 인덱스를 데이터프레임 조회에 넣어서 해당 인덱스들 기준으로 보는 방법</li>
<li>위 그룹바이 마지막 예시도 마찬가지</li>
<li>unstack() : 시리즈는 데이터프레임으로, 데이터프레임은 시리즈로 돌려줌</li>
<li>reset_index() : 다른 인덱스로 구성된 시리즈나 데이터프레임을 기본인덱스 데이터프레임으로 돌려줌</li>
</ul>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">df2</span> <span class="o">=</span> <span class="n">df</span><span class="p">.</span><span class="n">unstack</span><span class="p">()</span>
<span class="n">df2</span>
<span class="s">'''
Year 2014 2015 2016 2017
Team
Devils 863.0 673.0 NaN NaN
Kings 741.0 NaN 756.0 788.0
Riders 876.0 789.0 694.0 690.0
Royals 701.0 804.0 NaN NaN
kings NaN 812.0 NaN NaN
'''</span>
<span class="n">df3</span> <span class="o">=</span> <span class="n">df</span><span class="p">.</span><span class="n">reset_index</span><span class="p">()</span>
<span class="n">df3</span>
<span class="s">'''
Team Year Points
0 Devils 2014 863
1 Devils 2015 673
2 Kings 2014 741
3 Kings 2016 756
4 Kings 2017 788
5 Riders 2014 876
6 Riders 2015 789
7 Riders 2016 694
8 Riders 2017 690
9 Royals 2014 701
10 Royals 2015 804
11 kings 2015 812
'''</span>
</code></pre></div></div>
<ul>
<li>swap_level() : 인덱스 순서(계층) 를 바꿔줌</li>
<li>sort_index() : 인덱스 기준 정렬</li>
<li>sort_values() : 값 기준 정렬</li>
</ul>
<h3 id="grouped">grouped</h3>
<ul>
<li>그룹바이에 의해 스플릿된 상태 추출</li>
<li>튜플로 키, 밸류가 엮여서 나옴</li>
<li>따로 함수는 아니고 groupby 로 나온 제너레이터 활용하는 방법임</li>
<li>타입은 pd.DataFrame.Groupby</li>
</ul>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">grouped</span> <span class="o">=</span> <span class="n">df</span><span class="p">.</span><span class="n">groupby</span><span class="p">(</span><span class="s">"Team"</span><span class="p">)</span>
<span class="k">for</span> <span class="n">gr</span> <span class="ow">in</span> <span class="n">grouped</span><span class="p">:</span>
<span class="k">print</span><span class="p">(</span><span class="n">gr</span><span class="p">)</span>
<span class="s">'''
('Devils', Team Year
Devils 2014 863
2015 673
Name: Points, dtype: int64)
('Kings', Team Year
Kings 2014 741
2016 756
2017 788
Name: Points, dtype: int64)
('Riders', Team Year
Riders 2014 876
2015 789
2016 694
2017 690
Name: Points, dtype: int64)
('Royals', Team Year
Royals 2014 701
2015 804
Name: Points, dtype: int64)
('kings', Team Year
kings 2015 812
Name: Points, dtype: int64)
'''</span>
<span class="k">for</span> <span class="n">name</span><span class="p">,</span> <span class="n">group</span> <span class="ow">in</span> <span class="n">grouped</span><span class="p">:</span>
<span class="k">print</span><span class="p">(</span><span class="n">name</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">group</span><span class="p">)</span>
<span class="s">'''
Devils
Team Year
Devils 2014 863
2015 673
Name: Points, dtype: int64
Kings
Team Year
Kings 2014 741
2016 756
2017 788
Name: Points, dtype: int64
Riders
Team Year
Riders 2014 876
2015 789
2016 694
2017 690
Name: Points, dtype: int64
Royals
Team Year
Royals 2014 701
2015 804
Name: Points, dtype: int64
kings
Team Year
kings 2015 812
Name: Points, dtype: int64
'''</span>
</code></pre></div></div>
<ul>
<li>grouped.get_group() : 특정 그룹 가져옴</li>
</ul>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">grouped</span><span class="p">.</span><span class="n">get_group</span><span class="p">(</span><span class="s">"Kings"</span><span class="p">)</span>
<span class="s">'''
Team Year
Kings 2014 741
2016 756
2017 788
Name: Points, dtype: int64
'''</span>
</code></pre></div></div>
<ul>
<li>grouped 된 상태는 세 가지 유형의 apply 가능
<ul>
<li>Aggregation : 요약된 통계정보 추출</li>
</ul>
</li>
</ul>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">grouped</span><span class="p">.</span><span class="n">agg</span><span class="p">(</span><span class="nb">sum</span><span class="p">)</span>
<span class="s">'''
Team
Devils 1536
Kings 2285
Riders 3049
Royals 1505
kings 812
Name: Points, dtype: int64
'''</span>
<span class="c1"># 여러 개도 가능
</span><span class="n">grouped</span><span class="p">.</span><span class="n">agg</span><span class="p">([</span><span class="nb">sum</span><span class="p">,</span> <span class="n">np</span><span class="p">.</span><span class="n">mean</span><span class="p">,</span> <span class="nb">max</span><span class="p">])</span>
<span class="s">'''
sum mean max
Team
Devils 1536 768.000000 863
Kings 2285 761.666667 788
Riders 3049 762.250000 876
Royals 1505 752.500000 804
kings 812 812.000000 812
'''</span>
</code></pre></div></div>
<ul>
<li>Transformation : group 된 데이터에서 해당 함수대로 모든 행에 적용, 그룹 별 연산에서 각각의 값에 영향 주고 싶을 때 사용</li>
</ul>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">score</span> <span class="o">=</span> <span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="p">(</span><span class="n">x</span> <span class="o">-</span> <span class="n">x</span><span class="p">.</span><span class="n">mean</span><span class="p">())</span> <span class="o">/</span> <span class="n">x</span><span class="p">.</span><span class="n">std</span><span class="p">()</span>
<span class="n">grouped</span><span class="p">.</span><span class="n">transform</span><span class="p">(</span><span class="n">score</span><span class="p">)</span>
<span class="s">'''
Rank Year Points
0 -1.500000 -1.161895 1.284327
1 0.500000 -0.387298 0.302029
2 -0.707107 -0.707107 0.707107
3 0.707107 0.707107 -0.707107
4 1.154701 -1.091089 -0.860862
5 NaN NaN NaN
6 -0.577350 0.218218 -0.236043
7 -0.577350 0.872872 1.096905
8 0.500000 0.387298 -0.770596
9 0.707107 -0.707107 -0.707107
10 -0.707107 0.707107 0.707107
11 0.500000 1.161895 -0.815759
'''</span>
</code></pre></div></div>
<ul>
<li>Filteration : 특정 정보 제거해서 보여주는 필터기능</li>
</ul>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">df</span><span class="p">.</span><span class="n">groupby</span><span class="p">(</span><span class="s">'Team'</span><span class="p">).</span><span class="nb">filter</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="n">x</span><span class="p">[</span><span class="s">"Points"</span><span class="p">].</span><span class="nb">max</span><span class="p">()</span> <span class="o">></span> <span class="mi">800</span><span class="p">)</span>
<span class="s">'''
Team Rank Year Points
0 Riders 1 2014 876
1 Riders 2 2015 789
2 Devils 2 2014 863
3 Devils 3 2015 673
5 kings 4 2015 812
8 Riders 2 2016 694
9 Royals 4 2014 701
10 Royals 1 2015 804
11 Riders 2 2017 690
'''</span>
</code></pre></div></div>
<h2 id="컬럼의-데이터-타입-바꾸기">컬럼의 데이터 타입 바꾸기</h2>
<ul>
<li>apply 사용</li>
</ul>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">dateutil</span>
<span class="n">df_phone</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">read_csv</span><span class="p">(</span><span class="s">"./data/phone_data.csv"</span><span class="p">)</span>
<span class="n">df_phone</span><span class="p">.</span><span class="n">head</span><span class="p">()</span>
<span class="s">'''
index date duration item month network network_type
0 0 15/10/14 06:58 34.429 data 2014-11 data data
1 1 15/10/14 06:58 13.000 call 2014-11 Vodafone mobile
2 2 15/10/14 14:46 23.000 call 2014-11 Meteor mobile
3 3 15/10/14 14:48 4.000 call 2014-11 Tesco mobile
4 4 15/10/14 17:27 4.000 call 2014-11 Tesco mobile
'''</span>
<span class="n">df_phone</span><span class="p">[</span><span class="s">"date"</span><span class="p">]</span> <span class="o">=</span> <span class="n">df_phone</span><span class="p">[</span><span class="s">"date"</span><span class="p">].</span><span class="nb">apply</span><span class="p">(</span><span class="n">dateutil</span><span class="p">.</span><span class="n">parser</span><span class="p">.</span><span class="n">parse</span><span class="p">,</span> <span class="n">dayfirst</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="n">df_phone</span><span class="p">.</span><span class="n">dtypes</span>
<span class="s">'''
index int64
date datetime64[ns]
duration float64
item object
month object
network object
network_type object
dtype: object
'''</span>
</code></pre></div></div>
<h2 id="plot">plot</h2>
<ul>
<li>matplotlib 설치
<ul>
<li>!conda install - - y matplotlib</li>
</ul>
</li>
<li>DF 나 시리즈 뒤에 .plot() 해주면 그림 나옴, 따로 임포트 안해도 됨</li>
</ul>
<h2 id="pivot-table">Pivot Table</h2>
<ul>
<li>엑셀의 기능과 같음</li>
<li>index 축은 groupby 와 동일</li>
<li>column 에 추가로 라벨링 값 추가하여 value 에 numeric 타입 값을 aggregation 하는 형태</li>
</ul>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">df_phone</span><span class="p">.</span><span class="n">pivot_table</span><span class="p">(</span>
<span class="n">values</span><span class="o">=</span><span class="p">[</span><span class="s">"duration"</span><span class="p">],</span>
<span class="n">index</span><span class="o">=</span><span class="p">[</span><span class="n">df_phone</span><span class="p">.</span><span class="n">month</span><span class="p">,</span> <span class="n">df_phone</span><span class="p">.</span><span class="n">item</span><span class="p">],</span>
<span class="n">columns</span><span class="o">=</span><span class="n">df_phone</span><span class="p">.</span><span class="n">network</span><span class="p">,</span>
<span class="n">aggfunc</span><span class="o">=</span><span class="s">"sum"</span><span class="p">,</span>
<span class="n">fill_value</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span>
<span class="p">)</span>
<span class="s">'''
duration
network Meteor Tesco Three Vodafone data landline special voicemail world
month item
2014-11 call 1521 4045 12458 4316 0.000 2906 0 301 0
data 0 0 0 0 998.441 0 0 0 0
sms 10 3 25 55 0.000 0 1 0 0
2014-12 call 2010 1819 6316 1302 0.000 1424 0 690 0
data 0 0 0 0 1032.870 0 0 0 0
sms 12 1 13 18 0.000 0 0 0 4
2015-01 call 2207 2904 6445 3626 0.000 1603 0 285 0
data 0 0 0 0 1067.299 0 0 0 0
sms 10 3 33 40 0.000 0 0 0 0
2015-02 call 1188 4087 6279 1864 0.000 730 0 268 0
data 0 0 0 0 1067.299 0 0 0 0
sms 1 2 11 23 0.000 0 2 0 0
2015-03 call 274 973 4966 3513 0.000 11770 0 231 0
data 0 0 0 0 998.441 0 0 0 0
sms 0 4 5 13 0.000 0 0 0 3
'''</span>
<span class="c1"># groupby 로 구현
</span><span class="n">df_phone</span><span class="p">.</span><span class="n">groupby</span><span class="p">([</span><span class="s">"month"</span><span class="p">,</span> <span class="s">"item"</span><span class="p">,</span> <span class="s">"network"</span><span class="p">])[</span><span class="s">"duration"</span><span class="p">].</span><span class="nb">sum</span><span class="p">().</span><span class="n">unstack</span><span class="p">()</span>
<span class="s">'''
network Meteor Tesco Three Vodafone data landline special voicemail world
month item
2014-11 call 1521.0 4045.0 12458.0 4316.0 NaN 2906.0 NaN 301.0 NaN
data NaN NaN NaN NaN 998.441 NaN NaN NaN NaN
sms 10.0 3.0 25.0 55.0 NaN NaN 1.0 NaN NaN
2014-12 call 2010.0 1819.0 6316.0 1302.0 NaN 1424.0 NaN 690.0 NaN
data NaN NaN NaN NaN 1032.870 NaN NaN NaN NaN
sms 12.0 1.0 13.0 18.0 NaN NaN NaN NaN 4.0
2015-01 call 2207.0 2904.0 6445.0 3626.0 NaN 1603.0 NaN 285.0 NaN
data NaN NaN NaN NaN 1067.299 NaN NaN NaN NaN
sms 10.0 3.0 33.0 40.0 NaN NaN NaN NaN NaN
2015-02 call 1188.0 4087.0 6279.0 1864.0 NaN 730.0 NaN 268.0 NaN
data NaN NaN NaN NaN 1067.299 NaN NaN NaN NaN
sms 1.0 2.0 11.0 23.0 NaN NaN 2.0 NaN NaN
2015-03 call 274.0 973.0 4966.0 3513.0 NaN 11770.0 NaN 231.0 NaN
data NaN NaN NaN NaN 998.441 NaN NaN NaN NaN
sms NaN 4.0 5.0 13.0 NaN NaN NaN NaN 3.0
'''</span>
</code></pre></div></div>
<h2 id="crosstab">Crosstab</h2>
<ul>
<li>피벗테이블과 거의 동일</li>
<li>네트워크 데이터 (a 와 b 가 상관 있음) 에 사용하면 편함</li>
<li>인덱스, 컬럼, 벨류, 어그리게이션 세팅 하면됨</li>
</ul>
<p>→ groupby, pivot_table, crosstab 다 가능</p>
<h2 id="merge--concat">merge & concat</h2>
<h3 id="merge-join-과-같음">merge (join 과 같음)</h3>
<ul>
<li>sql 에서 많이 사용하는 merge 와 같은 기능</li>
<li>두 개의 테이블을 하나로 합침</li>
<li>기준이 있어야함</li>
<li>pd.merge(df_a, df_b, on=’subject_id’) # 두 테이블을 subject_id 를 기준으로 합침</li>
<li>두 테이블에서 컬럼명이 다를 때는 left_on 과 right_on 따로 적어주면 됨</li>
<li>join method
<ul>
<li>inner join : 겹치는 내용만 보여줌</li>
<li>full join : 모든 내용 다 합쳐서 보여줌</li>
<li>left join : 왼쪽 모든 내용 + 오른쪽 겹치는 내용 보여줌</li>
<li>right join : left join 반대</li>
<li>없는 값은 NaN 으로 채워짐</li>
<li>merge(~~, how=”inner”) 로 적어주면 됨, 기본은 inner</li>
</ul>
</li>
</ul>
<h3 id="concat">concat</h3>
<ul>
<li>컬럼을 더 넓히는게 아니라 데이터 양을 더 넓힘 (세로로) → 같은 컬럼을 갖고 있어야함</li>
<li>axis=1 하면 옆으로 붙음</li>
<li>pd.concat([df_a, df_b])</li>
</ul>
<p>=> 여러 엑셀 파일들 합치고 필요한 정보 뽑을 때 groupby merge concat 등등 쓰면 유용</p>
<h2 id="persistance">Persistance</h2>
<h3 id="db-연결">DB 연결</h3>
<h4 id="sqlite3">sqlite3</h4>
<ul>
<li>로컬 디비</li>
<li>import sqlite3 해서 써도 됨</li>
<li>원격 되는 mysql 등 써도 됨</li>
</ul>
<h3 id="엑셀-작성기">엑셀 작성기</h3>
<ul>
<li>!conda install —y XlsxWriter
<ul>
<li>df_routes 사용가능</li>
</ul>
</li>
<li>writer = pd.ExcelWriter(…) 쓰고 df_routes.to_excel(writer, sheet_name=”my_data”) 하면 작성가능</li>
<li>df_routes.to_pickle 가능</li>
</ul>
<p><br /></p>
<hr />
<p><br /></p>
<h1 id="확률론-맛보기">확률론 맛보기</h1>
<p><br /></p>
<h2 id="딥러닝에서-확률론이-필요한-이유">딥러닝에서 확률론이 필요한 이유</h2>
<ul>
<li>딥러닝은 확률론 기반의 기계학습 이론에 기반함</li>
<li>손실함수 (loss function) 들의 작동 원리는 데이터 공간을 통계적으로 해석해서 유도함
<ul>
<li>예측이 틀릴 위험 (risk) 를 최소화하도록 데이터를 학습 → SGD</li>
</ul>
</li>
<li>회귀 분석에서 손실함수로 사용되는 L2-norm 은 <strong>예측오차의 분산</strong>을 가장 최소화하는 방향으로 학습하도록 유도</li>
<li>분류 문제에서 사용되는 교차엔트로피 (cross-entropy) 는 모델 <strong>예측의 불확실성</strong>을 최소화하는 방향으로 학습</li>
<li>분산 및 불확실성을 최소화하기 위해서는 측정하는 방법을 알아야 함
<ul>
<li>두 대상을 측정하는 방법은 통계학 기반이므로 확률론을 알아야 함</li>
</ul>
</li>
</ul>
<h2 id="확률분포는-데이터의-초상화">확률분포는 데이터의 초상화</h2>
<ul>
<li>테이터 공간을 $x$ x $y$ 라 표기하고 𝔇 는 데이터공간에서 데이터를 추출하는 분포</li>
<li>데이터는 확률변수로 ($x$, $y$) ~ 𝔇 라 표기
<ul>
<li>확률변수는 함수로 표시, 임의로 데이터 공간에서 관측된 데이터를 확률변수로 데이터 추출</li>
<li>추출한 데이터의 분포 → 𝔇</li>
</ul>
</li>
<li>결합분포 P(x, y) 는 𝔇 를 모델링
<ul>
<li>결합분포는 원래 확률분포 타입에 상관없이 이산형이나 연속형 가능</li>
<li>결합분포는 아규먼트로 쓰인 확률변수들을 같이 고려한다는 뜻</li>
</ul>
</li>
<li>P(x) 는 입력 x 에 대한 주변확률분포로 y 에 대한 정보를 주지 않음
<ul>
<li>주변확률분포 P(x) 는 결합분포 P(x, y) 를 y 에 대해 더하거나 적분해서 유도</li>
</ul>
</li>
<li>조건부확률분포 P(x | y) 는 데이터 공간에서 입력 x 와 출력 y 사이의 관계를 모델링
<ul>
<li>P(X | Y = 1) : Y 가 1 일 때 X 의 확률분포</li>
<li>원딜님 설명 : 전체 공간 S 대신 Y 공간에서 X 의 확률분포</li>
<li>결합분포말고 조건부확률분포를 쓰면 데이터 각각에 대해 더 명확하게 알아낼 수 있음</li>
</ul>
</li>
<li>확률분포는 데이터를 해석하는데 도움을 줌 (초상화)</li>
</ul>
<p><img src="/assets/img/ustage_day9/2.png" alt="image2" /></p>
<h3 id="이산확률변수-vs-연속확률변수">이산확률변수 vs 연속확률변수</h3>
<ul>
<li>확률변수는 확률분포 𝔇 에 따라 이산형 (discrete) 과 연속형 (continuous) 확률변수로 구분
<ul>
<li>데이터 공간 $x$ x $y$ 로 구분하는게 아니라 확률분포의 종류에 따라 구분!</li>
</ul>
</li>
<li>이산형확률변수
<ul>
<li>확률변수가 가질 수 있는 경우의 수를 모두 고려하여 확률을 <strong>더해서</strong> 모델링함</li>
<li>P(X = x) 는 확률변수가 x 값을 가질 확률</li>
</ul>
<p><img src="/assets/img/ustage_day9/3.png" alt="image3" /></p>
</li>
<li>연속형확률변수
<ul>
<li>데이터 공간에 정의된 확률변수의 밀도 (density) 위에서의 <strong>적분</strong>을 통해 모델링</li>
<li>P(x) : 밀도함수, 누적확률분포, 데이터 공간에 정의된 확률보다는 밀도 (적분 필요)
<ul>
<li>밀도는 누적확률분포의 변화율을 모델링, 확률로 해석 x</li>
</ul>
</li>
<li>보통 컴퓨터에 쓰는 데이터는 이산형이지만 기계학습에는 정규분포, 감마분포 등 연속형확률변수 씀</li>
</ul>
<p><img src="/assets/img/ustage_day9/4.png" alt="image4" /></p>
</li>
<li>이산형과 연속형으로 모든 확률분포 표현되는건 아님, 더 있음</li>
</ul>
<h3 id="조건부확률과-기계학습">조건부확률과 기계학습</h3>
<ul>
<li>조건부확률 P(y | x) 는 입력변수 x 에 대해 정답이 y 일 확률
<ul>
<li>연속확률분포면 확률 대신 밀도로 해석</li>
</ul>
</li>
<li>저번 시간에 사용한 로지스틱 회귀의 선형모델과 소프트맥스 함수의 결합은 <strong>데이터에서 추출된 패턴을 기반으로 확률 해석</strong>
<ul>
<li>선형함수가 비선형함수를 거치면 확률이 됨</li>
</ul>
</li>
<li>분류 문제에서 softmax($W\phi + b)$ 는 데이터 x 로부터 추출된 특징패턴 $\phi(x)$ 과 가중치행렬 W 을 통해 조건부 확률 P(y | x) (= P(y | $\phi(x)$) 를 계산</li>
<li>회귀 문제의 경우 조건부기대값 E[y | x] 를 추정
<ul>
<li>조건부 확률 대신 조건부기대값을 구해야(추정)한다는 말</li>
<li>보통 회귀 문제는 연속확률분포를 다루므로 적분 사용</li>
<li>왜 조건부기대값을 구하나?
<ul>
<li>목적식 L2-norm 을 최소화하는 함수 = 조건부기대값 이기 때문</li>
</ul>
</li>
<li>robust (강건) 하게 예측할 때는 조건부기대값 대신 median (중간값) 사용</li>
<li>통계적 모형에서 원하는 목적에 따라 추정량이 달라질 수 있다!</li>
</ul>
<p><img src="/assets/img/ustage_day9/5.png" alt="image5" /></p>
</li>
<li>딥러닝은 다층신경망을 사용하여 데이터로부터 특징패턴 $\phi$ 를 추출
<ul>
<li>특징패턴을 학습하기 위해 어떤 손실함수를 사용할지는 기계학습 문제와 모델에 의해 결정됨</li>
</ul>
</li>
</ul>
<h3 id="기대값">기대값</h3>
<ul>
<li>확률분포가 주어지면 데이터를 분석하는데 사용 가능한 여러 종류의 통계적 범함수 (statistical function) 계산 가능</li>
<li>기대값 (expectation) 은 <strong>데이터를 대표하는 통계량</strong>이면서 동시에 <strong>확률분포를 통해 다른 통계적 범함수를 계산</strong>하는데 사용</li>
</ul>
<p><img src="/assets/img/ustage_day9/6.png" alt="image6" /></p>
<ul>
<li>기대값을 이용해 분산, 첨도(첨도말고 왜도인듯 = 비대칭도), 공분산 등 여러 통계량 계산 가능</li>
</ul>
<p><img src="/assets/img/ustage_day9/7.png" alt="image7" /></p>
<ul>
<li>기억해야할 것 : 이산이면 급수(질량함수), 연속이면 적분 사용</li>
</ul>
<h3 id="몬테카를로-샘플링">몬테카를로 샘플링</h3>
<ul>
<li>기계학습의 많은 문제들은 확률분포를 명시적으로 모를 때가 대부분 → 몬테카를로 샘플링은 기계학습에서 매우 다양하게 응용</li>
<li>확률분포를 모르기에 데이터를 이용해 기대값을 계산하기 위해 몬테카를로 샘플링을 사용</li>
<li>이산형 연속형 상관없이 성립</li>
<li>
<p>독립추출 (분포에서 독립적으로 추출 = 샘플링) 이 보장된다면 대수의 법칙 (law of large number) 에 의해 수렴성을 보장<br />
(Q. 대수의 법칙이 뭐지 -> 전체 모집단에서 랜덤한 표본의 평균은 전체의 평균과 가까울 가능성이 높다는 법칙)</p>
<p><img src="/assets/img/ustage_day9/8.png" alt="image8" /></p>
</li>
<li>예제 : 적분 계산하기
<ul>
<li>확률분포가 아닌 공간에서 적분은 불가능 → 몬테카를로</li>
<li>예제의 f(x) 는 우리가 아는 적분식으로 적분 구하기 힘듦</li>
<li>f(x) 의 적분의 길이가 2 이므로 반으로 나누면 기대값. 기대값은 몬테카를로 방법 가능.</li>
<li>다 구하고 다시 2 곱하면 됨.</li>
<li>uniform (균등) 분포에서 샘플링해주면 오차 범위 안에 들어옴.
<ul>
<li>샘플 사이즈가 적으면 오차범위 커짐 → 참값에 멀어짐, 적절히 조절해야 함</li>
</ul>
</li>
</ul>
<p><img src="/assets/img/ustage_day9/9.png" alt="image9" /></p>
<p><img src="/assets/img/ustage_day9/10.png" alt="image10" /></p>
</li>
</ul>
<p><br /></p>
<hr />
<p><br /></p>
<h1 id="피어-세션">피어 세션</h1>
<p><br /></p>
<h2 id="피어-세션이-피어씁니다">피어 세션이 피어씁니다</h2>
<ul>
<li>각오 : 우리 나이에 늦은건 키즈 모델뿐! 초심과 맥심을 잃지 말자^^</li>
</ul>
<h2 id="수업-질문">수업 질문</h2>
<ul>
<li>iid = 서로 독립이고 동일한 분포를 따른다. ~ 물결 표시로 표현. 이게 돼야 몬테카를로 샘플링 가능 (전제조건임)</li>
<li>확률 배우고 이런거 실제로 많이 쓰일까?<br />
→ 논문 볼 때 수식 엄청 나와서 모르면 이해가 안됨</li>
<li>펭귄님 블로깅 팁 : 아웃라인 먼저 막 적어놓고 정리를 해나감</li>
<li>서폿님 : 수식을 인식해서 라텍스 문법으로 바꿔주는 프로젝트 해보고 싶다 (OCR)<br />
→ 엠제이님 : mask RCNN 논문 읽어보는거 추천</li>
</ul>
<p><br /></p>
<hr />
<p><br /></p>
<h1 id="today-i-felt">Today I Felt</h1>
<p><br /></p>
<h2 id="조화">조화</h2>
<p>2 주차는 머신러닝에 필요한 수학에 대해 공부하고 있다. 수학에 관련되다보니 요즘 피어세션에서 가장 두드러지는 사람은 원딜님이다 (통계갓,,) . 통계에 대한 기본 지식도 정리해서 올려주고 피어 세션에 나오는 질문도 잘 알려주고 계신데, 우리 조에 컴공만이 아니라 통계학과 수학과 등 여러 환경의 사람들이 모였기 때문에 더 도움 받기 좋음을 느꼈다. 왜 요즘 회사들도 비전공자 출신을 뽑는지 알 것 같았다. 기본 실력만 있다면 다채로움이 만들어내는 조화가 더 좋기 때문이 아닐까?</p>
</section>
</div>
<div id="top" class="top-btn" onclick="moveTop()">
<i class="fas fa-chevron-up"></i>
</div>
<!-- Disqus -->
<div id="comments">
<div class="border">
<div id="disqus_thread"></div>
<script type="text/javascript">
var disqus_shortname = 'heeseok-jeong';
(function () {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript></noscript>
</div>
</div>
<!-- Footer -->
<footer>
<div class="footer">
Copyright © 2019
<a href="https://github.com/NAYE0NG">Nayeong Kim</a>.
Powered by Jekyll with
<a href="https://github.com/naye0ng/Grape-Theme">Grape Theme</a>.
</div>
</footer>
<script>
var lastScrollTop = 0;
window.onscroll = function () {
var st = document.body.scrollTop || document.documentElement.scrollTop;
if (st > 250) {
document.getElementById("top").style.display = "block"
if (st > lastScrollTop) {
document.getElementById("top").style.opacity = 0
} else {
document.getElementById("top").style.opacity = 1
}
} else {
document.getElementById("top").style.opacity = 0
if (st > lastScrollTop) {
document.getElementById("top").style.display = "none"
}
}
lastScrollTop = st <= 0 ? 0 : st;
}
function moveTop() {
document.body.scrollTop = 0
document.documentElement.scrollTop = 0
}
</script>
</div>
</body>
</html> | 35.416569 | 712 | 0.611657 |
4db67d6e5607dbea3f5622462b734474322e940c | 11,585 | asm | Assembly | vtcomp/runner.asm | nanoflite/victracker | 5728bba3a9df449996ab1c0a0911cf282ac4657e | [
"BSD-3-Clause"
] | 1 | 2021-09-20T20:35:14.000Z | 2021-09-20T20:35:14.000Z | vtcomp/runner.asm | nanoflite/victracker | 5728bba3a9df449996ab1c0a0911cf282ac4657e | [
"BSD-3-Clause"
] | null | null | null | vtcomp/runner.asm | nanoflite/victracker | 5728bba3a9df449996ab1c0a0911cf282ac4657e | [
"BSD-3-Clause"
] | null | null | null | ;**************************************************************************
;*
;* FILE runner.asm
;* Copyright (c) 1994, 2001, 2003 Daniel Kahlin <daniel@kahlin.net>
;* Written by Daniel Kahlin <daniel@kahlin.net>
;* $Id: runner.asm,v 1.12 2003/08/26 16:51:38 tlr Exp $
;*
;* DESCRIPTION
;* runner for packed vic-tracker tunes. Uses player.asm.
;* Works on both unexpanded and expanded VIC-20s.
;*
;******
PROCESSOR 6502
; song configuration.
NUMSONGS EQU @NUMSONGS@
TITLE EQM @TITLE@
AUTHOR EQM @AUTHOR@
VERSION EQM @VERSION@
IFNCONST RN_VTCOMP
; modes
;RN_DEBUG EQU 1
;RN_DEBUG EQU 1
RN_UNEXP EQU 1
RN_SPEED_1X EQU 1
;RN_SPEED_2X EQU 1
;RN_SPEED_3X EQU 1
;RN_SPEED_4X EQU 1
ENDIF ;RN_VTCOMP
; macros
MAC HEXDIGIT
IFCONST [{1}]
IF [{1}]<10
dc.b "0"+[{1}]
ELSE
dc.b "A"+[{1}]-10
ENDIF
ELSE
dc.b "x"
ENDIF
ENDM
MAC HEXWORD
HEXDIGIT [{1}]>>12
HEXDIGIT [[{1}]>>8]&$0f
HEXDIGIT [[{1}]>>4]&$0f
HEXDIGIT [{1}]&$0f
ENDM
BorderColor EQU 6
BorderColor_Play EQU 3
BackgroundColor EQU 14
NormalColor EQU [BackgroundColor<<4]+BorderColor+8
PlayColor EQU [BackgroundColor<<4]+BorderColor_Play+8
INFO_POS EQU 7
INFO_HEIGHT EQU 6
BONUS_POS EQU 15
IFCONST RN_DEBUG
SCROLL_POS EQU 15
SCROLL_HEIGHT EQU 7
DATA_POS EQU 0
ENDIF ;RN_DEBUG
;the length of a screen in cycles (PAL)
SCREENTIME_PAL EQU 22150
;the length of a screen in cycles (NTSC)
SCREENTIME_NTSC EQU 16963
IFCONST RN_SPEED_1X
STARTLINE EQU 74+8*6
STARTLINE_PAL EQU STARTLINE
STARTLINE_NTSC EQU STARTLINE-24
ENDIF ;RN_SPEED_1X
IFCONST RN_SPEED_2X
SCREENTIMETWO_PAL EQU SCREENTIME_PAL/2
SCREENTIMETWO_NTSC EQU SCREENTIME_NTSC/2
INT_TIMES EQU 1
STARTLINE EQU 74+8*2
STARTLINE_PAL EQU STARTLINE
STARTLINE_NTSC EQU STARTLINE-24
ENDIF ;RN_SPEED_2X
IFCONST RN_SPEED_3X
SCREENTIMETWO_PAL EQU SCREENTIME_PAL/3
SCREENTIMETWO_NTSC EQU SCREENTIME_NTSC/3
INT_TIMES EQU 2
STARTLINE EQU 74-8*2
STARTLINE_PAL EQU STARTLINE
STARTLINE_NTSC EQU STARTLINE-24
ENDIF ;RN_SPEED_3X
IFCONST RN_SPEED_4X
SCREENTIMETWO_PAL EQU SCREENTIME_PAL/4
SCREENTIMETWO_NTSC EQU SCREENTIME_NTSC/4
INT_TIMES EQU 3
STARTLINE EQU 34
STARTLINE_PAL EQU STARTLINE
STARTLINE_NTSC EQU STARTLINE-24
ENDIF ;RN_SPEED_4X
IFCONST RN_UNEXP
rn_ScreenRAM EQU $1e00
rn_ColorRAM EQU $9600
ELSE ;!RN_UNEXP
rn_ScreenRAM EQU $1000
rn_ColorRAM EQU $9400
ENDIF ;RN_UNEXP
rn_CopyZP EQU $fb ;only used during copy down
rn_ScreenZP EQU $d1
rn_ColorZP EQU $fd
rn_YPosZP EQU $ff
rn_YTempZP EQU $fb
rn_XTempZP EQU $fc
seg code
org $1201 ; Normal 8,16,24Kb basic starting point
rn_LoadStart:
;**************************************************************************
;*
;* Basic line!
;*
;******
TOKEN_SYS EQU $9e
TOKEN_PEEK EQU $c2
TOKEN_PLUS EQU $aa
TOKEN_TIMES EQU $ac
StartOfFile:
dc.w EndLine
dc.w 2003
dc.b TOKEN_SYS,"(",TOKEN_PEEK,"(43)",TOKEN_PLUS,"256",TOKEN_TIMES,TOKEN_PEEK,"(44)",TOKEN_PLUS,"36) /T.L.R/",0
; 2003 SYS(PEEK(43)+256*PEEK(44)+36) /T.L.R/
EndLine:
dc.w 0
;**************************************************************************
;*
;* SysAddress... When run we will enter here!
;*
;******
startoffset EQU cp_store-StartOfFile
endoffset EQU startoffset+(cp_end-cp_start)
startoffset2 EQU rn_MainStart_st-StartOfFile
SysAddress:
sei
ldy #startoffset
sa_lp1:
lda ($2b),y
sta cp_start-startoffset,y
iny
cpy #endoffset
bne sa_lp1
lda $2b
clc
adc #<startoffset2
sta rn_CopyZP
lda $2c
adc #>startoffset2
sta rn_CopyZP+1
jmp cp_start
cp_store:
rorg $200
cp_start:
ldy #0
cp_lp1:
lda (rn_CopyZP),y
cp_lp2:
sta rn_Main,y
iny
bne cp_skp1
inc rn_CopyZP+1
inc cp_lp2+2
cp_skp1:
lda cp_lp2+2
cmp #>rn_MainEnd
bne cp_lp1
cpy #<rn_MainEnd
bne cp_lp1
jmp rn_Main
cp_end:
rend
echo "copydown", cp_start, "-", cp_end
rn_MainStart_st:
IFCONST RN_UNEXP
rorg $1000
ELSE ;RN_UNEXP
rorg $1200
ENDIF ;RN_UNEXP
;**************************************************************************
;*
;* This is the main program!
;*
;******
rn_Main:
jsr InterruptInit
jsr rn_InitScreen
rn_Restart:
lda #0
sta pl_PlayFlag
rn_mn_Toggle:
lda pl_PlayFlag
pha
lda rn_ThisSong
jsr pl_Init
pla
eor #$ff
sta pl_PlayFlag
beq rn_mn_lp1
lda #0
sta rn_MaxLines
rn_mn_lp1:
jsr $ffe4
beq rn_mn_lp1
cmp #" "
beq rn_mn_Toggle
cmp #"P"
beq rn_mn_Toggle
cmp #"M"
beq rn_Restart
cmp #"1" ;Less than "1"
bcc rn_mn_lp1 ;yes, loop.
cmp #"1"+NUMSONGS ;Greater than NUMSONGS
bcs rn_mn_lp1 ;yes, loop.
rn_mn_StartSong:
sec
sbc #"1"
sta rn_ThisSong
jmp rn_Restart
;**************************************************************************
;*
;* Initialize Interrupts!
;*
;******
InterruptInit:
sei
lda #$7f
sta $912e
sta $912d
lda #%11000000 ; T1 Interrupt Enabled
sta $912e
lda #%01000000
sta $912b
lda #<IRQServer
sta $0314
lda #>IRQServer
sta $0315
jsr CheckPAL
php
IFNCONST RN_SPEED_1X
ldx #<SCREENTIMETWO_PAL
ldy #>SCREENTIMETWO_PAL
stx Int_CurCycles
sty Int_CurCycles+1
ENDIF ;RN_SPEED_1X
ldx #<SCREENTIME_PAL
ldy #>SCREENTIME_PAL
lda #STARTLINE_PAL/2
plp
bne ii_skp1
IFNCONST RN_SPEED_1X
ldx #<SCREENTIMETWO_NTSC
ldy #>SCREENTIMETWO_NTSC
stx Int_CurCycles
sty Int_CurCycles+1
ENDIF ;RN_SPEED_1X
ldx #<SCREENTIME_NTSC
ldy #>SCREENTIME_NTSC
lda #STARTLINE_NTSC/2
ii_skp1:
jsr WaitLine
stx $9124
sty $9125 ;load T1
cli
rts
;**************************************************************************
;*
;* CheckPAL
;* Returns: Acc=0 on NTSC-M systems, Acc!=0 on PAL-B systems
;*
;******
CheckPAL:
; find raster line 2
lda #2/2
cpl_lp1:
cmp $9004
bne cpl_lp1
; now we know that we are past raster line 0, see if we find raster line 268
; before we find raster line 0
cpl_lp2:
lda $9004
beq cpl_ex1
cmp #268/2 ; This line does not exist on NTSC.
bne cpl_lp2
cpl_ex1:
cmp #0 ; test Acc;
rts
;**************************************************************************
;*
;* Wait until line ACC is passed
;*
;******
WaitLine:
wl_lp1:
cmp $9004
bne wl_lp1
wl_lp2:
cmp $9004
beq wl_lp2
rts
;**************************************************************************
;*
;* IRQ Interrupt server
;*
;******
IRQServer:
lda $912d
asl
asl
bcs irq_skp1 ;Did T1 time out?
IFNCONST RN_SPEED_1X
asl
bcs irq_skp2 ;Did T2 time out?
ENDIF ;RN_SPEED_1X
jmp $eabf
IFNCONST RN_SPEED_1X
irq_skp2:
dec Int_Count
bmi irq_skp3 ; Last Interrupt?
lda Int_CurCycles
sta $9128
lda Int_CurCycles+1
sta $9129 ;load T2
irq_skp3:
lda $9128 ;ACK T2 interrupt.
jsr rn_Frame ;Yes, run player.
jmp $eb18 ;Just pulls the registers
ENDIF ;RN_SPEED_1X
irq_skp1:
IFNCONST RN_SPEED_1X
lda Int_CurCycles
sta $9128
lda Int_CurCycles+1
sta $9129 ;load T2
lda #INT_TIMES
sta Int_Count
lda #%11100000 ;T1 Interrupt + T2 Interrupt
sta $912e
lda $9124 ;ACK T1 interrupt.
cli ;Enable nesting
ENDIF ;RN_SPEED_1X
jsr rn_Frame ;Yes, run player.
lda $9124 ;ACK T1 interrupt.
irq_ex1:
jmp $eabf
IFNCONST RN_SPEED_1X
Int_CurCycles:
dc.w 0
Int_CurTimes:
dc.b 0
Int_Count:
dc.b 0
ENDIF ;RN_SPEED_1X
;**************************************************************************
;*
;* Interrupt Routine
;* This gets called every frame!
;*
;******
rn_Frame:
lda #PlayColor
sta $900f
lda $9004 ;Rasterline
sta rn_Lines
jsr pl_Play
lda $9004 ;Rasterline
sec
sbc rn_Lines
asl ; multiply by two
sta rn_Lines
cmp rn_MaxLines
bcc rn_fr_skp2
sta rn_MaxLines
rn_fr_skp2:
; if we are not playing, wait a while to ensure that the color is visible
lda pl_PlayFlag
bne rn_fr_skp1
ldx #10
rn_fr_lp1:
dex
bne rn_fr_lp1
rn_fr_skp1:
lda #NormalColor
sta $900f
jsr rn_ShowData
IFCONST RN_DEBUG
lda pl_Count
cmp pl_Speed
bne rn_fr_ex1
ldx #0
rn_fr_lp2:
lda rn_ScreenRAM+[22*[SCROLL_POS+1]],x
sta rn_ScreenRAM+[22*[SCROLL_POS]],x
inx
cpx #22*6
bne rn_fr_lp2
jsr rn_UpdateScroll
rn_fr_ex1:
ENDIF ;RN_DEBUG
rts
;**************************************************************************
;*
;* This displays all other data!
;*
;******
rn_ShowData:
;Show number of raster lines
ldx #<[rn_ScreenRAM+[22*[INFO_POS+5]]]
ldy #>[rn_ScreenRAM+[22*[INFO_POS+5]]]
jsr rn_ScreenPtr
ldy #9
sty rn_YPosZP
lda rn_Lines
jsr rn_PutHex
ldy #18
sty rn_YPosZP
lda rn_MaxLines
jsr rn_PutHex
IFCONST RN_DEBUG
ldx #<[rn_ScreenRAM+[22*DATA_POS]]
ldy #>[rn_ScreenRAM+[22*DATA_POS]]
jsr rn_ScreenPtr
;Show a selection of internal player parameters
ldy #[22*0+3]
sty rn_YPosZP
ldx #0
rn_sd_lp1:
lda pl_vd_PattlistStep,x
jsr rn_PutHex
lda pl_vd_FetchMode,x
jsr rn_PutHex
lda pl_vd_CurrentPattern,x
jsr rn_PutHex
lda pl_vd_PatternStep,x
jsr rn_PutHex
lda pl_vd_FreqOffsetLow,x
jsr rn_PutHex
lda pl_vd_FreqOffsetHigh,x
jsr rn_PutHex
lda pl_vd_ArpStep,x
jsr rn_PutHex
lda pl_vd_ArpOffset,x
jsr rn_PutHex
lda rn_YPosZP
clc
adc #6
sta rn_YPosZP
inx
cpx #5
bne rn_sd_lp1
rts
IFCONST RN_DEBUG
ENDIF ;RN_DEBUG
rn_UpdateScroll:
ldx #<[rn_ScreenRAM+[22*[SCROLL_POS+SCROLL_HEIGHT-1]]]
ldy #>[rn_ScreenRAM+[22*[SCROLL_POS+SCROLL_HEIGHT-1]]]
jsr rn_ScreenPtr
;Handle update of the scroller
ldy #1
sty rn_YPosZP
ldx #0
rn_sd_lp4:
lda pl_vd_Note,x
jsr rn_PutHex
lda pl_vd_Param,x
jsr rn_PutHex
inx
cpx #5
bne rn_sd_lp4
rts
ENDIF ;RN_DEBUG
rn_ScreenPtr:
stx rn_ScreenZP
sty rn_ScreenZP+1
rts
rn_PutHex:
sty rn_YTempZP
stx rn_XTempZP
pha
lsr
lsr
lsr
lsr
jsr rn_ph_Put
pla
and #$0f
jsr rn_ph_Put
ldx rn_XTempZP
ldy rn_YTempZP
rts
rn_ph_Put:
tax
ldy rn_YPosZP
lda rn_HexTab,x
sta (rn_ScreenZP),y
inc rn_YPosZP
rts
rn_HexTab:
dc.b "0123456789",1,2,3,4,5,6
rn_ThisSong:
dc.b 0
rn_Lines:
dc.b 0
rn_MaxLines:
dc.b 0
rn_InitScreen:
IFCONST RN_UNEXP
; screenmem at $1e00, colormem at $9600
lda $9002
ora #$80
sta $9002
lda #$f0
sta $9005
ELSE ;RN_UNEXP
; screenmem at $1000, colormem at $9400
lda $9002
and #$7f
sta $9002
lda #$c0
sta $9005
ENDIF ;!RN_UNEXP
lda #NormalColor
sta $900f
ldx #0
rn_is_lp1:
lda #$a0
sta rn_ScreenRAM,x
sta rn_ScreenRAM+$100,x
lda #6
sta rn_ColorRAM,x
sta rn_ColorRAM+$100,x
inx
bne rn_is_lp1
IFCONST RN_DEBUG
lda #>[rn_ColorRAM+[22*SCROLL_POS]]
sta rn_ColorZP+1
lda #<[rn_ColorRAM+[22*SCROLL_POS]]
sta rn_ColorZP
ldx #SCROLL_HEIGHT-1
rn_is_lp2:
ldy #21
rn_is_lp3:
lda rn_ColorTab,y
sta (rn_ColorZP),y
dey
bpl rn_is_lp3
lda rn_ColorZP
clc
adc #22
sta rn_ColorZP
bcc rn_is_skp1
inc rn_ColorZP+1
rn_is_skp1:
dex
bpl rn_is_lp2
ENDIF ;RN_DEBUG
ldx #22-1
rn_is_lp4:
lda #$20
sta rn_ScreenRAM+22*6,x
sta rn_ScreenRAM+22*13,x
lda rn_Bonus_MSG,x
and #$3f
ora #$80
sta rn_ScreenRAM+22*BONUS_POS,x
dex
bpl rn_is_lp4
ldx #22*INFO_HEIGHT
rn_is_lp5:
lda rn_Info_MSG-1,x
and #$3f
sta rn_ScreenRAM+22*INFO_POS-1,x
lda #1
sta rn_ColorRAM+22*INFO_POS-1,x
dex
bne rn_is_lp5
rts
rn_Info_MSG:
; line1
dc.b "TITLE : "
dc.b TITLE
; line2
dc.b "AUTHOR: "
dc.b AUTHOR
; line3
dc.b "SONGS : "
HEXDIGIT NUMSONGS
IF NUMSONGS>1
dc.b " (1-"
HEXDIGIT NUMSONGS
dc.b ") "
ELSE
dc.b " "
ENDIF
; line4
dc.b "ADDR : $"
HEXWORD start
dc.b "-$"
HEXWORD end
dc.b " "
; line5
dc.b "LENGTH: $"
HEXWORD end-start
dc.b " "
; line6
dc.b "LINES : $00 (MAX $00) "
rn_Bonus_MSG:
dc.b " VIC-PLAYER "
dc.b VERSION
dc.b " "
IFCONST RN_DEBUG
rn_ColorTab:
dc.b 6,2,2,2,2,6,6,6,6,2,2,2,2,6,6,6,6,2,2,2,2,6
ENDIF ;RN_DEBUG
IFNCONST RN_UNEXP
align 256
ENDIF ;RN_UNEXP
start:
include @FILE@
end:
rn_MainEnd:
rend
rn_LoadEnd:
echo "Player: ",start,"-",end,"(=",end-start,"bytes,",(end-start+253)/254,"blocks)"
echo "Load: ",rn_LoadStart,"-",rn_LoadEnd,"(=",rn_LoadEnd-rn_LoadStart,"bytes,",(rn_LoadEnd-rn_LoadStart+253)/254,"blocks)"
; eof
| 17.11226 | 124 | 0.676047 |
c69f89a439477b7a0538e3950ce71183f5ea9b2e | 5,926 | tab | SQL | src/numeric.tab | Acidburn0zzz/tethys | 2456a24764729620735010db1a37fb6fb060c1a3 | [
"MIT"
] | 4 | 2015-01-06T13:02:16.000Z | 2015-03-28T15:13:30.000Z | src/numeric.tab | atheme/tethys | e0eb8c458369b64848c3486d553e650c2f86e31b | [
"MIT"
] | null | null | null | src/numeric.tab | atheme/tethys | e0eb8c458369b64848c3486d553e650c2f86e31b | [
"MIT"
] | 2 | 2016-01-09T03:30:18.000Z | 2019-06-04T23:45:19.000Z | RPL_WELCOME 1 ":Welcome to the %s Internet Relay Chat Network %s"
RPL_YOURHOST 2 ":Your host is %s, running version %s"
RPL_CREATED 3 ":This server was born on %s"
RPL_MYINFO 4 "%s %s %s %s idfk"
RPL_ISUPPORT 5 "%s :are supported by this server"
RPL_YOUREJAMESBOND 7 ":You are now Bond. James Bond."
RPL_MAP 15 ":%s"
RPL_MAPEND 17 ":End of /MAP"
RPL_STATSLINKINFO 211
RPL_STATSCOMMANDS 212
RPL_STATSCLINE 213
RPL_STATSNLINE 214
RPL_STATSILINE 215 "I %s %s %s"
RPL_STATSKLINE 216
RPL_STATSYLINE 218
RPL_ENDOFSTATS 219 "%s :End of /STATS report"
RPL_STATSPLINE 220
RPL_UMODEIS 221 "%s"
RPL_STATSFLINE 224
RPL_STATSDLINE 225
RPL_SERVLIST 234
RPL_SERVLISTEND 235
RPL_STATSLLINE 241
RPL_STATSUPTIME 242 ":Server up %d days, %02d:%02d:%02d"
RPL_STATSOLINE 243 "O %s %s %s"
RPL_STATSHLINE 244
RPL_STATSSLINE 245
RPL_STATSXLINE 247
RPL_STATSULINE 248
RPL_STATSDEBUG 249
RPL_STATSCONN 250
RPL_LUSERCLIENT 251
RPL_LUSEROP 252
RPL_LUSERUNKNOWN 253
RPL_LUSERCHANNELS 254
RPL_LUSERME 255
RPL_ADMINME 256 ":Administrative info about %S"
RPL_ADMINLOC1 257 ":%s"
RPL_ADMINLOC2 258 ":%s"
RPL_ADMINEMAIL 259 ":%s"
RPL_TRACELOG 261
RPL_ENDOFTRACE 262
RPL_NONE 300
RPL_AWAY 301 "%s :%s"
RPL_USERHOST 302 ":%s"
RPL_ISON 303
RPL_UNAWAY 305 ":You are no longer marked as being away"
RPL_NOWAWAY 306 ":You have been marked as being away"
RPL_WHOISUSER 311 "%s %s %s * :%s"
RPL_WHOISSERVER 312 "%s %s :%s"
RPL_WHOISOPERATOR 313 "%s :is %s"
RPL_WHOWASUSER 314
RPL_ENDOFWHO 315 "%s :End of /WHO list."
RPL_WHOISIDLE 317 "%s %u %u :seconds idle, signon time"
RPL_ENDOFWHOIS 318 "%s :End of /WHOIS list."
RPL_WHOISCHANNELS 319 "%s :%s"
RPL_LISTSTART 321 "Channel :Users Name"
RPL_LIST 322 "%s %d :%s"
RPL_LISTEND 323 ":End of /LIST"
RPL_CHANNELMODEIS 324 "%C %s"
RPL_CHANNELMLOCK 325
RPL_WHOISLOGGEDIN 330 "%s %s :is logged in as"
RPL_NOTOPIC 331 "%C :No topic is set"
RPL_TOPIC 332 "%C :%s"
RPL_TOPICWHOTIME 333 "%C %s %u"
RPL_WHOISTEXT 337
RPL_WHOISACTUALLY 338
RPL_INVITING 341 "%U %C"
RPL_SUMMONING 342
RPL_INVITELIST 346 "%C %s %s %u"
RPL_ENDOFINVITELIST 347 "%C :End of Channel Invite List"
RPL_EXCEPTLIST 348 "%C %s %s %u"
RPL_ENDOFEXCEPTLIST 349 "%C :End of Channel Exception List"
RPL_VERSION 351 "%s %s :[%s] %s"
RPL_WHOREPLY 352 "%C %s %s %s %s %s :%d %s"
RPL_NAMREPLY 353 "%c %C :%s"
RPL_LINKS 364
RPL_ENDOFLINKS 365
RPL_ENDOFNAMES 366 "%C :End of /NAMES list"
RPL_BANLIST 367 "%C %s %s %u"
RPL_ENDOFBANLIST 368 "%C :End of Channel Ban List"
RPL_ENDOFWHOWAS 369
RPL_INFO 371
RPL_MOTD 372 ":- %s"
RPL_ENDOFINFO 374
RPL_MOTDSTART 375 ":- %s Message of the day -"
RPL_ENDOFMOTD 376 ":End of /MOTD command"
RPL_YOUREOPER 381 ":MAIN SCREEN TURN ON"
RPL_REHASHING 382 ":Rehashing"
RPL_UPGRADEFAILED 383 ":Upgrade failed."
RPL_UPGRADESTARTING 384 ":Now upgrading..."
RPL_TIME 391
RPL_USERSSTART 392
RPL_USERS 393
RPL_ENDOFUSERS 394
RPL_NOUSERS 395
ERR_GENERIC 400 ":Error: %s"
ERR_NOSUCHNICK 401 "%s :No such nick/channel"
ERR_NOSUCHSERVER 402 "%s :No such server"
ERR_NOSUCHCHANNEL 403 "%s :No such channel"
ERR_CANNOTSENDTOCHAN 404 "%C :Cannot send to channel (+%c)"
ERR_TOOMANYCHANNELS 405 "%s :You have joined too many channels"
ERR_WASNOSUCHNICK 406 "%s :There was no such nickname"
ERR_TOOMANYTARGETS 407 "%s :Too many recipients."
ERR_NOORIGIN 409 ":No origin specified"
ERR_NORECIPIENT 411 ":No recipient given"
ERR_NOTTEXTTOSEND 412 ":No text to send"
ERR_NOTOPLEVEL 413 ":No toplevel domain specified"
ERR_WILDTOPLEVEL 414 ":Wildcard in toplevel domain"
ERR_UNKNOWNCOMMAND 421 "%s :Unknown command"
ERR_NOMOTD 422 ":MOTD missing"
ERR_NOADMININFO 423
ERR_FILEERROR 424
ERR_NONICKNAMEGIVEN 431 ":No nickname given"
ERR_ERRONEOUSNICKNAME 432 "%s :Erroneous nickname"
ERR_NICKNAMEINUSE 433 "%s :Nickname is already in use"
ERR_NICKCOLLISION 436
ERR_SERVICESDOWN 440 "%s :Services are currently unavailable"
ERR_USERNOTINCHANNEL 441 "%U %C :They aren't on that channel"
ERR_NOTONCHANNEL 442 "%C :You're not on that channel"
ERR_USERONCHANNEL 443 "%U %C :They're already on that channel"
ERR_NOLOGIN 444
ERR_SUMMONDISABLED 445 ":/SUMMON is disabled on this server"
ERR_USERSDISABLED 446
ERR_NOTREGISTERED 451 ":You have not registered"
ERR_NEEDMOREPARAMS 461 "%s :Not enough parameters"
ERR_ALREADYREGISTERED 462 ":You may not reregister"
ERR_NOPERMFORHOST 463
ERR_PASSWDMISMATCH 464 ":Password incorrect"
ERR_YOUREBANNEDCREEP 465
ERR_KEYSET 467
ERR_CHANNELISFULL 471 "%C :Channel is full"
ERR_UNKNOWNMODE 472 "%c :is an unknown mode char to me"
ERR_INVITEONLYCHAN 473 "%C :Cannot join channel (+i)"
ERR_BANNEDFROMCHAN 474 "%C :Cannot join channel (+b)"
ERR_BADCHANNELKEY 475 "%C :Cannot join channel (+k)"
ERR_BANLISTFULL 478 "%C %s :Channel ban list is full"
ERR_BADCHANNAME 479 "%s :Illegal channel name"
ERR_NOPRIVILEGES 481 ":You're not an IRC operator"
ERR_CHANOPRIVSNEEDED 482 "%C :You're not a channel operator"
ERR_CANTKILLSERVER 483 ":You don't kill a server, moron. Try /DIE. Who gave you your O-line?"
ERR_NOOPERHOST 491 ":No O-lines for your host"
ERR_UMODEUNKNOWNFLAG 501 ":Unknown MODE flag"
ERR_USERSDONTMATCH 502 ":Can't change mode for other users"
ERR_HELPNOTFOUND 524 "%s :Help not found"
RPL_HELPSTART 704 "%s :%s"
RPL_HELPTXT 705 "%s :%s"
RPL_ENDOFHELP 706 "%s :End of /HELP."
RPL_QUIETLIST 728 "%C q %s %s %u"
RPL_ENDOFQUIETLIST 729 "%C q :End of Channel Quiet List"
ERR_CHALLENGE_NOSUPPORT 737 ":CHALLENGE is not supported on this server"
ERR_CHALLENGE_NOPUBKEY 738 ":CHALLENGE is not enabled for this operator"
ERR_CHALLENGE_GENERATE 739 ":Unable to generate a challenge"
RPL_CHALLENGE_STRING 740 ":%s"
RPL_CHALLENGE_FINISH 741 ":End of challenge"
RPL_CHALLENGE_SUCCESS 742 ":Challenge successful"
ERR_CHALLENGE_FAILURE 743 ":Challenge failed"
ERR_CHALLENGE_EXPIRED 744 ":The challenge for this operator has expired"
ERR_CHALLENGE_INPROG 745 ":A CHALLENGE for this operator is already in progress"
ERR_CHALLENGE_NINPROG 746 ":A CHALLENGE for this operator is not in progress"
| 28.76699 | 93 | 0.769997 |
2f1982c903c616c8e070edbca5af7436b37495c7 | 1,571 | java | Java | netty-websocket-http2/src/main/java/com/jauntsdn/netty/handler/codec/http2/websocketx/Http2WebSocketChannelFutureListener.java | jauntsdn/netty-websocket-http2 | d76982d2afadec9447cd98922e435173a214b3d3 | [
"Apache-2.0"
] | 11 | 2020-07-30T14:12:13.000Z | 2021-09-05T16:00:26.000Z | netty-websocket-http2/src/main/java/com/jauntsdn/netty/handler/codec/http2/websocketx/Http2WebSocketChannelFutureListener.java | jauntsdn/netty-websocket-http2 | d76982d2afadec9447cd98922e435173a214b3d3 | [
"Apache-2.0"
] | 1 | 2020-07-30T14:13:42.000Z | 2020-09-05T08:31:32.000Z | netty-websocket-http2/src/main/java/com/jauntsdn/netty/handler/codec/http2/websocketx/Http2WebSocketChannelFutureListener.java | jauntsdn/netty-websocket-http2 | d76982d2afadec9447cd98922e435173a214b3d3 | [
"Apache-2.0"
] | 1 | 2021-05-15T01:16:06.000Z | 2021-05-15T01:16:06.000Z | /*
* Copyright 2020 - present Maksym Ostroverkhov.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jauntsdn.netty.handler.codec.http2.websocketx;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.util.concurrent.GenericFutureListener;
/**
* ChannelFuture listener that gracefully closes websocket by sending empty DATA frame with
* END_STREAM flag set.
*/
public final class Http2WebSocketChannelFutureListener
implements GenericFutureListener<ChannelFuture> {
public static final Http2WebSocketChannelFutureListener CLOSE =
new Http2WebSocketChannelFutureListener();
private Http2WebSocketChannelFutureListener() {}
@Override
public void operationComplete(ChannelFuture future) {
Channel channel = future.channel();
Throwable cause = future.cause();
if (cause != null) {
Http2WebSocketEvent.fireFrameWriteError(channel, cause);
}
channel
.pipeline()
.fireUserEventTriggered(Http2WebSocketEvent.Http2WebSocketLocalCloseEvent.INSTANCE);
}
}
| 34.152174 | 92 | 0.762572 |
46df6d8dc26c9ba58ad23b32e94e052d481eb2cc | 763 | html | HTML | AULA 06/ex006.html | joaovianayt/javascript | 0ba7c264d50d87783580f853b9f8055798e5fd3a | [
"MIT"
] | null | null | null | AULA 06/ex006.html | joaovianayt/javascript | 0ba7c264d50d87783580f853b9f8055798e5fd3a | [
"MIT"
] | null | null | null | AULA 06/ex006.html | joaovianayt/javascript | 0ba7c264d50d87783580f853b9f8055798e5fd3a | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Primeiro Passos com DOM</title>
<style>
body{
background: rgb(255, 108, 108);
color: rgb(255, 255, 255);
font: normal 18pt Ariaç;;
}
</style>
</head>
<body>
<h1>Iniciando Estudos com DOM
<p>Aqui vai o Resultado</p>
<p>Aprendendo a usar o <strong> DOM </strong> em Java Script. </p>
<div>CLIQUE EM MIM</div>
<script>
var p1 = window.document.getElementsByTagName("p")[1 ]
window.document.write(" Está Escrito Assim: " + p1.innerText)
</script>
</h1>
</body>
</html>
| 25.433333 | 74 | 0.600262 |
9bcc4a3f169a9a86cc8bd011d09cb448feae09f2 | 2,093 | kt | Kotlin | src/main/kotlin/br/com/zup/edu/keymanager/chavepix/lista/ListaChavesPixEndPoint.kt | jaacksonalves/orange-talents-02-template-pix-keymanager-grpc | e11f987f10675ce553549f6a1c24e404a7f29a3c | [
"Apache-2.0"
] | null | null | null | src/main/kotlin/br/com/zup/edu/keymanager/chavepix/lista/ListaChavesPixEndPoint.kt | jaacksonalves/orange-talents-02-template-pix-keymanager-grpc | e11f987f10675ce553549f6a1c24e404a7f29a3c | [
"Apache-2.0"
] | null | null | null | src/main/kotlin/br/com/zup/edu/keymanager/chavepix/lista/ListaChavesPixEndPoint.kt | jaacksonalves/orange-talents-02-template-pix-keymanager-grpc | e11f987f10675ce553549f6a1c24e404a7f29a3c | [
"Apache-2.0"
] | null | null | null | package br.com.zup.edu.keymanager.chavepix.lista
import br.com.zup.edu.*
import br.com.zup.edu.keymanager.chavepix.ChavePixRepository
import br.com.zup.edu.keymanager.chavepix.compartilhado.exceptions.handlers.ErrorHandler
import com.google.protobuf.Timestamp
import io.grpc.stub.StreamObserver
import java.time.ZoneId
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
@ErrorHandler
@Singleton
class ListaChavesPixEndPoint(@Inject private val repository: ChavePixRepository) :
ListaChavePixServiceGrpc.ListaChavePixServiceImplBase() {
override fun lista(request: ListaChavePixRequest, responseObserver: StreamObserver<ListaChavePixResponse>) {
if (request.clienteId.isNullOrBlank()) {
throw IllegalArgumentException("Deve preencher corretamente ClienteId")
}
if (!repository.existsByContaAssociadaTitularTitularId(UUID.fromString(request.clienteId))) {
throw java.lang.IllegalArgumentException("Cliente não encontrado")
}
val chavesPorId = repository.findAllByContaAssociadaTitularTitularId(UUID.fromString(request.clienteId))
val chavesResponse = chavesPorId.map {
ListaChavePixResponse.ChavePixLista.newBuilder()
.setPixId(it.id.toString())
.setTipoChave(TipoChave.valueOf(it.tipoChave.name))
.setChave(it.chave)
.setTipoConta(TipoConta.valueOf(it.contaAssociada.tipoConta.name))
.setCriadaEm(it.criadoEm.let {
val createdAt = it.atZone(ZoneId.of("GMT-3")).toInstant()
Timestamp.newBuilder()
.setSeconds(createdAt.epochSecond)
.setNanos(createdAt.nano)
.build()
})
.build()
}
responseObserver.onNext(
ListaChavePixResponse.newBuilder()
.setClienteId(request.clienteId)
.addAllChaves(chavesResponse)
.build()
)
responseObserver.onCompleted()
}
} | 38.054545 | 112 | 0.664118 |
56d4ddce648019b565c593f21460de091db5ac38 | 62 | dart | Dart | lib/src/enum.dart | dart-bitcoin-lib/dart-bech32 | 5683fd9b1ddb4f1524dd23ea6cf50239dd37c097 | [
"MIT"
] | null | null | null | lib/src/enum.dart | dart-bitcoin-lib/dart-bech32 | 5683fd9b1ddb4f1524dd23ea6cf50239dd37c097 | [
"MIT"
] | null | null | null | lib/src/enum.dart | dart-bitcoin-lib/dart-bech32 | 5683fd9b1ddb4f1524dd23ea6cf50239dd37c097 | [
"MIT"
] | null | null | null | /// Encoding Enums
enum EncodingEnum {
bech32,
bech32m,
}
| 10.333333 | 19 | 0.677419 |
4c9f05d78b3dcead14b4232d51c62231aaab5f7c | 6,055 | kt | Kotlin | twitlin/src/common/main/kotlin/com/sorrowblue/twitlin/v2/tweets/impl/TweetsApiImp.kt | SorrowBlue/Twitlin | 728f84d96dab86f43309674ddee7754b77fce956 | [
"MIT"
] | 1 | 2021-11-20T06:02:03.000Z | 2021-11-20T06:02:03.000Z | twitlin/src/common/main/kotlin/com/sorrowblue/twitlin/v2/tweets/impl/TweetsApiImp.kt | SorrowBlue/Twitlin | 728f84d96dab86f43309674ddee7754b77fce956 | [
"MIT"
] | 1 | 2020-08-08T15:29:10.000Z | 2020-08-08T15:31:44.000Z | twitlin/src/common/main/kotlin/com/sorrowblue/twitlin/v2/tweets/impl/TweetsApiImp.kt | SorrowBlue/Twitlin | 728f84d96dab86f43309674ddee7754b77fce956 | [
"MIT"
] | null | null | null | /*
* (c) 2020-2021 SorrowBlue.
*/
package com.sorrowblue.twitlin.v2.tweets.impl
import com.sorrowblue.twitlin.core.Urls
import com.sorrowblue.twitlin.v2.client.Response
import com.sorrowblue.twitlin.v2.client.UserClient
import com.sorrowblue.twitlin.v2.field.Expansion
import com.sorrowblue.twitlin.v2.field.MediaField
import com.sorrowblue.twitlin.v2.field.PlaceField
import com.sorrowblue.twitlin.v2.field.PollField
import com.sorrowblue.twitlin.v2.field.TweetField
import com.sorrowblue.twitlin.v2.field.UserField
import com.sorrowblue.twitlin.v2.field.toParameter
import com.sorrowblue.twitlin.v2.objects.OptionalData
import com.sorrowblue.twitlin.v2.objects.OptionalListData
import com.sorrowblue.twitlin.v2.objects.PagingData
import com.sorrowblue.twitlin.v2.objects.Tweet
import com.sorrowblue.twitlin.v2.objects.User
import com.sorrowblue.twitlin.v2.tweets.TweetsApi
import com.sorrowblue.twitlin.v2.tweets.request.HiddenRequest
import com.sorrowblue.twitlin.v2.tweets.response.HiddenResponse
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.encodeToISOString
import kotlinx.serialization.builtins.ListSerializer
import com.sorrowblue.twitlin.v2.users.Expansion as UsersExpansion
private const val TWEETS = "${Urls.V2}/tweets"
private const val USERS = "${Urls.V2}/users"
internal class TweetsApiImp(private val userClient: UserClient) : TweetsApi {
override suspend fun tweet(
id: String,
expansions: List<Expansion>?,
mediaFields: List<MediaField>?,
placeFields: List<PlaceField>?,
pollFields: List<PollField>?,
tweetFields: List<TweetField>?,
userFields: List<UserField>?
): Response<OptionalData<Tweet>> {
return userClient.get(
"$TWEETS/$id",
Response.serializer(OptionalData.serializer(Tweet.serializer())),
"expansions" to expansions?.toParameter(),
"media.fields" to mediaFields?.toParameter(),
"place.fields" to placeFields?.toParameter(),
"poll.fields" to pollFields?.toParameter(),
"tweet.fields" to tweetFields?.toParameter(),
"user.fields" to userFields?.toParameter()
)
}
override suspend fun tweet(
ids: List<String>,
expansions: List<Expansion>?,
mediaFields: List<MediaField>?,
placeFields: List<PlaceField>?,
pollFields: List<PollField>?,
tweetFields: List<TweetField>?,
userFields: List<UserField>?
): Response<OptionalData<List<Tweet>>> = userClient.get(
TWEETS,
Response.serializer(OptionalData.serializer(ListSerializer(Tweet.serializer()))),
"ids" to ids.joinToString(","),
"expansions" to expansions?.toParameter(),
"media.fields" to mediaFields?.toParameter(),
"place.fields" to placeFields?.toParameter(),
"poll.fields" to pollFields?.toParameter(),
"tweet.fields" to tweetFields?.toParameter(),
"user.fields" to userFields?.toParameter()
)
override suspend fun hidden(id: String, isHidden: Boolean): Response<Boolean> =
userClient.putJson(
"$TWEETS/$id/hidden",
Response.serializer(HiddenResponse.serializer()),
HiddenRequest(isHidden)
).convertData { it.data.hidden }
override suspend fun mentions(
id: String,
endTime: LocalDateTime?,
startTime: LocalDateTime?,
maxResults: Int,
paginationToken: String?,
sinceId: String?,
untilId: String?,
expansions: List<Expansion>?,
mediaFields: List<MediaField>?,
placeFields: List<PlaceField>?,
pollFields: List<PollField>?,
tweetFields: List<TweetField>?,
userFields: List<UserField>?
): Response<PagingData<Tweet>> {
return userClient.get(
"$USERS/$id/mentions",
serializer = Response.serializer(PagingData.serializer(Tweet.serializer())),
"end_time" to endTime?.encodeToISOString(),
"start_time" to startTime?.encodeToISOString(),
"max_results" to maxResults,
"expansions" to expansions?.toParameter(),
"pagination_token" to paginationToken,
"media.fields" to mediaFields?.toParameter(),
"place.fields" to placeFields?.toParameter(),
"poll.fields" to pollFields?.toParameter(),
"since_id" to sinceId,
"until_id" to untilId,
"tweet.fields" to tweetFields?.toParameter(),
"user.fields" to userFields?.toParameter(),
)
}
override suspend fun likingUsers(
id: String,
expansions: List<UsersExpansion>?,
tweetFields: List<TweetField>?,
userFields: List<UserField>?
): Response<PagingData<User>> {
return userClient.get(
"$TWEETS/$id/liking_users",
serializer = Response.serializer(PagingData.serializer(User.serializer())),
"expansions" to expansions?.toParameter(),
"tweet.fields" to tweetFields?.toParameter(),
"user.fields" to userFields?.toParameter()
)
}
override suspend fun retweetedBy(
tweetId: String,
expansions: List<com.sorrowblue.twitlin.v2.users.Expansion>?,
mediaFields: List<MediaField>?,
placeFields: List<PlaceField>?,
pollFields: List<PollField>?,
tweetFields: List<TweetField>?,
userFields: List<UserField>?
): Response<OptionalListData<User>> {
return userClient.get(
"$TWEETS/$tweetId/retweeted_by",
serializer = Response.serializer(OptionalListData.serializer(User.serializer())),
"expansions" to expansions?.toParameter(),
"media.fields" to mediaFields?.toParameter(),
"place.fields" to placeFields?.toParameter(),
"poll.fields" to pollFields?.toParameter(),
"tweet.fields" to tweetFields?.toParameter(),
"user.fields" to userFields?.toParameter()
)
}
}
| 39.575163 | 93 | 0.661272 |
a7226573fe35541c62d27b5a531aeae6c52697ab | 496 | dart | Dart | bin/AdventureGame/item/GoldPurse.dart | jonelleamio/AdventureGameServer | be55e48508be4df83fa5e44c77aae26ee072d8e8 | [
"MIT"
] | null | null | null | bin/AdventureGame/item/GoldPurse.dart | jonelleamio/AdventureGameServer | be55e48508be4df83fa5e44c77aae26ee072d8e8 | [
"MIT"
] | null | null | null | bin/AdventureGame/item/GoldPurse.dart | jonelleamio/AdventureGameServer | be55e48508be4df83fa5e44c77aae26ee072d8e8 | [
"MIT"
] | null | null | null | import '../character/Player.dart';
import 'Item.dart';
class GoldPurse implements Item {
final int gold;
final int id;
@override
int get getId => id;
GoldPurse(this.gold, this.id);
@override
Map isUsedBy(Player p) {
p.gold += gold;
return {
'description' : '${p.name} gain ${gold} gold',
'gold' : gold,
'totalGold': p.gold,
};
}
@override
Map state() => {
'description' : '${gold} gold',
'guid' : id,
'type': 'GOLD PURSE'
};
} | 16.533333 | 52 | 0.560484 |
e976d3bd42a280b13be02b87367bae1f6bb8b0d8 | 2,400 | go | Go | internal/localfs/localfs_test.go | PithomLabs/gitfs | 35c333f5834c28ba5aa47d842abaae10c5b04a60 | [
"Apache-2.0"
] | 121 | 2019-07-13T14:02:05.000Z | 2021-08-04T03:28:26.000Z | internal/localfs/localfs_test.go | PithomLabs/gitfs | 35c333f5834c28ba5aa47d842abaae10c5b04a60 | [
"Apache-2.0"
] | 20 | 2019-07-20T14:33:04.000Z | 2021-05-29T18:38:05.000Z | internal/localfs/localfs_test.go | PithomLabs/gitfs | 35c333f5834c28ba5aa47d842abaae10c5b04a60 | [
"Apache-2.0"
] | 8 | 2019-07-13T14:02:34.000Z | 2021-01-16T11:50:46.000Z | package localfs
import (
"net/http"
"os"
"path/filepath"
"testing"
"github.com/posener/gitfs/internal/testfs"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNew(t *testing.T) {
t.Parallel()
testfs.TestFS(t, func(t *testing.T, project string) (http.FileSystem, error) {
return New(project, ".")
})
}
func TestComputeSubdir(t *testing.T) {
t.Parallel()
gitRoot, err := lookupGitRoot(".")
require.NoError(t, err)
tests := []struct {
project string
wantSubDir string
}{
// Simple case.
{project: "github.com/posener/gitfs", wantSubDir: ""},
// Any ref should be omitted.
{project: "github.com/posener/gitfs@123", wantSubDir: ""},
// With subdirectories.
{project: "github.com/posener/gitfs/internal@123", wantSubDir: "internal"},
{project: "github.com/posener/gitfs/internal/testdata", wantSubDir: "internal/testdata"},
}
for _, tt := range tests {
t.Run(tt.project, func(t *testing.T) {
subDir, err := computeSubdir(tt.project, gitRoot)
require.NoError(t, err)
assert.Equal(t, tt.wantSubDir, subDir)
})
}
}
func TestComputeSubdir_failure(t *testing.T) {
t.Parallel()
gitRoot, err := lookupGitRoot(".")
require.NoError(t, err)
tests := []struct {
project string
path string
}{
// Should not have a .git suffix.
{project: "github.com/posener/gitfs.git", path: gitRoot},
// Wrong domain.
{project: "git.com/posener/gitfs", path: gitRoot},
// Correct project but not a repository directory.
{project: "github.com/posener/gitfs", path: "/tmp"},
}
for _, tt := range tests {
t.Run(tt.project, func(t *testing.T) {
_, err := computeSubdir(tt.project, tt.path)
assert.Error(t, err)
})
}
}
func TestCleanRevision(t *testing.T) {
t.Parallel()
assert.Equal(t, "x", cleanRevision("x"))
assert.Equal(t, "x", cleanRevision("x@"))
assert.Equal(t, "x", cleanRevision("x@v"))
}
func TestLookupGitRoot(t *testing.T) {
t.Parallel()
gitRoot, err := filepath.Abs("../..")
require.NoError(t, err)
// Check from current directory (not a git root)
path, err := lookupGitRoot(".")
require.NoError(t, err)
assert.Equal(t, gitRoot, path)
// Check from git root
os.Chdir(gitRoot)
path, err = lookupGitRoot(gitRoot)
require.NoError(t, err)
assert.Equal(t, gitRoot, path)
// Check from /tmp - not a git repository
path, err = lookupGitRoot("/tmp")
assert.Error(t, err)
}
| 24.242424 | 91 | 0.670417 |
b0a624542df9fb9fa4bd0f89d6fd1b5213ee62d3 | 4,029 | ps1 | PowerShell | Google.PowerShell.IntegrationTests/SQL/SQL.GcSqlConfiguration.Tests.ps1 | pjmcc2009/google-cloud-powershell | fe1d8b12b7a2276bf53546b4b85abbb7d550a454 | [
"Apache-2.0"
] | 125 | 2016-07-24T04:17:13.000Z | 2022-03-14T18:30:38.000Z | Google.PowerShell.IntegrationTests/SQL/SQL.GcSqlConfiguration.Tests.ps1 | pjmcc2009/google-cloud-powershell | fe1d8b12b7a2276bf53546b4b85abbb7d550a454 | [
"Apache-2.0"
] | 484 | 2016-07-20T21:54:10.000Z | 2022-01-29T11:02:47.000Z | Google.PowerShell.IntegrationTests/SQL/SQL.GcSqlConfiguration.Tests.ps1 | pjmcc2009/google-cloud-powershell | fe1d8b12b7a2276bf53546b4b85abbb7d550a454 | [
"Apache-2.0"
] | 71 | 2016-07-20T21:48:52.000Z | 2022-02-22T06:12:02.000Z | . $PSScriptRoot\..\GcloudCmdlets.ps1
Install-GcloudCmdlets
$project, $zone, $oldActiveConfig, $configName = Set-GCloudConfig
Describe "New-GcSqlInstanceReplicaConfig" {
It "shouldn't require any parameters" {
$config = New-GcSqlInstanceReplicaConfig
$config.MysqlReplicaConfiguration.ConnectRetryInterval | Should Be 60
$config.MysqlReplicaConfiguration.CaCertificate | Should BeNullOrEmpty
}
It "should be able to update the default value" {
$config = New-GcSqlInstanceReplicaConfig -MySqlRetryInterval 100
$config.MysqlReplicaConfiguration.ConnectRetryInterval | Should Be 100
}
It "should be able to take in other parameters" {
$config = New-GcSqlInstanceReplicaConfig -MySqlVerifyCertificate -MySqlCaCert "Certificate"
$config.MysqlReplicaConfiguration.VerifyServerCertificate | Should Be true
$config.MysqlReplicaConfiguration.CaCertificate | Should Be "Certificate"
}
}
Describe "New-GcSqlSettingConfig" {
It "should be able to instantiate itself with just Tier passed in" {
$setting = New-GcSqlSettingConfig "D1"
$setting.Tier | Should Be "D1"
$setting.DataDiskSizeGb | Should Be 50
$setting.DataDiskType | Should be "PD_SSD"
$setting.DatabaseFlags | Should BeNullOrEmpty
}
It "should be able to accept parameters with defaults and adjust accordingly" {
$setting = New-GcSqlSettingConfig "D1" -DataDiskSizeGb 11
$setting.DataDiskSizeGb | Should Be 11
}
It "should be able to take in something that isn't default" {
$setting = New-GcSqlSettingConfig "D1" -MaintenanceWindowDay 1
$setting.MaintenanceWindow.Day = 1
}
It "should be able to take in database flags" {
$setting = New-GcSqlSettingConfig "D1" `
-DatabaseFlag `
@{"Name" = "binlog_checksum"; "Value" = "NONE"},@{"Name" = "ft_max_word_len"; "Value" = 12}
$flags = $setting.DatabaseFlags
$flags.Count | Should Be 2
$flag = $flags | Select-Object -first 1
$flag.Name | Should Be "binlog_checksum"
$flag.Value | Should be "NONE"
}
It "should be able to take in an IP Configuration Network" {
$setting = New-GcSqlSettingConfig "D1" `
-IpConfigAuthorizedNetwork `
@{"ExpirationTimeRaw" = "2012-11-15T16:19:00.094Z"; "Kind" = "sql::aclEntry"; "Name" = "test"; }, `
@{"ExpirationTimeRaw" = "2012-11-15T16:19:00.094Y"; "Kind" = "sql::aclEntry"; "Name" = "test2"; }
$networks = $setting.IpConfiguration.AuthorizedNetworks
$networks.Count | Should Be 2
$network = $networks | Select-Object -first 1
$network.Name | Should Be "test"
}
}
Describe "New-GcSqlInstanceConfig" {
It "should be able to instantiate with just the most basic information" {
$setting = New-GcSqlSettingConfig "D1"
$config = New-GcSqlInstanceConfig "test-inst" -SettingConfig $setting
$config.Settings.Tier | Should Be "D1"
$config.Name | Should Be "test-inst"
}
It "should be able to replace the region" {
$setting = New-GcSqlSettingConfig "D1"
$config = New-GcSqlInstanceConfig "test-inst" -Region "us-central2" -SettingConfig $setting
$config.Region | Should Be "us-central2"
}
It "should be able to take in a pipelined Setting" {
$config = New-GcSqlSettingConfig "D2" | New-GcSqlInstanceConfig "test-inst"
$config.Settings.Tier | Should Be "D2"
}
It "should be able to take in a pipelined replica config" {
$setting = New-GcSqlSettingConfig "D2"
$config = New-GcSqlInstanceReplicaConfig -MySqlVerifyCertificate -MySqlCaCert "Certificate"`
| New-GcSqlInstanceConfig "test-inst" -SettingConfig $setting
$config.Settings.Tier | Should Be "D2"
$config.ReplicaConfiguration.MysqlReplicaConfiguration.CaCertificate | Should Be "Certificate"
}
}
Reset-GCloudConfig $oldActiveConfig $configName
| 41.536082 | 111 | 0.670638 |
754613e91f665940ac5ca0d10352af8d07df2878 | 3,717 | c | C | caesar.c | JacobGrisham/Encryption-Arrays-using-C | a9bddc834d04ce02dfbb4e009adfa872fce247ca | [
"MIT"
] | 1 | 2021-05-24T06:14:09.000Z | 2021-05-24T06:14:09.000Z | caesar.c | JacobGrisham/Encryption-Arrays-using-C | a9bddc834d04ce02dfbb4e009adfa872fce247ca | [
"MIT"
] | 1 | 2021-05-02T20:04:05.000Z | 2021-05-02T20:04:05.000Z | caesar.c | JacobGrisham/Encryption-Arrays-using-C | a9bddc834d04ce02dfbb4e009adfa872fce247ca | [
"MIT"
] | 1 | 2021-05-02T11:37:37.000Z | 2021-05-02T11:37:37.000Z | // Includes
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdbool.h>
// Delcare functions
bool text(char *s);
void cipher(char *plaintext, char *ciphertext, int k);
char *get_string(const char *prompt);
// argv[1] is the secret key (i.e., a non-negative integer)
int main(int argc, char *argv[])
{
// No user input or multiple inputs error handling
// Text input error handling
if (argc != 2 || text(argv[1]) == true)
{
printf("Usage: %s key\n", argv[0]);
return 1;
}
// Finally run program
else
{
// Capture secret key
int k = atoi(argv[1]);
// Prompt user for text input
char *plaintext = get_string("plaintext: ");
// Get number of characters
int n = strlen(plaintext);
// Make sure to capture terminating null character
char ciphertext[n + 1];
// Call cipher function
cipher(plaintext, ciphertext, k);
// Print ciphertext
printf("ciphertext: %s\n", ciphertext);
// Program exit
return 0;
}
}
// Function to determine if user inputted text
bool text(char *s)
{
// Use a loop to iterate over argv
for (int i = 0; i < strlen(s); i++)
{
char c = s[i];
// If any of the inputted text is non-numerical, return false
if (isdigit(c))
{
return false;
}
}
return true;
}
// Main function: encrpyting the plaintext
void cipher(char *plaintext, char *ciphertext, int k)
{
// Declare i
int i = 0;
// Iterate over each character of the plaintext using for loop:
for (i = 0; i < strlen(plaintext); i++)
{
char ch = plaintext[i];
// Change characters using formula. Change all to lowercase and then convert back to uppercase
if (isalpha(ch))
{
char lower = tolower(ch);
int pi = lower - 'a';
// ci returns number, therefore must anchor the number to letter
char ci = ((pi + k) % 26) + 'a';
// Change character using ci value. If lowercase, keep it as is
if (islower(ch))
{
ciphertext[i] = ci;
}
// Change character using ci value. If uppercase, change to uppercase
else
{
ciphertext[i] = toupper(ci);
}
}
// Non-alphabetical characters should be outputted unchanged
else
{
ciphertext[i] = ch;
}
}
// Lastly, add terminating null character
ciphertext[i] = '\0';
}
// get_string function. Source: https://stackoverflow.com/questions/48282630/troubles-creating-a-get-string-function-in-c
char *get_string(const char *prompt)
{
char temp[26] = "";//24 + newline + '\0'
int size,count;
while ( 1)
{
printf ( "%s",prompt);
if ( fgets ( temp, sizeof temp, stdin)) {
if ( !strchr ( temp, '\n')) {//no newline
printf("\x1B[31mError\x1B[0m: too long.\n%s",prompt);
size = strlen ( temp);
do {
fgets ( temp, sizeof temp, stdin);//read more and discard
size += strlen ( temp);
} while (!strchr ( temp, '\n'));//loop until newline found
printf("size :%i\n",size);
continue;//re prompt
}
break;
}
else {
fprintf ( stderr, "fgets problem\n");
return NULL;
}
}
temp[strcspn ( temp,"\n")] = '\0';//remove newline
char *word = malloc(strlen ( temp) + 1);
strcpy ( word, temp);
return word;
}
| 27.533333 | 121 | 0.532688 |
5b08a8619921a349f512e1b6580f6a67ed90a1f5 | 2,426 | cpp | C++ | tools/clang/test/CXX/class.access/class.access.base/p5.cpp | clayne/DirectXShaderCompiler | 0ef9b702890b1d45f0bec5fa75481290323e14dc | [
"NCSA"
] | 3,102 | 2015-01-04T02:28:35.000Z | 2022-03-30T12:53:41.000Z | tools/clang/test/CXX/class.access/class.access.base/p5.cpp | clayne/DirectXShaderCompiler | 0ef9b702890b1d45f0bec5fa75481290323e14dc | [
"NCSA"
] | 2,214 | 2019-05-06T22:22:53.000Z | 2022-03-31T19:38:50.000Z | tools/clang/test/CXX/class.access/class.access.base/p5.cpp | clayne/DirectXShaderCompiler | 0ef9b702890b1d45f0bec5fa75481290323e14dc | [
"NCSA"
] | 1,868 | 2015-01-03T04:27:11.000Z | 2022-03-25T13:37:35.000Z | // RUN: %clang_cc1 -verify %s
namespace test0 {
struct A {
static int x;
};
struct B : A {};
struct C : B {};
int test() {
return A::x
+ B::x
+ C::x;
}
}
namespace test1 {
struct A {
private: static int x; // expected-note 5 {{declared private here}}
static int test() { return x; }
};
struct B : public A {
static int test() { return x; } // expected-error {{private member}}
};
struct C : private A {
static int test() { return x; } // expected-error {{private member}}
};
struct D {
public: static int x; // expected-note{{member is declared here}}
static int test() { return x; }
};
struct E : private D { // expected-note{{constrained by private inheritance}}
static int test() { return x; }
};
int test() {
return A::x // expected-error {{private member}}
+ B::x // expected-error {{private member}}
+ C::x // expected-error {{private member}}
+ D::x
+ E::x; // expected-error {{private member}}
}
}
namespace test2 {
class A {
protected: static int x; // expected-note{{member is declared here}}
};
class B : private A {}; // expected-note {{private inheritance}}
class C : private A {
int test(B *b) {
return b->x; // expected-error {{private member}}
}
};
}
namespace test3 {
class A {
protected: static int x;
};
class B : public A {};
class C : private A {
int test(B *b) {
// x is accessible at C when named in A.
// A is an accessible base of B at C.
// Therefore this succeeds.
return b->x;
}
};
}
// Don't crash. <rdar://12926092>
// Note that 'field' is indeed a private member of X but that access
// is indeed ultimately constrained by the protected inheritance from Y.
// If someone wants to put the effort into improving this diagnostic,
// they can feel free; even explaining it in person would be a pain.
namespace test4 {
class Z;
class X {
public:
void f(Z *p);
private:
int field; // expected-note {{member is declared here}}
};
class Y : public X { };
class Z : protected Y { }; // expected-note 2 {{constrained by protected inheritance here}}
void X::f(Z *p) {
p->field = 0; // expected-error {{cannot cast 'test4::Z' to its protected base class 'test4::X'}} expected-error {{'field' is a private member of 'test4::X'}}
}
}
// TODO: flesh out these cases
| 24.505051 | 162 | 0.595218 |
163d7ab38b1236776565772e71c249a29c5fff59 | 653 | h | C | Applications/TVPhotos/TVPhotosTopShelfExtendedTraitCollection.h | lechium/tvOS124Headers | 11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475 | [
"MIT"
] | 4 | 2019-08-27T18:03:47.000Z | 2021-09-18T06:29:00.000Z | Applications/TVPhotos/TVPhotosTopShelfExtendedTraitCollection.h | lechium/tvOS124Headers | 11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475 | [
"MIT"
] | null | null | null | Applications/TVPhotos/TVPhotosTopShelfExtendedTraitCollection.h | lechium/tvOS124Headers | 11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475 | [
"MIT"
] | null | null | null | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "PXExtendedTraitCollection.h"
@interface TVPhotosTopShelfExtendedTraitCollection : PXExtendedTraitCollection
{
}
- (double)displayScale; // IMP=0x0000000100082f80
- (struct CGSize)layoutReferenceSize; // IMP=0x0000000100082f6c
- (long long)layoutOrientation; // IMP=0x0000000100082f64
- (long long)layoutSizeSubclass; // IMP=0x0000000100082f5c
- (long long)layoutSizeClass; // IMP=0x0000000100082f54
- (long long)userInterfaceIdiom; // IMP=0x0000000100082f4c
- (id)init; // IMP=0x0000000100082f14
@end
| 28.391304 | 83 | 0.75804 |
f5f4d28559bffa9a95892217e61e494ab2fe5fd4 | 427 | rs | Rust | checker/src/utils.rs | kumanote/gaiamon | d6428bf857c52157d1ed4b979f5362c8e03e8dcc | [
"MIT"
] | null | null | null | checker/src/utils.rs | kumanote/gaiamon | d6428bf857c52157d1ed4b979f5362c8e03e8dcc | [
"MIT"
] | 1 | 2022-02-01T02:57:19.000Z | 2022-02-01T04:23:30.000Z | checker/src/utils.rs | kumanote/gaiamon | d6428bf857c52157d1ed4b979f5362c8e03e8dcc | [
"MIT"
] | null | null | null | use crate::{CustomError, Result};
use sha2::{Digest, Sha256};
use std::fmt::Write;
pub fn calculate_hash(bytes: &[u8]) -> Result<String> {
// sha256
let mut hasher = Sha256::new();
hasher.update(bytes);
let output = hasher.finalize();
let mut result = String::new();
for byte in &output[..32] {
write!(result, "{:02X?}", byte).map_err(|cause| CustomError::from(cause))?;
}
Ok(result)
}
| 26.6875 | 83 | 0.606557 |
355d03cc131039161d328c540a189b9e10046aac | 425 | dart | Dart | lib/src/service/justin_endpoints.dart | masich/djustin | 5b06ce7d123587501821ecf5f09804980c9daf13 | [
"MIT"
] | null | null | null | lib/src/service/justin_endpoints.dart | masich/djustin | 5b06ce7d123587501821ecf5f09804980c9daf13 | [
"MIT"
] | null | null | null | lib/src/service/justin_endpoints.dart | masich/djustin | 5b06ce7d123587501821ecf5f09804980c9daf13 | [
"MIT"
] | null | null | null | library justin_endpoints;
const String justinBase = 'http://openapi.justin.ua';
const String justinBranches = '/branches';
const String justinBranchTypes = '/branch_types';
const String justinBranchLocator = '/branches_locator';
const String justinTracking = '/tracking';
const String justinTrackingHistory = '/tracking_history';
const String justinLocalities = '/localities';
const String justinServicesInfo = '/services';
| 38.636364 | 57 | 0.792941 |
29162de07be391441baba79f55a715b9d6c4c3ce | 158 | py | Python | flaskrestful/FlaskProject/App/models/UserModel.py | riverstation/project-all | c56f1879e1303d561e95a3ff3a70f94fb5fa2191 | [
"Apache-2.0"
] | null | null | null | flaskrestful/FlaskProject/App/models/UserModel.py | riverstation/project-all | c56f1879e1303d561e95a3ff3a70f94fb5fa2191 | [
"Apache-2.0"
] | null | null | null | flaskrestful/FlaskProject/App/models/UserModel.py | riverstation/project-all | c56f1879e1303d561e95a3ff3a70f94fb5fa2191 | [
"Apache-2.0"
] | null | null | null | from App.ext import db
class User(db.Model):
u_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
u_name = db.Column(db.String(16))
| 17.555556 | 70 | 0.702532 |
4c20ae23b8e85c203e8ffcbe75e7829749b5dce0 | 5,869 | php | PHP | resources/views/blogs.blade.php | leostark08/FinbuProject-Laravel-backend | 0af42f7a2e15c57b4e7f02d0f5fa210406e51641 | [
"MIT"
] | null | null | null | resources/views/blogs.blade.php | leostark08/FinbuProject-Laravel-backend | 0af42f7a2e15c57b4e7f02d0f5fa210406e51641 | [
"MIT"
] | 1 | 2021-02-02T18:09:33.000Z | 2021-02-02T18:09:33.000Z | resources/views/blogs.blade.php | leostark08/FinbuProject-Laravel-backend | 0af42f7a2e15c57b4e7f02d0f5fa210406e51641 | [
"MIT"
] | null | null | null | {{-- resources/views/admin/dashboard.blade.php --}}
@extends('adminlte::page')
@section('title', 'Người dùng')
@section('content_header')
<h1>Người dùng</h1>
@stop
@section('content')
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<link rel="stylesheet" href="{{asset('css/users.css')}}">
<script src="https://kit.fontawesome.com/2e591a5e23.js" crossorigin="anonymous"></script>
<div class="row">
<div class="col-sm-12">
<div class="box">
<div class="box-header">
<div class="box-tools row">
<div class="col-sm-3 offset-sm-8">
<input type="text" name="table_search" class="form-control pull-right" placeholder="Search">
</div>
<div class="col-sm-1">
<div class="input-group-btn">
<button type="submit" class="btn btn-default"><i class="fa fa-search"></i></button>
</div>
</div>
</div>
</div>
<!-- /.box-header -->
<div class="box-body table-responsive no-padding">
<table class="table table-hover table-striped">
<tbody>
<tr>
<th width="4%">STT</th>
<th width="15%">Họ và tên</th>
<th width="10%">Giới tính</th>
<th width="10%">Ngày sinh</th>
<th width="10%">Điện thoại</th>
<th width="24%">Địa chỉ</th>
<th width="18%">Email</th>
<th width="3%"></th>
<th width="3%"></th>
<th width="3%"></th>
</tr>
@foreach ($blogs as $blog)
<tr>
<td>{{ $stt = $stt+1 }}</td>
<td> {{$blog->User_Firstname}} {{ $user->User_Name }}</td>
@if($user->Gender == 1)
<td>Nam</td>
@else
<td>Nữ</td>
@endif
<td>{{ $user->User_DoB }}</td>
<td>{{ $user->Cellphone }}</td>
@if(isset($user->Address))
<td>{{ $user->Cellphone }}</td>
@else
<td><i>Chưa cập nhật</i></td>
@endif
<td>{{ $user->Email }}</td>
<td id="btn_action"><button class="btn btn-info" title="Chi tiết"><i class="fas fa-info-circle"></i></button></td>
<td id="btn_action"><button class="btn btn-success"><i class="fas fa-edit" title="Sửa"></i></button></td>
<td id="btn_action"><button class="btn btn-danger"><i class="fas fa-trash-alt" title="Xóa"></i></button></td>
</tr>
@endforeach
</tbody>
</table>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
{{-- <div class="col-sm-5">
<div class="box box-primary">
<!-- form start -->
<form role="form" method="POST">
<div class="box-body">
{{ csrf_field() }}
<div class="form-group">
<label for="exampleInputName">name</label>
<input type="text" class="form-control" id="exampleInputName" name="exampleInputName" placeholder="Name">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" name="exampleInputEmail1" placeholder="Enter email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" name="exampleInputPassword1" placeholder="Password">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" class="btn btn-primary">Registration</button>
</div>
</form>
</div>
</div> --}}
</div>
@stop
| 54.850467 | 208 | 0.429715 |
5991b77f4655b48433a5b58e3fb8605272061471 | 4,181 | cpp | C++ | src/physical_plan/auto_inc.cpp | tullyliu/BaikalDB | 08c4430a79c2621714a2bc9b024380877b7db499 | [
"Apache-2.0"
] | 984 | 2018-08-03T16:22:49.000Z | 2022-03-22T07:54:48.000Z | src/physical_plan/auto_inc.cpp | tullyliu/BaikalDB | 08c4430a79c2621714a2bc9b024380877b7db499 | [
"Apache-2.0"
] | 100 | 2018-08-07T11:33:18.000Z | 2021-12-22T19:22:43.000Z | src/physical_plan/auto_inc.cpp | tullyliu/BaikalDB | 08c4430a79c2621714a2bc9b024380877b7db499 | [
"Apache-2.0"
] | 157 | 2018-08-04T05:32:34.000Z | 2022-03-10T03:16:47.000Z | // Copyright (c) 2018-present Baidu, Inc. 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.
#include "auto_inc.h"
#include <boost/algorithm/string.hpp>
#include "exec_node.h"
#include "query_context.h"
#include "schema_factory.h"
#include "insert_node.h"
#include "network_socket.h"
#include "meta_server_interact.hpp"
namespace baikaldb {
int AutoInc::analyze(QueryContext* ctx) {
ExecNode* plan = ctx->root;
if (ctx->insert_records.size() == 0) {
return 0;
}
InsertNode* insert_node = static_cast<InsertNode*>(plan->get_node(pb::INSERT_NODE));
int64_t table_id = -1;
if (insert_node != NULL) {
table_id = insert_node->table_id();
}
SchemaFactory* schema_factory = SchemaFactory::get_instance();
auto table_info_ptr = schema_factory->get_table_info_ptr(table_id);
if (table_info_ptr == nullptr || table_info_ptr->auto_inc_field_id == -1) {
return 0;
}
return update_auto_inc(table_info_ptr, ctx->client_conn, ctx->use_backup, ctx->insert_records);
}
int AutoInc::update_auto_inc(SmartTable table_info_ptr,
NetworkSocket* client_conn,
bool use_backup,
std::vector<SmartRecord>& insert_records) {
int auto_id_count = 0;
int64_t max_id = 0;
for (auto& record : insert_records) {
auto field = record->get_field_by_tag(table_info_ptr->auto_inc_field_id);
ExprValue value = record->get_value(field);
// 兼容mysql,值为0会分配自增id
if (value.is_null() || value.get_numberic<int64_t>() == 0) {
++auto_id_count;
} else {
int64_t int_val = value.get_numberic<int64_t>();
if (int_val > max_id) {
max_id = int_val;
}
}
}
auto field_info = table_info_ptr->get_field_ptr(table_info_ptr->auto_inc_field_id);
// 通过字段注释可以标示:自增id不会随着插入id进行跳号,当插入的自增id来自于异构数据源时,用于避免自增id的双写冲突问题.
if (field_info != nullptr && field_info->noskip) {
max_id = 0;
}
if (auto_id_count == 0 && max_id == 0) {
return 0;
}
// 请求meta来获取自增id
pb::MetaManagerRequest request;
pb::MetaManagerResponse response;
request.set_op_type(pb::OP_GEN_ID_FOR_AUTO_INCREMENT);
auto auto_increment_ptr = request.mutable_auto_increment();
auto_increment_ptr->set_table_id(table_info_ptr->id);
auto_increment_ptr->set_count(auto_id_count);
auto_increment_ptr->set_start_id(max_id);
MetaServerInteract* interact = MetaServerInteract::get_auto_incr_instance();
if (use_backup) {
interact = MetaServerInteract::get_backup_instance();
}
if (interact->send_request("meta_manager", request, response) != 0) {
DB_FATAL("gen id from meta_server fail");
return -1;
}
if (auto_id_count == 0) {
if (max_id > 0) {
client_conn->last_insert_id = max_id;
}
return 0;
}
int64_t start_id = response.start_id();
client_conn->last_insert_id = start_id;
for (auto& record : insert_records) {
auto field = record->get_field_by_tag(table_info_ptr->auto_inc_field_id);
ExprValue value = record->get_value(field);
if (value.is_null() || value.get_numberic<int64_t>() == 0) {
value.type = pb::INT64;
value._u.int64_val = start_id++;
record->set_value(field, value);
}
}
if (start_id != (int64_t)response.end_id()) {
DB_FATAL("gen id count not equal to request id count");
return -1;
}
return 0;
}
}
/* vim: set ts=4 sw=4 sts=4 tw=100 */
| 36.356522 | 99 | 0.644822 |
8e5ce0115c3358b694058055922d244564c4a78f | 2,013 | swift | Swift | Pods/CommonDataModelsKit-iOS/CommonDataModelsKit-iOS/CommonDataModelsKit-iOS/Core/models/TapCountry.swift | Tap-Payments/TapCheckoutApiKIT | 9d55499ac09199bd62379f721cf11ae0489f142f | [
"MIT"
] | 5 | 2021-01-05T02:18:40.000Z | 2022-01-14T19:50:31.000Z | Pods/CommonDataModelsKit-iOS/CommonDataModelsKit-iOS/CommonDataModelsKit-iOS/Core/models/TapCountry.swift | Tap-Payments/TapCheckoutApiKIT | 9d55499ac09199bd62379f721cf11ae0489f142f | [
"MIT"
] | null | null | null | Pods/CommonDataModelsKit-iOS/CommonDataModelsKit-iOS/CommonDataModelsKit-iOS/Core/models/TapCountry.swift | Tap-Payments/TapCheckoutApiKIT | 9d55499ac09199bd62379f721cf11ae0489f142f | [
"MIT"
] | 3 | 2020-04-02T07:57:34.000Z | 2021-09-16T11:34:26.000Z | import Foundation
/// Represents a model for the country object
@objc public class TapCountry : NSObject,Codable {
/// Arabic name
public let nameAR : String?
/// English name
public let nameEN : String?
/// Phone calling international code
public let code : String?
/// The correct mobile length for the country
public let phoneLength : Int?
enum CodingKeys: String, CodingKey {
case nameAR = "nameAR"
case nameEN = "nameEN"
case code = "code"
case phoneLength = "phoneLength"
}
required public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
nameAR = try values.decodeIfPresent(String.self, forKey: .nameAR)
nameEN = try values.decodeIfPresent(String.self, forKey: .nameEN)
code = try values.decodeIfPresent(String.self, forKey: .code)
phoneLength = try values.decodeIfPresent(Int.self, forKey: .phoneLength)
}
/**
Creats tap cointry from input
- Parameter nameAR: Country Arabic name
- Parameter nameEN: Coutnry English name
- Parameter code: Country international phone code
- Parameter phoneLength: Maximum allowed phone length
*/
@objc public init(nameAR: String?, nameEN: String?, code: String?, phoneLength: Int = 0) {
self.nameAR = nameAR
self.nameEN = nameEN
self.code = code
self.phoneLength = phoneLength
}
/**
Wrapper for deciding the name to be displayed. Will hide the inner logiccal formatting or model attributes changes
- Parameter lang: The lang code you want to the country ode localisation for
- Returns: The localized country code and "" as a fallback for any error
*/
public func localizedName(for lang:String) -> String {
guard let nameAR = nameAR, let nameEN = nameEN else { return "" }
return lang.lowercased() == "ar" ? nameAR : nameEN
}
}
| 34.706897 | 119 | 0.647789 |
2f02927a8fc9f3aa94a343439b8ec770f8add2ac | 4,500 | java | Java | src/main/java/fr/nimrod/recognition/web/controller/EnrollmentController.java | VirtualIdentity/facial-recognition | a33ca0c22629c351cbdea135641b22a215b493b8 | [
"MIT"
] | null | null | null | src/main/java/fr/nimrod/recognition/web/controller/EnrollmentController.java | VirtualIdentity/facial-recognition | a33ca0c22629c351cbdea135641b22a215b493b8 | [
"MIT"
] | null | null | null | src/main/java/fr/nimrod/recognition/web/controller/EnrollmentController.java | VirtualIdentity/facial-recognition | a33ca0c22629c351cbdea135641b22a215b493b8 | [
"MIT"
] | null | null | null | package fr.nimrod.recognition.web.controller;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Base64;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import fr.nimrod.recognition.kairos.model.api.KairosEnrollRequest;
import fr.nimrod.recognition.kairos.model.api.KairosEnrollResponse;
import fr.nimrod.recognition.kairos.repositories.KairosRecognitionRepository;
import fr.nimrod.recognition.storage.StorageFileNotFoundException;
import fr.nimrod.recognition.storage.StorageService;
import fr.nimrod.recognition.web.dto.EnrollementDto;
@Controller
public class EnrollmentController {
private final StorageService storageService;
@Autowired
private KairosRecognitionRepository repository;
@Autowired
public EnrollmentController(StorageService storageService) {
this.storageService = storageService;
}
@GetMapping("/enrollement")
public String listUploadedFiles(EnrollementDto enrollement, Model model) throws IOException {
model.addAttribute("files",
storageService.loadAll()
.map(path -> MvcUriComponentsBuilder
.fromMethodName(EnrollmentController.class, "serveFile", path.getFileName().toString()).build()
.toString())
.collect(Collectors.toList()));
return "enrollement";
}
@GetMapping("/files/{filename:.+}")
@ResponseBody
public ResponseEntity<Resource> serveFile(@PathVariable String filename) {
Resource file = storageService.loadAsResource(filename);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file);
}
@PostMapping("/enrollement")
public String handleFileUpload(EnrollementDto enrollement, @RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) throws IllegalStateException, IOException, InterruptedException, ExecutionException {
storageService.store(file);
redirectAttributes.addFlashAttribute("message", "You successfully uploaded " + file.getOriginalFilename() + "!");
//On y va a la sauvage
KairosEnrollRequest kairoEnrollRequest = new KairosEnrollRequest();
kairoEnrollRequest.setGalleryName("demo");
kairoEnrollRequest.setSubjectId(enrollement.getNom());
String fileName = enrollement.getNom() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'));
storageService.storeAsFile(file, fileName);
storageService.delete(file.getOriginalFilename());
Path fileStored = storageService.load(fileName);
kairoEnrollRequest.setImage(Base64.getEncoder().encodeToString(FileUtils.readFileToByteArray(fileStored.toFile())));
Future<ResponseEntity<KairosEnrollResponse>> result = repository.enroll(kairoEnrollRequest);
while(!result.isDone()){
Thread.sleep(100);
}
String message = "";
if(result.get().getStatusCode().is2xxSuccessful())
message = "That's good " + enrollement.getNom() + " is enroll";
else {
message = "That's too bad ";
}
redirectAttributes.addFlashAttribute("message", message);
return "redirect:/enrollement";
}
@ExceptionHandler(StorageFileNotFoundException.class)
public ResponseEntity<?> handleStorageFileNotFound(StorageFileNotFoundException exc) {
return ResponseEntity.notFound().build();
}
}
| 39.823009 | 228 | 0.748222 |
f3681bd31baba142f5f116686b29a44c06bf8906 | 14,348 | dart | Dart | lib/forms/operator_form.dart | ibstelix/donation-app-via-creditemoi | 9ee8f0f4972ce462e4342e481b6f5f4fe9d1bed2 | [
"MIT"
] | null | null | null | lib/forms/operator_form.dart | ibstelix/donation-app-via-creditemoi | 9ee8f0f4972ce462e4342e481b6f5f4fe9d1bed2 | [
"MIT"
] | null | null | null | lib/forms/operator_form.dart | ibstelix/donation-app-via-creditemoi | 9ee8f0f4972ce462e4342e481b6f5f4fe9d1bed2 | [
"MIT"
] | null | null | null | import 'dart:io';
import 'package:after_layout/after_layout.dart';
import 'package:codedecoders/scope/main_model.dart';
import 'package:codedecoders/strings/const.dart';
import 'package:codedecoders/utils/general.dart';
import 'package:codedecoders/widgets/input_formatters.dart';
import 'package:codedecoders/widgets/item_to_buy_card.dart';
import 'package:codedecoders/widgets/loading_spinner.dart';
import 'package:codedecoders/widgets/payment_card.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
class OperatorForm extends StatefulWidget {
final MainModel model;
const OperatorForm({Key key, this.model}) : super(key: key);
@override
_OperatorFormState createState() => _OperatorFormState();
}
class _OperatorFormState extends State<OperatorForm>
with AfterLayoutMixin<OperatorForm> {
String _appBarText = "Etape 2";
bool _loading = false;
var _formKey = new GlobalKey<FormState>();
var _scaffoldKey = new GlobalKey<ScaffoldState>();
var _amountController = new TextEditingController();
var _phoneController = new TextEditingController();
List<DropdownMenuItem<String>> _operatorsdropDownMenuItems;
List<DropdownMenuItem<String>> _groupdropDownMenuItems;
String _currentOperator;
String _currentGroup;
Map _selectedOperator;
List _listServiceProviders = [];
List _selectedServiceProviders = [];
List _listCountries = [];
List _selectedProviderItems = [];
Map _selectedItem;
@override
void afterFirstLayout(BuildContext context) {
_anonymeAuthenticate(context);
}
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
key: _scaffoldKey,
body: Stack(
children: <Widget>[
Form(key: _formKey, child: _bodyContent(context)),
LoadingSpinner(
loading: _loading,
)
],
),
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.blue,
elevation: 2,
child: Icon(
Icons.arrow_forward,
color: Colors.white,
size: 30,
),
onPressed: () {
FocusScope.of(context).requestFocus(new FocusNode());
if (!_formKey.currentState.validate()) {
return;
}
if (_selectedOperator == null) {
showSnackBar(context, "Veuillez d'abord choisir un operateur");
return;
}
if (_phoneController.text.isEmpty) {
showSnackBar(
context, "Veuillez d'abord saisir un numero de telephone",
duration: 5);
return;
}
print(isNumeric(_amountController.text));
if (!isNumeric(_amountController.text)) {
showSnackBar(context, "Veuillez d'abord saisir un montant valide",
duration: 5);
return;
}
widget.model.amount = int.tryParse(_amountController.text);
widget.model.phone_number = _phoneController.text;
widget.model.selectedOperator = _selectedOperator;
Navigator.pushNamed(context, "/confirmation-form/Mobile");
/* widget.model.selected_country_code = _currentCountry;
var selected_op_type = _operatorsTypes[_selected_operator_index];
widget.model.selected_operator_type = selected_op_type;
Navigator.pushNamed(context, "/$selected_op_type");*/
},
),
),
);
}
Widget _bodyContent(BuildContext context) {
return CustomScrollView(
slivers: <Widget>[
SliverAppBar(
backgroundColor: HexColor.fromHex("#062b66"),
expandedHeight: HEADER_HEIGHT,
floating: false,
pinned: true,
flexibleSpace: FlexibleSpaceBar(
title: Text(_appBarText),
background: Image.asset(FORM_BACKGROUND_ASSET, fit: BoxFit.cover),
),
),
SliverList(
// itemExtent: 100.0,
delegate: SliverChildListDelegate(
[
/*Padding(
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 20),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text("Saisir le Montant",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18,
color: Colors.black)),
IconButton(
icon: Icon(Icons.exit_to_app),
tooltip: "Revenir à la page d'accueil",
onPressed: () {
Navigator.pushReplacementNamed(context, "/home");
},
)
],
),
),*/
SizedBox(
height: 30,
),
Container(
padding:
const EdgeInsets.symmetric(horizontal: 40, vertical: 10),
child: _operatorsDropDown(),
),
SizedBox(
height: 40,
),
Container(
margin: EdgeInsets.only(right: 20),
padding: const EdgeInsets.symmetric(horizontal: 20),
child: _phoneInput(),
),
SizedBox(
height: 40,
),
Container(
margin: EdgeInsets.only(right: 20),
padding: const EdgeInsets.symmetric(horizontal: 20),
child: _amountInput(),
),
SizedBox(
height: 20,
),
Container(color: Colors.grey.withOpacity(0.3)),
],
),
),
],
);
}
Widget _amountInput() {
return TextFormField(
controller: _amountController,
validator: (String value) {
if (value.isEmpty) {
return 'Champ obligatoire';
}
return null;
},
inputFormatters: [
WhitelistingTextInputFormatter.digitsOnly,
],
decoration: new InputDecoration(
border: InputBorder.none,
filled: true,
icon: Icon(Icons.dialpad),
hintText: 'Votre donation',
labelText: 'Montant',
),
keyboardType: TextInputType.number,
);
}
Widget _phoneInput() {
return TextFormField(
controller: _phoneController,
validator: (String value) {
if (value.isEmpty) {
return 'Champ obligatoire';
}
RegExp regex = new RegExp("[^0][0-9]{8,}");
if (!regex.hasMatch(value)) {
return "Le format n'est pas respecté. Minimum 9 chiffres";
}
return null;
},
inputFormatters: [
WhitelistingTextInputFormatter.digitsOnly,
],
decoration: new InputDecoration(
border: InputBorder.none,
filled: true,
icon: Icon(Icons.phone),
hintText: 'Votre Numero de telephone',
labelText: 'Telephone',
),
keyboardType: TextInputType.number,
);
}
Widget _operatorsDropDown() {
return Row(
children: <Widget>[
Expanded(
child: Container(
decoration: BoxDecoration(
border: Border.all(
color: Colors.grey.withOpacity(0.5),
width: 1.0,
),
borderRadius: BorderRadius.circular(10.0),
),
child: DropdownButtonHideUnderline(
child: SizedBox(
child: ButtonTheme(
alignedDropdown: true,
child: new DropdownButton(
isExpanded: true,
// style: Theme.of(context).textTheme.title,
hint: new Text("Operateur"),
value: _currentOperator,
items: _operatorsdropDownMenuItems,
onChanged: _operatorChangedDropDownItem,
),
),
),
),
),
),
],
);
}
Widget _buildGridViewCards() {
var selectedIndex = 0;
print('1. selected index is $selectedIndex');
return GridView.builder(
shrinkWrap: true,
physics: ClampingScrollPhysics(),
itemCount: _selectedProviderItems.length,
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
itemBuilder: (context, i) {
Map<String, dynamic> servItem = _selectedProviderItems[i];
return InkWell(
onTap: () {
setState(() {
if (_selectedItem == servItem) {
_selectedItem = null;
} else {
_selectedItem = servItem;
}
});
},
child: ItemToBuyCard(
checked: _selectedItem != null &&
_selectedItem['id'] == servItem['id'],
model: widget.model,
data: _selectedProviderItems[i],
context: context),
);
});
}
void _anonymeAuthenticate(BuildContext context) async {
var connected = widget.model.aconnected;
print('checking connected....$connected');
setState(() {
_loading = true;
});
if (connected) {
_processData();
} else {
var authentification = await widget.model.anonymousAuth();
checkErrorMessge(authentification);
if (authentification['status']) {
_processData();
}
}
}
void _processData() async {
if (widget.model.aServiceProviders.length == 0) {
var url = '${baseurl}auth/service_providers';
print('get API Data service_providers');
var res = await widget.model.get_api(url, true);
checkErrorMessge(res);
if (res['status']) {
setState(() {
_loading = false;
});
List data = res['msg'];
if (data.length == 0) {
showSnackBar(context, "Aucun operateur trouvé",
status: false, duration: 5);
} else {
_processServicePRovidersData(data);
}
}
} else {
setState(() {
_loading = false;
});
_processServicePRovidersData(widget.model.aServiceProviders);
}
}
void _processServicePRovidersData(data) {
_listServiceProviders = data;
var listCountries = [];
for (var val in data) {
var country = val['country'];
listCountries.add(country);
}
_listCountries = Set.of(listCountries).toList();
print('listcountries is $_listCountries');
var mapCountryCode = _listCountries.firstWhere(
(i) => i.toUpperCase() == widget.model.selected_country_code,
orElse: () => null);
print(
'mapcountrycode is ${widget.model.selected_country_code} \n$mapCountryCode');
if (mapCountryCode != null) {
_selectedServiceProviders = _listServiceProviders
.where((i) => i['country'] == mapCountryCode)
.toList();
widget.model.aServiceProviders = _selectedServiceProviders;
setState(() {
print('selected providers $_selectedServiceProviders');
_operatorsdropDownMenuItems =
_getOperatorsDropDownMenuItems(_selectedServiceProviders);
_groupdropDownMenuItems =
_getGroupeYpeDropDownMenuItems(_selectedServiceProviders);
});
} else {
showSnackBar(context, "Aucun operateur supporté pour votre pays",
status: false, duration: 5);
}
}
List<DropdownMenuItem<String>> _getOperatorsDropDownMenuItems(
List<dynamic> data) {
List<DropdownMenuItem<String>> items = new List();
/* items.add(new DropdownMenuItem(
value: 'all',
child: FittedBox(
fit: BoxFit.contain,
child: Text("-- Tous --", overflow: TextOverflow.ellipsis),
)));*/
for (var val in data) {
// print('dropdown item $val');
var leadingIc = Image.network(
val['logo'],
width: 30,
);
items.add(new DropdownMenuItem(
value: val['name'],
child: Row(
children: <Widget>[
leadingIc,
SizedBox(
width: 10,
),
new Text(val['name'], overflow: TextOverflow.ellipsis),
],
)));
}
return items;
}
List<DropdownMenuItem<String>> _getGroupeYpeDropDownMenuItems(
List<dynamic> data) {
List<DropdownMenuItem<String>> items = new List();
for (var val in data) {
items.add(new DropdownMenuItem(
value: val['name'],
child: Text(val['name'], overflow: TextOverflow.ellipsis)));
}
return items;
}
void _operatorChangedDropDownItem(String selected) {
print("Selected operator $selected");
setState(() {
_selectedProviderItems = [];
_selectedItem = null;
});
_selectedOperator = _selectedServiceProviders
.firstWhere((i) => i['name'] == selected, orElse: () => null);
print('selected providers $_selectedOperator');
setState(() {
if (_selectedOperator != null) {
_selectedProviderItems = _selectedOperator['items']
.where((i) => i['is_withdrawable'] == 0)
.toList();
} else {
if (selected == 'all') {
_selectedServiceProviders.forEach((mp) => _selectedProviderItems +=
mp['items'].where((i) => i['is_withdrawable'] == 0).toList());
}
}
_currentOperator = selected;
});
}
void _validateInputs() {}
checkErrorMessge(res) {
setState(() {
_loading = false;
});
if (!res['status']) {
var msg = res.containsKey('msg')
? res['msg']
: "Une Erreur s'est produite. Veuillez contacter l'Admin";
showSnackBar(context, msg, status: false, duration: 6);
// Navigator.of(_scaffoldKey.currentContext).pop(msg);
}
}
}
| 29.954071 | 85 | 0.559451 |
945db4dde993b4f79d4dc2b434c02b5c1e455816 | 455 | cpp | C++ | src/AppConsole.cpp | kommander/cinderjs | 9fc6c7f50ccb1783f7074a616f8830e5eb13c7c3 | [
"Unlicense"
] | 17 | 2015-02-25T08:33:31.000Z | 2021-02-17T04:40:49.000Z | src/AppConsole.cpp | kommander/cinderjs | 9fc6c7f50ccb1783f7074a616f8830e5eb13c7c3 | [
"Unlicense"
] | 1 | 2015-07-21T07:31:50.000Z | 2015-08-25T19:23:48.000Z | src/AppConsole.cpp | kommander/cinderjs | 9fc6c7f50ccb1783f7074a616f8830e5eb13c7c3 | [
"Unlicense"
] | 4 | 2015-05-08T01:13:11.000Z | 2019-02-20T05:42:30.000Z | //
// Console.cpp
// cinderjs
//
// Created by Sebastian Herrlinger on 16/10/14.
//
//
#include <stdio.h>
#include "AppConsole.h"
namespace cjs {
bool AppConsole::sInitialized = false;
bool AppConsole::sChanged = false;
int AppConsole::sNumLinesToShow = 10;
int AppConsole::sMaxLines = 100;
cinder::gl::TextureRef AppConsole::_sTexture;
std::vector<std::string> AppConsole::sLines = std::vector<std::string>();
int AppConsole::linesToShow = 20;
} | 20.681818 | 73 | 0.714286 |
f100738806ad130a667882b3bbc66cf6ce4437d5 | 1,610 | rb | Ruby | ch07_Classes_and_Modules/7.5.rb | DouglasAllen/RPLExamples | 7baf3a9cd5ef2fb609cb66250ac8f4819b43d5c9 | [
"Ruby",
"Unlicense"
] | null | null | null | ch07_Classes_and_Modules/7.5.rb | DouglasAllen/RPLExamples | 7baf3a9cd5ef2fb609cb66250ac8f4819b43d5c9 | [
"Ruby",
"Unlicense"
] | null | null | null | ch07_Classes_and_Modules/7.5.rb | DouglasAllen/RPLExamples | 7baf3a9cd5ef2fb609cb66250ac8f4819b43d5c9 | [
"Ruby",
"Unlicense"
] | null | null | null | # ---------------------------
# 7.5.1.1 Nested namespaces
module Base64
DIGITS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
class Encoder
def encode
end
end
class Decoder
def decode
end
end
# A utility function for use by both classes
def Base64.helper
end
end
# ---------------------------
# 7.5.2 Modules As Mixins
class Point
include Comparable
end
# ---------------------------
class Point
include(Comparable)
end
# ---------------------------
include Enumerable, Comparable
# ---------------------------
"text".is_a? Comparable # => true
Enumerable === "text" # => true in Ruby 1.8, false in 1.9
# ---------------------------
"text".instance_of? Comparable # => false
# ---------------------------
module Iterable # Classes that define next can include this module
include Enumerable # Define iterators on top of each
def each # And define each on top of next
loop { yield self.next }
end
end
# ---------------------------
countdown = Object.new # A plain old object
def countdown.each # The each iterator as a singleton method
yield 3
yield 2
yield 1
end
countdown.extend(Enumerable) # Now the object has all Enumerable methods
print countdown.sort # Prints "[1, 2, 3]"
# ---------------------------
# 7.5.3 Includable Namespace Modules
Math.sin(0) # => 0.0: Math is a namespace
include Math # The Math namespace can be included
sin(0) # => 0.0: Now we have easy access to the functions
# --------------------------- | 21.466667 | 77 | 0.545342 |
11f0623956ed84d36cbf26d6d013ac3077bd4415 | 1,084 | sql | SQL | sql/20150723/add_parallel_questions_for_dcs_spanish.sql | ufbmi/CCDA_MAIN | 34d470d2883aa710bda5ca9e86befe12e9558608 | [
"Apache-2.0"
] | 1 | 2021-04-25T16:36:49.000Z | 2021-04-25T16:36:49.000Z | sql/20150723/add_parallel_questions_for_dcs_spanish.sql | ufbmi/CCDA_MAIN | 34d470d2883aa710bda5ca9e86befe12e9558608 | [
"Apache-2.0"
] | null | null | null | sql/20150723/add_parallel_questions_for_dcs_spanish.sql | ufbmi/CCDA_MAIN | 34d470d2883aa710bda5ca9e86befe12e9558608 | [
"Apache-2.0"
] | null | null | null | INSERT INTO `questions` (`id`, `sections_id`, `next_questions_id`, `previous_questions_id`, `is_required`, `sort_order`, `created_at`, `updated_at`, `deleted_at`) VALUES
(NULL, 45, NULL, NULL, 0, 0, NOW(), '0000-00-00 00:00:00', '0000-00-00 00:00:00'),
(NULL, 45, NULL, NULL, 0, 1, NOW(), '0000-00-00 00:00:00', '0000-00-00 00:00:00'),
(NULL, 45, NULL, NULL, 0, 2, NOW(), '0000-00-00 00:00:00', '0000-00-00 00:00:00'),
(NULL, 45, NULL, NULL, 0, 3, NOW(), '0000-00-00 00:00:00', '0000-00-00 00:00:00'),
(NULL, 45, NULL, NULL, 0, 4, NOW(), '0000-00-00 00:00:00', '0000-00-00 00:00:00'),
(NULL, 45, NULL, NULL, 0, 5, NOW(), '0000-00-00 00:00:00', '0000-00-00 00:00:00'),
(NULL, 45, NULL, NULL, 0, 6, NOW(), '0000-00-00 00:00:00', '0000-00-00 00:00:00'),
(NULL, 45, NULL, NULL, 0, 7, NOW(), '0000-00-00 00:00:00', '0000-00-00 00:00:00'),
(NULL, 45, NULL, NULL, 0, 8, NOW(), '0000-00-00 00:00:00', '0000-00-00 00:00:00'),
(NULL, 45, NULL, NULL, 0, 9, NOW(), '0000-00-00 00:00:00', '0000-00-00 00:00:00'),
(NULL, 45, NULL, NULL, 0, 10, NOW(), '0000-00-00 00:00:00', '0000-00-00 00:00:00');
| 83.384615 | 169 | 0.595018 |
3315429c0aa928801a1243413b1efad540cf1405 | 1,102 | py | Python | core/migrations/0002_meetup.py | hatsem78/django_docker_nginex_nginx_gunicorn | 15cb7d2d9ecfd2a2f9bf054997a35903c2ee0ce3 | [
"MIT"
] | null | null | null | core/migrations/0002_meetup.py | hatsem78/django_docker_nginex_nginx_gunicorn | 15cb7d2d9ecfd2a2f9bf054997a35903c2ee0ce3 | [
"MIT"
] | null | null | null | core/migrations/0002_meetup.py | hatsem78/django_docker_nginex_nginx_gunicorn | 15cb7d2d9ecfd2a2f9bf054997a35903c2ee0ce3 | [
"MIT"
] | null | null | null | # Generated by Django 2.2.16 on 2020-09-29 23:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Meetup',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255)),
('date', models.DateTimeField(help_text='Date start Meetup')),
('description', models.TextField(blank=True)),
('count_beer', models.IntegerField(default=0, help_text='Count Beer')),
('maximum_temperature', models.FloatField(blank=True, default=0, help_text='Maximum Temperature')),
('count_participants', models.IntegerField(default=0, help_text='Count Participants')),
('direction', models.CharField(max_length=350)),
],
options={
'verbose_name_plural': 'Meetup',
},
),
]
| 36.733333 | 115 | 0.579855 |
9140dc29704868f2b229da3cd3db733792d75aa4 | 703 | sql | SQL | 32_event_trigger.sql | zimirrr/postgres-showcase | 7a3cd5ddc71f88c933e2739ec779209fd0fb12ff | [
"BSD-3-Clause"
] | 153 | 2017-05-22T15:59:29.000Z | 2022-03-26T00:30:37.000Z | 32_event_trigger.sql | zimirrr/postgres-showcase | 7a3cd5ddc71f88c933e2739ec779209fd0fb12ff | [
"BSD-3-Clause"
] | 7 | 2017-08-24T16:20:55.000Z | 2017-09-11T22:12:39.000Z | 32_event_trigger.sql | zimirrr/postgres-showcase | 7a3cd5ddc71f88c933e2739ec779209fd0fb12ff | [
"BSD-3-Clause"
] | 35 | 2017-08-24T13:26:09.000Z | 2022-03-26T00:30:53.000Z | \c pg_features_demo
SET ROLE TO demorole;
CREATE OR REPLACE FUNCTION rewrite_date_check() RETURNS event_trigger AS
$$
BEGIN
-- disallow full re-writes of the "account" table during business hours as it could block all operations
IF pg_event_trigger_table_rewrite_oid() = 'banking_schema.account'::regclass THEN
IF extract('hour' from current_time) BETWEEN 8 AND 17 THEN
RAISE EXCEPTION 'full table rewrites not allowed during business hours!';
END IF;
END IF;
END;
$$
LANGUAGE plpgsql;
RESET ROLE; -- managing event triggers needs superuser privileges
CREATE EVENT TRIGGER rewrite_date_check
ON table_rewrite
EXECUTE PROCEDURE rewrite_date_check();
SET ROLE TO demorole;
| 29.291667 | 108 | 0.773826 |
d5ff2fa8ade11ccfcfc61130bba55dbe85bae56a | 70 | dart | Dart | lib/sticky_float_button.dart | yoehwan/flutter_sticky_float_button | 9d300c03d39cefb8c9d664fd520a5bfb1a91913f | [
"MIT"
] | null | null | null | lib/sticky_float_button.dart | yoehwan/flutter_sticky_float_button | 9d300c03d39cefb8c9d664fd520a5bfb1a91913f | [
"MIT"
] | 1 | 2021-09-19T02:34:04.000Z | 2021-09-19T02:35:06.000Z | lib/sticky_float_button.dart | yoehwan/flutter_sticky_float_button | 9d300c03d39cefb8c9d664fd520a5bfb1a91913f | [
"MIT"
] | null | null | null | library sticky_float_button;
export 'src/sticky_float_button.dart';
| 14 | 38 | 0.828571 |
105cad50b01a4e0a3897975a8ca56d074ba712f0 | 672 | kt | Kotlin | app/src/main/java/nl/rvbsoftdev/curiosityreporting/feature/more/MoreViewModel.kt | rbenza/Curiosity-Reporting | c824d6a08e9576232c7f57e7f7e9f1ba247495d4 | [
"Apache-2.0"
] | 4 | 2019-08-19T18:18:50.000Z | 2019-10-14T09:20:48.000Z | app/src/main/java/nl/rvbsoftdev/curiosityreporting/feature/more/MoreViewModel.kt | rbenza/Curiosity-Reporting | c824d6a08e9576232c7f57e7f7e9f1ba247495d4 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/nl/rvbsoftdev/curiosityreporting/feature/more/MoreViewModel.kt | rbenza/Curiosity-Reporting | c824d6a08e9576232c7f57e7f7e9f1ba247495d4 | [
"Apache-2.0"
] | 3 | 2020-02-23T18:23:14.000Z | 2022-02-09T05:36:30.000Z | package nl.rvbsoftdev.curiosityreporting.feature.more
import androidx.lifecycle.ViewModel
import nl.rvbsoftdev.curiosityreporting.R
class MoreViewModel : ViewModel() {
val moreItemslist = listOf(
MoreItem(0, R.drawable.icon_mission, "Visit the NASA website", "Get to know more about Mars and the mission of Curiosity"),
MoreItem(1, R.drawable.icon_share, "Share", "Share this app with friends and family"),
MoreItem(2, R.drawable.icon_settings, "Settings", "Adjust appearance and settings"),
MoreItem(3, R.drawable.icon_info, "About this app", "View the Privacy Policy, GitHub repository or contact the developer"))
} | 51.692308 | 135 | 0.72619 |
53ccdd4d03a2b3a4ca12159e87562494f4990ce1 | 167 | java | Java | src/org/theusaf/BattlefieldChess/game/GameTeam.java | theusaf/BattlefieldChess | 23fc3319822c55726811be35010826b796500bdb | [
"MIT"
] | null | null | null | src/org/theusaf/BattlefieldChess/game/GameTeam.java | theusaf/BattlefieldChess | 23fc3319822c55726811be35010826b796500bdb | [
"MIT"
] | null | null | null | src/org/theusaf/BattlefieldChess/game/GameTeam.java | theusaf/BattlefieldChess | 23fc3319822c55726811be35010826b796500bdb | [
"MIT"
] | null | null | null | package org.theusaf.BattlefieldChess.game;
/**
* The two sides in chess.
*/
public enum GameTeam {
/**
* White
*/
WHITE,
/**
* Black
*/
BLACK
}
| 10.4375 | 42 | 0.556886 |
8c901becb0d41ae43c3de39fb47eed1bdd2752b5 | 567 | asm | Assembly | pgm_1.asm | mitchGuthrieDev/Assembly-code | 521a539cc4bb59b94c751eba65036035d4df8c15 | [
"MIT"
] | null | null | null | pgm_1.asm | mitchGuthrieDev/Assembly-code | 521a539cc4bb59b94c751eba65036035d4df8c15 | [
"MIT"
] | null | null | null | pgm_1.asm | mitchGuthrieDev/Assembly-code | 521a539cc4bb59b94c751eba65036035d4df8c15 | [
"MIT"
] | null | null | null | # C code:
# f = (g + h) - (i + j);
.data
f: .word 0 # RAM storage location for "f"
g: .word 10
h: .word 20
i: .word 1
j: .word 4
.text
lw $s0, f # load all the data from RAM into registers
lw $s1, g
lw $s2, h
lw $s3, i
lw $s4, j
add $t0, $s1, $s2 # g + h
add $t1, $s3, $s4 # i + j
sub $s0, $t0, $t1 # (g + h) - (i +j)
sw $s0, f # save result back into f
li $v0, 1 # Setup to call system for I/O; 1 means print an integer (word)
lw $a0, f # "load word" (integer) from RAM location
syscall # invoke system to perform terminal I/O
| 19.551724 | 75 | 0.553792 |
ddeb9514c0d60fb12a896af0982bdbd357faeb28 | 168 | php | PHP | app/Http/Controllers/Admin/License/Management.php | kennyLtv/PHP-License-System | b0aba80c9190792c05adacfff40f1dd47e2eaffc | [
"MIT"
] | 13 | 2018-11-17T04:35:21.000Z | 2022-02-20T18:16:22.000Z | app/Http/Controllers/Admin/License/Management.php | kennyLtv/PHP-License-System | b0aba80c9190792c05adacfff40f1dd47e2eaffc | [
"MIT"
] | 4 | 2017-06-05T09:28:34.000Z | 2017-09-14T05:56:05.000Z | app/Http/Controllers/Admin/License/Management.php | kennyLtv/PHP-License-System | b0aba80c9190792c05adacfff40f1dd47e2eaffc | [
"MIT"
] | 5 | 2019-08-19T01:18:20.000Z | 2022-01-03T21:03:35.000Z | <?php
namespace App\Http\Controllers\Admin\License;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class Management extends Controller
{
//
}
| 14 | 45 | 0.767857 |
64d7eed18f29816f86d02c566ff6e24fd7bd2319 | 149 | java | Java | android/src/main/java/cn/finalteam/rxgalleryfinalprovider/utils/FileUtils.java | yuvaraj119/react-native-multiple-camera-gallery-image-picker | 3fecd0eb7184677ec5b5d22f1d5e01d70e857d62 | [
"Apache-2.0"
] | null | null | null | android/src/main/java/cn/finalteam/rxgalleryfinalprovider/utils/FileUtils.java | yuvaraj119/react-native-multiple-camera-gallery-image-picker | 3fecd0eb7184677ec5b5d22f1d5e01d70e857d62 | [
"Apache-2.0"
] | null | null | null | android/src/main/java/cn/finalteam/rxgalleryfinalprovider/utils/FileUtils.java | yuvaraj119/react-native-multiple-camera-gallery-image-picker | 3fecd0eb7184677ec5b5d22f1d5e01d70e857d62 | [
"Apache-2.0"
] | null | null | null | package cn.finalteam.rxgalleryfinalprovider.utils;
/**
* Desction:文件工具类
* Author:pengjianbo
* Date:16/5/6 下午5:45
*/
public class FileUtils {
}
| 13.545455 | 50 | 0.718121 |
19ac11601202a098703cea743fa7e72da7700050 | 2,058 | swift | Swift | Sources/AdvancedCodableHelpers/delayed/DelayedEncodingContainer.swift | TheAngryDarling/SwiftAdvancedCodableHelpers | 7e3434edebe925453daefb0ac2321e0ffb56a143 | [
"Apache-2.0"
] | null | null | null | Sources/AdvancedCodableHelpers/delayed/DelayedEncodingContainer.swift | TheAngryDarling/SwiftAdvancedCodableHelpers | 7e3434edebe925453daefb0ac2321e0ffb56a143 | [
"Apache-2.0"
] | null | null | null | Sources/AdvancedCodableHelpers/delayed/DelayedEncodingContainer.swift | TheAngryDarling/SwiftAdvancedCodableHelpers | 7e3434edebe925453daefb0ac2321e0ffb56a143 | [
"Apache-2.0"
] | null | null | null | //
// DelayedEncodingContainer.swift
// AdvancedCodableHelpers
//
// Created by Tyler Anger on 2018-11-06.
//
import Foundation
/// Base class for delayed encoding container
public class DelayedEncodingContainer {
/// The path of coding keys taken to get to this point in encoding.
public private(set) var codingPath: [CodingKey]
/// Indicator of wether the real container was set yet
public private(set) var wasContainerSet: Bool = false
/// Initialize a new instance of DelayedEncodingContainer with the given coding path
///
/// This is a base class and should never be initilize directly
///
/// - Parameter codingPath: The path of coding keys taken to get to this point in encoding.
public init(codingPath: [CodingKey]) {
self.codingPath = codingPath
}
/// Initialize using an UnkeyedEncodingContainer.
/// Once called, any pending encoding actions will be called upon the real container
///
/// Note: initializeContainer should only be called once on any instance
///
/// - Parameter realContainer: Initialize using an UnkeyedEncodingContainer parent
internal func initializeContainer(from realContainer: inout UnkeyedEncodingContainer) throws {
self.wasContainerSet = true
}
/// Initialize using an KeyedEncodingContainer
/// Once called, any pending encoding actions will be called upon the real container
///
/// Note: initializeContainer should only be called once on any instance
///
/// - Parameters:
/// - parent: Initialize using an KeyedEncodingContainer parent
/// - key: Key to initialize with
internal func initializeContainer<ParentKey>(fromParent parent: inout KeyedEncodingContainer<ParentKey>,
forKey key: ParentKey) throws /* where ParentKey : CodingKey */ {
self.wasContainerSet = true
self.codingPath.append(key)
}
internal func initializeContainer() {
self.wasContainerSet = true
}
}
| 37.418182 | 114 | 0.684159 |
9bd5298505f5b1d3642e39d91a0fcd5422105c30 | 1,016 | sql | SQL | src/main/java/com/fivetran/agent/mysql/source/table_column_attributes.sql | fivetran/mysql-secure-agent | 304e47b3a9c651c55d8496628b109f0c651024f7 | [
"MIT"
] | 1 | 2018-05-08T19:40:20.000Z | 2018-05-08T19:40:20.000Z | src/main/java/com/fivetran/agent/mysql/source/table_column_attributes.sql | fivetran/mysql-secure-agent | 304e47b3a9c651c55d8496628b109f0c651024f7 | [
"MIT"
] | null | null | null | src/main/java/com/fivetran/agent/mysql/source/table_column_attributes.sql | fivetran/mysql-secure-agent | 304e47b3a9c651c55d8496628b109f0c651024f7 | [
"MIT"
] | null | null | null | SELECT
c.TABLE_SCHEMA,
c.TABLE_NAME,
c.COLUMN_NAME,
c.ORDINAL_POSITION,
c.COLUMN_TYPE,
c.CHARACTER_SET_NAME,
c.COLUMN_KEY,
k.REFERENCED_TABLE_SCHEMA,
k.REFERENCED_TABLE_NAME,
k.REFERENCED_COLUMN_NAME
FROM information_schema.COLUMNS c
LEFT JOIN information_schema.KEY_COLUMN_USAGE k
ON k.TABLE_SCHEMA = c.TABLE_SCHEMA COLLATE 'utf8_bin'
AND k.TABLE_NAME = c.TABLE_NAME COLLATE 'utf8_bin'
AND k.COLUMN_NAME = c.COLUMN_NAME COLLATE 'utf8_bin'
LEFT JOIN information_schema.TABLES t
ON t.TABLE_SCHEMA = c.TABLE_SCHEMA COLLATE 'utf8_bin'
AND t.TABLE_NAME = c.TABLE_NAME COLLATE 'utf8_bin'
WHERE t.TABLE_TYPE = 'BASE TABLE'
AND c.TABLE_SCHEMA NOT IN ('performance_schema',
'information_schema',
'mysql',
'sys',
'innodb')
ORDER BY c.TABLE_SCHEMA COLLATE 'utf8_bin',
c.TABLE_NAME COLLATE 'utf8_bin',
c.ORDINAL_POSITION; | 36.285714 | 57 | 0.647638 |
2f75076f1c12ba45cc5dce57b0eb1982a87ef449 | 5,092 | php | PHP | app/Http/Controllers/TarefasController.php | Wanderson-A-Timoteo/laravel-project | 18a1cfb52ef28b951edc00aca623c8a6f9d39ff9 | [
"MIT"
] | null | null | null | app/Http/Controllers/TarefasController.php | Wanderson-A-Timoteo/laravel-project | 18a1cfb52ef28b951edc00aca623c8a6f9d39ff9 | [
"MIT"
] | null | null | null | app/Http/Controllers/TarefasController.php | Wanderson-A-Timoteo/laravel-project | 18a1cfb52ef28b951edc00aca623c8a6f9d39ff9 | [
"MIT"
] | null | null | null | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
//use Illuminate\Support\Facades\DB; // usar com Query Builder
use App\Models\Tarefa;
class TarefasController extends Controller
{
// Controllers com suas respectivas actions
public function list() {
// Exemplo com query build para listar tudo
// $list = DB::select('SELECT * FROM tarefas');
// return view('tarefas.list', [
// 'list' => $list
// ]);
// Exemplo com Eloquent ORM para listar tudo
$list = Tarefa::all();
return view('tarefas.list', [
'list' => $list
]);
}
public function add() {
return view('tarefas.add');
}
public function addAction(Request $request) {
$request->validate([
'titulo' => [ 'required', 'string' ]
]);
$titulo = $request->input('titulo');
// Exemplo com Query Builder
// DB::insert('INSERT INTO tarefas (titulo) VALUES (:titulo)', [
// 'titulo' => $titulo
// ]);
// Exemplo com Eloquent ORM
$tarefa = new Tarefa;
$tarefa->titulo = $titulo;
$tarefa->save();
return redirect()->route('tarefas.list');
// if ($request->filled('titulo')) { // Se o campo título estiver preenchido
// $titulo = $request->input('titulo');
// DB::insert('INSERT INTO tarefas (titulo) VALUES (:titulo)', [
// 'titulo' => $titulo
// ]);
// return redirect()->route('tarefas.list');
// } else { // Se o campo título NÃO estiver preenchido, será redirecionado para a própria pg com a mensagem warning
// return redirect()
// ->route('tarefas.add')
// ->with('warning', 'Você não preencheu o título');
// }
}
public function edit($id) {
//Exemplo com Query Builder
// $data = DB::select('SELECT * FROM tarefas WHERE id = :id', [
// 'id'=> $id
// ]);
// if(count($data) > 0) {
// return view('tarefas.edit', [
// 'data' => $data[0]
// ]);
// } else {
// return redirect()->route('tarefas.list');
// }
// Exemplo com Eloquent ORM
$data = Tarefa::find($id);
if ($data) {
return view('tarefas.edit', [
'data' => $data
]);
} else {
return redirect()->route('tarefas.list');
}
}
public function editAction(Request $request, $id) {
$request->validate([
'titulo' => [ 'required', 'string' ]
]);
$titulo = $request->input('titulo');
// Exemplo com Query Builder
// DB::update('UPDATE tarefas SET titulo = :titulo WHERE id = :id', [
// 'id' => $id,
// 'titulo' => $titulo
// ]);
// Exemplo com Eloquent ORM
// $tarefa = Tarefa::find($id);
// $tarefa->titulo = $titulo;
// $tarefa->save();
// Usando Tarefa::find($id)->update([ titulo'->$titulo ]);
// Exemplo com Eloquent para permitira editar varios campos ao mesmo tempo
// É preciso definir a permição em Models Tarefas.php
Tarefa::find($id)->update([ 'titulo'->$titulo ]);
return redirect()->route('tarefas.list');
// if ($request->filled('titulo')) {
// $titulo = $request->input('titulo');
// $data = DB::select('SELECT * FROM tarefas WHERE id = :id', [
// 'id'=> $id
// ]);
// if(count($data) > 0) {
// DB::update('UPDATE tarefas SET titulo = :titulo WHERE id = :id', [
// 'id' => $id,
// 'titulo' => $titulo
// ]);
// }
// return redirect()->route('tarefas.list');
// } else {
// return redirect()
// ->route('tarefas.edit', ['id'=>$id])
// ->with('warning', 'Você não preencheu o título');
// }
}
public function del($id) {
// Exemplo com Query Builder
// DB::delete('DELETE FROM tarefas WHERE id = :id', [
// 'id' => $id
// ]);
// Exemplo com Eloquent ORM
Tarefa::find($id)->delete();
return redirect()->route('tarefas.list');
}
public function done($id) {
// opção 1: select + update
// opção 2: update matematico
// Vamos usar a segunda opção, neste caso ficará:
// Se resolvido = 0, será 1 - 0 = 1 marcará
// Se resolvido = 1, será 1 -1 = 0 desmarcará
// Exemplo com Query Builder
// DB::update('UPDATE tarefas SET resolvido = 1 - resolvido WHERE id = :id', [
// 'id' => $id
// ]);
// Exemplo com Eloquent ORM
$tarefa = Tarefa::find($id);
if($tarefa) {
$tarefa->resolvido = 1 - $tarefa->resolvido;
$tarefa->save();
}
return redirect()->route('tarefas.list');
}
}
| 29.777778 | 124 | 0.485075 |
c51a23b707834b9705e441b3a81ed636c82f96e3 | 331 | lua | Lua | fs/writelines/writelines.lua | aiq/luazdf | 4f23aa7c6c9ce38f72b361b5a7c067480a97a178 | [
"0BSD"
] | 48 | 2018-02-14T08:28:58.000Z | 2021-12-08T02:06:43.000Z | fs/writelines/writelines.lua | aiq/luazdf | 4f23aa7c6c9ce38f72b361b5a7c067480a97a178 | [
"0BSD"
] | 10 | 2018-02-23T11:55:20.000Z | 2019-09-03T19:08:02.000Z | fs/writelines/writelines.lua | aiq/luazdf | 4f23aa7c6c9ce38f72b361b5a7c067480a97a178 | [
"0BSD"
] | 2 | 2018-02-26T11:57:12.000Z | 2018-03-06T18:37:43.000Z | --ZFUNC-writelines-v1
local function writelines( filename, strlst ) --> res, err
local f, err = io.open( filename, "w" )
if err then return nil, err end
for _, str in ipairs( strlst ) do
local wres, err = f:write( str, "\n" )
if err then return nil, err end
end
return f:close()
end
return writelines
| 22.066667 | 58 | 0.637462 |
badeb62172715705b39bbd9612d76eb1f70d6c4e | 1,720 | lua | Lua | SVUI_Skins/components/blizzard/talkinghead.lua | FailcoderAddons/supervillain-ui | 04ad89eef9d19659f804346d7baa4fe5d4cd619a | [
"MIT"
] | 38 | 2016-10-25T23:09:31.000Z | 2020-09-18T15:33:19.000Z | SVUI_Skins/components/blizzard/talkinghead.lua | FailcoderAddons/supervillain-ui | 04ad89eef9d19659f804346d7baa4fe5d4cd619a | [
"MIT"
] | 223 | 2016-10-26T15:36:36.000Z | 2021-06-26T12:33:39.000Z | SVUI_Skins/components/blizzard/talkinghead.lua | failcoder/supervillain-ui | 04ad89eef9d19659f804346d7baa4fe5d4cd619a | [
"MIT"
] | 24 | 2016-10-26T06:21:41.000Z | 2020-11-23T10:49:25.000Z | --[[
##############################################################################
S V U I By: Failcoder
Talking Head By: JoeyMagz
##############################################################################
--]]
--[[ GLOBALS ]]--
local _G = _G;
local unpack = _G.unpack;
local select = _G.select;
local ipairs = _G.ipairs;
local pairs = _G.pairs;
local type = _G.type;
--[[ ADDON ]]--
local SV = _G['SVUI'];
local L = SV.L;
local MOD = SV.Skins;
local Schema = MOD.Schema;
--[[
##########################################################
TALKING HEAD
##########################################################
]]--
-- Create Talking Head Minion
local THFMinion = CreateFrame("Frame", "SVUI_THFMinion");
local thf;
THFMinion:RegisterEvent("ADDON_LOADED");
--THFMinion:RegisterEvent("TALKINGHEAD_REQUESTED");
local function initializeTHF()
if (thf ~= nil) then return end
thf = CreateFrame("Frame", "SVUI_TalkingHeadFrame", UIParent);
thf:SetPoint("CENTER", 0, 0);
thf:SetSize(500, 200);
SV.API:Set("Window", thf, true);
SV:NewAnchor(thf, L["Talking Head Anchor"]);
end
function THFMinion:OnEvent(event, ...)
if (event == "ADDON_LOADED") then
initializeTHF();
end
end
THFMinion:SetScript("OnEvent", THFMinion.OnEvent);
function SV:MoveTHF()
TalkingHeadFrame:SetPoint("TOP", SVUI_TalkingHeadFrame_MOVE, 0, 0);
end
local function TalkingHeadStyle()
if SV.db.Skins.blizzard.enable ~= true or SV.db.Skins.blizzard.talkinghead ~= true then
return
end
SV:MoveTHF();
end
--[[
##########################################################
MOD LOADING
##########################################################
]]--
MOD:SaveBlizzardStyle("Blizzard_TalkingHeadUI",TalkingHeadStyle)
| 24.927536 | 88 | 0.537209 |
5948068215ad563bf89a0a60702071bed77fd915 | 3,843 | cpp | C++ | src/Pattern.cpp | tapio/Wendy | 41ba0af0158bfe9fe50c0e881b451342602aa327 | [
"Zlib"
] | 1 | 2017-08-28T05:49:37.000Z | 2017-08-28T05:49:37.000Z | src/Pattern.cpp | tapio/Wendy | 41ba0af0158bfe9fe50c0e881b451342602aa327 | [
"Zlib"
] | null | null | null | src/Pattern.cpp | tapio/Wendy | 41ba0af0158bfe9fe50c0e881b451342602aa327 | [
"Zlib"
] | null | null | null | ///////////////////////////////////////////////////////////////////////
// Wendy core library
// Copyright (c) 2009 Camilla Berglund <elmindreda@elmindreda.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any
// damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any
// purpose, including commercial applications, and to alter it and
// redistribute it freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you
// must not claim that you wrote the original software. If you use
// this software in a product, an acknowledgment in the product
// documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and
// must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
///////////////////////////////////////////////////////////////////////
#include <wendy/Config.hpp>
#include <wendy/Core.hpp>
#include <wendy/Pattern.hpp>
#define PCRE_STATIC
#include <pcre.h>
///////////////////////////////////////////////////////////////////////
namespace wendy
{
///////////////////////////////////////////////////////////////////////
PatternMatch::PatternMatch(const String& text, int* ranges, uint count)
{
for (uint i = 0; i < count; i++)
{
m_strings.push_back(text.substr(ranges[i * 2], ranges[i * 2 + 1]));
m_offsets.push_back(ranges[i * 2]);
}
}
///////////////////////////////////////////////////////////////////////
Pattern::Pattern(const String& source):
m_object(nullptr)
{
if (!init(source))
throw Exception("Failed to compile PCRE pattern");
}
Pattern::~Pattern()
{
if (m_object)
pcre_free(m_object);
}
bool Pattern::matches(const String& text) const
{
// NOTE: Static sizes are bad, but what is one to do?
int results[300];
int pairs = pcre_exec((pcre*) m_object, nullptr,
text.c_str(), text.length(), 0, 0,
results, sizeof(results) / sizeof(int));
if (pairs < 0)
{
if (pairs != PCRE_ERROR_NOMATCH)
logError("Error when matching pattern");
return false;
}
// Check if the whole text was matched
if (results[0] != 0 || (size_t) results[1] != text.length())
return false;
return true;
}
bool Pattern::contains(const String& text) const
{
if (!pcre_exec((pcre*) m_object, nullptr, text.c_str(), text.length(), 0, 0, nullptr, 0))
return false;
return true;
}
PatternMatch* Pattern::match(const String& text) const
{
// NOTE: Static sizes are bad, but what is one to do?
int ranges[300];
int count = pcre_exec((pcre*) m_object, nullptr,
text.c_str(), text.length(), 0, 0,
ranges, sizeof(ranges) / sizeof(int));
if (count < 0)
{
if (count != PCRE_ERROR_NOMATCH)
logError("Error when matching pattern");
return nullptr;
}
return new PatternMatch(text, ranges, count);
}
Pattern* Pattern::create(const String& source)
{
Ptr<Pattern> pattern(new Pattern());
if (!pattern->init(source))
return nullptr;
return pattern.detachObject();
}
Pattern::Pattern():
m_object(nullptr)
{
}
bool Pattern::init(const String& source)
{
const char* message = nullptr;
int offset = 0;
m_object = pcre_compile(source.c_str(), 0, &message, &offset, nullptr);
if (!m_object)
{
logError("Failed to compile PCRE pattern: %s", message);
return false;
}
return true;
}
///////////////////////////////////////////////////////////////////////
} /*namespace wendy*/
///////////////////////////////////////////////////////////////////////
| 25.966216 | 91 | 0.574291 |
1d2f4bd7f4e78dae3f0de34d43222d26899138db | 12,722 | swift | Swift | AppTapia/AppTapia/Utils/Utils.swift | otakutronic/WebRTCiOSApp | 835d09c222cc0da435c4f33cbd9ec839f46bf026 | [
"AML"
] | null | null | null | AppTapia/AppTapia/Utils/Utils.swift | otakutronic/WebRTCiOSApp | 835d09c222cc0da435c4f33cbd9ec839f46bf026 | [
"AML"
] | null | null | null | AppTapia/AppTapia/Utils/Utils.swift | otakutronic/WebRTCiOSApp | 835d09c222cc0da435c4f33cbd9ec839f46bf026 | [
"AML"
] | null | null | null | //
// Utils.swift
// CyberhoodEIP
//
// Created by user on 2014/10/1.
// Copyright (c) 2014年 kinghood. All rights reserved.
//
import Foundation
import UIKit
let mailReceiveDateLocalDateTimeFormatter = "yyyy-MM-dd HH:mm";
// MARK: - Alert utils
public func showWarningAlert(viewController: UIViewController, Message msg:String, OkAction okAction:UIAlertAction?){
let alert = UIAlertController(title: msg, message: nil, preferredStyle: UIAlertControllerStyle.alert)
if let okAction = okAction {
alert.addAction(okAction)
} else {
alert.addAction(UIAlertAction(title: NSLocalizedString("BACK", comment: ""), style: UIAlertActionStyle.default, handler: nil))
}
viewController.present(alert, animated: true, completion: nil)
}
public func showConfirmAlert(viewController: UIViewController, Message msg:String, OkAction okAction:UIAlertAction?, CancelAction cancelAction:UIAlertAction?){
let alert = UIAlertController(title: msg, message: nil, preferredStyle: UIAlertControllerStyle.alert)
// Create the actions.
// let cancelAction = UIAlertAction(title: NSLocalizedString("CANCEL", comment: ""), style: UIAlertActionStyle.Cancel) {
// UIAlertAction in
// NSLog("Cancel Pressed")
// }
// Add the actions.
if let cancelAction = cancelAction {
alert.addAction(cancelAction)
}
if let okAction = okAction {
alert.addAction(okAction)
}
viewController.present(alert, animated: true, completion: nil)
}
// MARK: - String utils
extension String {
func isEmail() -> Bool {
let emailRegEx = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluate(with: self)
}
}
// MARK: - String HMAC encrypt utils
enum CryptoAlgorithm {
case MD5, SHA1, SHA224, SHA256, SHA384, SHA512
var HMACAlgorithm: CCHmacAlgorithm {
var result: Int = 0
switch self {
case .MD5: result = kCCHmacAlgMD5
case .SHA1: result = kCCHmacAlgSHA1
case .SHA224: result = kCCHmacAlgSHA224
case .SHA256: result = kCCHmacAlgSHA256
case .SHA384: result = kCCHmacAlgSHA384
case .SHA512: result = kCCHmacAlgSHA512
}
return CCHmacAlgorithm(result)
}
var digestLength: Int {
var result: Int32 = 0
switch self {
case .MD5: result = CC_MD5_DIGEST_LENGTH
case .SHA1: result = CC_SHA1_DIGEST_LENGTH
case .SHA224: result = CC_SHA224_DIGEST_LENGTH
case .SHA256: result = CC_SHA256_DIGEST_LENGTH
case .SHA384: result = CC_SHA384_DIGEST_LENGTH
case .SHA512: result = CC_SHA512_DIGEST_LENGTH
}
return Int(result)
}
}
extension String {
var md5: String! {
let str = self.cString(using: String.Encoding.utf8)
let strLen = CC_LONG(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_MD5_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
CC_MD5(str!, strLen, result)
return stringFromBytes(bytes: result, length: digestLen)
}
var sha1: String! {
let str = self.cString(using: String.Encoding.utf8)
let strLen = CC_LONG(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA1_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
CC_SHA1(str!, strLen, result)
return stringFromBytes(bytes: result, length: digestLen)
}
var sha256String: String! {
let str = self.cString(using: String.Encoding.utf8)
let strLen = CC_LONG(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
CC_SHA256(str!, strLen, result)
return stringFromBytes(bytes: result, length: digestLen)
}
// var sha512String: String! {
// let str = self.cString(using: String.Encoding.utf8)
// let strLen = CC_LONG(self.lengthOfBytes(using: String.Encoding.utf8))
// let digestLen = Int(CC_SHA512_DIGEST_LENGTH)
// let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
// CC_SHA512(str!, strLen, result)
// return stringFromBytes(bytes: result, length: digestLen)
// }
func stringFromBytes(bytes: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String{
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", bytes[i])
}
bytes.deallocate(capacity: length)
return String(format: hash as String)
}
// func hmac(algorithm: CryptoAlgorithm, key: String) -> String {
// let str = self.cStringUsingEncoding(NSUTF8StringEncoding)
// let strLen = Int(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
// let digestLen = algorithm.digestLength
// let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
// let keyStr = key.cStringUsingEncoding(NSUTF8StringEncoding)
// let keyLen = Int(key.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
//
// CCHmac(algorithm.HMACAlgorithm, keyStr!, keyLen, str!, strLen, result)
//
// let digest = stringFromResult(result, length: digestLen)
//
// result.dealloc(digestLen)
//
// return digest
// }
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
// MARK: - Date utils
//func UTC2Date(utc: String) -> NSDate {
// let dateFormatter = NSDateFormatter()
// //get utc date
// dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss Z"
// dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC")
// let date = dateFormatter.dateFromString(utc)
// return date!
//}
func UTCDateTime2Date(dateTimeString: String) -> NSDate {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC") as TimeZone!
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
if let date = dateFormatter.date(from: dateTimeString) {
return date as NSDate
}
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
if let date = dateFormatter.date(from: dateTimeString) {
return date as NSDate
}
dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss Z"
if let date = dateFormatter.date(from: dateTimeString) {
return date as NSDate
}
return NSDate()
}
extension NSDate {
// //NSDate(dateString:"2014-06-06")
// convenience init(dateString:String) {
// let dateStringFormatter = DateFormatter()
// dateStringFormatter.dateFormat = "yyyy-MM-dd"
// dateStringFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale!
// let d = dateStringFormatter.date(from: dateString)
// self.init(timeInterval:0, sinceDate:d!)
// }
// //NSDate(dateTimeString:"2014-06-06 08:11:22")
// convenience init(dateTimeString:String) {
// let dateStringFormatter = DateFormatter()
// dateStringFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
// let d = dateStringFormatter.date(from: dateTimeString)
// self.init(timeInterval:0, sinceDate:d!)
// }
func ToCalendarMenuViewString() -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy / MM"
dateFormatter.timeZone = NSTimeZone.local
return dateFormatter.string(from: self as Date)
}
func ToDateString() -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.timeZone = NSTimeZone.local
return dateFormatter.string(from: self as Date)
}
func ToMDTimeString() -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd"
dateFormatter.timeZone = NSTimeZone.local
return dateFormatter.string(from: self as Date)
}
func ToHMSTimeString() -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
dateFormatter.timeZone = NSTimeZone.local
return dateFormatter.string(from: self as Date)
}
func ToHMTimeString() -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
dateFormatter.timeZone = NSTimeZone.local
return dateFormatter.string(from: self as Date)
}
func ToYMDHMString() -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
dateFormatter.timeZone = NSTimeZone.local
return dateFormatter.string(from: self as Date)
}
func ToLocalDateTimeString() -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = NSTimeZone.local
return dateFormatter.string(from: self as Date)
}
func ToUTCDateTimeString() -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC") as TimeZone!
return dateFormatter.string(from: self as Date)
}
}
// MARK: - File utils
func getImageIconForFilename(fileName: String) -> UIImage{
let ext = NSURL(fileURLWithPath: fileName).pathExtension
switch ext!.lowercased() {
case "xls", "xlsx":
return UIImage(named: "FileTypeExcel")!
case "doc","docx":
return UIImage(named: "FileTypeDoc")!
case "ppt","pptx":
return UIImage(named: "FileTypePpt")!
case "pdf":
return UIImage(named: "FileTypePdf")!
case "mp3":
return UIImage(named: "FileTypeAudio")!
case "jpg", "jpeg", "png", "gif":
return UIImage(named: "FileTypeImage")!
case "txt":
return UIImage(named: "FileTypeTxt")!
case "zip":
return UIImage(named: "FileTypeZip")!
case "mov","mp4", "3gp", "mpeg":
return UIImage(named: "FileTypeVideo")!
case "rar":
return UIImage(named: "FileTypeRar")!
default:
return UIImage(named: "FileTypeUnknow")!
}
}
func isFileStreamable(fileName: String) -> Bool{
let ext = NSURL(fileURLWithPath: fileName).pathExtension
switch ext!.lowercased() {
case "mp3":
return true
case "mov","mp4", "3gp", "mpeg", "avi", "wmv", "mkv", "rmvb", "wma", "wav", "webm":
return true
default:
return false
}
}
func getFormattedFileSize(size: Double) -> String{
var result = ""
if size == 0 {
result = "0 bytes"
}else if (size > 0) && (size < 1024) {
result = String(format: "%.0f bytes", size)
}else if (size >= 1024) && (size < pow(1024.0,2.0)) {
result = String(format: "%.1f KB", (size / 1024.0))
}else if (size >= pow(1024.0,2.0)) && (size < pow(1024.0,3.0)) {
result = String(format: "%.2f MB", (size / pow(1024.0, 2.0)))
}else { //fileSize >= pow(1024,3)
result = String(format: "%.3f GB", (size / pow(1024.0, 3.0)))
}
return result
}
// MARK: - Color utils
extension UIColor {
public convenience init?(hexString: String) {
let r, g, b, a: CGFloat
if hexString.hasPrefix("#") {
let start = hexString.index(hexString.startIndex, offsetBy: 1)
let hexColor = hexString.substring(from: start)
if hexColor.count == 8 {
let scanner = Scanner(string: hexColor)
var hexNumber: UInt64 = 0
if scanner.scanHexInt64(&hexNumber) {
r = CGFloat((hexNumber & 0xff000000) >> 24) / 255
g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255
b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255
a = CGFloat(hexNumber & 0x000000ff) / 255
self.init(red: r, green: g, blue: b, alpha: a)
return
}
}
}
return nil
}
}
| 34.107239 | 160 | 0.621679 |
c418854cde10e03f0e166e6c3f5a32ee706b80cc | 91,996 | c | C | arch/risc-v/src/esp32c3/esp32c3_bignum.c | eenurkka/incubator-nuttx | 5c3d6bba6d9ec5015896c3019cd2064696373210 | [
"Apache-2.0"
] | 1 | 2022-01-04T04:04:56.000Z | 2022-01-04T04:04:56.000Z | arch/risc-v/src/esp32c3/esp32c3_bignum.c | eenurkka/incubator-nuttx | 5c3d6bba6d9ec5015896c3019cd2064696373210 | [
"Apache-2.0"
] | 4 | 2021-12-04T01:29:43.000Z | 2022-03-30T00:02:20.000Z | arch/risc-v/src/esp32c3/esp32c3_bignum.c | eenurkka/incubator-nuttx | 5c3d6bba6d9ec5015896c3019cd2064696373210 | [
"Apache-2.0"
] | null | null | null | /****************************************************************************
* arch/risc-v/src/esp32c3/esp32c3_bignum.c
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#ifdef CONFIG_ESP32C3_BIGNUM_ACCELERATOR
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <limits.h>
#include <assert.h>
#include <stdlib.h>
#include <sys/param.h>
#include <debug.h>
#include <semaphore.h>
#include "riscv_internal.h"
#include "hardware/esp32c3_rsa.h"
#include "hardware/esp32c3_system.h"
#include "esp32c3_bignum.h"
/****************************************************************************
* Pre-processor Macros
****************************************************************************/
#undef MIN
#undef MAX
#define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
#define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
#define SOC_RSA_MAX_BIT_LEN (3072)
#define CIL (sizeof(uint32_t)) /* chars in limb */
#define BIL (CIL << 3) /* bits in limb */
#define BIH (CIL << 2) /* half limb size */
#define MPI_SIZE_T_MAX ((size_t) -1) /* SIZE_T_MAX is not standard */
/* Convert between bits/chars and number of limbs
* Divide first in order to avoid potential overflows
*/
#define BITS_TO_LIMBS(i) ((i) / BIL + ((i) % BIL != 0))
#define CHARS_TO_LIMBS(i) ((i) / CIL + ((i) % CIL != 0))
/* Get a specific byte, without range checks. */
#define BYTE_BITS (8)
#define BYTE_CHECKS (0xff)
#define GET_BYTE(X, i) (((X)->p[(i) / CIL] >> \
(((i) % CIL) * BYTE_BITS)) & BYTE_CHECKS)
/****************************************************************************
* Private Data
****************************************************************************/
static sem_t g_rsa_sem = SEM_INITIALIZER(1);
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Name: esp32c3_mpi_to_mem_block
*
* Description:
* Copy MPI bignum 'mpi' to hardware memory block.
*
* Input Parameters:
* mem_base - The hardware memory block
* mpi - The bignum 'mpi' from the previous calculation
* num_words - The number of words to be represented
*
* Returned Value:
* None.
*
****************************************************************************/
static void esp32c3_mpi_to_mem_block(uint32_t mem_base,
const struct esp32c3_mpi_s *mpi,
size_t num_words)
{
uint32_t *pbase = (uint32_t *)mem_base;
uint32_t copy_words = MIN(num_words, mpi->n);
int i;
/* Copy MPI data to memory block registers */
memcpy(pbase, mpi->p, copy_words * sizeof(uint32_t));
/* Zero any remaining memory block data */
for (i = copy_words; i < num_words; i++)
{
pbase[i] = 0;
}
}
/****************************************************************************
* Name: esp32c3_mem_block_to_mpi
*
* Description:
* Read MPI bignum back from hardware memory block.
*
* Input Parameters:
* x - The result from the previous calculation
* mem_base - The hardware memory block
* num_words - The number of words to be represented
*
* Returned Value:
* None.
*
****************************************************************************/
static void esp32c3_mem_block_to_mpi(struct esp32c3_mpi_s *x,
uint32_t mem_base, int num_words)
{
int i;
/* Copy data from memory block registers */
const size_t REG_WIDTH = sizeof(uint32_t);
for (i = 0; i < num_words; i++)
{
x->p[i] = getreg32(mem_base + (i * REG_WIDTH));
}
/* Zero any remaining limbs in the bignum,
* if the buffer is bigger than num_words
*/
for (i = num_words; i < x->n; i++)
{
x->p[i] = 0;
}
}
/****************************************************************************
* Name: esp32c3_mpi_start_op
*
* Description:
* Begin an RSA operation.
*
* Input Parameters:
* op_reg - Specifies which 'START' register to write to.
*
* Returned Value:
* None.
*
****************************************************************************/
static void esp32c3_mpi_start_op(uint32_t op_reg)
{
/* Clear interrupt status */
putreg32(1, RSA_CLEAR_INTERRUPT_REG);
/* Note: above putreg32 includes a memw, so we know any writes
* to the memory blocks are also complete.
*/
putreg32(1, op_reg);
}
/****************************************************************************
* Name: esp32c3_mpi_wait_op_complete
*
* Description:
* Wait for an RSA operation to complete.
*
* Input Parameters:
* None
*
* Returned Value:
* None.
*
****************************************************************************/
static void esp32c3_mpi_wait_op_complete(void)
{
while (getreg32(RSA_IDLE_REG) != 1)
{
}
/* clear the interrupt */
putreg32(1, RSA_CLEAR_INTERRUPT_REG);
}
/****************************************************************************
* Name: esp32c3_mpi_enable_hardware_hw_op
*
* Description:
* Enable the MPI hardware and acquire the lock.
*
* Input Parameters:
* None
*
* Returned Value:
* None.
*
****************************************************************************/
static void esp32c3_mpi_enable_hardware_hw_op(void)
{
nxsem_wait(&g_rsa_sem);
/* Enable RSA hardware */
modifyreg32(SYSTEM_PERIP_CLK_EN1_REG, 0, SYSTEM_CRYPTO_RSA_CLK_EN);
modifyreg32(SYSTEM_PERIP_RST_EN1_REG, (SYSTEM_CRYPTO_RSA_RST |
SYSTEM_CRYPTO_DS_RST), 0);
modifyreg32(SYSTEM_RSA_PD_CTRL_REG, SYSTEM_RSA_MEM_PD, 0);
while (getreg32(RSA_CLEAN_REG) != 1)
{
}
}
/****************************************************************************
* Name: esp32c3_mpi_disable_hardware_hw_op
*
* Description:
* Disable the MPI hardware and release the lock.
*
* Input Parameters:
* None
*
* Returned Value:
* None.
*
****************************************************************************/
static void esp32c3_mpi_disable_hardware_hw_op(void)
{
modifyreg32(SYSTEM_RSA_PD_CTRL_REG, 0, SYSTEM_RSA_MEM_PD);
/* Disable RSA hardware */
modifyreg32(SYSTEM_PERIP_CLK_EN1_REG, SYSTEM_CRYPTO_RSA_CLK_EN, 0);
modifyreg32(SYSTEM_PERIP_RST_EN1_REG, 0, SYSTEM_CRYPTO_RSA_RST);
nxsem_post(&g_rsa_sem);
}
/****************************************************************************
* Name: esp32c3_mpi_read_result_hw_op
*
* Description:
* Read out the result from the previous calculation.
*
* Input Parameters:
* Z - The result from the previous calculation
* z_words - The number of words to be represented
*
* Returned Value:
* None.
*
****************************************************************************/
static void esp32c3_mpi_read_result_hw_op(struct esp32c3_mpi_s *Z,
size_t z_words)
{
esp32c3_mpi_wait_op_complete();
esp32c3_mem_block_to_mpi(Z, RSA_MEM_Z_BLOCK_REG, z_words);
}
/****************************************************************************
* Name: esp32c3_mpi_mul_mpi_hw_op
*
* Description:
* Starts a (X * Y) calculation in hardware.
*
* Input Parameters:
* X - First multiplication argument
* Y - Second multiplication argument
* n_words - The number of words to be represented
*
* Returned Value:
* None.
*
****************************************************************************/
static void esp32c3_mpi_mul_mpi_hw_op(const struct esp32c3_mpi_s *X,
const struct esp32c3_mpi_s *Y,
size_t n_words)
{
/* Copy X (right-extended) & Y (left-extended) to memory block */
esp32c3_mpi_to_mem_block(RSA_MEM_X_BLOCK_REG, X, n_words);
esp32c3_mpi_to_mem_block(RSA_MEM_Z_BLOCK_REG + n_words * 4, Y, n_words);
putreg32(((n_words * 2) - 1), RSA_MODE_REG);
esp32c3_mpi_start_op(RSA_MULT_START_REG);
}
/****************************************************************************
* Name: esp32c3_mpi_mult_failover_mod_op
*
* Description:
* Special-case of (X * Y), where we use hardware montgomery mod
* multiplication to calculate result where either A or B are > 2048 bits
* so can't use the standard multiplication method.
*
* Input Parameters:
* X - First multiplication argument
* Y - Second multiplication argument
* num_words - The number of words to be represented
*
* Returned Value:
* None.
*
****************************************************************************/
static void esp32c3_mpi_mult_failover_mod_op(const struct esp32c3_mpi_s *X,
const struct esp32c3_mpi_s *Y,
size_t num_words)
{
int i;
/* M = 2^num_words - 1, so block is entirely FF */
for (i = 0; i < num_words; i++)
{
putreg32(UINT32_MAX, RSA_MEM_M_BLOCK_REG + i * 4);
}
/* mprime = 1 */
putreg32(1, RSA_M_PRIME_REG);
putreg32(num_words - 1, RSA_MODE_REG);
/* Load X & Y */
esp32c3_mpi_to_mem_block(RSA_MEM_X_BLOCK_REG, X, num_words);
esp32c3_mpi_to_mem_block(RSA_MEM_Y_BLOCK_REG, Y, num_words);
/* rinv = 1, write first word */
putreg32(1, RSA_MEM_RB_BLOCK_REG);
/* Zero out rest of the rinv words */
for (i = 1; i < num_words; i++)
{
putreg32(0, RSA_MEM_RB_BLOCK_REG + i * 4);
}
esp32c3_mpi_start_op(RSA_MODMULT_START_REG);
}
/****************************************************************************
* Name: esp32c3_mpi_zeroize
*
* Description:
* Zero any limbs data.
*
* Input Parameters:
* v - The pointer to limbs
* n - The total number of limbs
*
* Returned Value:
* None.
*
****************************************************************************/
static void esp32c3_mpi_zeroize(uint32_t *v, size_t n)
{
memset(v, 0, CIL * n);
}
/****************************************************************************
* Name: bits_to_words
*
* Description:
* Convert bit count to 32-bits word count.
*
* Input Parameters:
* bits - The number of bit count
*
* Returned Value:
* Number of words count.
*
****************************************************************************/
static size_t bits_to_words(size_t bits)
{
return (bits + 31) / 32;
}
/****************************************************************************
* Name: mpi_sub_hlp
*
* Description:
* Helper for esp32c3_mpi subtraction
*
* Input Parameters:
* n - Number of limbs of \p d and \p s
* d - On input, the left operand, On output, the result operand
* s - The right operand
*
* Returned Value:
* \c 1 if \p `d < \p s`.
* \c 0 if \p `d >= \p s`..
*
****************************************************************************/
static uint32_t mpi_sub_hlp(size_t n,
uint32_t *d,
const uint32_t *s)
{
size_t i;
uint32_t c;
uint32_t z;
for (i = c = 0; i < n; i++, s++, d++)
{
z = (*d < c);
*d -= c;
c = (*d < *s) + z;
*d -= *s;
}
return c;
}
/****************************************************************************
* Name: mpi_mul_addc
*
* Description:
* Helper for esp32c3_mpi multiplication
*
* Input Parameters:
* count - The count of limbs
* c - The result number of limbs
* s - The target number of limbs
* d - The pointer to limbs
* b - The total number of limbs
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
static inline void mpi_mul_addc(uint32_t count, uint32_t *c,
uint32_t **s, uint32_t **d, uint32_t b)
{
uint32_t s0;
uint32_t s1;
uint32_t b0;
uint32_t b1;
uint32_t r0;
uint32_t r1;
uint32_t rx;
uint32_t ry;
b0 = (b << BIH) >> BIH;
b1 = (b >> BIH);
for (int i = 0; i < count; ++i)
{
s0 = (**s << BIH) >> BIH;
s1 = (**s >> BIH);
(*s)++;
rx = s0 * b1;
r0 = s0 * b0;
ry = s1 * b0;
r1 = s1 * b1;
r1 += (rx >> BIH);
r1 += (ry >> BIH);
rx <<= BIH;
ry <<= BIH;
r0 += rx;
r1 += (r0 < rx);
r0 += ry;
r1 += (r0 < ry);
r0 += *c;
r1 += (r0 < *c);
r0 += **d;
r1 += (r0 < **d);
*c = r1;
*((*d)++) = r0;
}
}
/****************************************************************************
* Name: mpi_mul_hlp
*
* Description:
* Helper for esp32c3_mpi multiplication
*
* Input Parameters:
* i - The MPI context to grow
* s - The target number of limbs
* d - The pointer to limbs
* b - The total number of limbs
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
static void mpi_mul_hlp(size_t i, uint32_t *s, uint32_t *d, uint32_t b)
{
uint32_t c = 0;
for (; i >= 16; i -= 16)
{
mpi_mul_addc(16, &c, &s, &d, b);
}
for (; i >= 8; i -= 8)
{
mpi_mul_addc(8, &c, &s, &d, b);
}
for (; i > 0; i--)
{
mpi_mul_addc(1, &c, &s, &d, b);
}
do
{
*d += c;
c = (*d < c);
d++;
}
while (c != 0);
}
/****************************************************************************
* Name: mpi_safe_cond_assign
*
* Description:
* Conditionally assign dest = src, without leaking information
* about whether the assignment was made or not.
*
* Input Parameters:
* n - The MPI context to grow
* dest - The MPI to conditionally assign to
* src - The MPI to conditionally assign from
* assign - The condition deciding whether perform the assignment or not
*
* Returned Value:
* None.
*
****************************************************************************/
static void mpi_safe_cond_assign(size_t n,
uint32_t *dest,
const uint32_t *src,
unsigned char assign)
{
size_t i;
for (i = 0; i < n; i++)
{
dest[i] = dest[i] * (1 - assign) + src[i] * assign;
}
}
/****************************************************************************
* Name: mpi_montg_init
*
* Description:
* Fast Montgomery initialization
*
* Input Parameters:
* X - The MPI context to grow
* nblimbs - The target number of limbs
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
static void mpi_montg_init(uint32_t *mm, const struct esp32c3_mpi_s *N)
{
uint32_t x;
uint32_t m0 = N->p[0];
unsigned int i;
x = m0 + (((m0 + 2) & 4) << 1);
for (i = BIL; i >= 8; i /= 2)
{
x *= (2 - (m0 * x));
}
*mm = ~x + 1;
}
/****************************************************************************
* Name: mpi_montmul
*
* Description:
* Montgomery multiplication: A = A * B * R^-1 mod N
*
* Input Parameters:
* A - One of the numbers to multiply,
* It must have at least as many limbs as N
* (A->n >= N->n), and any limbs beyond n are ignored.
* On successful completion, A contains the result of
* the multiplication A * B * R^-1 mod N where
* R = (2^CIL)^n.
* B - One of the numbers to multiply, It must be nonzero
* and must not have more limbs than N (B->n <= N->n)
* N - The modulo. N must be odd.
* mm - The value calculated by `mpi_montg_init(&mm, N)`.
* This is -N^-1 mod 2^CIL.
* T - A bignum for temporary storage.
* It must be at least twice the limb size of N plus 2
* (T->n >= 2 * (N->n + 1)).
*
* Returned Value:
* None.
*
****************************************************************************/
static void mpi_montmul(struct esp32c3_mpi_s *A,
const struct esp32c3_mpi_s *B,
const struct esp32c3_mpi_s *N,
uint32_t mm,
const struct esp32c3_mpi_s *T)
{
size_t i;
size_t n;
size_t m;
uint32_t u0;
uint32_t u1;
uint32_t *d;
memset(T->p, 0, T->n * CIL);
d = T->p;
n = N->n;
m = (B->n < n) ? B->n : n;
for (i = 0; i < n; i++)
{
/* T = (T + u0*B + u1*N) / 2^BIL */
u0 = A->p[i];
u1 = (d[0] + u0 * B->p[0]) * mm;
mpi_mul_hlp(m, B->p, d, u0);
mpi_mul_hlp(n, N->p, d, u1);
*d++ = u0;
d[n + 1] = 0;
}
/* At this point, d is either the desired result or the desired result
* plus N. We now potentially subtract N, avoiding leaking whether the
* subtraction is performed through side channels.
*/
/* Copy the n least significant limbs of d to A, so that
* A = d if d < N (recall that N has n limbs).
*/
memcpy(A->p, d, n * CIL);
/* If d >= N then we want to set A to d - N. To prevent timing attacks,
* do the calculation without using conditional tests.
*/
/* Set d to d0 + (2^BIL)^n - N where d0 is the current value of d.
*/
d[n] += 1;
d[n] -= mpi_sub_hlp(n, d, N->p);
/* If d0 < N then d < (2^BIL)^n
* so d[n] == 0 and we want to keep A as it is.
* If d0 >= N then d >= (2^BIL)^n, and d <= (2^BIL)^n + N < 2 * (2^BIL)^n
* so d[n] == 1 and we want to set A to the result of the subtraction
* which is d - (2^BIL)^n, i.e. the n least significant limbs of d.
* This exactly corresponds to a conditional assignment.
*/
mpi_safe_cond_assign(n, A->p, d, (unsigned char) d[n]);
}
/****************************************************************************
* Name: mpi_montred
*
* Description:
* Montgomery reduction: A = A * R^-1 mod N
*
* Input Parameters:
* A - One of the numbers to multiply,
* It must have at least as many limbs as N
* (A->n >= N->n), and any limbs beyond n are ignored.
* On successful completion, A contains the result of
* the multiplication A * B * R^-1 mod N where
* R = (2^CIL)^n.
* N - The modulo. N must be odd.
* mm - The value calculated by `mpi_montg_init(&mm, N)`.
* This is -N^-1 mod 2^CIL.
* T - A bignum for temporary storage.
* It must be at least twice the limb size of N plus 2
* (T->n >= 2 * (N->n + 1)).
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
static void mpi_montred(struct esp32c3_mpi_s *A,
const struct esp32c3_mpi_s *N,
uint32_t mm,
const struct esp32c3_mpi_s *T)
{
uint32_t z = 1;
struct esp32c3_mpi_s U;
U.n = (int) z;
U.s = (int) z;
U.p = &z;
mpi_montmul(A, &U, N, mm, T);
}
/****************************************************************************
* Name: mpi_mult_mpi_overlong
*
* Description:
* Deal with the case when X & Y are too long for the hardware unit,
* by splitting one operand into two halves.
*
* Input Parameters:
* Z - The destination MPI
* X - The first factor
* Y - The second factor
* y_words - The number of words to be process
* z_words - The number of words to be represented
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
static int mpi_mult_mpi_overlong(struct esp32c3_mpi_s *Z,
const struct esp32c3_mpi_s *X,
const struct esp32c3_mpi_s *Y,
size_t y_words, size_t z_words)
{
int ret = 0;
struct esp32c3_mpi_s ztemp;
/* Rather than slicing in two on bits we slice on limbs (32 bit words) */
const size_t words_slice = y_words / 2;
/* yp holds lower bits of Y */
const struct esp32c3_mpi_s yp = {
.p = Y->p,
.n = words_slice,
.s = Y->s
};
/* ypp holds upper bits of Y,
* right shifted (also reuses Y's array contents)
*/
const struct esp32c3_mpi_s ypp = {
.p = Y->p + words_slice,
.n = y_words - words_slice,
.s = Y->s
};
esp32c3_mpi_init(&ztemp);
/* Get result ztemp = yp * X (need temporary variable ztemp) */
ESP32C3_MPI_CHK(esp32c3_mpi_mul_mpi(&ztemp, X, &yp), cleanup);
/* Z = ypp * Y */
ESP32C3_MPI_CHK(esp32c3_mpi_mul_mpi(Z, X, &ypp), cleanup);
/* Z = Z << b */
ESP32C3_MPI_CHK(esp32c3_mpi_shift_l(Z, words_slice * 32), cleanup);
/* Z += ztemp */
ESP32C3_MPI_CHK(esp32c3_mpi_add_mpi(Z, Z, &ztemp), cleanup);
cleanup:
esp32c3_mpi_free(&ztemp);
return ret;
}
/****************************************************************************
* Name: mpi_mult_mpi_failover_mod_mult
*
* Description:
* Where we use hardware montgomery mod multiplication to calculate an
* esp32c3_mpi_mult_mpi result where either A or B are > 2048 bits
* so can't use the standard multiplication method.
*
* Input Parameters:
* Z - The destination MPI
* X - The first factor
* Y - The second factor
* z_words - The number of words to be represented
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
static int mpi_mult_mpi_failover_mod_mult(struct esp32c3_mpi_s *Z,
const struct esp32c3_mpi_s *X,
const struct esp32c3_mpi_s *Y,
size_t z_words)
{
int ret;
esp32c3_mpi_enable_hardware_hw_op();
esp32c3_mpi_mult_failover_mod_op(X, Y, z_words);
ESP32C3_MPI_CHK(esp32c3_mpi_grow(Z, z_words), cleanup);
esp32c3_mpi_read_result_hw_op(Z, z_words);
Z->s = X->s * Y->s;
cleanup:
esp32c3_mpi_disable_hardware_hw_op();
return ret;
}
/****************************************************************************
* Name: esp32c3_bignum_clz
*
* Description:
* Count leading zero bits in a given integer
*
* Input Parameters:
* x - The MPI context to query
*
* Returned Value:
* The count leading zero bits in a given integer.
*
****************************************************************************/
static size_t esp32c3_bignum_clz(const uint32_t x)
{
size_t j;
uint32_t mask = UINT32_C(1) << (BIL - 1);
for (j = 0; j < BIL; j++)
{
if (x & mask)
{
break;
}
mask >>= 1;
}
return j;
}
/****************************************************************************
* Name: mpi_get_digit
*
* Description:
* Convert an ASCII character to digit value
*
* Input Parameters:
* d - The destination MPI
* radix - The numeric base of the input character
* c - An ASCII character
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
static int mpi_get_digit(uint32_t *d, int radix, char c)
{
*d = 255;
if (c >= 0x30 && c <= 0x39)
{
*d = c - 0x30;
}
if (c >= 0x41 && c <= 0x46)
{
*d = c - 0x37;
}
if (c >= 0x61 && c <= 0x66)
{
*d = c - 0x57;
}
if (*d >= (uint32_t) radix)
{
return ESP32C3_ERR_MPI_INVALID_CHARACTER;
}
return OK;
}
/****************************************************************************
* Name: mpi_write_hlp
*
* Description:
* Helper to write the digits high-order first
*
* Input Parameters:
* X - The source MPI
* radix - The numeric base of the output string
* p - The buffer to write the string to
* buflen - The available size in Bytes of p
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
static int mpi_write_hlp(struct esp32c3_mpi_s *X, int radix,
char **p, const size_t buflen)
{
int ret;
uint32_t r;
size_t length = 0;
char *p_end = *p + buflen;
do
{
if (length >= buflen)
{
return ESP32C3_ERR_MPI_BUFFER_TOO_SMALL;
}
ESP32C3_MPI_CHK(esp32c3_mpi_mod_int(&r, X, radix), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_div_int(X, NULL, X, radix), cleanup);
/* Write the residue in the current position, as an ASCII character.
*/
if (r < 0xa)
{
*(--p_end) = (char)('0' + r);
}
else
{
*(--p_end) = (char)('A' + (r - 0xa));
}
length++;
}
while (esp32c3_mpi_cmp_int(X, 0) != 0);
memmove(*p, p_end, length);
*p += length;
cleanup:
return ret;
}
/****************************************************************************
* Name: mpi_uint_bigendian_to_host
*
* Description:
* Convert a big-endian byte array aligned to the size of uint32_t
* into the storage form used by esp32c3_mpi
*
* Input Parameters:
* X - The MPI context to convert
*
* Returned Value:
* The size of uint32_t into the storage form used by esp32c3_mpi.
*
****************************************************************************/
static uint32_t mpi_uint_bigendian_to_host(uint32_t x)
{
uint8_t i;
unsigned char *x_ptr;
uint32_t tmp = 0;
for (i = 0, x_ptr = (unsigned char *) &x; i < CIL; i++, x_ptr++)
{
tmp <<= CHAR_BIT;
tmp |= (uint32_t) *x_ptr;
}
return (tmp);
}
/****************************************************************************
* Name: mpi_bigendian_to_host
*
* Description:
* Enlarge an MPI to the specified number of limbs
*
* Input Parameters:
* p - The MPI context to grow
* limbs - The target number of limbs
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
static void mpi_bigendian_to_host(uint32_t * const p, size_t limbs)
{
uint32_t *cur_limb_left;
uint32_t *cur_limb_right;
if (limbs == 0)
{
return ;
}
/* Traverse limbs and
* - adapt byte-order in each limb
* - swap the limbs themselves.
* For that, simultaneously traverse the limbs from left to right
* and from right to left, as long as the left index is not bigger
* than the right index (it's not a problem if limbs is odd and the
* indices coincide in the last iteration).
*/
for (cur_limb_left = p, cur_limb_right = p + (limbs - 1);
cur_limb_left <= cur_limb_right;
cur_limb_left++, cur_limb_right--)
{
uint32_t tmp;
/* Note that if cur_limb_left == cur_limb_right,
* this code effectively swaps the bytes only once.
*/
tmp = mpi_uint_bigendian_to_host(*cur_limb_left);
*cur_limb_left = mpi_uint_bigendian_to_host(*cur_limb_right);
*cur_limb_right = tmp;
}
}
/****************************************************************************
* Name: ct_lt_mpi_uint
*
* Description:
* Decide if an integer is less than the other, without branches.
*
* Input Parameters:
* X - First integer
* nblimbs - Second integer
*
* Returned Value:
* 1 if \p x is less than \p y, 0 otherwise.
*
****************************************************************************/
static unsigned ct_lt_mpi_uint(const uint32_t x,
const uint32_t y)
{
uint32_t ret;
uint32_t cond;
/* Check if the most significant bits (MSB) of the operands are different.
*/
cond = (x ^ y);
/* If the MSB are the same then the difference x-y will be negative (and
* have its MSB set to 1 during conversion to unsigned) if and only if x<y.
*/
ret = (x - y) & ~cond;
/* If the MSB are different, then the operand with the MSB of 1 is the
* bigger. (That is if y has MSB of 1, then x<y is true and it is false if
* the MSB of y is 0.)
*/
ret |= y & cond;
ret = ret >> (BIL - 1);
return (unsigned) ret;
}
/****************************************************************************
* Name: esp32c3_bignum_int_div_int
*
* Description:
* Unsigned integer divide - double uint32_t dividend, u1/u0, and
* uint32_t divisor, d
*
* Input Parameters:
* X - The MPI context to grow
* nblimbs - The target number of limbs
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
static uint32_t esp32c3_bignum_int_div_int(uint32_t u1, uint32_t u0,
uint32_t d, uint32_t *r)
{
const uint32_t radix = (uint32_t) 1 << BIH;
const uint32_t uint_halfword_mask = ((uint32_t) 1 << BIH) - 1;
uint32_t d0;
uint32_t d1;
uint32_t q0;
uint32_t q1;
uint32_t rax;
uint32_t r0;
uint32_t quotient;
uint32_t u0_msw;
uint32_t u0_lsw;
size_t s;
/* Check for overflow */
if (0 == d || u1 >= d)
{
if (r != NULL)
{
*r = ~0;
}
return (~0);
}
/* Algorithm D, Section 4.3.1 - The Art of Computer Programming
* Vol. 2 - Seminumerical Algorithms, Knuth
*/
/* Normalize the divisor, d, and dividend, u0, u1
*/
s = esp32c3_bignum_clz(d);
d = d << s;
u1 = u1 << s;
u1 |= (u0 >> (BIL - s)) & (-(int32_t)s >> (BIL - 1));
u0 = u0 << s;
d1 = d >> BIH;
d0 = d & uint_halfword_mask;
u0_msw = u0 >> BIH;
u0_lsw = u0 & uint_halfword_mask;
/* Find the first quotient and remainder
*/
q1 = u1 / d1;
r0 = u1 - d1 * q1;
while (q1 >= radix || (q1 * d0 > radix * r0 + u0_msw))
{
q1 -= 1;
r0 += d1;
if (r0 >= radix)
{
break;
}
}
rax = (u1 * radix) + (u0_msw - q1 * d);
q0 = rax / d1;
r0 = rax - q0 * d1;
while (q0 >= radix || (q0 * d0 > radix * r0 + u0_lsw))
{
q0 -= 1;
r0 += d1;
if (r0 >= radix)
{
break;
}
}
if (r != NULL)
{
*r = (rax * radix + u0_lsw - q0 * d) >> s;
}
quotient = q1 * radix + q0;
return quotient;
}
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: esp32c3_mpi_init
*
* Description:
* Initialize an MPI context
*
* Input Parameters:
* X - The MPI context to initialize
*
* Returned Value:
* None.
*
****************************************************************************/
void esp32c3_mpi_init(struct esp32c3_mpi_s *X)
{
DEBUGASSERT(X != NULL);
X->s = 1;
X->n = 0;
X->p = NULL;
}
/****************************************************************************
* Name: esp32c3_mpi_free
*
* Description:
* Frees the components of an MPI context
*
* Input Parameters:
* X - The MPI context to be cleared
*
* Returned Value:
* None.
*
****************************************************************************/
void esp32c3_mpi_free(struct esp32c3_mpi_s *X)
{
if (X == NULL)
{
return ;
}
if (X->p != NULL)
{
esp32c3_mpi_zeroize(X->p, X->n);
free(X->p);
}
X->s = 1;
X->n = 0;
X->p = NULL;
}
/****************************************************************************
* Name: esp32c3_mpi_grow
*
* Description:
* Enlarge an MPI to the specified number of limbs
*
* Input Parameters:
* X - The MPI context to grow
* nblimbs - The target number of limbs
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
int esp32c3_mpi_grow(struct esp32c3_mpi_s *X, size_t nblimbs)
{
uint32_t *p;
DEBUGASSERT(X != NULL);
if (nblimbs > ESP32C3_MPI_MAX_LIMBS)
{
return ESP32C3_ERR_MPI_ALLOC_FAILED;
}
if (X->n < nblimbs)
{
if ((p = (uint32_t *)calloc(nblimbs, CIL)) == NULL)
{
return ESP32C3_ERR_MPI_ALLOC_FAILED;
}
if (X->p != NULL)
{
memcpy(p, X->p, X->n * CIL);
esp32c3_mpi_zeroize(X->p, X->n);
free(X->p);
}
X->n = nblimbs;
X->p = p;
}
return OK;
}
/****************************************************************************
* Name: esp32c3_mpi_shrink
*
* Description:
* Resizes an MPI downwards, keeping at least the specified number of limbs
*
* Input Parameters:
* X - The MPI context to shrink
* nblimbs - The minimum number of limbs
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
int esp32c3_mpi_shrink(struct esp32c3_mpi_s *X, size_t nblimbs)
{
uint32_t *p;
size_t i;
DEBUGASSERT(X != NULL);
if (nblimbs > ESP32C3_MPI_MAX_LIMBS)
{
return ESP32C3_ERR_MPI_ALLOC_FAILED;
}
/* Actually resize up if there are currently fewer than nblimbs limbs. */
if (X->n <= nblimbs)
{
return (esp32c3_mpi_grow(X, nblimbs));
}
/* After this point, then X->n > nblimbs and in particular X->n > 0. */
for (i = X->n - 1; i > 0; i--)
{
if (X->p[i] != 0)
{
break;
}
}
i++;
if (i < nblimbs)
{
i = nblimbs;
}
if ((p = (uint32_t *)calloc(i, CIL)) == NULL)
{
return ESP32C3_ERR_MPI_ALLOC_FAILED;
}
if (X->p != NULL)
{
memcpy(p, X->p, i * CIL);
esp32c3_mpi_zeroize(X->p, X->n);
free(X->p);
}
X->n = i;
X->p = p;
return OK;
}
/****************************************************************************
* Name: esp32c3_mpi_copy
*
* Description:
* Copy the contents of Y into X
*
* Input Parameters:
* X - The destination MPI
* Y - The source MPI
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
int esp32c3_mpi_copy(struct esp32c3_mpi_s *X,
const struct esp32c3_mpi_s *Y)
{
int ret = 0;
size_t i;
DEBUGASSERT(X != NULL);
DEBUGASSERT(Y != NULL);
if (X == Y)
{
return OK;
}
if (Y->n == 0)
{
esp32c3_mpi_free(X);
return OK;
}
for (i = Y->n - 1; i > 0; i--)
{
if (Y->p[i] != 0)
{
break;
}
}
i++;
X->s = Y->s;
if (X->n < i)
{
ESP32C3_MPI_CHK(esp32c3_mpi_grow(X, i), cleanup);
}
else
{
memset(X->p + i, 0, (X->n - i) * CIL);
}
memcpy(X->p, Y->p, i * CIL);
cleanup:
return ret;
}
/****************************************************************************
* Name: esp32c3_mpi_swap
*
* Description:
* Swap the contents of X and Y
*
* Input Parameters:
* X - The first MPI
* nblimbs - The second MPI
*
* Returned Value:
* None.
*
****************************************************************************/
void esp32c3_mpi_swap(struct esp32c3_mpi_s *X, struct esp32c3_mpi_s *Y)
{
struct esp32c3_mpi_s T;
DEBUGASSERT(X != NULL);
DEBUGASSERT(Y != NULL);
memcpy(&T, X, sizeof(struct esp32c3_mpi_s));
memcpy(X, Y, sizeof(struct esp32c3_mpi_s));
memcpy(Y, &T, sizeof(struct esp32c3_mpi_s));
}
/****************************************************************************
* Name: esp32c3_mpi_safe_cond_assign
*
* Description:
* Perform a safe conditional copy of MPI which doesn't
* reveal whether the condition was true or not.
*
* Input Parameters:
* X - The MPI to conditionally assign to
* Y - The MPI to be assigned from
* assign - The condition deciding whether perform the assignment or not
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
int esp32c3_mpi_safe_cond_assign(struct esp32c3_mpi_s *X,
const struct esp32c3_mpi_s *Y,
unsigned char assign)
{
int ret = 0;
size_t i;
DEBUGASSERT(X != NULL);
DEBUGASSERT(Y != NULL);
/* make sure assign is 0 or 1 in a time-constant manner */
assign = (assign | (unsigned char)-assign) >> 7;
ESP32C3_MPI_CHK(esp32c3_mpi_grow(X, Y->n), cleanup);
X->s = X->s * (1 - assign) + Y->s * assign;
mpi_safe_cond_assign(Y->n, X->p, Y->p, assign);
for (i = Y->n; i < X->n; i++)
{
X->p[i] *= (1 - assign);
}
cleanup:
return ret;
}
/****************************************************************************
* Name: esp32c3_mpi_safe_cond_swap
*
* Description:
* Perform a safe conditional swap which doesn't
* reveal whether the condition was true or not.
*
* Input Parameters:
* X - The first MPI
* Y - The second MPI
* swap - The condition deciding whether to perform the swap or not
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
int esp32c3_mpi_safe_cond_swap(struct esp32c3_mpi_s *X,
struct esp32c3_mpi_s *Y,
unsigned char swap)
{
int ret;
int s;
size_t i;
uint32_t tmp;
DEBUGASSERT(X != NULL);
DEBUGASSERT(Y != NULL);
if (X == Y)
{
return OK;
}
/* make sure swap is 0 or 1 in a time-constant manner */
swap = (swap | (unsigned char)-swap) >> 7;
ESP32C3_MPI_CHK(esp32c3_mpi_grow(X, Y->n), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_grow(Y, X->n), cleanup);
s = X->s;
X->s = X->s * (1 - swap) + Y->s * swap;
Y->s = Y->s * (1 - swap) + s * swap;
for (i = 0; i < X->n; i++)
{
tmp = X->p[i];
X->p[i] = X->p[i] * (1 - swap) + Y->p[i] * swap;
Y->p[i] = Y->p[i] * (1 - swap) + tmp * swap;
}
cleanup:
return ret;
}
/****************************************************************************
* Name: esp32c3_mpi_lset
*
* Description:
* Set value from integer
*
* Input Parameters:
* X - The MPI to set
* z - The value to use
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
int esp32c3_mpi_lset(struct esp32c3_mpi_s *X, int32_t z)
{
int ret;
DEBUGASSERT(X != NULL);
ESP32C3_MPI_CHK(esp32c3_mpi_grow(X, 1), cleanup);
memset(X->p, 0, X->n * CIL);
X->p[0] = (z < 0) ? -z : z;
X->s = (z < 0) ? -1 : 1;
cleanup:
return ret;
}
/****************************************************************************
* Name: esp32c3_mpi_get_bit
*
* Description:
* Get a specific bit from an MPI
*
* Input Parameters:
* X - The MPI context to query
* pos - Zero-based index of the bit to query
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
int esp32c3_mpi_get_bit(const struct esp32c3_mpi_s *X, size_t pos)
{
DEBUGASSERT(X != NULL);
if (X->n * BIL <= pos)
{
return OK;
}
return ((X->p[pos / BIL] >> (pos % BIL)) & 0x01);
}
/****************************************************************************
* Name: esp32c3_mpi_set_bit
*
* Description:
* Modify a specific bit in an MPI
*
* Input Parameters:
* X - The MPI context to modify
* pos - Zero-based index of the bit to modify
* val - The desired value of bit
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
int esp32c3_mpi_set_bit(struct esp32c3_mpi_s *X,
size_t pos, unsigned char val)
{
int ret = 0;
size_t off = pos / BIL;
size_t idx = pos % BIL;
DEBUGASSERT(X != NULL);
if (val != 0 && val != 1)
{
return ESP32C3_ERR_MPI_BAD_INPUT_DATA;
}
if (X->n * BIL <= pos)
{
if (val == 0)
{
return OK;
}
ESP32C3_MPI_CHK(esp32c3_mpi_grow(X, off + 1), cleanup);
}
X->p[off] &= ~((uint32_t) 0x01 << idx);
X->p[off] |= (uint32_t) val << idx;
cleanup:
return ret;
}
/****************************************************************************
* Name: esp32c3_mpi_lsb
*
* Description:
* Return the number of bits of value
*
* Input Parameters:
* X - The MPI context to query
*
* Returned Value:
* The number of bits of value.
*
****************************************************************************/
size_t esp32c3_mpi_lsb(const struct esp32c3_mpi_s *X)
{
size_t i;
size_t j;
size_t count = 0;
DEBUGASSERT(X != NULL);
for (i = 0; i < X->n; i++)
{
for (j = 0; j < BIL; j++, count++)
{
if (((X->p[i] >> j) & 1) != 0)
{
return (count);
}
}
}
return OK;
}
/****************************************************************************
* Name: esp32c3_mpi_bitlen
*
* Description:
* Return the number of bits up to and including the most
* significant bit of value
*
* Input Parameters:
* X - The MPI context to query
*
* Returned Value:
* The number of bits up and including the most significant bit of value.
*
****************************************************************************/
size_t esp32c3_mpi_bitlen(const struct esp32c3_mpi_s *X)
{
size_t i;
size_t j;
if (X->n == 0)
{
return OK;
}
for (i = X->n - 1; i > 0; i--)
{
if (X->p[i] != 0)
{
break;
}
}
j = BIL - esp32c3_bignum_clz(X->p[i]);
return ((i * BIL) + j);
}
/****************************************************************************
* Name: esp32c3_mpi_size
*
* Description:
* Return the total size of an MPI value in bytes
*
* Input Parameters:
* X - The MPI context to query
*
* Returned Value:
* The least number of bytes capable of storing the absolute value.
*
****************************************************************************/
size_t esp32c3_mpi_size(const struct esp32c3_mpi_s *X)
{
return ((esp32c3_mpi_bitlen(X) + 7) >> 3);
}
/****************************************************************************
* Name: esp32c3_mpi_read_string
*
* Description:
* Import from an ASCII string
*
* Input Parameters:
* X - The destination MPI
* radix - The numeric base of the input string
* s - Null-terminated string buffer
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
int esp32c3_mpi_read_string(struct esp32c3_mpi_s *X,
int radix, const char *s)
{
int ret;
size_t i;
size_t j;
size_t slen;
size_t n;
uint32_t d;
struct esp32c3_mpi_s T;
DEBUGASSERT(X != NULL);
DEBUGASSERT(s != NULL);
if (radix < 2 || radix > 16)
{
return ESP32C3_ERR_MPI_BAD_INPUT_DATA;
}
esp32c3_mpi_init(&T);
slen = strlen(s);
if (radix == 16)
{
if (slen > MPI_SIZE_T_MAX >> 2)
{
return ESP32C3_ERR_MPI_BAD_INPUT_DATA;
}
n = BITS_TO_LIMBS(slen << 2);
ESP32C3_MPI_CHK(esp32c3_mpi_grow(X, n), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_lset(X, 0), cleanup);
for (i = slen, j = 0; i > 0; i--, j++)
{
if (i == 1 && s[i - 1] == '-')
{
X->s = -1;
break;
}
ESP32C3_MPI_CHK(mpi_get_digit(&d, radix, s[i - 1]), cleanup);
X->p[j / (2 * CIL)] |= d << ((j % (2 * CIL)) << 2);
}
}
else
{
ESP32C3_MPI_CHK(esp32c3_mpi_lset(X, 0), cleanup);
for (i = 0; i < slen; i++)
{
if (i == 0 && s[i] == '-')
{
X->s = -1;
continue;
}
ESP32C3_MPI_CHK(mpi_get_digit(&d, radix, s[i]), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_mul_int(&T, X, radix), cleanup);
if (X->s == 1)
{
ESP32C3_MPI_CHK(esp32c3_mpi_add_int(X, &T, d), cleanup);
}
else
{
ESP32C3_MPI_CHK(esp32c3_mpi_sub_int(X, &T, d), cleanup);
}
}
}
cleanup:
esp32c3_mpi_free(&T);
return ret;
}
/****************************************************************************
* Name: esp32c3_mpi_write_string
*
* Description:
* Export an MPI to an ASCII string
*
* Input Parameters:
* X - The source MPI
* radix - The numeric base of the output string
* buf - The buffer to write the string to
* buflen - The available size in Bytes of buf
* olen - The address at which to store the length of the string written
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
int esp32c3_mpi_write_string(const struct esp32c3_mpi_s *X, int radix,
char *buf, size_t buflen, size_t *olen)
{
int ret = 0;
size_t n;
char *p;
struct esp32c3_mpi_s T;
DEBUGASSERT(X != NULL);
DEBUGASSERT(olen != NULL);
DEBUGASSERT(buflen == 0 || buf != NULL);
if (radix < 2 || radix > 16)
{
return ESP32C3_ERR_MPI_BAD_INPUT_DATA;
}
/* Number of bits necessary to present `n`. */
n = esp32c3_mpi_bitlen(X);
if (radix >= 4)
{
/* Number of 4-adic digits necessary to present
* `n`. If radix > 4, this might be a strict
* overapproximation of the number of
* radix-adic digits needed to present `n`.
*/
n >>= 1;
}
if (radix >= 16)
{
/* Number of hexadecimal digits necessary to
* present `n`.
*/
n >>= 1;
}
/* Terminating null byte */
n += 1;
/* Compensate for the divisions above, which round down `n`
* in case it's not even.
*/
n += 1;
/* Potential '-'-sign. */
n += 1;
/* Make n even to have enough space for hexadecimal writing,
* which always uses an even number of hex-digits.
*/
n += (n & 1);
if (buflen < n)
{
*olen = n;
return ESP32C3_ERR_MPI_BUFFER_TOO_SMALL;
}
p = buf;
esp32c3_mpi_init(&T);
if (X->s == -1)
{
*p++ = '-';
buflen--;
}
if (radix == 16)
{
int c;
size_t i;
size_t j;
size_t k;
for (i = X->n, k = 0; i > 0; i--)
{
for (j = CIL; j > 0; j--)
{
c = (X->p[i - 1] >> ((j - 1) << 3)) & 0xff;
if (c == 0 && k == 0 && (i + j) != 2)
{
continue;
}
*(p++) = "0123456789ABCDEF" [c / 16];
*(p++) = "0123456789ABCDEF" [c % 16];
k = 1;
}
}
}
else
{
ESP32C3_MPI_CHK(esp32c3_mpi_copy(&T, X), cleanup);
if (T.s == -1)
{
T.s = 1;
}
ESP32C3_MPI_CHK(mpi_write_hlp(&T, radix, &p, buflen), cleanup);
}
*p++ = '\0';
*olen = p - buf;
cleanup:
esp32c3_mpi_free(&T);
return ret;
}
/****************************************************************************
* Name: esp32c3_mpi_read_binary
*
* Description:
* Import an MPI from unsigned big endian binary data
*
* Input Parameters:
* X - The destination MPI
* buf - The input buffer
* buflen - The length of the input buffer
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
int esp32c3_mpi_read_binary(struct esp32c3_mpi_s *X,
const unsigned char *buf,
size_t buflen)
{
int ret;
size_t const limbs = CHARS_TO_LIMBS(buflen);
size_t const overhead = (limbs * CIL) - buflen;
unsigned char *XP;
DEBUGASSERT(X != NULL);
DEBUGASSERT(buflen == 0 || buf != NULL);
/* Ensure that target MPI has exactly the necessary number of limbs */
if (X->n != limbs)
{
esp32c3_mpi_free(X);
esp32c3_mpi_init(X);
ESP32C3_MPI_CHK(esp32c3_mpi_grow(X, limbs), cleanup);
}
ESP32C3_MPI_CHK(esp32c3_mpi_lset(X, 0), cleanup);
/* Avoid calling `memcpy` with NULL source argument,
* even if buflen is 0.
*/
if (buf != NULL)
{
XP = (unsigned char *) X->p;
memcpy(XP + overhead, buf, buflen);
mpi_bigendian_to_host(X->p, limbs);
}
cleanup:
return ret;
}
/****************************************************************************
* Name: esp32c3_mpi_write_binary
*
* Description:
* Export X into unsigned binary data, big endian
*
* Input Parameters:
* X - The source MPI
* buf - The output buffer
* buflen - The length of the output buffer
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
int esp32c3_mpi_write_binary(const struct esp32c3_mpi_s *X,
unsigned char *buf, size_t buflen)
{
size_t stored_bytes;
size_t bytes_to_copy;
unsigned char *p;
size_t i;
DEBUGASSERT(X != NULL);
DEBUGASSERT(buflen == 0 || buf != NULL);
stored_bytes = X->n * CIL;
if (stored_bytes < buflen)
{
/* There is enough space in the output buffer. Write initial
* null bytes and record the position at which to start
* writing the significant bytes. In this case, the execution
* trace of this function does not depend on the value of the
* number.
*/
bytes_to_copy = stored_bytes;
p = buf + buflen - stored_bytes;
memset(buf, 0, buflen - stored_bytes);
}
else
{
/* The output buffer is smaller than the allocated size of X.
* However X may fit if its leading bytes are zero.
*/
bytes_to_copy = buflen;
p = buf;
for (i = bytes_to_copy; i < stored_bytes; i++)
{
if (GET_BYTE(X, i) != 0)
{
return ESP32C3_ERR_MPI_BUFFER_TOO_SMALL;
}
}
}
for (i = 0; i < bytes_to_copy; i++)
{
p[bytes_to_copy - i - 1] = GET_BYTE(X, i);
}
return OK;
}
/****************************************************************************
* Name: esp32c3_mpi_shift_l
*
* Description:
* Perform a left-shift on an MPI: X <<= count
*
* Input Parameters:
* X - The MPI to shift
* count - The number of bits to shift by
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
int esp32c3_mpi_shift_l(struct esp32c3_mpi_s *X, size_t count)
{
int ret;
size_t i;
size_t v0;
size_t t1;
uint32_t r0 = 0;
uint32_t r1;
DEBUGASSERT(X != NULL);
v0 = count / (BIL);
t1 = count & (BIL - 1);
i = esp32c3_mpi_bitlen(X) + count;
if (X->n * BIL < i)
{
ESP32C3_MPI_CHK(esp32c3_mpi_grow(X, BITS_TO_LIMBS(i)), cleanup);
}
ret = 0;
/* shift by count / limb_size */
if (v0 > 0)
{
for (i = X->n; i > v0; i--)
X->p[i - 1] = X->p[i - v0 - 1];
for (; i > 0; i--)
X->p[i - 1] = 0;
}
/* shift by count % limb_size
*/
if (t1 > 0)
{
for (i = v0; i < X->n; i++)
{
r1 = X->p[i] >> (BIL - t1);
X->p[i] <<= t1;
X->p[i] |= r0;
r0 = r1;
}
}
cleanup:
return ret;
}
/****************************************************************************
* Name: esp32c3_mpi_shift_r
*
* Description:
* Perform a right-shift on an MPI: X >>= count
*
* Input Parameters:
* X - The MPI to shift
* count - The number of bits to shift by
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
int esp32c3_mpi_shift_r(struct esp32c3_mpi_s *X, size_t count)
{
size_t i;
size_t v0;
size_t v1;
uint32_t r0 = 0;
uint32_t r1;
DEBUGASSERT(X != NULL);
v0 = count / BIL;
v1 = count & (BIL - 1);
if (v0 > X->n || (v0 == X->n && v1 > 0))
{
return esp32c3_mpi_lset(X, 0);
}
/* shift by count / limb_size
*/
if (v0 > 0)
{
for (i = 0; i < X->n - v0; i++)
{
X->p[i] = X->p[i + v0];
}
for (; i < X->n; i++)
{
X->p[i] = 0;
}
}
/* shift by count % limb_size
*/
if (v1 > 0)
{
for (i = X->n; i > 0; i--)
{
r1 = X->p[i - 1] << (BIL - v1);
X->p[i - 1] >>= v1;
X->p[i - 1] |= r0;
r0 = r1;
}
}
return OK;
}
/****************************************************************************
* Name: esp32c3_mpi_cmp_abs
*
* Description:
* Compare the absolute values of two MPIs
*
* Input Parameters:
* X - The left-hand MPI
* Y - The right-hand MPI
*
* Returned Value:
* 1 if \p `|X|` is greater than \p `|Y|`.
* -1 if \p `|X|` is lesser than \p `|Y|`.
* 0 if \p `|X|` is equal to \p `|Y|`.
*
****************************************************************************/
int esp32c3_mpi_cmp_abs(const struct esp32c3_mpi_s *X,
const struct esp32c3_mpi_s *Y)
{
size_t i;
size_t j;
DEBUGASSERT(X != NULL);
DEBUGASSERT(Y != NULL);
for (i = X->n; i > 0; i--)
{
if (X->p[i - 1] != 0)
{
break;
}
}
for (j = Y->n; j > 0; j--)
{
if (Y->p[j - 1] != 0)
{
break;
}
}
if (i == 0 && j == 0)
{
return OK;
}
if (i > j)
{
return (1);
}
if (j > i)
{
return (-1);
}
for (; i > 0; i--)
{
if (X->p[i - 1] > Y->p[i - 1])
{
return (1);
}
if (X->p[i - 1] < Y->p[i - 1])
{
return (-1);
}
}
return OK;
}
/****************************************************************************
* Name: esp32c3_mpi_cmp_mpi
*
* Description:
* Compare two MPIs.
*
* Input Parameters:
* X - The left-hand MPI
* Y - The right-hand MPI
*
* Returned Value:
* 1 if \p `X` is greater than \p `Y`.
* -1 if \p `X` is lesser than \p `Y`.
* 0 if \p `X` is equal to \p `Y`.
*
****************************************************************************/
int esp32c3_mpi_cmp_mpi(const struct esp32c3_mpi_s *X,
const struct esp32c3_mpi_s *Y)
{
size_t i;
size_t j;
DEBUGASSERT(X != NULL);
DEBUGASSERT(Y != NULL);
for (i = X->n; i > 0; i--)
{
if (X->p[i - 1] != 0)
{
break;
}
}
for (j = Y->n; j > 0; j--)
{
if (Y->p[j - 1] != 0)
{
break;
}
}
if (i == 0 && j == 0)
{
return OK;
}
if (i > j)
{
return (X->s);
}
if (j > i)
{
return (-Y->s);
}
if (X->s > 0 && Y->s < 0)
{
return (1);
}
if (Y->s > 0 && X->s < 0)
{
return (-1);
}
for (; i > 0; i--)
{
if (X->p[i - 1] > Y->p[i - 1])
{
return (X->s);
}
if (X->p[i - 1] < Y->p[i - 1])
{
return (-X->s);
}
}
return OK;
}
/****************************************************************************
* Name: esp32c3_mpi_lt_mpi_ct
*
* Description:
* Check if an MPI is less than the other in constant time
*
* Input Parameters:
* X - The left-hand MPI
* Y - The right-hand MPI
* ret - The result of the comparison:
* 1 if \p X is less than \p Y.
* 0 if \p X is greater than or equal to \p Y.
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
int esp32c3_mpi_lt_mpi_ct(const struct esp32c3_mpi_s *X,
const struct esp32c3_mpi_s *Y,
unsigned *ret)
{
size_t i;
/* The value of any of these variables is either 0 or 1 at all times. */
unsigned cond;
unsigned done;
unsigned x_is_negative;
unsigned y_is_negative;
DEBUGASSERT(X != NULL);
DEBUGASSERT(Y != NULL);
DEBUGASSERT(ret != NULL);
if (X->n != Y->n)
{
return ESP32C3_ERR_MPI_BAD_INPUT_DATA;
}
/* Set sign_N to 1 if N >= 0, 0 if N < 0.
* We know that N->s == 1 if N >= 0 and N->s == -1 if N < 0.
*/
x_is_negative = (X->s & 2) >> 1;
y_is_negative = (Y->s & 2) >> 1;
/* If the signs are different, then the positive operand is the bigger.
* That is if X is negative (x_is_negative == 1), then X < Y is true and it
* is false if X is positive (x_is_negative == 0).
*/
cond = (x_is_negative ^ y_is_negative);
*ret = cond & x_is_negative;
/* This is a constant-time function. We might have the result, but we still
* need to go through the loop. Record if we have the result already.
*/
done = cond;
for (i = X->n; i > 0; i--)
{
/* If Y->p[i - 1] < X->p[i - 1] then X < Y is true if and only if both
* X and Y are negative.
*
* Again even if we can make a decision, we just mark the result and
* the fact that we are done and continue looping.
*/
cond = ct_lt_mpi_uint(Y->p[i - 1], X->p[i - 1]);
*ret |= cond & (1 - done) & x_is_negative;
done |= cond;
/* If X->p[i - 1] < Y->p[i - 1] then X < Y is true if and only if both
* X and Y are positive.
*
* Again even if we can make a decision, we just mark the result and
* the fact that we are done and continue looping.
*/
cond = ct_lt_mpi_uint(X->p[i - 1], Y->p[i - 1]);
*ret |= cond & (1 - done) & (1 - x_is_negative);
done |= cond;
}
return OK;
}
/****************************************************************************
* Name: esp32c3_mpi_cmp_int
*
* Description:
* Compare an MPI with an integer
*
* Input Parameters:
* X - The left-hand MPI
* z - The integer value to compare \p X to
*
* Returned Value:
* \c 1 if \p X is greater than \p z.
* \c -1 if \p X is lesser than \p z.
* \c 0 if \p X is equal to \p z.
*
****************************************************************************/
int esp32c3_mpi_cmp_int(const struct esp32c3_mpi_s *X, int32_t z)
{
struct esp32c3_mpi_s Y;
uint32_t p[1];
DEBUGASSERT(X != NULL);
*p = (z < 0) ? -z : z;
Y.s = (z < 0) ? -1 : 1;
Y.n = 1;
Y.p = p;
return (esp32c3_mpi_cmp_mpi(X, &Y));
}
/****************************************************************************
* Name: esp32c3_mpi_add_abs
*
* Description:
* Perform an unsigned addition of MPIs: X = |A| + |B|
*
* Input Parameters:
* X - The left-hand MPI
* z - The integer value to compare \p X to.
*
* Returned Value:
* \c 1 if \p X is greater than \p z.
* \c -1 if \p X is lesser than \p z.
* \c 0 if \p X is equal to \p z.
*
****************************************************************************/
int esp32c3_mpi_add_abs(struct esp32c3_mpi_s *X,
const struct esp32c3_mpi_s *A,
const struct esp32c3_mpi_s *B)
{
int ret;
size_t i;
size_t j;
uint32_t *o;
uint32_t *p;
uint32_t c;
uint32_t tmp;
DEBUGASSERT(X != NULL);
DEBUGASSERT(A != NULL);
DEBUGASSERT(B != NULL);
if (X == B)
{
const struct esp32c3_mpi_s *T = A; A = X; B = T;
}
if (X != A)
{
ESP32C3_MPI_CHK(esp32c3_mpi_copy(X, A), cleanup);
}
/* X should always be positive as a result of unsigned additions.
*/
X->s = 1;
for (j = B->n; j > 0; j--)
{
if (B->p[j - 1] != 0)
{
break;
}
}
ESP32C3_MPI_CHK(esp32c3_mpi_grow(X, j), cleanup);
o = B->p; p = X->p; c = 0;
/* tmp is used because it might happen that p == o
*/
for (i = 0; i < j; i++, o++, p++)
{
tmp = *o;
*p += c; c = (*p < c);
*p += tmp; c += (*p < tmp);
}
while (c != 0)
{
if (i >= X->n)
{
ESP32C3_MPI_CHK(esp32c3_mpi_grow(X, i + 1), cleanup);
p = X->p + i;
}
*p += c; c = (*p < c); i++; p++;
}
cleanup:
return ret;
}
/****************************************************************************
* Name: esp32c3_mpi_sub_abs
*
* Description:
* Perform an unsigned subtraction of MPIs: X = |A| - |B|
*
* Input Parameters:
* X - The destination MPI
* A - The minuend
* B - The subtrahend
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
int esp32c3_mpi_sub_abs(struct esp32c3_mpi_s *X,
const struct esp32c3_mpi_s *A,
const struct esp32c3_mpi_s *B)
{
struct esp32c3_mpi_s TB;
int ret;
size_t n;
uint32_t carry;
DEBUGASSERT(X != NULL);
DEBUGASSERT(A != NULL);
DEBUGASSERT(B != NULL);
esp32c3_mpi_init(&TB);
if (X == B)
{
ESP32C3_MPI_CHK(esp32c3_mpi_copy(&TB, B), cleanup);
B = &TB;
}
if (X != A)
{
ESP32C3_MPI_CHK(esp32c3_mpi_copy(X, A), cleanup);
}
/* X should always be positive as a result of unsigned subtractions. */
X->s = 1;
ret = 0;
for (n = B->n; n > 0; n--)
{
if (B->p[n - 1] != 0)
{
break;
}
}
carry = mpi_sub_hlp(n, X->p, B->p);
if (carry != 0)
{
/* Propagate the carry to the first nonzero limb of X. */
for (; n < X->n && X->p[n] == 0; n++)
{
--X->p[n];
}
/* If we ran out of space for the carry, it means that the result
* is negative.
*/
if (n == X->n)
{
ret = ESP32C3_ERR_MPI_NEGATIVE_VALUE;
goto cleanup;
}
--X->p[n];
}
cleanup:
esp32c3_mpi_free(&TB);
return ret;
}
/****************************************************************************
* Name: esp32c3_mpi_add_mpi
*
* Description:
* Perform a signed addition of MPIs: X = A + B
*
* Input Parameters:
* X - The destination MPI
* A - The first summand
* B - The second summand
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
int esp32c3_mpi_add_mpi(struct esp32c3_mpi_s *X,
const struct esp32c3_mpi_s *A,
const struct esp32c3_mpi_s *B)
{
int ret;
int s;
DEBUGASSERT(X != NULL);
DEBUGASSERT(A != NULL);
DEBUGASSERT(B != NULL);
s = A->s;
if (A->s * B->s < 0)
{
if (esp32c3_mpi_cmp_abs(A, B) >= 0)
{
ESP32C3_MPI_CHK(esp32c3_mpi_sub_abs(X, A, B), cleanup);
X->s = s;
}
else
{
ESP32C3_MPI_CHK(esp32c3_mpi_sub_abs(X, B, A), cleanup);
X->s = -s;
}
}
else
{
ESP32C3_MPI_CHK(esp32c3_mpi_add_abs(X, A, B), cleanup);
X->s = s;
}
cleanup:
return ret;
}
/****************************************************************************
* Name: esp32c3_mpi_sub_mpi
*
* Description:
* Perform a signed subtraction of MPIs: X = A - B
*
* Input Parameters:
* X - The destination MPI
* A - The minuend
* B - The subtrahend
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
int esp32c3_mpi_sub_mpi(struct esp32c3_mpi_s *X,
const struct esp32c3_mpi_s *A,
const struct esp32c3_mpi_s *B)
{
int ret;
int s;
DEBUGASSERT(X != NULL);
DEBUGASSERT(A != NULL);
DEBUGASSERT(B != NULL);
s = A->s;
if (A->s * B->s > 0)
{
if (esp32c3_mpi_cmp_abs(A, B) >= 0)
{
ESP32C3_MPI_CHK(esp32c3_mpi_sub_abs(X, A, B), cleanup);
X->s = s;
}
else
{
ESP32C3_MPI_CHK(esp32c3_mpi_sub_abs(X, B, A), cleanup);
X->s = -s;
}
}
else
{
ESP32C3_MPI_CHK(esp32c3_mpi_add_abs(X, A, B), cleanup);
X->s = s;
}
cleanup:
return ret;
}
/****************************************************************************
* Name: esp32c3_mpi_add_int
*
* Description:
* Perform a signed addition of an MPI and an integer: X = A + b
*
* Input Parameters:
* X - The destination MPI
* A - The first summand
* b - The second summand
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
int esp32c3_mpi_add_int(struct esp32c3_mpi_s *X,
const struct esp32c3_mpi_s *A,
int32_t b)
{
struct esp32c3_mpi_s _B;
uint32_t p[1];
DEBUGASSERT(X != NULL);
DEBUGASSERT(A != NULL);
p[0] = (b < 0) ? -b : b;
_B.s = (b < 0) ? -1 : 1;
_B.n = 1;
_B.p = p;
return (esp32c3_mpi_add_mpi(X, A, &_B));
}
/****************************************************************************
* Name: esp32c3_mpi_sub_int
*
* Description:
* Perform a signed subtraction of an MPI and an integer: X = A - b
*
* Input Parameters:
* X - The destination MPI
* A - The minuend
* b - The subtrahend
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
int esp32c3_mpi_sub_int(struct esp32c3_mpi_s *X,
const struct esp32c3_mpi_s *A,
int32_t b)
{
struct esp32c3_mpi_s _B;
uint32_t p[1];
DEBUGASSERT(X != NULL);
DEBUGASSERT(A != NULL);
p[0] = (b < 0) ? -b : b;
_B.s = (b < 0) ? -1 : 1;
_B.n = 1;
_B.p = p;
return (esp32c3_mpi_sub_mpi(X, A, &_B));
}
/****************************************************************************
* Name: esp32c3_mpi_mul_mpi
*
* Description:
* Perform a multiplication of two MPIs: Z = X * Y
*
* Input Parameters:
* Z - The destination MPI
* X - The first factor
* Y - The second factor
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
int esp32c3_mpi_mul_mpi(struct esp32c3_mpi_s *Z,
const struct esp32c3_mpi_s *X,
const struct esp32c3_mpi_s *Y)
{
int ret = 0;
size_t x_bits = esp32c3_mpi_bitlen(X);
size_t y_bits = esp32c3_mpi_bitlen(Y);
size_t x_words = bits_to_words(x_bits);
size_t y_words = bits_to_words(y_bits);
size_t z_words = bits_to_words(x_bits + y_bits);
size_t hw_words = MAX(x_words, y_words);
/* Short-circuit eval if either argument is 0 or 1.
* This is needed as the mpi modular division
* argument will sometimes call in here when one
* argument is too large for the hardware unit, but the other
* argument is zero or one.
*/
if (x_bits == 0 || y_bits == 0)
{
esp32c3_mpi_lset(Z, 0);
return 0;
}
if (x_bits == 1)
{
ret = esp32c3_mpi_copy(Z, Y);
Z->s *= X->s;
return ret;
}
if (y_bits == 1)
{
ret = esp32c3_mpi_copy(Z, X);
Z->s *= Y->s;
return ret;
}
/* Grow Z to result size early, avoid interim allocations */
ESP32C3_MPI_CHK(esp32c3_mpi_grow(Z, z_words), cleanup);
/* If factor is over 2048 bits, we can't use the standard
* hardware multiplier
*/
if (hw_words * 32 > SOC_RSA_MAX_BIT_LEN / 2)
{
if (z_words * 32 <= SOC_RSA_MAX_BIT_LEN)
{
return mpi_mult_mpi_failover_mod_mult(Z, X, Y, z_words);
}
else
{
/* Still too long for the hardware unit... */
if (y_words > x_words)
{
return mpi_mult_mpi_overlong(Z, X, Y, y_words, z_words);
}
else
{
return mpi_mult_mpi_overlong(Z, Y, X, x_words, z_words);
}
}
}
/* Otherwise, we can use the (faster) multiply hardware unit */
esp32c3_mpi_enable_hardware_hw_op();
esp32c3_mpi_mul_mpi_hw_op(X, Y, hw_words);
esp32c3_mpi_read_result_hw_op(Z, z_words);
esp32c3_mpi_disable_hardware_hw_op();
Z->s = X->s * Y->s;
cleanup:
return ret;
}
/****************************************************************************
* Name: esp32c3_mpi_mul_int
*
* Description:
* Perform a multiplication of an MPI with an unsigned integer: X = A * b
*
* Input Parameters:
* X - The destination MPI
* A - The first factor
* b - The second factor.
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
int esp32c3_mpi_mul_int(struct esp32c3_mpi_s *X,
const struct esp32c3_mpi_s *A,
uint32_t b)
{
struct esp32c3_mpi_s _B;
uint32_t p[1];
DEBUGASSERT(X != NULL);
DEBUGASSERT(A != NULL);
_B.s = 1;
_B.n = 1;
_B.p = p;
p[0] = b;
return (esp32c3_mpi_mul_mpi(X, A, &_B));
}
/****************************************************************************
* Name: esp32c3_mpi_div_mpi
*
* Description:
* Perform a division with remainder of two MPIs: A = Q * B + R
*
* Input Parameters:
* Q - The destination MPI for the quotient
* R - The destination MPI for the remainder value
* A - The dividend
* B - The divisor
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
int esp32c3_mpi_div_mpi(struct esp32c3_mpi_s *Q,
struct esp32c3_mpi_s *R,
const struct esp32c3_mpi_s *A,
const struct esp32c3_mpi_s *B)
{
int ret;
size_t i;
size_t n;
size_t t;
size_t k;
struct esp32c3_mpi_s X;
struct esp32c3_mpi_s Y;
struct esp32c3_mpi_s Z;
struct esp32c3_mpi_s T1;
struct esp32c3_mpi_s T2;
DEBUGASSERT(A != NULL);
DEBUGASSERT(B != NULL);
if (esp32c3_mpi_cmp_int(B, 0) == 0)
{
return ESP32C3_ERR_MPI_DIVISION_BY_ZERO;
}
esp32c3_mpi_init(&X);
esp32c3_mpi_init(&Y);
esp32c3_mpi_init(&Z);
esp32c3_mpi_init(&T1);
esp32c3_mpi_init(&T2);
if (esp32c3_mpi_cmp_abs(A, B) < 0)
{
if (Q != NULL)
{
ESP32C3_MPI_CHK(esp32c3_mpi_lset(Q, 0), cleanup);
}
if (R != NULL)
{
ESP32C3_MPI_CHK(esp32c3_mpi_copy(R, A), cleanup);
}
return OK;
}
ESP32C3_MPI_CHK(esp32c3_mpi_copy(&X, A), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_copy(&Y, B), cleanup);
X.s = Y.s = 1;
ESP32C3_MPI_CHK(esp32c3_mpi_grow(&Z, A->n + 2), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_lset(&Z, 0), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_grow(&T1, 2), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_grow(&T2, 3), cleanup);
k = esp32c3_mpi_bitlen(&Y) % BIL;
if (k < BIL - 1)
{
k = BIL - 1 - k;
ESP32C3_MPI_CHK(esp32c3_mpi_shift_l(&X, k), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_shift_l(&Y, k), cleanup);
}
else
{
k = 0;
}
n = X.n - 1;
t = Y.n - 1;
ESP32C3_MPI_CHK(esp32c3_mpi_shift_l(&Y, BIL * (n - t)), cleanup);
while (esp32c3_mpi_cmp_mpi(&X, &Y) >= 0)
{
Z.p[n - t]++;
ESP32C3_MPI_CHK(esp32c3_mpi_sub_mpi(&X, &X, &Y), cleanup);
}
ESP32C3_MPI_CHK(esp32c3_mpi_shift_r(&Y, BIL * (n - t)), cleanup);
for (i = n; i > t ; i--)
{
if (X.p[i] >= Y.p[t])
{
Z.p[i - t - 1] = ~0;
}
else
{
Z.p[i - t - 1] = esp32c3_bignum_int_div_int(X.p[i], X.p[i - 1],
Y.p[t], NULL);
}
Z.p[i - t - 1]++;
do
{
Z.p[i - t - 1]--;
ESP32C3_MPI_CHK(esp32c3_mpi_lset(&T1, 0), cleanup);
T1.p[0] = (t < 1) ? 0 : Y.p[t - 1];
T1.p[1] = Y.p[t];
ESP32C3_MPI_CHK(esp32c3_mpi_mul_int(&T1, &T1, Z.p[i - t - 1]),
cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_lset(&T2, 0), cleanup);
T2.p[0] = (i < 2) ? 0 : X.p[i - 2];
T2.p[1] = (i < 1) ? 0 : X.p[i - 1];
T2.p[2] = X.p[i];
}
while (esp32c3_mpi_cmp_mpi(&T1, &T2) > 0);
ESP32C3_MPI_CHK(esp32c3_mpi_mul_int(&T1, &Y, Z.p[i - t - 1]), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_shift_l(&T1, BIL * (i - t - 1)), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_sub_mpi(&X, &X, &T1), cleanup);
if (esp32c3_mpi_cmp_int(&X, 0) < 0)
{
ESP32C3_MPI_CHK(esp32c3_mpi_copy(&T1, &Y), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_shift_l(&T1, BIL * (i - t - 1)),
cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_add_mpi(&X, &X, &T1), cleanup);
Z.p[i - t - 1]--;
}
}
if (Q != NULL)
{
ESP32C3_MPI_CHK(esp32c3_mpi_copy(Q, &Z), cleanup);
Q->s = A->s * B->s;
}
if (R != NULL)
{
ESP32C3_MPI_CHK(esp32c3_mpi_shift_r(&X, k), cleanup);
X.s = A->s;
ESP32C3_MPI_CHK(esp32c3_mpi_copy(R, &X), cleanup);
if (esp32c3_mpi_cmp_int(R, 0) == 0)
{
R->s = 1;
}
}
cleanup:
esp32c3_mpi_free(&X); esp32c3_mpi_free(&Y); esp32c3_mpi_free(&Z);
esp32c3_mpi_free(&T1); esp32c3_mpi_free(&T2);
return ret;
}
/****************************************************************************
* Name: esp32c3_mpi_div_int
*
* Description:
* Perform a division with remainder of an MPI by an integer: A = Q * b + R
*
* Input Parameters:
* Q - The destination MPI for the quotient
* R - The destination MPI for the remainder value
* A - The dividend
* B - The divisor
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
int esp32c3_mpi_div_int(struct esp32c3_mpi_s *Q,
struct esp32c3_mpi_s *R,
const struct esp32c3_mpi_s *A,
int32_t b)
{
struct esp32c3_mpi_s _B;
uint32_t p[1];
DEBUGASSERT(A != NULL);
p[0] = (b < 0) ? -b : b;
_B.s = (b < 0) ? -1 : 1;
_B.n = 1;
_B.p = p;
return (esp32c3_mpi_div_mpi(Q, R, A, &_B));
}
/****************************************************************************
* Name: esp32c3_mpi_mod_mpi
*
* Description:
* erform a modular reduction. R = A mod B
*
* Input Parameters:
* R - The destination MPI for the residue value
* A - The MPI to compute the residue of
* B - The base of the modular reduction
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
int esp32c3_mpi_mod_mpi(struct esp32c3_mpi_s *R,
const struct esp32c3_mpi_s *A,
const struct esp32c3_mpi_s *B)
{
int ret;
DEBUGASSERT(R != NULL);
DEBUGASSERT(A != NULL);
DEBUGASSERT(B != NULL);
if (esp32c3_mpi_cmp_int(B, 0) < 0)
{
return ESP32C3_ERR_MPI_NEGATIVE_VALUE;
}
ESP32C3_MPI_CHK(esp32c3_mpi_div_mpi(NULL, R, A, B), cleanup);
while (esp32c3_mpi_cmp_int(R, 0) < 0)
{
ESP32C3_MPI_CHK(esp32c3_mpi_add_mpi(R, R, B), cleanup);
}
while (esp32c3_mpi_cmp_mpi(R, B) >= 0)
{
ESP32C3_MPI_CHK(esp32c3_mpi_sub_mpi(R, R, B), cleanup);
}
cleanup:
return ret;
}
/****************************************************************************
* Name: esp32c3_mpi_mod_int
*
* Description:
* Perform a modular reduction with respect to an integer: r = A mod b
*
* Input Parameters:
* r - The address at which to store the residue
* A - The MPI to compute the residue of
* b - The integer base of the modular reduction
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
int esp32c3_mpi_mod_int(uint32_t *r,
const struct esp32c3_mpi_s *A, int32_t b)
{
size_t i;
uint32_t x;
uint32_t y;
uint32_t z;
DEBUGASSERT(r != NULL);
DEBUGASSERT(A != NULL);
if (b == 0)
{
return ESP32C3_ERR_MPI_DIVISION_BY_ZERO;
}
if (b < 0)
{
return ESP32C3_ERR_MPI_NEGATIVE_VALUE;
}
/* handle trivial cases */
if (b == 1)
{
*r = 0;
return OK;
}
if (b == 2)
{
*r = A->p[0] & 1;
return OK;
}
/* general case */
for (i = A->n, y = 0; i > 0; i--)
{
x = A->p[i - 1];
y = (y << BIH) | (x >> BIH);
z = y / b;
y -= z * b;
x <<= BIH;
y = (y << BIH) | (x >> BIH);
z = y / b;
y -= z * b;
}
/* If A is negative, then the current y represents a negative value.
* Flipping it to the positive side.
*/
if (A->s < 0 && y != 0)
{
y = b - y;
}
*r = y;
return OK;
}
/****************************************************************************
* Name: esp32c3_mpi_exp_mod
*
* Description:
* Perform a sliding-window exponentiation: X = A^E mod N
*
* Input Parameters:
* X - The destination MPI
* A - The base of the exponentiation
* E - The exponent MPI
* N - The base for the modular reduction
* _RR - A helper MPI depending solely on \p N which can be used to
* speed-up multiple modular exponentiations for the same value
* of \p N.
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
int esp32c3_mpi_exp_mod(struct esp32c3_mpi_s *X,
const struct esp32c3_mpi_s *A,
const struct esp32c3_mpi_s *E,
const struct esp32c3_mpi_s *N,
struct esp32c3_mpi_s *_RR)
{
int ret;
size_t wbits;
size_t wsize;
size_t one = 1;
size_t i;
size_t j;
size_t nblimbs;
size_t bufsize;
size_t nbits;
uint32_t ei;
uint32_t mm;
uint32_t state;
struct esp32c3_mpi_s RR;
struct esp32c3_mpi_s T;
struct esp32c3_mpi_s W[1 << ESP32C3_MPI_WINDOW_SIZE];
struct esp32c3_mpi_s apos;
int neg;
DEBUGASSERT(X != NULL);
DEBUGASSERT(A != NULL);
DEBUGASSERT(E != NULL);
DEBUGASSERT(N != NULL);
if (esp32c3_mpi_cmp_int(N, 0) <= 0 || (N->p[0] & 1) == 0)
{
return ESP32C3_ERR_MPI_BAD_INPUT_DATA;
}
if (esp32c3_mpi_cmp_int(E, 0) < 0)
{
return ESP32C3_ERR_MPI_BAD_INPUT_DATA;
}
if (esp32c3_mpi_bitlen(E) > ESP32C3_MPI_MAX_BITS ||
esp32c3_mpi_bitlen(N) > ESP32C3_MPI_MAX_BITS)
{
return ESP32C3_ERR_MPI_BAD_INPUT_DATA;
}
/* Init temps and window size
*/
mpi_montg_init(&mm, N);
esp32c3_mpi_init(&RR); esp32c3_mpi_init(&T);
esp32c3_mpi_init(&apos);
memset(W, 0, sizeof(W));
i = esp32c3_mpi_bitlen(E);
wsize = (i > 671) ? 6 : (i > 239) ? 5 :
(i > 79) ? 4 : (i > 23) ? 3 : 1;
#if (ESP32C3_MPI_WINDOW_SIZE < 6)
if (wsize > ESP32C3_MPI_WINDOW_SIZE)
{
wsize = ESP32C3_MPI_WINDOW_SIZE;
}
#endif
j = N->n + 1;
ESP32C3_MPI_CHK(esp32c3_mpi_grow(X, j), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_grow(&W[1], j), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_grow(&T, j * 2), cleanup);
/* Compensate for negative A (and correct at the end) */
neg = (A->s == -1);
if (neg)
{
ESP32C3_MPI_CHK(esp32c3_mpi_copy(&apos, A), cleanup);
apos.s = 1;
A = '
}
/* If 1st call, pre-compute R^2 mod N */
if (_RR == NULL || _RR->p == NULL)
{
ESP32C3_MPI_CHK(esp32c3_mpi_lset(&RR, 1), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_shift_l(&RR, N->n * 2 * BIL), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_mod_mpi(&RR, &RR, N), cleanup);
if (_RR != NULL)
{
memcpy(_RR, &RR, sizeof(struct esp32c3_mpi_s));
}
}
else
{
memcpy(&RR, _RR, sizeof(struct esp32c3_mpi_s));
}
/* W[1] = A * R^2 * R^-1 mod N = A * R mod N */
if (esp32c3_mpi_cmp_mpi(A, N) >= 0)
{
ESP32C3_MPI_CHK(esp32c3_mpi_mod_mpi(&W[1], A, N), cleanup);
}
else
{
ESP32C3_MPI_CHK(esp32c3_mpi_copy(&W[1], A), cleanup);
}
mpi_montmul(&W[1], &RR, N, mm, &T);
/* X = R^2 * R^-1 mod N = R mod N */
ESP32C3_MPI_CHK(esp32c3_mpi_copy(X, &RR), cleanup);
mpi_montred(X, N, mm, &T);
if (wsize > 1)
{
/* W[1 << (wsize - 1)] = W[1] ^ (wsize - 1) */
j = one << (wsize - 1);
ESP32C3_MPI_CHK(esp32c3_mpi_grow(&W[j], N->n + 1), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_copy(&W[j], &W[1]), cleanup);
for (i = 0; i < wsize - 1; i++)
{
mpi_montmul(&W[j], &W[j], N, mm, &T);
}
/* W[i] = W[i - 1] * W[1] */
for (i = j + 1; i < (one << wsize); i++)
{
ESP32C3_MPI_CHK(esp32c3_mpi_grow(&W[i], N->n + 1), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_copy(&W[i], &W[i - 1]), cleanup);
mpi_montmul(&W[i], &W[1], N, mm, &T);
}
}
nblimbs = E->n;
bufsize = 0;
nbits = 0;
wbits = 0;
state = 0;
while (1)
{
if (bufsize == 0)
{
if (nblimbs == 0)
{
break;
}
nblimbs--;
bufsize = sizeof(uint32_t) << 3;
}
bufsize--;
ei = (E->p[nblimbs] >> bufsize) & 1;
/* skip leading 0s */
if (ei == 0 && state == 0)
{
continue;
}
if (ei == 0 && state == 1)
{
/* out of window, square X */
mpi_montmul(X, X, N, mm, &T);
continue;
}
/* add ei to current window */
state = 2;
nbits++;
wbits |= (ei << (wsize - nbits));
if (nbits == wsize)
{
/* X = X^wsize R^-1 mod N */
for (i = 0; i < wsize; i++)
{
mpi_montmul(X, X, N, mm, &T);
}
/* X = X * W[wbits] R^-1 mod N */
mpi_montmul(X, &W[wbits], N, mm, &T);
state--;
nbits = 0;
wbits = 0;
}
}
/* process the remaining bits */
for (i = 0; i < nbits; i++)
{
mpi_montmul(X, X, N, mm, &T);
wbits <<= 1;
if ((wbits & (one << wsize)) != 0)
mpi_montmul(X, &W[1], N, mm, &T);
}
/* X = A^E * R * R^-1 mod N = A^E mod N */
mpi_montred(X, N, mm, &T);
if (neg && E->n != 0 && (E->p[0] & 1) != 0)
{
X->s = -1;
ESP32C3_MPI_CHK(esp32c3_mpi_add_mpi(X, N, X), cleanup);
}
cleanup:
for (i = (one << (wsize - 1)); i < (one << wsize); i++)
{
esp32c3_mpi_free(&W[i]);
}
esp32c3_mpi_free(&W[1]);
esp32c3_mpi_free(&T);
esp32c3_mpi_free(&apos);
if (_RR == NULL || _RR->p == NULL)
{
esp32c3_mpi_free(&RR);
}
return ret;
}
/****************************************************************************
* Name: esp32c3_mpi_gcd
*
* Description:
* Compute the greatest common divisor: G = gcd(A, B)
*
* Input Parameters:
* G - The destination MPI
* A - The first operand
* B - The second operand
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
int esp32c3_mpi_gcd(struct esp32c3_mpi_s *G,
const struct esp32c3_mpi_s *A,
const struct esp32c3_mpi_s *B)
{
int ret;
size_t lz;
size_t lzt;
struct esp32c3_mpi_s TG;
struct esp32c3_mpi_s TA;
struct esp32c3_mpi_s TB;
DEBUGASSERT(G != NULL);
DEBUGASSERT(A != NULL);
DEBUGASSERT(B != NULL);
esp32c3_mpi_init(&TG); esp32c3_mpi_init(&TA); esp32c3_mpi_init(&TB);
ESP32C3_MPI_CHK(esp32c3_mpi_copy(&TA, A), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_copy(&TB, B), cleanup);
lz = esp32c3_mpi_lsb(&TA);
lzt = esp32c3_mpi_lsb(&TB);
if (lzt < lz)
{
lz = lzt;
}
ESP32C3_MPI_CHK(esp32c3_mpi_shift_r(&TA, lz), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_shift_r(&TB, lz), cleanup);
TA.s = TB.s = 1;
while (esp32c3_mpi_cmp_int(&TA, 0) != 0)
{
ESP32C3_MPI_CHK(esp32c3_mpi_shift_r(&TA, esp32c3_mpi_lsb(&TA)),
cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_shift_r(&TB, esp32c3_mpi_lsb(&TB)),
cleanup);
if (esp32c3_mpi_cmp_mpi(&TA, &TB) >= 0)
{
ESP32C3_MPI_CHK(esp32c3_mpi_sub_abs(&TA, &TA, &TB), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_shift_r(&TA, 1), cleanup);
}
else
{
ESP32C3_MPI_CHK(esp32c3_mpi_sub_abs(&TB, &TB, &TA), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_shift_r(&TB, 1), cleanup);
}
}
ESP32C3_MPI_CHK(esp32c3_mpi_shift_l(&TB, lz), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_copy(G, &TB), cleanup);
cleanup:
esp32c3_mpi_free(&TG); esp32c3_mpi_free(&TA); esp32c3_mpi_free(&TB);
return ret;
}
/****************************************************************************
* Name: esp32c3_mpi_fill_random
*
* Description:
* Fill an MPI with a number of random bytes
*
* Input Parameters:
* X - The destination MPI
* size - The number of random bytes to generate
* f_rng - The RNG function to use. This must not be \c NULL
* p_rng - The RNG parameter to be passed to \p f_rng
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
int esp32c3_mpi_fill_random(struct esp32c3_mpi_s *X, size_t size,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng)
{
int ret;
size_t const limbs = CHARS_TO_LIMBS(size);
size_t const overhead = (limbs * CIL) - size;
unsigned char *XP;
DEBUGASSERT(X != NULL);
DEBUGASSERT(f_rng != NULL);
/* Ensure that target MPI has exactly the necessary number of limbs */
if (X->n != limbs)
{
esp32c3_mpi_free(X);
esp32c3_mpi_init(X);
ESP32C3_MPI_CHK(esp32c3_mpi_grow(X, limbs), cleanup);
}
ESP32C3_MPI_CHK(esp32c3_mpi_lset(X, 0), cleanup);
XP = (unsigned char *) X->p;
ESP32C3_MPI_CHK(f_rng(p_rng, XP + overhead, size), cleanup);
mpi_bigendian_to_host(X->p, limbs);
cleanup:
return ret;
}
/****************************************************************************
* Name: esp32c3_mpi_inv_mod
*
* Description:
* Compute the modular inverse: X = A^-1 mod N
*
* Input Parameters:
* X - The destination MPI
* A - The MPI to calculate the modular inverse of
* N - The base of the modular inversion
*
* Returned Value:
* OK on success; Negated errno on failure.
*
****************************************************************************/
int esp32c3_mpi_inv_mod(struct esp32c3_mpi_s *X,
const struct esp32c3_mpi_s *A,
const struct esp32c3_mpi_s *N)
{
int ret;
struct esp32c3_mpi_s G;
struct esp32c3_mpi_s TA;
struct esp32c3_mpi_s TU;
struct esp32c3_mpi_s U1;
struct esp32c3_mpi_s U2;
struct esp32c3_mpi_s TB;
struct esp32c3_mpi_s TV;
struct esp32c3_mpi_s V1;
struct esp32c3_mpi_s V2;
DEBUGASSERT(X != NULL);
DEBUGASSERT(A != NULL);
DEBUGASSERT(N != NULL);
if (esp32c3_mpi_cmp_int(N, 1) <= 0)
{
return ESP32C3_ERR_MPI_BAD_INPUT_DATA;
}
esp32c3_mpi_init(&TA);
esp32c3_mpi_init(&TU);
esp32c3_mpi_init(&U1);
esp32c3_mpi_init(&U2);
esp32c3_mpi_init(&G);
esp32c3_mpi_init(&TB);
esp32c3_mpi_init(&TV);
esp32c3_mpi_init(&V1);
esp32c3_mpi_init(&V2);
ESP32C3_MPI_CHK(esp32c3_mpi_gcd(&G, A, N), cleanup);
if (esp32c3_mpi_cmp_int(&G, 1) != 0)
{
ret = ESP32C3_ERR_MPI_NOT_ACCEPTABLE;
goto cleanup;
}
ESP32C3_MPI_CHK(esp32c3_mpi_mod_mpi(&TA, A, N), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_copy(&TU, &TA), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_copy(&TB, N), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_copy(&TV, N), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_lset(&U1, 1), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_lset(&U2, 0), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_lset(&V1, 0), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_lset(&V2, 1), cleanup);
do
{
while ((TU.p[0] & 1) == 0)
{
ESP32C3_MPI_CHK(esp32c3_mpi_shift_r(&TU, 1), cleanup);
if ((U1.p[0] & 1) != 0 || (U2.p[0] & 1) != 0)
{
ESP32C3_MPI_CHK(esp32c3_mpi_add_mpi(&U1, &U1, &TB), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_sub_mpi(&U2, &U2, &TA), cleanup);
}
ESP32C3_MPI_CHK(esp32c3_mpi_shift_r(&U1, 1), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_shift_r(&U2, 1), cleanup);
}
while ((TV.p[0] & 1) == 0)
{
ESP32C3_MPI_CHK(esp32c3_mpi_shift_r(&TV, 1), cleanup);
if ((V1.p[0] & 1) != 0 || (V2.p[0] & 1) != 0)
{
ESP32C3_MPI_CHK(esp32c3_mpi_add_mpi(&V1, &V1, &TB), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_sub_mpi(&V2, &V2, &TA), cleanup);
}
ESP32C3_MPI_CHK(esp32c3_mpi_shift_r(&V1, 1), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_shift_r(&V2, 1), cleanup);
}
if (esp32c3_mpi_cmp_mpi(&TU, &TV) >= 0)
{
ESP32C3_MPI_CHK(esp32c3_mpi_sub_mpi(&TU, &TU, &TV), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_sub_mpi(&U1, &U1, &V1), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_sub_mpi(&U2, &U2, &V2), cleanup);
}
else
{
ESP32C3_MPI_CHK(esp32c3_mpi_sub_mpi(&TV, &TV, &TU), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_sub_mpi(&V1, &V1, &U1), cleanup);
ESP32C3_MPI_CHK(esp32c3_mpi_sub_mpi(&V2, &V2, &U2), cleanup);
}
}
while (esp32c3_mpi_cmp_int(&TU, 0) != 0);
while (esp32c3_mpi_cmp_int(&V1, 0) < 0)
{
ESP32C3_MPI_CHK(esp32c3_mpi_add_mpi(&V1, &V1, N), cleanup);
}
while (esp32c3_mpi_cmp_mpi(&V1, N) >= 0)
{
ESP32C3_MPI_CHK(esp32c3_mpi_sub_mpi(&V1, &V1, N), cleanup);
}
ESP32C3_MPI_CHK(esp32c3_mpi_copy(X, &V1), cleanup);
cleanup:
esp32c3_mpi_free(&TA);
esp32c3_mpi_free(&TU);
esp32c3_mpi_free(&U1);
esp32c3_mpi_free(&U2);
esp32c3_mpi_free(&G);
esp32c3_mpi_free(&TB);
esp32c3_mpi_free(&TV);
esp32c3_mpi_free(&V1);
esp32c3_mpi_free(&V2);
return ret;
}
#endif /* CONFIG_ESP32C3_BIGNUM_ACCELERATOR */
| 23.753163 | 78 | 0.488423 |
63330b9a3adee8ff4a3c433f34f8793c1aaa119e | 361 | swift | Swift | Sources/ChouTi/Operations/OperationQueue.swift | ChouTi-Lab/ChouTi | 083dd4df77e6f9b11fc78c7913e25bf2e6b96b6d | [
"MIT"
] | 9 | 2019-03-09T12:24:56.000Z | 2019-12-29T01:09:25.000Z | Sources/ChouTi/Operations/OperationQueue.swift | Ch0uti/ChouTi | 083dd4df77e6f9b11fc78c7913e25bf2e6b96b6d | [
"MIT"
] | 2 | 2018-11-16T19:20:25.000Z | 2019-12-24T04:19:59.000Z | Sources/ChouTi/Operations/OperationQueue.swift | ChouTi-Lab/ChouTi | 083dd4df77e6f9b11fc78c7913e25bf2e6b96b6d | [
"MIT"
] | 5 | 2018-11-12T05:30:26.000Z | 2020-01-03T15:19:18.000Z | //
// File.swift
//
//
// Created by Honghao Zhang on 2/12/20.
//
import Foundation
public extension OperationQueue {
convenience init(name: String) {
self.init()
self.name = name
}
func addTask(_ task: Operation) {
self.addOperation(task)
}
}
public extension Operation {
func add(to queue: OperationQueue) {
queue.addOperation(self)
}
}
| 13.884615 | 40 | 0.67867 |
74446a6af0dc30982416a705fcb538fbc6f87123 | 751 | sql | SQL | .erda/migrations/pipeline/20210528-runner-scheduler-base.sql | harverywxu/erda | 521b773a73424f514756b7bfcb515c594003b19a | [
"Apache-2.0"
] | 2,402 | 2021-03-08T00:47:58.000Z | 2022-03-31T15:15:54.000Z | .erda/migrations/pipeline/20210528-runner-scheduler-base.sql | harverywxu/erda | 521b773a73424f514756b7bfcb515c594003b19a | [
"Apache-2.0"
] | 3,828 | 2021-03-15T03:33:16.000Z | 2022-03-31T10:51:30.000Z | .erda/migrations/pipeline/20210528-runner-scheduler-base.sql | harverywxu/erda | 521b773a73424f514756b7bfcb515c594003b19a | [
"Apache-2.0"
] | 315 | 2021-03-05T09:53:24.000Z | 2022-03-31T09:48:35.000Z | -- MIGRATION_BASE
CREATE TABLE `dice_runner_tasks`
(
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`job_id` varchar(150) DEFAULT NULL,
`status` varchar(150) DEFAULT NULL,
`open_api_token` text,
`context_data_url` varchar(255) DEFAULT NULL,
`result_data_url` varchar(255) DEFAULT NULL,
`commands` text,
`targets` text,
`work_dir` varchar(255) DEFAULT NULL,
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `idx_status` (`status`),
KEY `idx_job_id` (`job_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='action runner 任务执行信息';
| 35.761905 | 71 | 0.591212 |
81d7ac9e8305661a3be844deb53e26064e3e995f | 1,319 | go | Go | build.go | bldy/build | d04b29acc6a742388d5696bbff0d7fca49117189 | [
"BSD-3-Clause"
] | 15 | 2016-11-03T10:49:09.000Z | 2020-02-20T06:34:32.000Z | build.go | bldy/build | d04b29acc6a742388d5696bbff0d7fca49117189 | [
"BSD-3-Clause"
] | 52 | 2016-11-02T16:47:54.000Z | 2019-03-31T15:38:36.000Z | build.go | bldy/build | d04b29acc6a742388d5696bbff0d7fca49117189 | [
"BSD-3-Clause"
] | 2 | 2016-11-06T20:42:13.000Z | 2017-01-03T21:39:20.000Z | // Copyright 2015-2016 Sevki <s@sevki.org>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package build defines build target and build context structures
package build
import (
"bldy.build/build/executor"
"bldy.build/build/label"
"bldy.build/build/workspace"
)
//go:generate stringer -type=Status
// Status represents a nodes status.
type Status int
const (
// Success is success
Success Status = iota
// Fail is a failed job
Fail
// Pending is a pending job
Pending
// Started is a started job
Started
// Fatal is a fatal crash
Fatal
// Warning is a job that has warnings
Warning
// Building is a job that's being built
Building
)
var (
HostPlatform = label.Label("@bldy//platforms:host")
DefaultPlatform = HostPlatform
)
// Rule defines the interface that rules must implement for becoming build targets.
type Rule interface {
Name() string
Dependencies() []label.Label
Outputs() []string
Hash() []byte
Build(*executor.Executor) error
Platform() label.Label
Workspace() workspace.Workspace
}
// VM seperate the parsing and evauluating targets logic from rest of bldy
// so we can implement and use new grammars like jsonnet or go it self.
type VM interface {
GetTarget(label.Label) (Rule, error)
}
| 23.553571 | 83 | 0.73768 |
5757cd01671a6c2ebd37f245e66a465337fe4227 | 7,721 | h | C | aws-cpp-sdk-lookoutequipment/include/aws/lookoutequipment/model/IngestionS3InputConfiguration.h | Nexuscompute/aws-sdk-cpp | e7ef485e46e6962c9e084b8c9b104c1bfcceaf26 | [
"Apache-2.0"
] | 1 | 2022-01-05T18:20:03.000Z | 2022-01-05T18:20:03.000Z | aws-cpp-sdk-lookoutequipment/include/aws/lookoutequipment/model/IngestionS3InputConfiguration.h | Nexuscompute/aws-sdk-cpp | e7ef485e46e6962c9e084b8c9b104c1bfcceaf26 | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-lookoutequipment/include/aws/lookoutequipment/model/IngestionS3InputConfiguration.h | Nexuscompute/aws-sdk-cpp | e7ef485e46e6962c9e084b8c9b104c1bfcceaf26 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/lookoutequipment/LookoutEquipment_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace LookoutEquipment
{
namespace Model
{
/**
* <p> Specifies S3 configuration information for the input data for the data
* ingestion job. </p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/lookoutequipment-2020-12-15/IngestionS3InputConfiguration">AWS
* API Reference</a></p>
*/
class AWS_LOOKOUTEQUIPMENT_API IngestionS3InputConfiguration
{
public:
IngestionS3InputConfiguration();
IngestionS3InputConfiguration(Aws::Utils::Json::JsonView jsonValue);
IngestionS3InputConfiguration& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The name of the S3 bucket used for the input data for the data ingestion.
* </p>
*/
inline const Aws::String& GetBucket() const{ return m_bucket; }
/**
* <p>The name of the S3 bucket used for the input data for the data ingestion.
* </p>
*/
inline bool BucketHasBeenSet() const { return m_bucketHasBeenSet; }
/**
* <p>The name of the S3 bucket used for the input data for the data ingestion.
* </p>
*/
inline void SetBucket(const Aws::String& value) { m_bucketHasBeenSet = true; m_bucket = value; }
/**
* <p>The name of the S3 bucket used for the input data for the data ingestion.
* </p>
*/
inline void SetBucket(Aws::String&& value) { m_bucketHasBeenSet = true; m_bucket = std::move(value); }
/**
* <p>The name of the S3 bucket used for the input data for the data ingestion.
* </p>
*/
inline void SetBucket(const char* value) { m_bucketHasBeenSet = true; m_bucket.assign(value); }
/**
* <p>The name of the S3 bucket used for the input data for the data ingestion.
* </p>
*/
inline IngestionS3InputConfiguration& WithBucket(const Aws::String& value) { SetBucket(value); return *this;}
/**
* <p>The name of the S3 bucket used for the input data for the data ingestion.
* </p>
*/
inline IngestionS3InputConfiguration& WithBucket(Aws::String&& value) { SetBucket(std::move(value)); return *this;}
/**
* <p>The name of the S3 bucket used for the input data for the data ingestion.
* </p>
*/
inline IngestionS3InputConfiguration& WithBucket(const char* value) { SetBucket(value); return *this;}
/**
* <p>The prefix for the S3 location being used for the input data for the data
* ingestion. </p>
*/
inline const Aws::String& GetPrefix() const{ return m_prefix; }
/**
* <p>The prefix for the S3 location being used for the input data for the data
* ingestion. </p>
*/
inline bool PrefixHasBeenSet() const { return m_prefixHasBeenSet; }
/**
* <p>The prefix for the S3 location being used for the input data for the data
* ingestion. </p>
*/
inline void SetPrefix(const Aws::String& value) { m_prefixHasBeenSet = true; m_prefix = value; }
/**
* <p>The prefix for the S3 location being used for the input data for the data
* ingestion. </p>
*/
inline void SetPrefix(Aws::String&& value) { m_prefixHasBeenSet = true; m_prefix = std::move(value); }
/**
* <p>The prefix for the S3 location being used for the input data for the data
* ingestion. </p>
*/
inline void SetPrefix(const char* value) { m_prefixHasBeenSet = true; m_prefix.assign(value); }
/**
* <p>The prefix for the S3 location being used for the input data for the data
* ingestion. </p>
*/
inline IngestionS3InputConfiguration& WithPrefix(const Aws::String& value) { SetPrefix(value); return *this;}
/**
* <p>The prefix for the S3 location being used for the input data for the data
* ingestion. </p>
*/
inline IngestionS3InputConfiguration& WithPrefix(Aws::String&& value) { SetPrefix(std::move(value)); return *this;}
/**
* <p>The prefix for the S3 location being used for the input data for the data
* ingestion. </p>
*/
inline IngestionS3InputConfiguration& WithPrefix(const char* value) { SetPrefix(value); return *this;}
/**
* <p> Pattern for matching the Amazon S3 files which will be used for ingestion.
* If no KeyPattern is provided, we will use the default hierarchy file structure,
* which is same as KeyPattern {prefix}/{component_name}/ * </p>
*/
inline const Aws::String& GetKeyPattern() const{ return m_keyPattern; }
/**
* <p> Pattern for matching the Amazon S3 files which will be used for ingestion.
* If no KeyPattern is provided, we will use the default hierarchy file structure,
* which is same as KeyPattern {prefix}/{component_name}/ * </p>
*/
inline bool KeyPatternHasBeenSet() const { return m_keyPatternHasBeenSet; }
/**
* <p> Pattern for matching the Amazon S3 files which will be used for ingestion.
* If no KeyPattern is provided, we will use the default hierarchy file structure,
* which is same as KeyPattern {prefix}/{component_name}/ * </p>
*/
inline void SetKeyPattern(const Aws::String& value) { m_keyPatternHasBeenSet = true; m_keyPattern = value; }
/**
* <p> Pattern for matching the Amazon S3 files which will be used for ingestion.
* If no KeyPattern is provided, we will use the default hierarchy file structure,
* which is same as KeyPattern {prefix}/{component_name}/ * </p>
*/
inline void SetKeyPattern(Aws::String&& value) { m_keyPatternHasBeenSet = true; m_keyPattern = std::move(value); }
/**
* <p> Pattern for matching the Amazon S3 files which will be used for ingestion.
* If no KeyPattern is provided, we will use the default hierarchy file structure,
* which is same as KeyPattern {prefix}/{component_name}/ * </p>
*/
inline void SetKeyPattern(const char* value) { m_keyPatternHasBeenSet = true; m_keyPattern.assign(value); }
/**
* <p> Pattern for matching the Amazon S3 files which will be used for ingestion.
* If no KeyPattern is provided, we will use the default hierarchy file structure,
* which is same as KeyPattern {prefix}/{component_name}/ * </p>
*/
inline IngestionS3InputConfiguration& WithKeyPattern(const Aws::String& value) { SetKeyPattern(value); return *this;}
/**
* <p> Pattern for matching the Amazon S3 files which will be used for ingestion.
* If no KeyPattern is provided, we will use the default hierarchy file structure,
* which is same as KeyPattern {prefix}/{component_name}/ * </p>
*/
inline IngestionS3InputConfiguration& WithKeyPattern(Aws::String&& value) { SetKeyPattern(std::move(value)); return *this;}
/**
* <p> Pattern for matching the Amazon S3 files which will be used for ingestion.
* If no KeyPattern is provided, we will use the default hierarchy file structure,
* which is same as KeyPattern {prefix}/{component_name}/ * </p>
*/
inline IngestionS3InputConfiguration& WithKeyPattern(const char* value) { SetKeyPattern(value); return *this;}
private:
Aws::String m_bucket;
bool m_bucketHasBeenSet;
Aws::String m_prefix;
bool m_prefixHasBeenSet;
Aws::String m_keyPattern;
bool m_keyPatternHasBeenSet;
};
} // namespace Model
} // namespace LookoutEquipment
} // namespace Aws
| 36.766667 | 127 | 0.672581 |
c309e261011eac217cb60e05f1d0ae9a2cf4e6d1 | 2,143 | rs | Rust | crates/eosio_rpc/src/chain/get_table_rows.rs | datudou/rust-eos | 636073c21d2ab21af3f853fd09c907a3564a5a4e | [
"Apache-2.0",
"MIT"
] | null | null | null | crates/eosio_rpc/src/chain/get_table_rows.rs | datudou/rust-eos | 636073c21d2ab21af3f853fd09c907a3564a5a4e | [
"Apache-2.0",
"MIT"
] | null | null | null | crates/eosio_rpc/src/chain/get_table_rows.rs | datudou/rust-eos | 636073c21d2ab21af3f853fd09c907a3564a5a4e | [
"Apache-2.0",
"MIT"
] | 1 | 2020-12-21T02:03:38.000Z | 2020-12-21T02:03:38.000Z | use crate::{Client, Error};
use eosio::{AccountName, ScopeName, TableName};
use serde::{Deserialize, Serialize};
use std::marker::PhantomData;
#[derive(Serialize)]
pub struct GetTableRowsBuilder<Row> {
#[serde(skip)]
_data: PhantomData<Row>,
scope: ScopeName,
code: AccountName,
table: TableName,
json: bool,
#[serde(skip_serializing_if = "Option::is_none")]
lower_bound: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
upper_bound: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
limit: Option<u32>,
}
impl<Row> crate::builder::Builder for GetTableRowsBuilder<Row>
where
Row: for<'a> Deserialize<'a> + 'static,
{
const PATH: &'static str = "/v1/chain/get_table_rows";
type Output = GetTableRows<Row>;
}
impl<Row> GetTableRowsBuilder<Row> {
pub fn json(&mut self, value: bool) -> &mut Self {
self.json = value;
self
}
pub fn lower_bound<V: Into<u64>>(&mut self, value: V) -> &mut Self {
self.lower_bound = Some(value.into());
self
}
pub fn no_lower_bound(&mut self) -> &mut Self {
self.lower_bound = None;
self
}
pub fn upper_bound<V: Into<u64>>(&mut self, value: V) -> &mut Self {
self.upper_bound = Some(value.into());
self
}
pub fn no_upper_bound(&mut self) -> &mut Self {
self.upper_bound = None;
self
}
pub fn limit(&mut self, value: u32) -> &mut Self {
self.limit = Some(value);
self
}
pub fn no_limit(&mut self) -> &mut Self {
self.limit = None;
self
}
}
pub fn get_table_rows<Row>(
code: AccountName,
scope: ScopeName,
table: TableName,
) -> GetTableRowsBuilder<Row>
where
Row: for<'a> Deserialize<'a> + 'static,
{
GetTableRowsBuilder {
_data: PhantomData,
code,
scope,
table,
json: true,
lower_bound: None,
upper_bound: None,
limit: None,
}
}
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct GetTableRows<Row> {
pub rows: Vec<Row>,
pub more: bool,
}
| 23.293478 | 72 | 0.600093 |
19e949377f39913b5ec0ae3a29c9efa1a3342bf3 | 32 | lua | Lua | Themes/Til Death/BGAnimations/_mouseselect.lua | kangalioo/etterna | 11630aa1c23bad46b2da993602b06f8b659a4961 | [
"MIT"
] | 1 | 2021-05-06T09:07:47.000Z | 2021-05-06T09:07:47.000Z | Themes/Til Death/BGAnimations/_mouseselect.lua | kangalioo/etterna | 11630aa1c23bad46b2da993602b06f8b659a4961 | [
"MIT"
] | null | null | null | Themes/Til Death/BGAnimations/_mouseselect.lua | kangalioo/etterna | 11630aa1c23bad46b2da993602b06f8b659a4961 | [
"MIT"
] | null | null | null | -- merged into mousewheelscroll
| 16 | 31 | 0.8125 |
2d812a57f9359fddd77c06c2ee327f55fdd7305e | 936 | html | HTML | ASP.NET/ASPNET Application/wwwroot/App/Views/UniquePages/Menu/MainMenuView.html | marcvil/WPF-App | c27b2890f8c144f0faccf55a43097e5162e0f2d0 | [
"MIT"
] | null | null | null | ASP.NET/ASPNET Application/wwwroot/App/Views/UniquePages/Menu/MainMenuView.html | marcvil/WPF-App | c27b2890f8c144f0faccf55a43097e5162e0f2d0 | [
"MIT"
] | null | null | null | ASP.NET/ASPNET Application/wwwroot/App/Views/UniquePages/Menu/MainMenuView.html | marcvil/WPF-App | c27b2890f8c144f0faccf55a43097e5162e0f2d0 | [
"MIT"
] | null | null | null |
<div class="Main">
<!-- Intro -->
<section id="intro" class="wrapper style1 fullscreen fade-up" style="background-color:brown">
<div class="inner">
<h1 style="color:azure">Welcome to ITAcademy!</h1>
<p style="color:azure">
IT Academy de Cibernàrium t'ofereix cursos gratuïts de programació web (back-end Java, front-end, .NET i Android).
</p>
<iframe width="720" height="480" align="middle"
src="https://www.youtube.com/embed/watch?v=2B47sIS2z4Y&list=PL26B5539E3ADCB05A&index=24">
</iframe>
<ul class="actions">
<li><a href="https://www.youtube.com/watch?v=WkH6sP_6Ryw&list=PL26B5539E3ADCB05A&index=1" target="_blank" class="button">Examples of Success!</a></li>
</ul>
</div>
</section>
</div>
| 34.666667 | 170 | 0.535256 |
040024577472b83deb5852c2cb67057d9fdc656d | 2,193 | js | JavaScript | src/components/AuthorMessage.js | jumpalottahigh/blog.georgiyanev.me | 1d101fa7aefbb05f24428c5cafd0526b39f327a7 | [
"MIT"
] | 21 | 2017-11-22T07:45:16.000Z | 2022-02-10T15:56:08.000Z | src/components/AuthorMessage.js | jumpalottahigh/blog.georgi-yanev.com | 99e5bd6e18348fcb4c3365e4af622b68db7ebbee | [
"MIT"
] | 33 | 2017-10-22T10:54:21.000Z | 2021-12-28T09:43:30.000Z | src/components/AuthorMessage.js | jumpalottahigh/blog.georgiyanev.me | 1d101fa7aefbb05f24428c5cafd0526b39f327a7 | [
"MIT"
] | 6 | 2018-10-11T15:39:25.000Z | 2019-10-08T17:42:17.000Z | import React from 'react'
import { graphql, useStaticQuery } from 'gatsby'
import Img from 'gatsby-image'
import svgReact from '../../static/react.svg'
import svgJS from '../../static/javascript.svg'
const AuthorMessage = ({ type = 'fpv', style }) => {
const authorImage = useStaticQuery(graphql`
{
georgiFpv: file(relativePath: { regex: "/^home/georgi-face.png/" }) {
name
childImageSharp {
fluid(maxWidth: 100, quality: 75) {
...GatsbyImageSharpFluid
}
}
}
georgi: file(relativePath: { regex: "/^home/georgi-face-3.jpg/" }) {
name
childImageSharp {
fluid(maxWidth: 100, quality: 75) {
...GatsbyImageSharpFluid
}
}
}
}
`)
return (
<div
style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
marginBottom: '1rem',
...style,
}}
>
<div style={{ width: '20%' }}>
<div style={{ maxWidth: '100px' }}>
<Img
fluid={
type === 'fpv'
? authorImage.georgiFpv.childImageSharp.fluid
: authorImage.georgi.childImageSharp.fluid
}
alt="Georgi Yanev portrait"
style={{ borderRadius: '50%' }}
/>
</div>
</div>
{type === 'fpv' ? (
<h2
style={{
fontSize: '1.4rem',
width: '80%',
margin: 0,
paddingLeft: '1rem',
}}
>
Hi, I'm Georgi and I love all things FPV racing drones.
</h2>
) : (
<h2
style={{
fontSize: '1.4rem',
width: '80%',
margin: 0,
paddingLeft: '1rem',
}}
>
Hi, I'm Georgi and I build things on the web with{` `}
<img className="framework-logo" src={svgJS} alt="JavaScript logo" />
{` `}
JavaScript and{` `}
<img className="framework-logo" src={svgReact} alt="React.js logo" />
{` `}
React
</h2>
)}
</div>
)
}
export default AuthorMessage
| 24.920455 | 79 | 0.468764 |
e788846d47fb067c9aee6172914d1dc99afb5108 | 2,304 | js | JavaScript | build/es6-amd/node_modules/@lrnwebcomponents/a11y-collapse/lib/a11y-collapse-group.js | profmikegreene/HAXcms | 50390c19bc91e49f05038fccb1104707153058f5 | [
"Apache-2.0"
] | 1 | 2019-09-04T20:40:47.000Z | 2019-09-04T20:40:47.000Z | build/es6-amd/node_modules/@lrnwebcomponents/a11y-collapse/lib/a11y-collapse-group.js | profmikegreene/HAXcms | 50390c19bc91e49f05038fccb1104707153058f5 | [
"Apache-2.0"
] | null | null | null | build/es6-amd/node_modules/@lrnwebcomponents/a11y-collapse/lib/a11y-collapse-group.js | profmikegreene/HAXcms | 50390c19bc91e49f05038fccb1104707153058f5 | [
"Apache-2.0"
] | null | null | null | define(["exports","../../../@polymer/polymer/polymer-element.js","../../../@polymer/polymer/lib/utils/render-status.js","../a11y-collapse.js"],function(_exports,_polymerElement,_renderStatus,_a11yCollapse){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.A11yCollapseGroup=void 0;class A11yCollapseGroup extends _polymerElement.PolymerElement{static get tag(){return"a11y-collapse-group"}static get template(){return _polymerElement.html`
<style>
:host {
display: block;
margin: var(--a11y-collapse-group-margin, 15px 0);
--a11y-collapse-margin: 15px;
@apply --a11y-collapse-group;
}
:host #heading {
font-weight: bold;
@apply --a11y-collapse-group-heading;
}
:host .wrapper {
border-radius: 0;
--a11y-collapse-margin: 0;
--a11y-collapse-border-between: none;
}
</style>
<div class="wrapper"><slot></slot></div>
`}static get properties(){return{globalOptions:{type:Object,value:{}},radio:{type:Boolean,value:!1},__items:{type:Array,value:[]}}}constructor(){super(),this.addEventListener("a11y-collapse-attached",function(e){this._attachItem(e.detail)}),this.addEventListener("a11y-collapse-detached",function(e){this._detachItem(e.detail)}),this.addEventListener("a11y-collapse-click",function(e){this.radioToggle(e.detail)})}_attachItem(item){for(let key in this.globalOptions)this.globalOptions.hasOwnProperty(key)&&item._overrideProp(key,this.globalOptions[key]);this.push("__items",item),this.notifyPath("__items")}_detachItem(item){if(this.__items&&item)for(let i=0;i<this.__items.length;i++)this.__items[i]===item&&this.splice("__items",i,1)}radioToggle(item){if(this.radio&&item.expanded)for(let i=0;i<this.__items.length;i++)this.__items[i]!==item&&this.__items[i].toggle(!1)}disconnectedCallback(){this.removeEventListener("a11y-collapse-click",function(e){this.radioToggle(e.detail)}),this.removeEventListener("a11y-collapse-attached",function(e){this.push("__items",e.detail)}),this.removeEventListener("a11y-collapse-detached",function(e){this._detachItem(e.detail)}),super.disconnectedCallback()}}_exports.A11yCollapseGroup=A11yCollapseGroup,window.customElements.define(A11yCollapseGroup.tag,A11yCollapseGroup)}); | 109.714286 | 1,319 | 0.720486 |
70a37a38b1480a8713090e2ca0213ca1f584cd4f | 385 | h | C | Projects/cube_demo/SpheresIntersecting.h | AlexLamson/ledcube | 66ae1e468bcfe0f9930e22773504ca474c987b52 | [
"MIT"
] | 4 | 2019-01-26T22:45:40.000Z | 2020-10-17T21:14:02.000Z | Projects/cube_demo/SpheresIntersecting.h | AlexLamson/ledcube | 66ae1e468bcfe0f9930e22773504ca474c987b52 | [
"MIT"
] | null | null | null | Projects/cube_demo/SpheresIntersecting.h | AlexLamson/ledcube | 66ae1e468bcfe0f9930e22773504ca474c987b52 | [
"MIT"
] | 2 | 2019-01-26T22:46:04.000Z | 2019-06-21T07:02:40.000Z | /*
* SpheresIntersecting.h
*
* Created on: Nov 2, 2018
* Author: raffc
*/
#ifndef SPHERESINTERSECTING_H_
#define SPHERESINTERSECTING_H_
#include "Demo.h"
class SpheresIntersecting: public Demo {
private:
float angle = 0;
const float angleIncremement = 0.05;
public:
SpheresIntersecting();
void initialize();
void tick();
};
#endif /* SPHERESINTERSECTING_H_ */
| 16.041667 | 40 | 0.703896 |
6e87a0a5ef048c85aecf1c878c2a0f8fa313e67b | 1,255 | dart | Dart | lema_predial/lib/data/file_names.dart | joaomarcelors/appLemaPredial | 0330de5e010960179c93555f01694a2b04659a51 | [
"MIT"
] | null | null | null | lema_predial/lib/data/file_names.dart | joaomarcelors/appLemaPredial | 0330de5e010960179c93555f01694a2b04659a51 | [
"MIT"
] | null | null | null | lema_predial/lib/data/file_names.dart | joaomarcelors/appLemaPredial | 0330de5e010960179c93555f01694a2b04659a51 | [
"MIT"
] | null | null | null | final NAMES_BCIS = [
{
'title': 'Bomba Cisterna A',
'API': 'get_bcis_a.php',
'data': 'bcis_data',
'hora': 'bcis_hora',
'status': 'bcis_status',
'temp': 'bcis_temperatura',
},
{
'title': 'Bomba Cisterna B',
'API': 'get_bcis_b.php',
'data': 'bcisb_data',
'hora': 'bcisb_hora',
'status': 'bcisb_status',
'temp': 'bcisb_temperatura',
},
];
final NAMES_RESERVATORIO = [
{
'title': "Caixa d'Água",
'API': 'get_caixa_a.php',
'qtd_boia': 'caa_qtd_boia',
'data': 'caa_data',
'hora': 'caa_hora',
'boia1': 'caa_boia1',
'boia2': 'caa_boia2',
'boia3': 'caa_boia3',
'boia4': 'caa_boia4',
'boia5': 'caa_boia5',
'boia6': 'caa_boia6',
'boia7': 'caa_boia7',
},
{
'title': "Cisterna",
'API': 'get_cis_a.php',
'qtd_boia': 'cis_qtd_boia',
'data': 'cis_data',
'hora': 'cis_hora',
'boia1': 'cis_boia1',
'boia2': 'cis_boia2',
'boia3': 'cis_boia3',
'boia4': 'cis_boia4',
'boia5': 'cis_boia5',
'boia6': 'cis_boia6',
'boia7': 'cis_boia7',
},
];
final NAMES_PORTAO = [
{
'title': 'Portão Garagem A',
'API': 'get_portao_a.php',
'data': 'pga_data',
'hora': 'pga_hora',
'status': 'pga_status',
},
];
| 20.916667 | 32 | 0.538645 |
1b3e71cf1b197bfdd1a6c986c8cd4890486feda4 | 541 | lua | Lua | prototypes/engineering/data.lua | jonkeda/Colonists | d65671942e9887682088311b1facabacacff413d | [
"MIT"
] | null | null | null | prototypes/engineering/data.lua | jonkeda/Colonists | d65671942e9887682088311b1facabacacff413d | [
"MIT"
] | null | null | null | prototypes/engineering/data.lua | jonkeda/Colonists | d65671942e9887682088311b1facabacacff413d | [
"MIT"
] | 1 | 2019-02-21T17:24:53.000Z | 2019-02-21T17:24:53.000Z | --require("prototypes.engineering.workshop_furnace_data")
require("prototypes.engineering.workshop_beacon_data")
require("prototypes.engineering.wear_and_tear")
table.insert(data.raw["technology"]["automation"].effects, {type = "unlock-recipe", recipe = "colonists-workshop-beacon-1"})
table.insert(data.raw["technology"]["automation-2"].effects, {type = "unlock-recipe", recipe = "colonists-workshop-beacon-2"})
table.insert(data.raw["technology"]["automation-3"].effects, {type = "unlock-recipe", recipe = "colonists-workshop-beacon-3"})
| 67.625 | 126 | 0.763401 |
e8f31d35996b9be1b63960dfeb46a66b8f3d9023 | 2,102 | asm | Assembly | compress.asm | neilbaldwin/PR8 | 045cbd282aba6357a4ae555958cf65c018952e49 | [
"BSD-2-Clause-FreeBSD",
"MIT"
] | 8 | 2021-03-14T18:20:40.000Z | 2021-08-04T20:32:25.000Z | compress.asm | neilbaldwin/PR8 | 045cbd282aba6357a4ae555958cf65c018952e49 | [
"BSD-2-Clause-FreeBSD",
"MIT"
] | 2 | 2021-09-17T02:53:10.000Z | 2021-09-17T03:11:10.000Z | compress.asm | neilbaldwin/PR8 | 045cbd282aba6357a4ae555958cf65c018952e49 | [
"BSD-2-Clause-FreeBSD",
"MIT"
] | null | null | null | ;
; Sequencer Pattern Compress/Decompress (RLE)
;
compress:
lda #WRAM_PATTERNS
jsr setMMC1r1
lda #<patterns
sta tmp0
lda #>patterns
sta tmp1
lda #<$7000
sta tmp2
lda #>$7000
sta tmp3
ldy #$00
lda #$FF
: sta (tmp2),y
iny
bne :-
ldx #$60 ;96 blocks
lda #$00
sta tmp4
: ldy #$00
lda (tmp0),y ;0?
bne :++
lda tmp4 ;yes, doing RLE?
bne :+ ;yes
sta (tmp2),y ;no, store 0 token
inc tmp2 ;update dest address
bne :+
inc tmp3
: inc tmp4 ;update RLE count
bne :+++ ;should never go over 255 (pattern would be 255 * 5)
: pha ;save byte
lda tmp4 ;any RLE?
beq :+ ;no
sta (tmp2),y ;yes, write count
lda #$00 ;clear count
sta tmp4
inc tmp2 ;update dest address
bne :+
inc tmp3
: pla ;retrieve byte
sta (tmp2),y
iny
lda (tmp0),y
sta (tmp2),y
iny
lda (tmp0),y
sta (tmp2),y
iny
lda (tmp0),y
sta (tmp2),y
iny
lda (tmp0),y
sta (tmp2),y
lda tmp2
clc
adc #$05
sta tmp2
bcc :+
inc tmp3
: lda tmp0
clc
adc #$05
sta tmp0
bcc :+
inc tmp1
: dex
bne :------
ldy #$00
lda tmp4
beq :+
sta (tmp2),y
iny
: lda #$00
sta (tmp2),y
iny
sta (tmp2),y
rts
decompress: lda #<$7000
sta tmp0
lda #>$7000
sta tmp1
lda #<$7200
sta tmp2
lda #>$7200
sta tmp3
: ldy #$00
lda (tmp0),y ;token?
bne :++ ;no
iny ;yes, get count
lda (tmp0),y
beq :+++++ ;00 00 so done
tax ;otherwise load count in X
: ldy #$00 ;clear 5 bytes
tya
sta (tmp2),y
iny
sta (tmp2),y
iny
sta (tmp2),y
iny
sta (tmp2),y
iny
sta (tmp2),y
lda tmp2 ;update dest pointer
clc
adc #$05
sta tmp2
lda tmp3
adc #$00
sta tmp3
dex ;dec count
bne :- ;done?
lda tmp0 ;yes update source pointer
clc
adc #$02
sta tmp0
lda tmp2
clc
adc #$00
sta tmp2
jmp :-- ;get more
: sta (tmp2),y ;copy 5 bytes
iny
lda (tmp0),y
sta (tmp2),y
iny
lda (tmp0),y
sta (tmp2),y
iny
lda (tmp0),y
sta (tmp2),y
iny
lda (tmp0),y
sta (tmp2),y
lda tmp0 ;update source
clc
adc #$05
sta tmp0
bne :+
inc tmp1
: lda tmp2 ;update dest
clc
adc #$05
sta tmp2
bne :+
inc tmp3
:
jmp :----- ;get more
: rts
| 12.150289 | 63 | 0.588011 |
6201c33ca227b7f9598de01c93fad286f900fa43 | 200 | dart | Dart | lib/backend/schema/index.dart | Fewsrt/yogaer | 74fc2aab04b561bd35e7a7aec614fd6e0ebbe734 | [
"MIT"
] | 2 | 2022-03-01T15:13:17.000Z | 2022-03-02T21:25:41.000Z | lib/backend/schema/index.dart | MaxHwK/Flutter_TaskManager | b7b3aeb5baf42704287e8cc110b590596d54117e | [
"MIT"
] | null | null | null | lib/backend/schema/index.dart | MaxHwK/Flutter_TaskManager | b7b3aeb5baf42704287e8cc110b590596d54117e | [
"MIT"
] | 1 | 2022-01-24T18:55:40.000Z | 2022-01-24T18:55:40.000Z | export 'package:cloud_firestore/cloud_firestore.dart';
export 'package:built_value/serializer.dart';
export 'package:built_collection/built_collection.dart';
export '../../flutter_flow/lat_lng.dart';
| 40 | 56 | 0.815 |
24a2a9e859f5fd25729e1baf44adceb9af3cff6a | 8,179 | sql | SQL | db.sql | chiechie/BasicAlgo | 1bbd686673c650a5c71ed0781d8081124841e282 | [
"MIT"
] | null | null | null | db.sql | chiechie/BasicAlgo | 1bbd686673c650a5c71ed0781d8081124841e282 | [
"MIT"
] | null | null | null | db.sql | chiechie/BasicAlgo | 1bbd686673c650a5c71ed0781d8081124841e282 | [
"MIT"
] | null | null | null | -- A Subquery or Inner query or a Nested query is a query within another SQL query and embedded within the WHERE clause.
-- A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved.
-- https://www.tutorialspoint.com/sql/sql-sub-queries.htm#:~:text=A%20Subquery%20or%20Inner%20query,the%20data%20to%20be%20retrieved.
-- There are a few rules that subqueries must follow −
-- sub query 可以出现在 select中,where中,from中
-- sub query出现在 from中
-- SELECT SP.TerritoryID,
-- SP.BusinessEntityID,
-- SP.Bonus,
-- TerritorySummary.AverageBonus
-- FROM (SELECT TerritoryID,
-- AVG(Bonus) AS AverageBonus
-- FROM Sales.SalesPerson
-- GROUP BY TerritoryID) AS TerritorySummary
-- INNER JOIN
-- Sales.SalesPerson AS SP
-- ON SP.TerritoryID = TerritorySummary.TerritoryID
# 175. 组合两个表
# SQL架构
# 表1: Person
# +-------------+---------+
# | 列名 | 类型 |
# +-------------+---------+
# | PersonId | int |
# | FirstName | varchar |
# | LastName | varchar |
# +-------------+---------+
# PersonId 是上表主键
# 表2: Address
# +-------------+---------+
# | 列名 | 类型 |
# +-------------+---------+
# | AddressId | int |
# | PersonId | int |
# | City | varchar |
# | State | varchar |
# +-------------+---------+
# AddressId 是上表主键
# 编写一个 SQL 查询,满足条件:无论 person 是否有地址信息,都需要基于上述两表提供 person 的以下信息:
# FirstName, LastName, City, State
# https://leetcode-cn.com/problems/combine-two-tables/
# Write your MySQL query statement below
select a.FirstName, a.LastName, b.City, b.State
from Person as a left join Address as b
on a.PersonId = b.PersonId
-- 176. 第二高的薪水
-- SQL架构
-- 编写一个 SQL 查询,获取 Employee 表中第二高的薪水(Salary) 。
-- +----+--------+
-- | Id | Salary |
-- +----+--------+
-- | 1 | 100 |
-- | 2 | 200 |
-- | 3 | 300 |
-- +----+--------+
-- 例如上述 Employee 表,SQL查询应该返回 200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null。
-- +---------------------+
-- | SecondHighestSalary |
-- +---------------------+
-- | 200 |
-- +---------------------+
-- https://leetcode-cn.com/problems/second-highest-salary/solution/di-er-gao-de-xin-shui-by-leetcode/
# 方法1关键词: 嵌套,递归
select max(Salary) as SecondHighestSalary
from Employee
where Salary < (select max(Salary) from Employee)
# 方法2关键词: offset, select 临时表 as 别名;
select
(
select Salary as SecondHighestSalary
from Employee
order by Salary desc
limit 1 offset 1) as SecondHighestSalary
-- 177. 第N高的薪水
-- 编写一个 SQL 查询,获取 Employee 表中第 n 高的薪水(Salary)。
-- +----+--------+
-- | Id | Salary |
-- +----+--------+
-- | 1 | 100 |
-- | 2 | 200 |
-- | 3 | 300 |
-- +----+--------+
-- 例如上述 Employee 表,n = 2 时,应返回第二高的薪水 200。如果不存在第 n 高的薪水,那么查询应返回 null。
-- +------------------------+
-- | getNthHighestSalary(2) |
-- +------------------------+
-- | 200 |
-- +------------------------+
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
set N:=N-1;
RETURN (
select Salary from Employee
GROUP BY salary
order by Salary desc
limit N, 1
);
END
-- 178 分数排名
-- SQL架构
-- 编写一个 SQL 查询来实现分数排名。
-- 如果两个分数相同,则两个分数排名(Rank)相同。请注意,平分后的下一个名次应该是下一个连续的整数值。换句话说,名次之间不应该有“间隔”。
-- +----+-------+
-- | Id | Score |
-- +----+-------+
-- | 1 | 3.50 |
-- | 2 | 3.65 |
-- | 3 | 4.00 |
-- | 4 | 3.85 |
-- | 5 | 4.00 |
-- | 6 | 3.65 |
-- +----+-------+
-- 例如,根据上述给定的 Scores 表,你的查询应该返回(按分数从高到低排列):
-- +-------+------+
-- | Score | Rank |
-- +-------+------+
-- | 4.00 | 1 |
-- | 4.00 | 1 |
-- | 3.85 | 2 |
-- | 3.65 | 3 |
-- | 3.65 | 3 |
-- | 3.50 | 4 |
-- +-------+------+
-- 重要提示:对于 MySQL 解决方案,如果要转义用作列名的保留字,可以在关键字之前和之后使用撇号。例如 `Rank`
select a.Score as Score,
(select count(distinct b.Score) from Scores b where b.Score >= a.Score) as `Rank`
from Scores as a
order by a.Score DESC
select score, DENSE_RANK() OVER (ORDER BY Score DESC) as 'Rank' from Scores;
-- 181. 超过经理收入的员工
-- SQL架构
-- Employee 表包含所有员工,他们的经理也属于员工。每个员工都有一个 Id,此外还有一列对应员工的经理的 Id。
-- +----+-------+--------+-----------+
-- | Id | Name | Salary | ManagerId |
-- +----+-------+--------+-----------+
-- | 1 | Joe | 70000 | 3 |
-- | 2 | Henry | 80000 | 4 |
-- | 3 | Sam | 60000 | NULL |
-- | 4 | Max | 90000 | NULL |
-- +----+-------+--------+-----------+
-- 给定 Employee 表,编写一个 SQL 查询,该查询可以获取收入超过他们经理的员工的姓名。在上面的表格中,Joe 是唯一一个收入超过他的经理的员工。
-- +----------+
-- | Employee |
-- +----------+
-- | Joe |
-- +----------+
# 关键词,select * from 表1,表2,是对表1和表2作笛卡尔积
select a.Name as Employee from Employee as a, Employee as b
where a.ManagerId = b.Id and a.Salary > b.Salary;
-- 182. 查找重复的电子邮箱
-- SQL架构
-- 编写一个 SQL 查询,查找 Person 表中所有重复的电子邮箱。
-- 示例:
-- +----+---------+
-- | Id | Email |
-- +----+---------+
-- | 1 | a@b.com |
-- | 2 | c@d.com |
-- | 3 | a@b.com |
-- +----+---------+
-- 根据以上输入,你的查询应返回以下结果:
-- +---------+
-- | Email |
-- +---------+
-- | a@b.com |
-- +---------+
-- 说明:所有电子邮箱都是小写字母。
# 关键词, select col1 from (select col1, col2 from t) as 临时表1 where cpl2 > 2
select Email from (
select Email, count(Email) as num from Person
GROUP by Email
) as statis
where num > 1;
-- 196. 删除重复的电子邮箱
-- SQL架构
-- 编写一个 SQL 查询,来删除 Person 表中所有重复的电子邮箱,重复的邮箱里只保留 Id 最小 的那个。
-- +----+------------------+
-- | Id | Email |
-- +----+------------------+
-- | 1 | john@example.com |
-- | 2 | bob@example.com |
-- | 3 | john@example.com |
-- +----+------------------+
-- Id 是这个表的主键。
-- 例如,在运行你的查询语句之后,上面的 Person 表应返回以下几行:
-- +----+------------------+
-- | Id | Email |
-- +----+------------------+
-- | 1 | john@example.com |
-- | 2 | bob@example.com |
-- +----+------------------+
-- 提示:
-- 执行 SQL 之后,输出是整个 Person 表。
-- 使用 delete 语句。
# delete 临时表1 from 临时表1, 临时表1 where *
# DELETE p1就表示从p1表中删除满足WHERE条件的记录。
# a. 从驱动表(左表)取出N条记录;
# b. 拿着这N条记录,依次到被驱动表(右表)查找满足WHERE条件的记录;
delete t1 from Person t1, Person t2
where t1.Email = t2.Email and t1.Id > t2.Id
-- 620. 有趣的电影
-- https://leetcode-cn.com/problems/not-boring-movies/
-- SQL架构
-- 某城市开了一家新的电影院,吸引了很多人过来看电影。该电影院特别注意用户体验,专门有个 LED显示板做电影推荐,上面公布着影评和相关电影描述。
-- 作为该电影院的信息部主管,您需要编写一个 SQL查询,找出所有影片描述为非 boring (不无聊) 的并且 id 为奇数 的影片,结果请按等级 rating 排列。
-- 例如,下表 cinema:
-- +---------+-----------+--------------+-----------+
-- | id | movie | description | rating |
-- +---------+-----------+--------------+-----------+
-- | 1 | War | great 3D | 8.9 |
-- | 2 | Science | fiction | 8.5 |
-- | 3 | irish | boring | 6.2 |
-- | 4 | Ice song | Fantacy | 8.6 |
-- | 5 | House card| Interesting| 9.1 |
-- +---------+-----------+--------------+-----------+
-- 对于上面的例子,则正确的输出是为:
-- +---------+-----------+--------------+-----------+
-- | id | movie | description | rating |
-- +---------+-----------+--------------+-----------+
-- | 5 | House card| Interesting| 9.1 |
-- | 1 | War | great 3D | 8.9 |
-- +---------+-----------+--------------+-----------+
select * from cinema
where id % 2 = 1 and description != "boring"
order by rating desc
## 或者:求余 用 mod, where mod(id, 2) = 1
select * from cinema
where mod(id, 2) = 1 and description != "boring"
order by rating desc
-- 给定一个salary表,如下所示,有 m = 男性 和 f = 女性 的值。
-- 交换所有的 f 和 m 值(例如,将所有 f 值更改为 m,反之亦然), 要求只使用一个更新(Update)语句,并且没有中间的临时表。
-- 注意,您必只能写一个 Update 语句,请不要编写任何 Select 语句。
-- 例如:
-- | id | name | sex | salary |
-- |----|------|-----|--------|
-- | 1 | A | m | 2500 |
-- | 2 | B | f | 1500 |
-- | 3 | C | m | 5500 |
-- | 4 | D | f | 500 |
-- 运行你所编写的更新语句之后,将会得到以下表:
-- | id | name | sex | salary |
-- |----|------|-----|--------|
-- | 1 | A | f | 2500 |
-- | 2 | B | m | 1500 |
-- | 3 | C | f | 5500 |
-- | 4 | D | m | 500 |
-- 来源:力扣(LeetCode)
-- 链接:https://leetcode-cn.com/problems/swap-salary
# 方法1的关键词: 使用 CASE...WHEN... 流程控制语句
UPDATE salary
SET sex = CASE sex
WHEN 'm' THEN 'f'
ELSE 'm'
END;
# 方法2的关键词:ascii和字母转换
update salary set sex = char(ascii('m') + ascii('f') - ascii(sex));
| 24.635542 | 133 | 0.488568 |