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
sequencelengths 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
sequencelengths 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
sequencelengths 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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8c47c36159db14c6829de538b8981a5ecf4be10b | 5,764 | dart | Dart | lib/view/home/home_view.dart | zekkontro/google-fake-music | 290c3d7ca4483462c36479710e0b289499fd6603 | [
"MIT"
] | null | null | null | lib/view/home/home_view.dart | zekkontro/google-fake-music | 290c3d7ca4483462c36479710e0b289499fd6603 | [
"MIT"
] | null | null | null | lib/view/home/home_view.dart | zekkontro/google-fake-music | 290c3d7ca4483462c36479710e0b289499fd6603 | [
"MIT"
] | 1 | 2021-04-14T16:32:05.000Z | 2021-04-14T16:32:05.000Z | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:google_musics/constant/color_constant.dart';
import 'package:google_musics/constant/svg_icons.dart';
import 'package:google_musics/core/services/playlists.dart';
import 'package:google_musics/core/services/profile_service.dart';
import 'package:google_musics/models/playlist.dart';
import 'package:google_musics/models/profile.dart';
import 'package:google_musics/widgets/appBar.dart';
import 'package:google_musics/core/extension/context_extension.dart';
import 'package:google_musics/widgets/today_biggest_hits.dart';
class HomeView extends StatefulWidget {
@override
_HomeViewState createState() => _HomeViewState();
}
class _HomeViewState extends State<HomeView> {
ColorConstants constants = ColorConstants.instance;
SvgIcons svgIcons = SvgIcons.instance;
PlaylistService service = PlaylistService();
ProfileService profservice = ProfileService();
@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(height: context.sizeH(0.01)),
Padding(
padding: EdgeInsets.all(24.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text("It's Friday Night",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 25)),
Text("Play something for...",
style: TextStyle(color: Colors.grey[600], fontSize: 18)),
],
),
),
SizedBox(height: context.sizeH(0.01)),
FutureBuilder(
future: service.getPlaylists(),
builder: (context, AsyncSnapshot<List<Playlist>> snapshot) {
return SizedBox(
width: double.infinity,
height: context.sizeH(0.3),
child: ListView(
scrollDirection: Axis.horizontal,
children: snapshot.data.map((data) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: TodayBiggestHits(
playlist: data,
),
);
}).toList(),
),
);
},
),
SizedBox(height: context.sizeH(0.05)),
Padding(
padding: EdgeInsets.all(24),
child: Text("Recommended for you",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 25)),
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 10),
child: Card(
child: ListTile(
title: Text("I'm feeling lucky radio",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w500,
fontSize: 20)),
subtitle: Text("Based on your music taste",
style: TextStyle(
color: Colors.black, fontWeight: FontWeight.w400)),
trailing: Container(
height: context.sizeH(0.2),
width: context.sizeW(0.15),
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/utilities/random-icon.png'),
fit: BoxFit.cover,
),
),
),
),
),
),
SizedBox(height: context.sizeH(0.05)),
FutureBuilder<Profile>(
future: profservice.getProfileByIndex(2),
builder: (context, snapshot) {
Profile profile = snapshot.data;
return Padding(
padding: EdgeInsets.symmetric(horizontal: 10),
child: Container(
child: Center(
child: Stack(
children: [
Container(
height: context.sizeH(0.5),
width: context.sizeW(0.5),
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(profile.profileImage))),
),
],
),
),
width: double.infinity,
height: context.sizeH(0.25),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
image: DecorationImage(
image: AssetImage(profile.backgroundImage),
fit: BoxFit.cover,
colorFilter: ColorFilter.mode(
profile.filterColor.withOpacity(0.9),
BlendMode.multiply))),
),
);
}),
SizedBox(height: context.sizeH(0.05)),
],
)),
appBar: CustomAppBar(
text: "Listen Now",
actions: [
CupertinoButton(child: svgIcons.broadcast, onPressed: () {}),
CupertinoButton(child: svgIcons.search, onPressed: () {})
],
height: context.sizeH(0.08),
),
);
}
}
| 38.426667 | 78 | 0.49306 |
d66270bf9106e05f546049c75c539c71136775ae | 4,331 | swift | Swift | Clark/UI Components/Bubbles/Carousel/CarouselContentNode.swift | ignotusverum/Clark | 697bb1ae25de18e6a81b0f88ef7ccd0f43092357 | [
"MIT"
] | null | null | null | Clark/UI Components/Bubbles/Carousel/CarouselContentNode.swift | ignotusverum/Clark | 697bb1ae25de18e6a81b0f88ef7ccd0f43092357 | [
"MIT"
] | null | null | null | Clark/UI Components/Bubbles/Carousel/CarouselContentNode.swift | ignotusverum/Clark | 697bb1ae25de18e6a81b0f88ef7ccd0f43092357 | [
"MIT"
] | null | null | null | //
// CarouselContentNode.swift
// Clark
//
// Created by Vladislav Zagorodnyuk on 7/8/17.
// Copyright © 2017 Clark. All rights reserved.
//
import UIKit
import NMessenger
import AsyncDisplayKit
protocol CarouselContentDelegate {
func datasourceSelected(items: [CarouselItem])
}
open class CarouselContentNode: ContentNode {
/// Carousel Items
var carouselItems: [CarouselItem] {
didSet {
/// Reload
collectionViewNode.reloadData()
}
}
/// Delegate
var delegate: CarouselContentDelegate?
/// Collection View node
lazy var collectionViewNode: ASCollectionNode = {
/// Layout
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.minimumLineSpacing = 16
layout.minimumInteritemSpacing = 16
layout.sectionInset = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)
/// Collection node
let collectionNode = ASCollectionNode(frame: .zero, collectionViewLayout: layout)
/// Node setup
collectionNode.view.showsHorizontalScrollIndicator = false
return collectionNode
}()
/// Inset for the node
open var insets = UIEdgeInsets(top: 8, left: 10, bottom: 8, right: 10) {
didSet {
setNeedsLayout()
}
}
/// Initializer for the cell
///
/// - Parameters:
/// - carouselItem: carouselItem model
/// - bubbleConfiguration: bubble setup
init(carouselItems: [CarouselItem], bubbleConfiguration: BubbleConfigurationProtocol? = nil) {
self.carouselItems = carouselItems
super.init(bubbleConfiguration: bubbleConfiguration)
self.setupCarouselNode()
}
/// Initializer for the cell
///
/// - Parameters:
/// - carouselItem: carouselItem model
/// - currentViewController: controller for presentation
/// - bubbleConfiguration: bubble setup
init(carouselItems: [CarouselItem], currentViewController: UIViewController, bubbleConfiguration: BubbleConfigurationProtocol? = nil) {
self.carouselItems = carouselItems
super.init(bubbleConfiguration: bubbleConfiguration)
self.currentViewController = currentViewController
self.setupCarouselNode()
}
// MARK: Initializer helper
/// Create carousel
///
/// - Parameter carouselItem: carousel model
fileprivate func setupCarouselNode() {
/// Clear background bubble
layer.backgroundColor = UIColor.clear.cgColor
addSubnode(collectionViewNode)
/// Collection node setup
collectionViewNode.delegate = self
collectionViewNode.dataSource = self
}
// MARK: - Collection layout
open override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
let carouselMessageSize = ASAbsoluteLayoutSpec()
carouselMessageSize.style.preferredSize = CGSize(width: constrainedSize.max.width, height: 160)
carouselMessageSize.sizing = .sizeToFit
carouselMessageSize.children = [collectionViewNode]
return ASInsetLayoutSpec(insets: insets, child: carouselMessageSize)
}
}
// MARK: - ASCollectionDataSource
extension CarouselContentNode: ASCollectionDataSource {
public func collectionNode(_ collectionNode: ASCollectionNode, nodeForItemAt indexPath: IndexPath) -> ASCellNode {
let carouselItem = carouselItems[indexPath.row]
return CarouselNode(with: carouselItem, count: carouselItems.count)
}
public func numberOfSections(in collectionNode: ASCollectionNode) -> Int {
return 1
}
public func collectionNode(_ collectionNode: ASCollectionNode, numberOfItemsInSection section: Int) -> Int {
return carouselItems.count
}
}
// MARK: - ASCollectionDelegate
extension CarouselContentNode: ASCollectionDelegate {
public func collectionNode(_ collectionNode: ASCollectionNode, didSelectItemAt indexPath: IndexPath) {
delegate?.datasourceSelected(items: carouselItems)
Analytics.trackEventWithID(.s1_6, eventParams: ["index": indexPath.row])
}
}
| 31.158273 | 139 | 0.661972 |
5d3007e2cdb1f41deddd699b0ed75aedfb21519d | 1,545 | cpp | C++ | B-CCP-400-LYN-4-1-theplazza/src/kitchen.cpp | Neotoxic-off/Epitech2024 | 8b3dd04fa9ac2b7019c0b5b1651975a7252d929b | [
"Apache-2.0"
] | 2 | 2022-02-07T12:44:51.000Z | 2022-02-08T12:04:08.000Z | B-CCP-400-LYN-4-1-theplazza/src/kitchen.cpp | Neotoxic-off/Epitech2024 | 8b3dd04fa9ac2b7019c0b5b1651975a7252d929b | [
"Apache-2.0"
] | null | null | null | B-CCP-400-LYN-4-1-theplazza/src/kitchen.cpp | Neotoxic-off/Epitech2024 | 8b3dd04fa9ac2b7019c0b5b1651975a7252d929b | [
"Apache-2.0"
] | 1 | 2022-01-23T21:26:06.000Z | 2022-01-23T21:26:06.000Z | /*
** EPITECH PROJECT, 2020
** C / C++ PROJECT
** File description:
** file
*/
#include "kitchen.hpp"
#include "commands.hpp"
#include "pool.hpp"
#include "self.hpp"
kitchen::kitchen(int multiplier, int cooks, int time, commands *commands_d,
std::vector<std::string> pizzas, std::vector<std::string> sizes)
{
this->multiplier_d = multiplier;
this->cooks_d = cooks;
this->time_d = time;
this->pizza_queue_d = pizzas;
this->size_queue_d = sizes;
this->commands_d = commands_d;
return;
}
kitchen::~kitchen()
{
this->multiplier_d = 0;
this->cooks_d = 0;
this->time_d = 0;
this->pizza_queue_d = {};
this->size_queue_d = {};
return;
}
int kitchen::multiplier()
{
return (this->multiplier_d);
}
int kitchen::cooks()
{
return (this->cooks_d);
}
int kitchen::time()
{
return (this->time_d);
}
std::vector<std::string> kitchen::pizza_queue()
{
return (this->pizza_queue_d);
}
std::vector<std::string> kitchen::size_queue()
{
return (this->size_queue_d);
}
bool kitchen::cook()
{
pool func_pool;
std::vector<std::thread> cooks_t;
for (int i = 0; i < this->cooks_d; i++)
cooks_t.push_back(std::thread(&pool::infinite_loop_func, &func_pool));
for (auto i = this->pizza_queue_d.begin(); i != this->pizza_queue_d.end(); i++)
func_pool.push(std::bind(&commands::launch, this->commands_d, this->commands_d->pizza));
func_pool.close();
for (unsigned int i = 0; i < cooks_t.size(); i++)
cooks_t[i].join();
return (true);
}
| 20.328947 | 96 | 0.629773 |
95acb879a8aa7f23220f5d16bab7b2625af4140a | 226 | rb | Ruby | cookbooks/ri_base/recipes/tools.rb | bopopescu/devops-opsworks | a5bbf0cc41853d4f8174542790ad8925f5310fea | [
"Apache-2.0"
] | null | null | null | cookbooks/ri_base/recipes/tools.rb | bopopescu/devops-opsworks | a5bbf0cc41853d4f8174542790ad8925f5310fea | [
"Apache-2.0"
] | 1 | 2016-04-14T05:42:52.000Z | 2016-04-14T05:42:52.000Z | cookbooks/ri_base/recipes/tools.rb | bopopescu/devops-opsworks | a5bbf0cc41853d4f8174542790ad8925f5310fea | [
"Apache-2.0"
] | 1 | 2020-07-24T10:29:32.000Z | 2020-07-24T10:29:32.000Z | # performance monitors
package "sysstat" do
action :upgrade
end
package "jnettop" do
action :upgrade
end
package "iperf" do
action :upgrade
end
# git client
package "git-core" do
action :upgrade
end | 12.555556 | 23 | 0.681416 |
f491fa7d5d142a79fcf5ef972ea4393c4dff830a | 2,166 | ts | TypeScript | 2021/mini-compiler/src/main.ts | KivalEvan/CPU-Scheduling-Simulation | f80d080aab94db053a70a1115ebd4cd97c41d65b | [
"MIT"
] | null | null | null | 2021/mini-compiler/src/main.ts | KivalEvan/CPU-Scheduling-Simulation | f80d080aab94db053a70a1115ebd4cd97c41d65b | [
"MIT"
] | null | null | null | 2021/mini-compiler/src/main.ts | KivalEvan/CPU-Scheduling-Simulation | f80d080aab94db053a70a1115ebd4cd97c41d65b | [
"MIT"
] | null | null | null | import './style.css';
import { scanner } from './lexicalAnalyser';
import { parser, AbstractSyntaxTree } from './syntaxAnalyser';
const htmlInputTextArea = document.querySelector<HTMLTextAreaElement>('#input-text')!;
const htmlOutputLexerTextArea =
document.querySelector<HTMLTextAreaElement>('#output-lexer')!;
const htmlOutputSyntaxTextArea =
document.querySelector<HTMLTextAreaElement>('#output-syntax')!;
const htmlOutputResultTextArea =
document.querySelector<HTMLTextAreaElement>('#output-result')!;
const htmlCompileMessage = document.querySelector<HTMLSpanElement>('#compile-message')!;
const htmlCompileTimeText = document.querySelector<HTMLSpanElement>('#compile-time')!;
const getInput = () => {
return htmlInputTextArea.value;
};
const setLexerOutput = (output: String[]) => {
htmlOutputLexerTextArea.value = output.join('\n');
};
const setSyntaxOutput = (output: AbstractSyntaxTree) => {
htmlOutputSyntaxTextArea.value = output.nodes
.map((n) => n.params)
.flat()
.map((n) => JSON.stringify(n))
.join('\n');
};
const setResultOutput = (output: AbstractSyntaxTree) => {
htmlOutputResultTextArea.value = JSON.stringify(output, null, 4);
};
const onTextInput = () => {
htmlOutputLexerTextArea.value = '';
htmlOutputSyntaxTextArea.value = '';
htmlOutputResultTextArea.value = '';
htmlCompileMessage.textContent = '';
if (!getInput().trim()) {
return;
}
let startTime = performance.now();
try {
const token = scanner(getInput());
setLexerOutput(token.map((t) => `${t.type}:${t.lexeme}`));
const ast = parser(token);
setSyntaxOutput(ast);
setResultOutput(ast);
} catch (e) {
console.error(e);
if (typeof e === 'string') {
htmlCompileMessage.textContent = e;
}
} finally {
let compileTime = performance.now() - startTime;
htmlCompileTimeText.textContent = (
Math.round(compileTime * 10) / 10
).toString();
}
};
htmlInputTextArea.addEventListener('input', onTextInput);
htmlInputTextArea.addEventListener('change', onTextInput);
| 32.818182 | 88 | 0.666667 |
a3e28678806235a3c3ee5c39e5d201596fec210d | 792 | java | Java | app/src/main/java/com/skytreasure/bingflightscraper/model/FlightModel.java | SkyTreasure/Bing-Flight-Status-Android-Scraper | 496de42c17a1a4104104e8984ca41bd90788d55c | [
"MIT"
] | 9 | 2018-04-11T15:02:43.000Z | 2021-10-31T13:34:04.000Z | app/src/main/java/com/skytreasure/bingflightscraper/model/FlightModel.java | SkyTreasure/Bing-Flight-Status-Android-Scraper | 496de42c17a1a4104104e8984ca41bd90788d55c | [
"MIT"
] | null | null | null | app/src/main/java/com/skytreasure/bingflightscraper/model/FlightModel.java | SkyTreasure/Bing-Flight-Status-Android-Scraper | 496de42c17a1a4104104e8984ca41bd90788d55c | [
"MIT"
] | 3 | 2019-03-13T23:24:44.000Z | 2020-09-30T13:35:44.000Z | package com.skytreasure.bingflightscraper.model;
/**
* Created by akash on 21/12/17.
*/
public class FlightModel {
public String flightNumber;
public String statusDetails;
public String statusBadge;
public String arivalTime;
public String departureTime;
public String departureArrivalTimings;
public String departureArrivalDates;
public String departureArrivalCities;
public String airportInfo;
public String sourceDestinationCode;
public String source;
public String destination;
public String date;
public String dTerminal;
public String aTerminal;
public String dGate;
public String aGate;
public String dCityName;
public String aCityName;
public String otherDetails;
public FlightModel() {
}
}
| 24 | 48 | 0.732323 |
b0c603eaeec37191e2ddc892dfa1344206c89b99 | 3,600 | py | Python | generator.py | koshian2/ImageNet | ed11a31637db6f7c2df12232e3cb1cabad8397e9 | [
"MIT"
] | null | null | null | generator.py | koshian2/ImageNet | ed11a31637db6f7c2df12232e3cb1cabad8397e9 | [
"MIT"
] | null | null | null | generator.py | koshian2/ImageNet | ed11a31637db6f7c2df12232e3cb1cabad8397e9 | [
"MIT"
] | null | null | null | from PIL import Image
from preprocess import imagenet_data_augmentation, validation_image_load
import numpy as np
from joblib import Parallel, delayed
def imagenet_generator(meta_data, size, is_train, batch_size, preprocess_func):
"""
ImageNet data generator
# Inputs
meta_data = [[path, class_idx], [...]] format meta data
size = output size of image (integer)
is_train = True if train, false if validation. True = enable shuffle & data augmentation
batch_size = batch size of generator
preprocess_func = color rescaling function of corresponding networks
# Outputs
yielding (X_batch, y_batch)
"""
X_cache, y_cache = [], []
while True:
if is_train:
indices = np.random.permutation(len(meta_data))
else:
indices = np.arange(len(meta_data))
for i in indices:
with Image.open(meta_data[i][0]) as img:
if is_train:
X_item = imagenet_data_augmentation(img, size)
else:
X_item = validation_image_load(img, size)
y_item = np.zeros((1000), np.float32)
y_item[meta_data[i][1]] = 1.0
X_cache.append(X_item)
y_cache.append(y_item)
if len(X_cache) == batch_size:
X_batch = np.asarray(X_cache, np.uint8)
y_batch = np.asarray(y_cache, np.float32)
X_cache, y_cache = [], []
yield (preprocess_func(X_batch), y_batch)
def _parallel_wrap(meta_item, size, is_train):
"""
Parallel wrap for multiprocessing
"""
with Image.open(meta_item[0]) as img:
if is_train:
X_item = imagenet_data_augmentation(img, size)
else:
X_item = validation_image_load(img, size)
y_item = np.zeros((1000), np.float32)
y_item[meta_item[1]] = 1.0
return [X_item, y_item]
def imagenet_generator_multi(meta_data, size, is_train, batch_size, preprocess_func):
"""
ImageNet data generator using multiprocessing
# Inputs
meta_data = [[path, class_idx], [...]] format meta data
size = output size of image (integer)
is_train = True if train, false if validation. True = enable shuffle & data augmentation
batch_size = batch size of generator
preprocess_func = color rescaling function of corresponding networks
# Outputs
yielding (X_batch, y_batch)
"""
while True:
if is_train:
indices = np.random.permutation(len(meta_data))
else:
indices = np.arange(len(meta_data))
for batch_idx in range(indices.shape[0]//batch_size):
current_indices = indices[batch_idx*batch_size:(batch_idx+1)*batch_size]
parallel_result = Parallel(n_jobs=4)( [delayed(_parallel_wrap)(meta_data[i], size, is_train)
for i in current_indices] )
X_batch = np.asarray([parallel_result[i][0] for i in range(batch_size)], np.uint8)
y_batch = np.asarray([parallel_result[i][1] for i in range(batch_size)], np.float32)
yield (preprocess_func(X_batch), y_batch)
def fake_data_generator(size, batch_size, preprocess_func):
"""
Generating random noise image, label (for benchmarkling)
"""
while True:
X_batch = np.random.randint(low=0, high=256, size=(batch_size, size, size, 3), dtype=np.uint8)
y_batch = np.identity(1000, dtype=np.float32)[np.random.randint(low=0, high=1000, size=batch_size)]
yield (preprocess_func(X_batch), y_batch) | 41.860465 | 107 | 0.63 |
a17d11a66b5590dd54e7d89c95a4f499d5de7353 | 1,771 | ts | TypeScript | src/types/Slice.ts | FontEndArt/typescript-utils-study | 97cb6b6f4771decce06fd39605361713318f4ce7 | [
"MIT"
] | 4 | 2022-02-25T06:21:19.000Z | 2022-03-05T07:36:30.000Z | src/types/Slice.ts | FontEndArt/typescript-utils-study | 97cb6b6f4771decce06fd39605361713318f4ce7 | [
"MIT"
] | 1 | 2022-02-25T06:21:13.000Z | 2022-03-01T06:29:45.000Z | src/types/Slice.ts | FontEndArt/typescript-utils-study | 97cb6b6f4771decce06fd39605361713318f4ce7 | [
"MIT"
] | null | null | null | /**
* @name NumberToTuple
* @descript number 转 tuple类型
* @example type A = NumberToTuple<0> // []
* @example type A = NumberToTuple<1> // [any]
* @example type A = NumberToTuple<2> // [any, any]
*/
export type NumberToTuple<T extends number = 0, R extends any[] = []> =
R['length'] extends T
? R
: NumberToTuple<T, [...R, any]>
/**
* @name Slice
* @description Just like what Array.prototype.slice() does, please implement Slice<A, S, E>.
* @example type A = Slice<[1,2,3,4], 0, 2> // [1, 2]
* @example type B = Slice<[1,2,3,4], 2> // [3, 4]
* @example type C = Slice<[number, boolean, bigint], 2, 5> // [bigint]
* @example type D = Slice<[string, boolean], 0, 1> // [string]
* @example type E = Slice<[number, boolean, bigint], 5, 6> // []
* > 可以使用LessThan来比较大小,由于索引都是大于等于0的整数,所以可以使用简版的LessThan
*/
export type Slice<
A extends any[],
S extends number = 0, // 起始节点
E extends number = A['length'], // 终止节点
C extends any[] = [],
D extends any[] = [],
ST extends any[] = NumberToTuple<S>,
ET extends any[] = NumberToTuple<E>,
> =
[0] extends [A['length']]
? D
: [ST['length']] extends [C['length']]
? [ET['length']] extends [C['length']]
? D
: A extends [infer L, ...infer R]
? Slice<R, S, E, [...C, 1], [...D, L], [...C, 1], ET>
: D
: A extends [infer L, ...infer R]
? Slice<R, S, E, [...C, 1], D, ST, ET>
: D
type A = Slice<[1,2,3,4], 0, 2> // [1, 2]
type B = Slice<[1,2,3,4], 2> // [3, 4]
type C = Slice<[number, boolean, bigint], 2, 5> // [bigint]
type D = Slice<[string, boolean], 0, 1> // [string]
type E = Slice<[number, boolean, bigint], 5, 6> // [] | 36.895833 | 93 | 0.517222 |
583ffaa85145763cf93fcde2e650ca8849d06fe9 | 741 | css | CSS | data/usercss/116983.user.css | 33kk/uso-archive | 2c4962d1d507ff0eaec6dcca555efc531b37a9b4 | [
"MIT"
] | 118 | 2020-08-28T19:59:28.000Z | 2022-03-26T16:28:40.000Z | data/usercss/116983.user.css | 33kk/uso-archive | 2c4962d1d507ff0eaec6dcca555efc531b37a9b4 | [
"MIT"
] | 38 | 2020-09-02T01:08:45.000Z | 2022-01-23T02:47:24.000Z | data/usercss/116983.user.css | 33kk/uso-archive | 2c4962d1d507ff0eaec6dcca555efc531b37a9b4 | [
"MIT"
] | 21 | 2020-08-19T01:12:43.000Z | 2022-03-15T21:55:17.000Z | /* ==UserStyle==
@name kuriyama mi
@namespace USO Archive
@author VanillaAmorDoce
@description `Kuriyama mirai ad`
@version 20150727.20.9
@license NO-REDISTRIBUTION
@preprocessor uso
==/UserStyle== */
@-moz-document domain("amordoce.com") {
#container{
background-image : url(http://i59.tinypic.com/15mnr80.jpg) !important ;
}
#container.connected #header { background-image : url(http://i62.tinypic.com/wa59io.png) !important ;
}
.idcard-member { background : url(http://i57.tinypic.com/2mmzuxc.png) no-repeat !important ;
}
}
@-moz-document regexp("http://www.amordoce.com/profil/Camilameiga") {
.idcard-member { background : url(Carteirinha personalizada) no-repeat !important ;
}
} | 32.217391 | 102 | 0.68691 |
b117282d23cee5f0d2e385fc62d45e2e90feda91 | 774 | lua | Lua | AttackOnPirates/gameLogic/score.lua | dyhpoon/game-project | d88e271002101e1eb87aba94d58b44c1f56cb7a0 | [
"Apache-2.0"
] | 5 | 2016-03-03T04:10:21.000Z | 2018-04-26T12:30:08.000Z | AttackOnPirates/gameLogic/score.lua | dyhpoon/Attack-on-Pirates | d88e271002101e1eb87aba94d58b44c1f56cb7a0 | [
"Apache-2.0"
] | null | null | null | AttackOnPirates/gameLogic/score.lua | dyhpoon/Attack-on-Pirates | d88e271002101e1eb87aba94d58b44c1f56cb7a0 | [
"Apache-2.0"
] | null | null | null | module(..., package.seeall)
function new()
local group = display.newGroup()
local score
local scoreText
score = 0
scoreText = display.newText( "SCORE: 0" , 0, 0, "impact", 13 )
scoreText.anchorX, scoreText.anchorY = 1, .5
scoreText.x = display.contentWidth - 8
scoreText.y = 40
scoreText.text = "SCORE: " .. score --string.format( "SCORE: %6.0f", score )
scoreText:setTextColor(255, 255, 255)
group:insert(scoreText)
function group:addScore(scoreToBeAdded)
score = score + scoreToBeAdded
scoreText.text = "SCORE: " .. score --string.format( "SCORE: %6.0f", score )
scoreText.anchorX, scoreText.anchorY = 1, .5
scoreText.x = display.contentWidth - 8
scoreText.y = 40
end
function group:getScore()
return score
end
return group
end
| 23.454545 | 83 | 0.68863 |
252a385359fd70f07bca972cac7210446cedd983 | 5,526 | swift | Swift | _src/Chapter09/Swift/Node.swift | paullewallencom/data-structures-978-1-7871-2104-1 | 85eaa72e7e77ea24fe7a28152159076619902247 | [
"Apache-2.0"
] | 12 | 2017-08-06T09:47:03.000Z | 2021-12-30T07:40:24.000Z | Chapter09/Swift/Node.swift | Danielr19/Everyday-Data-Structures | 9df026c1e3b11b69bf89e02ec8ade3966d042726 | [
"MIT"
] | null | null | null | Chapter09/Swift/Node.swift | Danielr19/Everyday-Data-Structures | 9df026c1e3b11b69bf89e02ec8ade3966d042726 | [
"MIT"
] | 13 | 2017-03-16T11:56:04.000Z | 2021-08-21T12:03:45.000Z | //
// Node.swift
// EverydayDataStructures-Swift
//
// Created by Will Smith on 9/24/16.
// Copyright © 2016 Websmiths, LLC. All rights reserved.
//
import Foundation
public class Node : Equatable
{
public var data: Int
public var left: Node?
public var right: Node?
public var children: Array<Node> {
return [left!, right!]
}
public init (nodeData: Int)
{
data = nodeData
}
public func insertData(data: Int) -> Bool
{
return insertNode(node: Node(nodeData:data))
}
public func insertNode(node: Node?) -> Bool
{
if (node == nil)
{
return false
}
if ((findNode(node: node!)) != nil)
{
return false
}
else if (node!.data < data)
{
if (left == nil)
{
left = node
return true
}
else
{
return left!.insertNode(node: node)
}
}
else
{
if (right == node)
{
right = node
return true
}
else
{
return right!.insertNode(node: node)
}
}
}
public func graft(node: Node?) -> Bool
{
if (node == nil)
{
return false
}
let nodes: Array = node!.listTree()
for n in nodes
{
self.insertNode(node: n)
}
return true
}
public func removeData(data: Int) -> Node?
{
return removeNode(node: Node(nodeData:data))
}
public func removeNode(node: Node?) -> Node?
{
if (node == nil)
{
return nil
}
var retNode: Node
var modNode: Node?
var treeList = Array<Node>()
if (self.data == node!.data)
{
//Root match
retNode = Node(nodeData: self.data)
modNode = self
if (children.count == 0)
{
return self //Root has no childen
}
}
else if (left!.data == node!.data)
{
//Match found
retNode = Node(nodeData: left!.data)
modNode = left!
}
else if (right!.data == node!.data)
{
//Match found
retNode = Node(nodeData: right!.data)
modNode = right!
}
else
{
for child in self.children
{
if (child.removeNode(node: node) != nil)
{
return child
}
}
//No match in tree
return nil
}
//Reorder the tree
if ((modNode!.left) != nil)
{
modNode!.data = modNode!.left!.data
treeList = modNode!.left!.listTree()
modNode!.left = nil
}
else if ((modNode!.right) != nil)
{
modNode!.data = modNode!.right!.data
treeList = modNode!.right!.listTree()
modNode!.right = nil
}
else
{
modNode = nil
}
for n in treeList
{
modNode!.insertNode(node: n)
}
//Finished
return retNode
}
public func prune(root: Node?) -> Node?
{
if (root == nil)
{
return nil
}
var matchNode: Node?
if (self.data == root!.data)
{
//Root match
let b = self.copyTree()
self.left = nil
self.right = nil
return b
}
else if (self.left!.data == root!.data)
{
matchNode = self.left!
}
else if (self.right!.data == root!.data)
{
matchNode = self.right!
}
else
{
for child in self.children
{
if (child.prune(root: root!) != nil)
{
return child
}
}
//No match in tree
return nil;
}
let branch = matchNode!.copyTree()
matchNode = nil
return branch
}
public func findData(data: Int) -> Node?
{
return findNode(node: Node(nodeData:data))
}
public func findNode(node: Node) -> Node?
{
if (node == self)
{
return self
}
for child in children
{
let result = child.findNode(node: node)
if (result != nil)
{
return result
}
}
return nil
}
public func copyTree() -> Node
{
let n = Node(nodeData: self.data)
if (self.left != nil)
{
n.left = self.left!.copyTree()
}
if(self.right != nil)
{
n.right = self.right!.copyTree()
}
return n
}
public func listTree() -> Array<Node>
{
var result = Array<Node>()
result.append(self)
for child in children
{
result.append(contentsOf: child.listTree())
}
return result
}
}
public func == (lhs: Node, rhs: Node) -> Bool {
return (lhs.data == rhs.data)
}
| 20.85283 | 57 | 0.412776 |
7b6381699372ac8e4d436098aec743919cfc66f1 | 397 | rb | Ruby | spec/lib/commontator/shared_helper_spec.rb | andreibondarev/commontator | a1400e9cc3668b4e1d7e5399c8dc0859a73201bc | [
"MIT"
] | null | null | null | spec/lib/commontator/shared_helper_spec.rb | andreibondarev/commontator | a1400e9cc3668b4e1d7e5399c8dc0859a73201bc | [
"MIT"
] | null | null | null | spec/lib/commontator/shared_helper_spec.rb | andreibondarev/commontator | a1400e9cc3668b4e1d7e5399c8dc0859a73201bc | [
"MIT"
] | null | null | null | require 'rails_helper'
RSpec.describe Commontator::SharedHelper, type: :lib do
let(:controller) { DummyModelsController.new }
before { setup_controller_spec }
it 'renders a commontator thread' do
@user.can_read = true
controller.current_user = @user
thread_link = controller.view_context.commontator_thread(DummyModel.create)
expect(thread_link).not_to be_blank
end
end
| 26.466667 | 79 | 0.763224 |
4fec34109c83cb90218da9b9751f1351f8d320ee | 10,654 | ps1 | PowerShell | src/metadata/GraphDataModel.ps1 | adamedx/poshgraph | af94b47ee14c89b9a46982833d34433dc3de5587 | [
"Apache-2.0"
] | 15 | 2018-09-28T23:44:15.000Z | 2021-07-23T19:05:24.000Z | src/metadata/GraphDataModel.ps1 | adamedx/autographps | af94b47ee14c89b9a46982833d34433dc3de5587 | [
"Apache-2.0"
] | 7 | 2018-10-15T02:50:41.000Z | 2021-06-15T13:28:03.000Z | src/metadata/GraphDataModel.ps1 | adamedx/autographps | af94b47ee14c89b9a46982833d34433dc3de5587 | [
"Apache-2.0"
] | 2 | 2018-10-16T10:57:45.000Z | 2020-02-23T11:25:22.000Z | # Copyright 2021, Adam Edwards
#
# 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.
. (import-script QualifiedSchema)
ScriptClass GraphDataModel {
$apiMetadata = $null
$apiModels = $null
$aliases = $null
$methodBindings = $null
$typeSchemas = $null
static {
const DefaultNamespace 'microsoft.graph'
}
function __initialize($apiMetadata) {
$this.apiMetadata = $apiMetadata
$this.apiModels = @{}
$this.aliases = @{}
$apiMetadata.Edmx.DataServices.Schema | foreach {
$schema = $_
$namespace = $schema.Namespace
if ( $this.apiModels[$namespace] ) {
throw "Namespace '$namespace' already exists as a namespace or alias"
}
$alias = $null
# For more information about namespace aliases, see the following OData documentation:
# https://www.odata.org/documentation/odata-version-3-0/common-schema-definition-language-csdl/
if ( $schema | gm Alias -erroraction ignore ) {
$alias = $schema.alias
if ( $this.aliases[$alias] -or $this.apiModels[$alias] ) {
throw "Alias '$alias' already exists as a namespace or alias"
}
$this.aliases.add($alias, $namespace)
}
$model = [PSCustomObject] @{
Namespace = $namespace
Alias = $alias
Schema = $schema
}
$this.apiModels.add($namespace, $model)
}
}
function GetDefaultNamespace {
$this.scriptclass.DefaultNamespace
}
function GetNamespaces {
$this.apiModels.keys
}
function GetSchema($namespace) {
if ( ! $this.apiModels[$namespace] ) {
throw "No model could be found for the specified namespace '$namespace'"
}
$this.apiModels[$namespace].Schema
}
function GetEntityTypeByName($typeName) {
__InitializeTypesOnDemand
$this.typeSchemas[$typeName]
}
function GetMethodBindingsForType($typeName) {
if ( $this.methodBindings -eq $null ) {
$this.methodBindings = @{}
$actions = GetActions
__AddMethodBindingsFromMethodSchemas $actions Action
$functions = GetFunctions
__AddMethodBindingsFromMethodSchemas $functions Function
}
$bindings = $this.methodBindings[$typeName]
if ( $bindings ) {
$bindings.Distinct.Values
}
}
function GetEntityTypes {
__InitializeTypesOnDemand
$this.typeSchemas.Values
}
function GetComplexTypes($typeName) {
Write-Progress -id 2 -activity "Reading complex types"
foreach ( $model in $this.apiModels.Values ) {
if ( $model.Schema | gm ComplexType -erroraction ignore ) {
$complexTypeSchemas = if ( $typeName ) {
$model.Schema.ComplexType | where Name -eq $typeName
} else {
$model.Schema.ComplexType
}
foreach ( $complexType in $complexTypeSchemas ) {
new-so QualifiedSchema ComplexType $model.namespace $complexType.name $complexType
}
}
}
Write-Progress -id 2 -activity "Reading complex types" -Completed
}
function GetEntitySets {
Write-Progress -id 2 -activity "Reading entity sets"
foreach ( $model in $this.apiModels.Values ) {
if ( $model.Schema | gm EntityContainer -erroraction ignore ) {
__QualifySchemaClass EntitySet $model.namespace $model.Schema.EntityContainer
}
}
Write-Progress -id 2 -activity "Reading entity sets" -Completed
}
function GetSingletons {
Write-Progress -id 2 -activity "Reading singletons"
foreach ( $model in $this.apiModels.Values ) {
if ( $model.Schema | gm EntityContainer -erroraction ignore ) {
__QualifySchemaClass Singleton $model.namespace $model.Schema.EntityContainer
}
}
Write-Progress -id 2 -activity "Reading singletons" -Completed
}
function GetEnumTypes {
Write-Progress -id 2 -activity "Reading enumerated types"
foreach ( $model in $this.apiModels.Values ) {
__QualifySchemaClass EnumType $model.namespace $model.Schema
}
Write-Progress -id 2 -activity "Reading enumerated types" -Completed
}
function GetActions {
Write-Progress -id 2 "Reading actions"
foreach ( $model in $this.apiModels.Values ) {
__QualifySchemaClass Action $model.namespace $model.Schema
}
Write-Progress -id 2 "Reading actions" -Completed
}
function GetFunctions {
Write-Progress -id 2 "Reading functions"
foreach ( $model in $this.apiModels.Values ) {
__QualifySchemaClass Function $model.namespace $model.Schema
}
Write-Progress -id 2 "Reading functions" -Completed
}
function UnqualifyTypeName($qualifiedTypeName) {
(ParseTypeName $qualifiedTypeName).UnqualifiedName
}
function ParseTypeName($qualifiedTypeName, $onlyIfQualified = $false) {
$prefix = ''
$namespace = $null
$unqualified = if ( $qualifiedTypeName.Contains('.') ) {
$lastElement = $null
$qualifiedTypeName -split '\.' | foreach {
$lastElement = $_
if ( $prefix.length + 1 + $_.length -lt $qualifiedTypeName.length ) {
if ( $prefix.length -gt 0 ) {
$prefix += '.'
}
$prefix += "$_"
}
}
if ( $this.apiModels[$prefix] ) {
$namespace = $prefix
$lastElement
} elseif ( $this.aliases[$prefix] ) {
$namespace = $this.aliases[$prefix]
$lastElement
}
}
$nameResult = if ( $unqualified ) {
$unqualified
} elseif ( ! $onlyIfQualified ) {
$qualifiedTypeName
}
[PSCustomObject] @{
Namespace = $namespace
UnqualifiedName = $nameResult
}
}
function UnaliasQualifiedName($name) {
$nameInfo = ParseTypeName $name $true
if ( $nameInfo.namespace ) {
$nameInfo.namespace, $nameInfo.UnqualifiedName -join '.'
} else {
$name
}
}
function GetNamespaceAlias($namespace) {
$this.aliases[$namespace]
}
function __InitializeTypesOnDemand {
if ( ! $this.typeSchemas ) {
$this.typeSchemas = @{}
Write-Progress -id 1 -activity "Reading entity types"
foreach ( $model in $this.apiModels.Values ) {
if ( $model.Schema | gm EntityType -erroraction ignore ) {
$typeSchemas = $model.Schema.EntityType
$typeSchemas | foreach {
$qualifiedSchema = new-so QualifiedSchema EntityType $model.namespace $_.name $_
$this.typeSchemas.Add($qualifiedSchema.qualifiedName, $qualifiedSchema)
}
}
}
Write-Progress -id 1 -activity "Reading entity types" -completed
}
}
function __QualifySchemaClass($schemaClass, $namespace, $schemaContainer) {
if ( $schemaContainer | gm $schemaClass -erroraction ignore ) {
foreach ( $schemaElement in $schemaContainer.$schemaClass ) {
new-so QualifiedSchema $schemaClass $namespace $schemaElement.name $schemaElement
}
}
}
function __AddMethodBindingsFromMethodSchemas($methodSchemas, $methodType) {
if ( $methodSchemas ) {
# Assume that the first parameter is actually the binding parameter -- it is usually,
# but not always, named 'bindingParameter'
foreach ( $methodSchema in $methodSchemas ) {
$nativeSchema = $methodSchema.Schema
if ( ( $nativeSchema | gm parameter -erroraction ignore ) -and $nativeSchema.parameter) {
$bindingParameter = $nativeSchema.parameter | where name -eq 'bindingParameter' | select -first 1
if ( ! $bindingParameter ) {
$bindingParameter = $nativeSchema.parameter | select -first 1
}
if ( $bindingParameter ) {
__AddMethodBinding $bindingParameter.type $nativeSchema $methodType
}
}
}
}
}
function __AddMethodBinding($typeName, $methodSchema, $methodType) {
$unaliasedName = UnaliasQualifiedName $typeName
if ( $this.methodBindings[$unaliasedName] -eq $null ) {
$this.methodBindings[$unaliasedName] = @{Distinct=@{};All=@()}
}
# TODO: Understand this strange behavior seen in real metadata.
# This covers a strange case -- it turns out that in 2021-02-22,
# driveItem has not one, but two function elements for getactivitybyinterval.
# The only difference is that one has no parameters, the other one does.
# From documentation (https://docs.microsoft.com/en-us/graph/api/itemactivitystat-getactivitybyinterval?view=graph-rest-1.0&tabs=http),
# there is nothing special about this function that would warrant such an odd
# representation in the schema. The current theory is that the second instance,
# which is the one that has the parameters, is the "real" instance, the first
# is some strange schema generation artifact, possibly one that is ignored by
# Microsoft Graph in some sort of "last writer wins" behavior.
$this.methodBindings[$unaliasedName]['Distinct'][$methodSchema.Name] = @{Type=$methodType;Schema=$methodSchema}
$this.methodBindings[$unaliasedName]['All'] += @{Type=$methodType;Schema=$methodSchema}
}
}
| 36.993056 | 143 | 0.589638 |
18db6e36e6a1a3051b73899a0e20041ce306d8c7 | 1,055 | rs | Rust | build.rs | spacekookie/railcar | ef5918e21e7ad9ffd25c1a507df96458ec4e0c24 | [
"Apache-2.0"
] | 1,189 | 2017-06-29T17:00:10.000Z | 2022-03-26T16:09:46.000Z | build.rs | spacekookie/railcar | ef5918e21e7ad9ffd25c1a507df96458ec4e0c24 | [
"Apache-2.0"
] | 36 | 2017-06-29T20:28:11.000Z | 2020-01-08T17:28:39.000Z | build.rs | spacekookie/railcar | ef5918e21e7ad9ffd25c1a507df96458ec4e0c24 | [
"Apache-2.0"
] | 133 | 2017-06-29T22:20:31.000Z | 2022-03-29T14:05:43.000Z | use std::env;
use std::fs::File;
use std::io::Read;
use std::process::Command;
fn main() {
// static link the musl target
if env::var("TARGET").unwrap() == "x86_64-unknown-linux-musl" {
let mut cmd = Command::new("./build_seccomp.sh");
let output = cmd.output().expect("cmd failed to start");
if !output.status.success() {
println!(
"failed to build libseccomp:\n{}\n{}",
&std::str::from_utf8(&output.stdout).unwrap(),
&std::str::from_utf8(&output.stderr).unwrap()
);
let mut f = File::open("libseccomp/config.log").unwrap();
let mut result = String::new();
f.read_to_string(&mut result).unwrap();
println!{"{}", &result};
std::process::exit(1);
}
let pwd = std::env::var("PWD").unwrap();
let dir = format!("{}/libseccomp/src/.libs", pwd);
println!("cargo:rustc-link-search=native={}", dir);
println!("cargo:rustc-link-lib=static=seccomp");
}
}
| 35.166667 | 69 | 0.535545 |
3935a7987c499f20196a15d615654e9bfef5ded0 | 1,722 | py | Python | viz/grid.py | Unathi-Skosana/ptycho | 95e49a092d1212e2d02349ad4c50ea7db93e2687 | [
"MIT"
] | null | null | null | viz/grid.py | Unathi-Skosana/ptycho | 95e49a092d1212e2d02349ad4c50ea7db93e2687 | [
"MIT"
] | null | null | null | viz/grid.py | Unathi-Skosana/ptycho | 95e49a092d1212e2d02349ad4c50ea7db93e2687 | [
"MIT"
] | null | null | null | import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
import numpy as np
from skimage.io import imread
from skimage import img_as_float
plt.style.use("mint")
im1 = img_as_float(imread("./v10_obj_ampl.png", as_gray=True))
im2 = img_as_float(imread("./v10_obj_phase.png", as_gray=True))
im3 = img_as_float(imread("./v10_probe_ampl.png", as_gray=True))
im4 = img_as_float(imread("./v10_probe_phase.png", as_gray=True))
im5 = img_as_float(imread("./v30_obj_ampl.png", as_gray=True))
im6 = img_as_float(imread("./v30_obj_phase.png", as_gray=True))
im7 = img_as_float(imread("./v30_probe_ampl.png", as_gray=True))
im8 = img_as_float(imread("./v30_probe_phase.png", as_gray=True))
im9 = img_as_float(imread("./v50_obj_ampl.png", as_gray=True))
im10 = img_as_float(imread("./v50_obj_phase.png", as_gray=True))
im11 = img_as_float(imread("./v50_probe_ampl.png", as_gray=True))
im12 = img_as_float(imread("./v50_probe_phase.png", as_gray=True))
fig = plt.figure(figsize=(16, 16))
grid = ImageGrid(
fig,
111, # similar to subplot(111)
nrows_ncols=(2, 6), # creates 2x2 grid of axes
axes_pad=0.1, # pad between axes in inch.
)
i = 0
j = 0
for ax, im in zip(
grid, [im1, im2, im5, im6, im9, im10, im3, im4, im7, im8, im11, im12]
):
if i % 2 == 0 and i < 6:
if j == 0:
ax.set_title(r"$\nu = 0.1$", size=40, x=1.0)
if j == 1:
ax.set_title(r"$\nu = 0.3$", size=40, x=1.0)
if j == 2:
ax.set_title(r"$\nu = 0.5$", size=40, x=1.0)
j += 1
ax.set_axis_off()
ax.imshow(im, cmap="gray")
i += 1
fig.savefig('random_grid.png', bbox_inches='tight',
pad_inches=0, transparent=False)
plt.show()
| 33.115385 | 73 | 0.654472 |
2c346285e09f1464ebbbe52ab2be306c48f58e10 | 2,386 | py | Python | src/channels/twilio.py | SimplyVC/panic_polkadot | 2c5517b0e01e27d4c54dc6a6609699471b833746 | [
"Apache-2.0"
] | 41 | 2020-01-22T14:37:17.000Z | 2021-12-30T16:12:20.000Z | src/channels/twilio.py | SimplyVC/panic_polkadot | 2c5517b0e01e27d4c54dc6a6609699471b833746 | [
"Apache-2.0"
] | 33 | 2020-01-31T15:04:03.000Z | 2022-02-27T11:23:13.000Z | src/channels/twilio.py | SimplyVC/panic_polkadot | 2c5517b0e01e27d4c54dc6a6609699471b833746 | [
"Apache-2.0"
] | 9 | 2020-04-16T07:59:03.000Z | 2021-10-09T04:35:35.000Z | import logging
from typing import Optional, List
from src.alerts.alerts import Alert, \
ProblemWhenCheckingIfCallsAreSnoozedAlert, ProblemWhenDialingNumberAlert
from src.channels.channel import Channel, ChannelSet
from src.store.redis.redis_api import RedisApi
from src.store.store_keys import Keys
from src.utils.alert_utils.twilio_api import TwilioApi
class TwilioChannel(Channel):
def __init__(self, channel_name: str, logger: logging.Logger,
redis: Optional[RedisApi], twilio: TwilioApi,
call_from: str, call_to: List[str], twiml: str,
twiml_is_url: bool, backup_channels: ChannelSet) -> None:
super().__init__(channel_name, logger, redis)
self._twilio = twilio
self._call_from = call_from
self._call_to = call_to
self._twiml = twiml
self._twiml_is_url = twiml_is_url
self._backup_channels = backup_channels
def _calls_snoozed(self, logger: logging.Logger) \
-> bool:
if self.redis_enabled:
key = Keys.get_twilio_snooze()
if self.redis.exists(key):
snooze_until = self.redis.get(key).decode("utf-8")
logger.info('Tried to call but calls are snoozed until {}.'
''.format(snooze_until))
return True
else:
logger.info('Twilio did not find a snooze in Redis.')
return False
def alert_critical(self, alert: Alert) -> None:
# Check if snoozed
try:
snoozed = self._calls_snoozed(self.logger)
except Exception as e:
self._backup_channels.alert_error(
ProblemWhenCheckingIfCallsAreSnoozedAlert())
self.logger.error(
'Error when checking if Twilio calls are snoozed: %s.', e)
snoozed = False
# Dial the numbers if not snoozed
if not snoozed:
for number in self._call_to:
self.logger.info("Twilio now dialing " + number)
try:
self._twilio.dial_number(self._call_from, number,
self._twiml, self._twiml_is_url)
except Exception as e:
self._backup_channels.alert_error(
ProblemWhenDialingNumberAlert(number, e))
| 39.114754 | 77 | 0.603521 |
da0676360548ed0c4f0bcf55acf745584d83cefa | 4,991 | rb | Ruby | spec/core/file/shared/fnmatch.rb | tqrg-bot/rubinius | beb0fe3968ea7ff3c09e192605eef066136105c8 | [
"BSD-3-Clause"
] | null | null | null | spec/core/file/shared/fnmatch.rb | tqrg-bot/rubinius | beb0fe3968ea7ff3c09e192605eef066136105c8 | [
"BSD-3-Clause"
] | null | null | null | spec/core/file/shared/fnmatch.rb | tqrg-bot/rubinius | beb0fe3968ea7ff3c09e192605eef066136105c8 | [
"BSD-3-Clause"
] | null | null | null | shared :file_fnmatch do |cmd|
describe "File.#{cmd}" do
it "matches entire strings" do
File.send(cmd, 'cat', 'cat').should == true
end
it "does not match partial strings" do
File.send(cmd, 'cat', 'category').should == false
end
it "does not support { } patterns" do
File.send(cmd, 'c{at,ub}s', 'cats').should == false
File.send(cmd, 'c{at,ub}s', 'c{at,ub}s').should == true
end
it "matches a single character for each ? character" do
File.send(cmd, 'c?t', 'cat').should == true
File.send(cmd, 'c??t', 'cat').should == false
end
it "matches zero or more characters for each * character" do
File.send(cmd, 'c*', 'cats').should == true
File.send(cmd, 'c*t', 'c/a/b/t').should == true
end
it "matches ranges of characters using bracket expresions (e.g. [a-z])" do
File.send(cmd, 'ca[a-z]', 'cat').should == true
end
it "does not match characters outside of the range of the bracket expresion" do
File.send(cmd, 'ca[x-z]', 'cat').should == false
end
it "matches ranges of characters using exclusive bracket expresions (e.g. [^t] or [!t])" do
File.send(cmd, 'ca[^t]', 'cat').should == false
File.send(cmd, 'ca[!t]', 'cat').should == false
end
it "matches characters with a case sensitive comparison" do
File.send(cmd, 'cat', 'CAT').should == false
end
it "matches characters with case insensitive comparison when flags includes FNM_CASEFOLD" do
File.send(cmd, 'cat', 'CAT', File::FNM_CASEFOLD).should == true
end
it "does not match '/' characters with ? or * when flags includes FNM_PATHNAME" do
File.send(cmd, '?', '/', File::FNM_PATHNAME).should == false
File.send(cmd, '*', '/', File::FNM_PATHNAME).should == false
end
it "does not match '/' characters inside bracket expressions when flags includes FNM_PATHNAME" do
File.send(cmd, '[/]', '/', File::FNM_PATHNAME).should == false
end
it "matches literal ? or * in path when pattern includes \\? or \\*" do
File.send(cmd, '\?', '?').should == true
File.send(cmd, '\*', '*').should == true
end
it "matches literal character (e.g. 'a') in path when pattern includes escaped character (e.g. \\a)" do
File.send(cmd, '\a', 'a').should == true
File.send(cmd, 'this\b', 'thisb').should == true
end
it "matches '\\' characters in path when flags includes FNM_NOESACPE" do
File.send(cmd, '\a', '\a', File::FNM_NOESCAPE).should == true
File.send(cmd, '\a', 'a', File::FNM_NOESCAPE).should == false
end
it "escapes special characters inside bracket expression" do
File.send(cmd, '[\?]', '?').should == true
File.send(cmd, '[\*]', '*').should == true
end
it "does not match leading periods in filenames with wildcards by default" do
File.send(cmd, '*', '.profile').should == false
File.send(cmd, '*', 'home/.profile').should == true
File.send(cmd, '*/*', 'home/.profile').should == true
File.send(cmd, '*/*', 'dave/.profile', File::FNM_PATHNAME).should == false
File.send(cmd, '.*', '.profile').should == true
end
it "matches leading periods in filenames when flags includes FNM_DOTMATCH" do
File.send(cmd, '*', '.profile', File::FNM_DOTMATCH).should == true
File.send(cmd, '*', 'home/.profile', File::FNM_DOTMATCH).should == true
end
it "matches multiple directories with ** and *" do
files = '**/*.rb'
File.send(cmd, files, 'main.rb').should == false
File.send(cmd, files, './main.rb').should == false
File.send(cmd, files, 'lib/song.rb').should == true
File.send(cmd, '**.rb', 'main.rb').should == true
File.send(cmd, '**.rb', './main.rb').should == false
File.send(cmd, '**.rb', 'lib/song.rb').should == true
File.send(cmd, '*', 'dave/.profile').should == true
end
it "requires that '/' characters in pattern match '/' characters in path when flags includes FNM_PATHNAME" do
pattern = '*/*'
File.send(cmd, pattern, 'dave/.profile', File::FNM_PATHNAME)
File.send(cmd, pattern, 'dave/.profile', File::FNM_PATHNAME | File::FNM_DOTMATCH)
pattern = '**/foo'
File.send(cmd, pattern, 'a/b/c/foo', File::FNM_PATHNAME)
File.send(cmd, pattern, '/a/b/c/foo', File::FNM_PATHNAME)
File.send(cmd, pattern, 'c:/a/b/c/foo', File::FNM_PATHNAME)
File.send(cmd, pattern, 'a/.b/c/foo', File::FNM_PATHNAME)
File.send(cmd, pattern, 'a/.b/c/foo', File::FNM_PATHNAME | File::FNM_DOTMATCH)
end
it "raises a TypeError if the first and second arguments are not string-like" do
should_raise(ArgumentError){ File.send(cmd, @path1, @path1, 0, 0) }
should_raise(TypeError){ File.send(cmd, 1, 'some/thing') }
should_raise(TypeError){ File.send(cmd, 'some/thing', 1) }
should_raise(TypeError){ File.send(cmd, 1, 1) }
end
end
end
| 41.247934 | 113 | 0.604889 |
385719a0fad54454237a7cbbb4713b1ae21743c6 | 75 | php | PHP | application/views/templates/echojson.php | abinj30/sales-dashboard | a565016ed4b11efc8370d1e0047a1ab69eb81583 | [
"Apache-2.0"
] | null | null | null | application/views/templates/echojson.php | abinj30/sales-dashboard | a565016ed4b11efc8370d1e0047a1ab69eb81583 | [
"Apache-2.0"
] | null | null | null | application/views/templates/echojson.php | abinj30/sales-dashboard | a565016ed4b11efc8370d1e0047a1ab69eb81583 | [
"Apache-2.0"
] | 2 | 2020-02-04T03:45:06.000Z | 2020-03-06T16:59:58.000Z | <?php
header('Content-type: application/json');
echo json_encode($data);
?> | 18.75 | 41 | 0.72 |
907fdd07414f454a4cd851e99202693d9d2cabee | 3,465 | dart | Dart | direct_test/header_parser_kickstart/parse_header_now.dart | jpedrosa/arpoador | e2fcc05f7cf922cb48e116fd9b3a23437524e8a6 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | null | null | null | direct_test/header_parser_kickstart/parse_header_now.dart | jpedrosa/arpoador | e2fcc05f7cf922cb48e116fd9b3a23437524e8a6 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | null | null | null | direct_test/header_parser_kickstart/parse_header_now.dart | jpedrosa/arpoador | e2fcc05f7cf922cb48e116fd9b3a23437524e8a6 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | null | null | null | import "../../lib/header_parser.dart";
import "../../lib/lang.dart";
genSample1() {
var s = """
GET /yes HTTP/1.1
Host: 127.0.0.1:8777
Connection: keep-alive
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/41.0.2272.76 Chrome/41.0.2272.76 Safari/537.36
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,pt-BR;q=0.6,pt;q=0.4
Cookie: GUID=QQ4Kwq0VRYGIJNsEduoX; sessions=%7B%7D
""";
return [71, 69, 84, 32, 47, 121, 101, 115, 32, 72, 84, 84, 80, 47, 49, 46, 49,
13, 10, 72, 111, 115, 116, 58, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 58, 56,
55, 55, 55, 13, 10, 67, 111, 110, 110, 101, 99, 116, 105, 111, 110, 58, 32,
107, 101, 101, 112, 45, 97, 108, 105, 118, 101, 13, 10, 65, 99, 99, 101,
112, 116, 58, 32, 116, 101, 120, 116, 47, 104, 116, 109, 108, 44, 97, 112,
112, 108, 105, 99, 97, 116, 105, 111, 110, 47, 120, 104, 116, 109, 108, 43,
120, 109, 108, 44, 97, 112, 112, 108, 105, 99, 97, 116, 105, 111, 110, 47,
120, 109, 108, 59, 113, 61, 48, 46, 57, 44, 105, 109, 97, 103, 101, 47,
119, 101, 98, 112, 44, 42, 47, 42, 59, 113, 61, 48, 46, 56, 13, 10, 85,
115, 101, 114, 45, 65, 103, 101, 110, 116, 58, 32, 77, 111, 122, 105,
108, 108, 97, 47, 53, 46, 48, 32, 40, 88, 49, 49, 59, 32, 76, 105, 110,
117, 120, 32, 120, 56, 54, 95, 54, 52, 41, 32, 65, 112, 112, 108, 101,
87, 101, 98, 75, 105, 116, 47, 53, 51, 55, 46, 51, 54, 32, 40, 75, 72, 84,
77, 76, 44, 32, 108, 105, 107, 101, 32, 71, 101, 99, 107, 111, 41, 32, 85,
98, 117, 110, 116, 117, 32, 67, 104, 114, 111, 109, 105, 117, 109, 47, 52,
49, 46, 48, 46, 50, 50, 55, 50, 46, 55, 54, 32, 67, 104, 114, 111, 109, 101,
47, 52, 49, 46, 48, 46, 50, 50, 55, 50, 46, 55, 54, 32, 83, 97, 102, 97, 114,
105, 47, 53, 51, 55, 46, 51, 54, 13, 10, 65, 99, 99, 101, 112, 116, 45, 69,
110, 99, 111, 100, 105, 110, 103, 58, 32, 103, 122, 105, 112, 44, 32, 100,
101, 102, 108, 97, 116, 101, 44, 32, 115, 100, 99, 104, 13, 10, 65, 99, 99,
101, 112, 116, 45, 76, 97, 110, 103, 117, 97, 103, 101, 58, 32, 101, 110, 45,
85, 83, 44, 101, 110, 59, 113, 61, 48, 46, 56, 44, 112, 116, 45, 66, 82, 59,
113, 61, 48, 46, 54, 44, 112, 116, 59, 113, 61, 48, 46, 52, 13, 10, 67, 111,
111, 107, 105, 101, 58, 32, 71, 85, 73, 68, 61, 81, 81, 52, 75, 119, 113, 48,
86, 82, 89, 71, 73, 74, 78, 115, 69, 100, 117, 111, 88, 59, 32, 115, 101,
115, 115, 105, 111, 110, 115, 61, 37, 55, 66, 37, 55, 68, 13, 10, 13, 10];
}
genSample10() {
var s = """
GET /yes HTTP/1.1
""";
return [71, 69, 84, 32, 47, 121, 101, 115, 32, 72, 84, 84, 80, 47, 49, 46, 49,
13, 10];
}
genSample20() {
var s = """
GET /yes HTTP/1.1
Host: 127.0.0.1:8777
""";
return [71, 69, 84, 32, 47, 121, 101, 115, 32, 72, 84, 84, 80, 47, 49, 46, 49,
13, 10, 72, 111, 115, 116, 58, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 58, 56,
55, 55, 55, 13, 10];
}
genSample30() {
var s = """
GET /yes HTTP/1.1
Host: 127.0.0.1:8777
Connection: keep-alive
""";
return [71, 69, 84, 32, 47, 121, 101, 115, 32, 72, 84, 84, 80, 47, 49, 46, 49,
13, 10, 72, 111, 115, 116, 58, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 58, 56,
55, 55, 55, 13, 10, 67, 111, 110, 110, 101, 99, 116, 105, 111, 110, 58, 32,
107, 101, 101, 112, 45, 97, 108, 105, 118, 101, 13, 10];
}
main() {
p("hey");
var parser = new HeaderParser();
parser.parse(genSample1());
p(["header", parser.header]);
}
| 41.25 | 145 | 0.562482 |
1badb3ae8c86dd857deb350fd3674516ba7e0baa | 781 | swift | Swift | ParallaxPagingViewController/Sources/ParallaxViewController.swift | tomokitakahashi/ParallaxPagingViewController | b33209bf3b89049dfa0b603a23154d7f5bcc6de6 | [
"MIT"
] | 18 | 2017-07-11T02:33:51.000Z | 2021-08-03T03:39:46.000Z | ParallaxPagingViewController/Sources/ParallaxViewController.swift | tomokitakahashi/ParallaxPagingViewController | b33209bf3b89049dfa0b603a23154d7f5bcc6de6 | [
"MIT"
] | 1 | 2019-01-23T07:48:08.000Z | 2019-01-23T13:31:45.000Z | ParallaxPagingViewController/Sources/ParallaxViewController.swift | tomokitakahashi/ParallaxPagingViewController | b33209bf3b89049dfa0b603a23154d7f5bcc6de6 | [
"MIT"
] | null | null | null | //
// ParallaxViewController.swift
// ParallaxPagingViewController
//
// Created by takahashi tomoki on 2017/07/05.
// Copyright © 2017年 TomokiTakahashi. All rights reserved.
//
import UIKit
open class ParallaxViewController: UIViewController {
open var backgroundView = ParallaxView()
@IBInspectable
open var parallaxImage: UIImage? {
didSet {
backgroundView.parallaxImage = parallaxImage
}
}
open override func viewDidLoad() {
super.viewDidLoad()
backgroundView.frame = view.bounds
view.addSubview(backgroundView)
// For xib & storyboard
view.sendSubview(toBack: backgroundView)
view.subviews.forEach{ $0.bringSubview(toFront: backgroundView) }
}
}
| 24.40625 | 73 | 0.660691 |
f7a4b046651341846eade1d20b786de9881ad7c2 | 373 | rb | Ruby | spec/moby_spec.rb | drichert/moby | 7fcbcaf0816832d0b0da0547204dea68cc1dcab9 | [
"MIT"
] | 9 | 2015-07-27T15:22:45.000Z | 2017-09-04T06:19:41.000Z | spec/moby_spec.rb | drichert/moby | 7fcbcaf0816832d0b0da0547204dea68cc1dcab9 | [
"MIT"
] | null | null | null | spec/moby_spec.rb | drichert/moby | 7fcbcaf0816832d0b0da0547204dea68cc1dcab9 | [
"MIT"
] | null | null | null | require 'spec_helper'
describe Moby do
describe "::VERSION" do
it "should be a valid SemVer string" do
Moby::VERSION.should match(/^(\d+\.){2}\d+([a-z](\w+)?)?$/)
end
end
describe "::base_path" do
it "should return the absolute root path of the application" do
Moby::base_path.should == File.expand_path("../..", __FILE__)
end
end
end
| 23.3125 | 67 | 0.627346 |
6a8bd6f623f6cc546b99b6c0059d3ea8f8ba7d0b | 2,654 | ps1 | PowerShell | ImageCreation/Scripts/InstallSoftware.ps1 | falldamagestudio/UE4-GHA-BuildAgent | 643013167fe82181a726447aed6f196b7d61904f | [
"MIT"
] | 1 | 2021-01-22T14:28:16.000Z | 2021-01-22T14:28:16.000Z | ImageCreation/Scripts/InstallSoftware.ps1 | falldamagestudio/UE4-GHA-BuildAgent | 643013167fe82181a726447aed6f196b7d61904f | [
"MIT"
] | 9 | 2020-06-03T15:59:25.000Z | 2021-07-13T10:45:47.000Z | ImageCreation/Scripts/InstallSoftware.ps1 | falldamagestudio/UE4-GHA-BuildAgent | 643013167fe82181a726447aed6f196b7d61904f | [
"MIT"
] | 2 | 2020-06-01T14:59:31.000Z | 2020-12-02T08:47:01.000Z | . ${PSScriptRoot}\..\Tools\Scripts\Enable-Win32LongPaths.ps1
. ${PSScriptRoot}\..\Tools\Scripts\Install-GitHubActionsRunner.ps1
. ${PSScriptRoot}\..\Tools\Scripts\Add-WindowsDefenderExclusionRule.ps1
. ${PSScriptRoot}\..\Tools\Scripts\Install-Git.ps1
. ${PSScriptRoot}\..\Tools\Scripts\Install-VisualStudioBuildTools.ps1
. ${PSScriptRoot}\..\Tools\Scripts\Install-DebuggingToolsForWindows.ps1
. ${PSScriptRoot}\..\Tools\Scripts\Install-DirectXRedistributable.ps1
. ${PSScriptRoot}\..\Tools\Scripts\Install-GCELoggingAgent.ps1
. ${PSScriptRoot}\..\Tools\Scripts\Install-GitHubActionsLoggingSourceForGCELoggingAgent.ps1
$GitHubActionsInstallationFolder = "C:\A"
$ToolsAndVersions = Import-PowerShellDataFile ${PSScriptRoot}\ToolsAndVersions.psd1 -ErrorAction Stop
Write-Host "Enabling Win32 Long Paths..."
Enable-Win32LongPaths
Write-Host "Installing GitHub Actions runner..."
Install-GitHubActionsRunner -RunnerDownloadURI $ToolsAndVersions.GitHubActionsRunnerDownloadURI -InstallationFolder $GitHubActionsInstallationFolder
Write-Host "Adding Windows Defender exclusion rule for Github Actions runner folder..."
Add-WindowsDefenderExclusionRule -Folder $GitHubActionsInstallationFolder
Write-Host "Installing Git for Windows..."
Install-Git -InstallerDownloadURI $ToolsAndVersions.GitForWindowsDownloadURI
Write-Host "Installing Visual Studio Build Tools..."
Install-VisualStudioBuildTools -InstallerDownloadURI $ToolsAndVersions.VisualStudioBuildToolsDownloadURI -WorkloadsAndComponents $ToolsAndVersions.VisualStudioBuildTools_WorkloadsAndComponents
Write-Host "Installing Debugging Tools for Windows..."
# This provides PDBCOPY.EXE which is used when packaging up the Engine
Install-DebuggingToolsForWindows -InstallerDownloadURI $ToolsAndVersions.WindowsSDKDownloadURI
Write-Host "Installing DirectX Redistributable..."
# This provides XINPUT1_3.DLL which is used when running the C++ apps (UE4Editor-Cmd.exe for example), even in headless mode
Install-DirectXRedistributable -InstallerDownloadURI $ToolsAndVersions.DirectXEndUserRuntimeWebInstallerDownloadURI
Write-Host "Installing GCE Logging Agent..."
# This will provide the basic forwarding of logs to GCP Logging, and send various Windows Event log activity there
Install-GCELoggingAgent -InstallerDownloadURI $ToolsAndVersions.GCELoggingAgentInstallerDownloadURI
Write-Host "Installing forwarding of GitHubActions Runner logs to GCP Logging..."
# This will capture GitHub Actions runner output and send it to GCP Logging
Install-GitHubActionsLoggingSourceForGCELoggingAgent -GitHubActionsRunnerInstallationFolder $GitHubActionsInstallationFolder
Write-Host "Done."
| 42.806452 | 192 | 0.834966 |
386198da674b579637e94115f8783b771b2f328f | 1,440 | cs | C# | Assets/SeeThru/Editor/SeeThru/Menu/SeeThruMenuItems.cs | movitto/seethru-documentation | 8a97a308f05b1ff309a9b0d51bbfd8fe8a9f8557 | [
"MIT"
] | 2 | 2021-04-05T14:24:10.000Z | 2021-10-30T16:19:10.000Z | Assets/SeeThru/Editor/SeeThru/Menu/SeeThruMenuItems.cs | movitto/seethru-documentation | 8a97a308f05b1ff309a9b0d51bbfd8fe8a9f8557 | [
"MIT"
] | 1 | 2021-10-30T22:54:30.000Z | 2021-10-31T16:41:02.000Z | Assets/SeeThru/Editor/SeeThru/Menu/SeeThruMenuItems.cs | movitto/seethru-documentation | 8a97a308f05b1ff309a9b0d51bbfd8fe8a9f8557 | [
"MIT"
] | 1 | 2021-10-30T16:20:40.000Z | 2021-10-30T16:20:40.000Z | // SeeThru © Dynamic Realities - https://twitter.com/DynRealities
// Documentation: https://github.com/dynamicrealities/seethru-documentation/wiki
using SeeThru.Cameras;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEditor;
using UnityEngine;
namespace SeeThru.Menu
{
public class SeeThruMenuItems
{
[MenuItem("GameObject/SeeThru/Free Flying Camera", false, 12)]
private static void CreateNewFreeFlyingCamera()
{
EditorUtility.CreateGameObjectWithHideFlags("FreeFlyingCamera", HideFlags.None, typeof(FreeFlyingCamera));
}
[MenuItem("GameObject/SeeThru/Target Framing Camera", false, 13)]
private static void CreateNewTargetFramingCamera()
{
EditorUtility.CreateGameObjectWithHideFlags("TargetFramingCamera", HideFlags.None, typeof(TargetFramingCamera));
}
[MenuItem("GameObject/SeeThru/Orbiting Camera", false, 14)]
private static void CreateNewOrbitingCamera()
{
EditorUtility.CreateGameObjectWithHideFlags("OrbitingCamera", HideFlags.None, typeof(OrbitingCamera));
}
[MenuItem("GameObject/SeeThru/RTS Camera", false, 15)]
private static void CreateNewRTSCamera()
{
EditorUtility.CreateGameObjectWithHideFlags("RTSCamera", HideFlags.None, typeof(RTSCamera));
}
}
} | 35.121951 | 124 | 0.706944 |
c5ed1985ee024535a07988b1867bae1c5e5d5479 | 4,744 | swift | Swift | DSFFinderLabels/ui/DSFFinderColorGridView.swift | dagronf/DSFFinderLabels | e1818fd02bec509fb36716a2587cbc6885380949 | [
"MIT"
] | 3 | 2020-05-11T15:13:51.000Z | 2021-06-19T17:29:07.000Z | DSFFinderLabels/ui/DSFFinderColorGridView.swift | dagronf/DSFFinderLabels | e1818fd02bec509fb36716a2587cbc6885380949 | [
"MIT"
] | null | null | null | DSFFinderLabels/ui/DSFFinderColorGridView.swift | dagronf/DSFFinderLabels | e1818fd02bec509fb36716a2587cbc6885380949 | [
"MIT"
] | 1 | 2020-03-09T13:14:05.000Z | 2020-03-09T13:14:05.000Z | //
// CircleColorButton.swift
// DSFFinderLabelsDemo
//
// Created by Darren Ford on 8/2/19.
// Copyright © 2019 Darren Ford. All rights reserved.
//
import Cocoa
/// Delegate protocol for users of the DSFFinderColorGridView
public protocol DSFFinderColorGridViewProtocol {
/// Called when the selection changes
func selectionChanged(colorIndexes: Set<DSFFinderLabels.ColorIndex>)
}
/// A view class for displaying and selecting finder colors
@objc open class DSFFinderColorGridView: NSView {
/// The Finder's colors
private static let FinderColors = DSFFinderLabels.FinderColors.colors
private var colorButtons = [DSFFinderColorCircleButton]()
private let grid = NSGridView()
private let buttonSize: CGFloat = 24
/// Delegate for notifying back when selections change
public var selectionDelegate: DSFFinderColorGridViewProtocol?
/// The colors currently selected in the control
public var selectedColors: [DSFFinderLabels.ColorIndex] {
return self.colorButtons
.filter({ $0.state == .on })
.compactMap { DSFFinderLabels.ColorIndex(rawValue: $0.tag) }
}
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
self.setup()
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
self.setup()
}
private func setup() {
self.translatesAutoresizingMaskIntoConstraints = false
self.colorButtons = self.finderColorButtons()
self.grid.translatesAutoresizingMaskIntoConstraints = false
self.grid.addRow(with: self.colorButtons)
self.grid.columnSpacing = 0
self.grid.setContentCompressionResistancePriority(.required, for: .horizontal)
self.grid.setContentCompressionResistancePriority(.required, for: .vertical)
self.grid.setContentHuggingPriority(.required, for: .horizontal)
self.grid.setContentHuggingPriority(.required, for: .vertical)
self.addSubview(self.grid)
self.addConstraints([
NSLayoutConstraint(item: self.grid, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 0),
NSLayoutConstraint(item: self.grid, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: 0),
NSLayoutConstraint(item: self.grid, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0),
NSLayoutConstraint(item: self.grid, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0),
NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: self.colorButtons[0].frame.height)
])
self.needsLayout = true
}
open override func prepareForInterfaceBuilder() {
self.setup()
self.reset()
self.needsLayout = true
//super.prepareForInterfaceBuilder()
}
/// Unselect all of the colors in the control
public func reset() {
self.setSelected(colors: [])
}
/// Set the colors to be selected within the control
///
/// - Parameter colors: The array of colors to set
public func setSelected(colors: [DSFFinderLabels.ColorIndex]) {
self.colorButtons.forEach {
if let which = DSFFinderLabels.ColorIndex(rawValue: $0.tag) {
let isSet = colors.contains(which)
$0.state = isSet ? .on : .off
}
}
}
@objc private func selectedButton(_ sender: DSFFinderColorCircleButton) {
if sender.tag == DSFFinderLabels.ColorIndex.none.rawValue {
self.reset()
}
// Tell our delegate when the change occurs
self.selectionDelegate?.selectionChanged(colorIndexes: Set(self.selectedColors))
}
private func finderColorButtons() -> [DSFFinderColorCircleButton] {
var arr = [DSFFinderColorCircleButton]()
for color in DSFFinderLabels.FinderColors.colorsRainbowOrdered {
let button = DSFFinderColorCircleButton(frame: NSRect(x: 0, y: 0, width: buttonSize, height: buttonSize))
button.translatesAutoresizingMaskIntoConstraints = false
button.isBordered = false
button.title = ""
button.bezelStyle = .shadowlessSquare
button.setButtonType(.toggle)
button.addConstraints([
NSLayoutConstraint(item: button, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: buttonSize),
NSLayoutConstraint(item: button, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: buttonSize)
])
if color.index != .none {
button.drawColor = color.color
}
else {
button.image = NSImage.init(named: NSImage.removeTemplateName)
}
button.tag = color.index.rawValue
button.setAccessibilityLabel(color.label)
button.toolTip = color.label
button.target = self
button.action = #selector(DSFFinderColorGridView.selectedButton(_:))
arr.append(button)
}
return arr
}
}
| 33.885714 | 165 | 0.744309 |
541e57364b0530b2c9537b01dd24ee114910cfef | 4,434 | css | CSS | public/vendor/wRunner/themes/wrunner-default-theme.css | super1114/Video-editor | 15bf4013a99d5729361437f54a9ad2023c567593 | [
"MIT"
] | null | null | null | public/vendor/wRunner/themes/wrunner-default-theme.css | super1114/Video-editor | 15bf4013a99d5729361437f54a9ad2023c567593 | [
"MIT"
] | null | null | null | public/vendor/wRunner/themes/wrunner-default-theme.css | super1114/Video-editor | 15bf4013a99d5729361437f54a9ad2023c567593 | [
"MIT"
] | null | null | null | .wrunner_theme_default.wrunner_direction_horizontal {
width: 100%;
padding-left: 0.625rem;
padding-right: 0.625rem;
box-sizing: border-box;
}
.wrunner_theme_default.wrunner_direction_vertical {
height: 100%;
width: max-content;
padding-top: 0.625rem;
padding-bottom: 0.625rem;
box-sizing: border-box;
}
.wrunner__outer_theme_default.wrunner__outer {
position: relative;
padding-top: 0.1px;
}
.wrunner__outer_theme_default.wrunner__outer_direction_horizontal {
height: 4rem;
width: 100%;
}
.wrunner__outer_theme_default.wrunner__outer_direction_vertical {
height: 100%;
width: 5.5rem;
min-height: 10rem;
}
.wrunner__scale-divisions-block_theme_default.wrunner__scale-divisions-block {
position: absolute;
display: flex;
}
.wrunner__scale-divisions-block_theme_default.wrunner__scale-divisions-block_direction_horizontal {
top: 3.5rem;
width: 100%;
justify-content: space-between;
}
.wrunner__scale-divisions-block_theme_default.wrunner__scale-divisions-block_direction_vertical {
height: 100%;
width: 0.5rem;
left: 0;
justify-content: space-between;
flex-direction: column;
}
.wrunner__scale-division_theme_default.wrunner__scale-division {
background-color: #cb73a4;
}
.wrunner__scale-division_theme_default.wrunner__scale-division_direction_horizontal {
height: 0.5rem;
width: 0.1rem;
}
.wrunner__scale-division_theme_default.wrunner__scale-division_direction_vertical {
height: 0.1rem;
width: 0.5rem;
}
.wrunner__handle_theme_default.wrunner__handle {
position: absolute;
height: 1.25rem;
width: 1.25rem;
border-radius: 40%;
background-color: #cf579a;
transition-duration: 0.2s;
transition-property: transform, background-color, border-radius;
cursor: pointer;
z-index: 1;
}
.wrunner__handle_theme_default.wrunner__handle:hover {
transform: scale(1.1);
border-radius: 50%;
background-color: #c54a8e;
}
.wrunner__handle_theme_default.wrunner__handle:active {
transform: scale(0.9);
border-radius: 50%;
background-color: #aa3d9c;
}
.wrunner__handle_theme_default.wrunner__handle_direction_vertical {
margin-top: -0.6rem;
margin-left: -0.4rem;
}
.wrunner__handle_theme_default.wrunner__handle_direction_horizontal {
margin-top: -0.35rem;
margin-left: -0.6rem;
}
.wrunner__track_theme_default.wrunner__track {
position: absolute;
background-color: rgba(205,205,205,0.75);
border-radius: 0.25rem;
cursor: pointer;
}
.wrunner__track_theme_default.wrunner__track_direction_horizontal {
height: 0.5rem;
width: 100%;
top: 2.3rem;
}
.wrunner__track_theme_default.wrunner__track_direction_vertical {
height: 100%;
width: 0.5rem;
left: 1.2rem;
}
.wrunner__progress_theme_default.wrunner__progress {
position: absolute;
background-color: #cb73a4;
border-radius: 0.25rem;
}
.wrunner__progress_theme_default.wrunner__progress_direction_horizontal {
height: 100%;
}
.wrunner__progress_theme_default.wrunner__progress_direction_vertical {
width: 100%;
bottom: 0;
}
.wrunner__value-note_theme_default.wrunner__value-note {
position: absolute;
padding: 0.35rem;
background-color: #c54a8e;
text-align: center;
color: #fff;
font-size: 0.75rem;
font-family: lato;
font-weight: 900;
cursor: default;
transition: 0.2s opacity;
display: flex;
white-space: pre;
}
.wrunner__value-note_theme_default.wrunner__value-note::after {
content: '';
position: absolute;
display: block;
height: 0;
width: 0;
}
.wrunner__value-note_theme_default.wrunner__value-note_direction_horizontal {
top: 0;
min-width: 1.5rem;
border-radius: 0.8rem 0.3rem 0.8rem 0.3rem;
justify-content: center;
}
.wrunner__value-note_theme_default.wrunner__value-note_direction_horizontal::after {
left: 50%;
margin-left: -0.25rem;
bottom: -0.5rem;
border: 0.25rem solid transparent;
border-top-color: #c54a8e;
}
.wrunner__value-note_theme_default.wrunner__value-note_direction_vertical {
left: 2.4rem;
min-width: 1.5rem;
border-radius: 0.3rem 0.7rem 0.3rem 0.7rem;
justify-content: center;
flex-direction: column;
}
.wrunner__value-note_theme_default.wrunner__value-note_direction_vertical::after {
top: 50%;
margin-top: -0.25rem;
left: -0.5rem;
border: 0.25rem solid transparent;
border-right-color: #c54a8e;
}
.wrunner__value-note_theme_default.wrunner__value-note_display_hidden {
opacity: 0;
}
.wrunner__value-note_theme_default.wrunner__value-note_display_visible {
opacity: 1;
}
| 26.710843 | 99 | 0.7659 |
57e614bc454d8e6ee755470ef1e051d1399c7914 | 1,892 | php | PHP | web/app/plugins/multi-step-form/includes/admin/partials/msf-plus-notice.php | kzachos/dr-rossa-kollegen | 7e440acc6f12afec16b6c8df02d4355e2ae61bf5 | [
"MIT"
] | null | null | null | web/app/plugins/multi-step-form/includes/admin/partials/msf-plus-notice.php | kzachos/dr-rossa-kollegen | 7e440acc6f12afec16b6c8df02d4355e2ae61bf5 | [
"MIT"
] | null | null | null | web/app/plugins/multi-step-form/includes/admin/partials/msf-plus-notice.php | kzachos/dr-rossa-kollegen | 7e440acc6f12afec16b6c8df02d4355e2ae61bf5 | [
"MIT"
] | null | null | null | <?php
if (!defined('ABSPATH')) exit;
?>
<style>
.wrap {
width: 75%;
float: left;
margin-right: 0px;
}
#msf-sidebar-container {
width: 260px;
padding: 0 0 0 30px;
float: left;
width: 20%;
margin-top: 20px;
}
#sidebar {
padding: 10px 15px 20px 15px;
background:#fff;
box-sizing: border-box;
border: 1px solid #ddd;
}
#sidebar h2 {
font-size: 22px;
font-weight: 400;
margin: 10px 0px 20px 0px;
color:#00b0a4;
}
#sidebar h4 {
margin: 20px 0px 0px 0px;
color:#ff6d00;
}
#sidebar p {
color:#777;
margin: 0px 0px 20px 0px;
}
img {
width: 100%;
height: auto;
}
</style>
<div class="msf_content_cell" id="msf-sidebar-container">
<div id="sidebar">
<div>
<h2>Multi Step Form Plus</h2>
<h4>Up to 10 steps</h4>
<p>
You can now divide your form in up to 10 Steps.
</p>
<h4>Save and export Form Data</h4>
<p>
With PLUS, you can save filled forms in the database and export them as CSV
</p>
<h4>Conditional fields</h4>
<p>
You want to bring more flexibility into your forms? Use conditional fields.
</p>
<p>
<a href="https://mondula.com/multi-step-form-plus/" target="_blank">
<img src="<?php echo plugins_url('assets/images/msf_plus_extension.png', dirname(__FILE__)) ?>" alt="MSF Plus">
</a>
</p>
<p>
<a class="button button-primary" href="https://mondula.com/multi-step-form-plus/" target="_blank">Get Multi Step Form Plus</a>
</p>
</div>
</div>
</div>
| 24.894737 | 142 | 0.487315 |
06a74f6300be484ea8a59e270aee6dfba6ab251b | 1,712 | css | CSS | frontend/styles/index.css | RutyRibeiro/chaDeCozinha | 03f617e7211a9ddb861e87306b828408cea023c2 | [
"MIT"
] | null | null | null | frontend/styles/index.css | RutyRibeiro/chaDeCozinha | 03f617e7211a9ddb861e87306b828408cea023c2 | [
"MIT"
] | null | null | null | frontend/styles/index.css | RutyRibeiro/chaDeCozinha | 03f617e7211a9ddb861e87306b828408cea023c2 | [
"MIT"
] | null | null | null | .container-items {
position: relative;
}
.container-info {
margin-bottom: 20px;
}
.container-info .info {
text-align: center;
}
.container-items .container-form {
width: 100%;
display: flex;
justify-content: space-between;
}
.container-form div {
display: flex;
align-items: center;
}
.container-form input {
padding-left: 10px;
width: 80%;
height: 20px;
}
.container-form label {
min-width: 75px;
}
.container-items button {
width: 100%;
background: #24d244;
height: 35px;
border-radius: 6px;
display: flex;
align-items: center;
justify-content: center;
color: #f6f1f1;
font-weight: bold;
transition: all 0.2s linear;
margin-top: 15px;
border: 1px solid rgb(226, 223, 223);
margin-top: 15px;
}
.container-items button:hover,
.container-items button:focus {
background: #1c9f34;
cursor: pointer;
}
.container-cadastrese {
margin-top: 20px;
width: 100%;
display: flex;
justify-content: center;
}
.container-cadastrese a {
text-decoration: none;
color: #f1519c
}
.container-cadastrese a:hover {
text-decoration: underline;
}
header .wrapper-header {
justify-content:center;
}
@media (max-width:768px) {
.container-items .container-form {
flex-direction: column;
justify-content: center;
}
.container-form div {
display: flex;
justify-content: space-between;
margin: 10px 0;
}
.container-cadastrese {
justify-content: flex-end;
margin-top: 10px;
}
}
@media (max-width:320px) {
.container-cadastrese {
font-size: 15px;
justify-content: center;
}
} | 15.851852 | 41 | 0.617407 |
3a4ba13cbc1a4f26fd4dc628ad8869d9d7c39fb3 | 2,762 | go | Go | lexer/indent_test.go | DataDrake/haml | 3d8df2e9681791beee1f5489ae9ee71eab33d5e8 | [
"Apache-2.0"
] | 1 | 2021-01-08T03:53:22.000Z | 2021-01-08T03:53:22.000Z | lexer/indent_test.go | DataDrake/haml | 3d8df2e9681791beee1f5489ae9ee71eab33d5e8 | [
"Apache-2.0"
] | null | null | null | lexer/indent_test.go | DataDrake/haml | 3d8df2e9681791beee1f5489ae9ee71eab33d5e8 | [
"Apache-2.0"
] | null | null | null | //
// Copyright 2021 Bryan T. Meyers <[email protected]>
//
// 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 lexer
import (
"testing"
)
func TestIndent2SP(t *testing.T) {
l := NewLexer(" ")
go l.Lex()
tok, err := l.Next()
if err != nil {
t.Fatalf("Should be no error, found: %s", err)
}
if tok == nil {
t.Fatal("token should not be nil")
}
if tok.Kind != Indent {
t.Errorf("expected '%d', found '%d'", Indent, tok.Kind)
}
if tok.Content != " " {
t.Errorf("expected '%s', found '%s'", " ", tok.Content)
}
if tok.Line != 1 {
t.Errorf("expected '%d', found '%d'", 1, tok.Line)
}
if tok.Col != 1 {
t.Errorf("expected '%d', found '%d'", 1, tok.Col)
}
tok, err = l.Next()
if err != nil {
t.Fatalf("Should be no error, found: %s", err)
}
if tok != nil {
t.Fatal("Should be the last token")
}
}
func TestIndent3T(t *testing.T) {
l := NewLexer("\t\t\t")
go l.Lex()
tok, err := l.Next()
if err != nil {
t.Fatalf("Should be no error, found: %s", err)
}
if tok == nil {
t.Fatal("token should not be nil")
}
if tok.Kind != Indent {
t.Errorf("expected '%d', found '%d'", Indent, tok.Kind)
}
if tok.Content != "\t\t\t" {
t.Errorf("expected '%s', found '%s'", "\t\t\t", tok.Content)
}
if tok.Line != 1 {
t.Errorf("expected '%d', found '%d'", 1, tok.Line)
}
if tok.Col != 1 {
t.Errorf("expected '%d', found '%d'", 1, tok.Col)
}
tok, err = l.Next()
if err != nil {
t.Fatalf("Should be no error, found: %s", err)
}
if tok != nil {
t.Fatal("Should be the last token")
}
}
func TestIndent2SP3T(t *testing.T) {
l := NewLexer(" \t\t\t")
go l.Lex()
tok, err := l.Next()
if err != nil {
t.Fatalf("Should be no error, found: %s", err)
}
if tok == nil {
t.Fatal("token should not be nil")
}
if tok.Kind != Indent {
t.Errorf("expected '%d', found '%d'", Indent, tok.Kind)
}
if tok.Content != " \t\t\t" {
t.Errorf("expected '%s', found '%s'", " \t\t\t", tok.Content)
}
if tok.Line != 1 {
t.Errorf("expected '%d', found '%d'", 1, tok.Line)
}
if tok.Col != 1 {
t.Errorf("expected '%d', found '%d'", 1, tok.Col)
}
tok, err = l.Next()
if err != nil {
t.Fatalf("Should be no error, found: %s", err)
}
if tok != nil {
t.Fatal("Should be the last token")
}
}
| 24.017391 | 75 | 0.594135 |
94f5177054270cccfc5b2b129159bff3a777087b | 7,911 | lua | Lua | .index.lua | DengSir/tdBag2 | 5738346a287b6c4a5fd5389cc5b4f44fc68f812b | [
"MIT"
] | 4 | 2020-03-28T12:22:31.000Z | 2022-01-25T08:40:58.000Z | .index.lua | DengSir/tdBag2 | 5738346a287b6c4a5fd5389cc5b4f44fc68f812b | [
"MIT"
] | 13 | 2019-10-25T08:58:28.000Z | 2022-02-16T19:12:11.000Z | .index.lua | DengSir/tdBag2 | 5738346a287b6c4a5fd5389cc5b4f44fc68f812b | [
"MIT"
] | 3 | 2021-05-23T22:17:08.000Z | 2022-01-06T03:45:37.000Z | -- .index.lua
-- @Author : Dencer ([email protected])
-- @Link : https://dengsir.github.io
-- @Date : 11/5/2020, 10:37:21 AM
---@class ns
---@field UI UI
---@field Addon Addon
---@field Events Events
---@field FrameMeta tdBag2FrameMeta
---@field Counter tdBag2Counter
---@field Forever tdBag2Forever
---@field Cache tdBag2Cache
---@field Current tdBag2Current
---@field Cacher tdBag2Cacher
---@field Thread tdBag2Thread
---@field Tooltip tdBag2Tooltip
---@field GlobalSearch tdBag2GlobalSearch
---@class tdBag2FrameProfile
---@field column number
---@field reverseBag boolean
---@field reverseSlot boolean
---@field managed boolean
---@field bagFrame boolean
---@field tokenFrame boolean
---@field pluginButtons boolean
---@field window table
---@field tradeBagOrder string
---@field iconCharacter boolean
---@field hiddenBags table<number, boolean>
---@class tdBag2Profile
---@field glowAlpha number
---@field textOffline boolean
---@field iconJunk boolean
---@field iconQuestStarter boolean
---@field glowQuest boolean
---@field glowUnusable boolean
---@field glowQuality boolean
---@field glowEquipSet boolean
---@field glowNew boolean
---@field colorSlots boolean
---@field lockFrame boolean
---@field emptyAlpha number
---@field remainLimit number
---@field style string
---@field searches string[]
---@class tdBag2WatchData
---@field itemId number
---@field watchAll boolean
---@class tdBag2CharacterProfile
---@field watches tdBag2WatchData[]
---@field hiddenBags table<number, boolean>
---@class tdBag2StyleData
---@field overrides table<string, table<string, any>>
---@field hooks table<string, table<string, function>>
---@class UI
---@field Frame tdBag2Frame
---@field SimpleFrame tdBag2SimpleFrame
---@field ContainerFrame tdBag2ContainerFrame
---@field ItemBase tdBag2ItemBase
---@field Item tdBag2Item
---@field Bag tdBag2Bag
---@field Container tdBag2Container
---@field TitleContainer tdBag2TitleContainer
---@field TitleFrame tdBag2TitleFrame
---@field OwnerSelector tdBag2OwnerSelector
---@field SearchBox tdBag2SearchBox
---@field GlobalSearchBox tdBag2GlobalSearchBox
---@field TokenFrame tdBag2TokenFrame
---@field Token tdBag2Token
---@field MenuButton tdBag2MenuButton
---@field PluginFrame tdBag2PluginFrame
---@alias tdBag2Frames table<string, tdBag2ContainerFrame>
---@class Addon
---@field private frames tdBag2Frames
---@field private styles table<string, tdBag2StyleData>
---@field private styleName string
---@class tdBag2ButtonPluginOptions
---@field type 'Button'
---@field icon number|string
---@field order number
---@field init function
---@field key string
---@field text string
---@class tdBag2ItemPluginOptions
---@field type 'Item'
---@field init function
---@field update function
---@field text string
---@alias tdBag2PluginOptions tdBag2ButtonPluginOptions|tdBag2ItemPluginOptions
---@class tdBag2Cacher
---@class tdBag2Thread
---@class tdBag2CacheOwnerData
---@field name string
---@field realm string
---@field faction string
---@field class string
---@field race string
---@field gender number
---@field cached boolean
---@field money number
---@class tdBag2CacheBagData
---@field slot number
---@field owned boolean
---@field cached boolean
---@field count number
---@field free number
---@field family number
---@field cost number
---@field link string
---@field icon string
---@field id number
---@field title string
---@class tdBag2CacheItemData
---@field link string
---@field count number
---@field cached boolean
---@field icon string
---@field locked boolean
---@field quality number
---@field id number
---@field readable boolean
---@field timeout number
---@class tdBag2Cache
---@class tdBag2Current
---@class tdBag2ForeverCharacter
---@field faction string
---@field class string
---@field race string
---@field gender number
---@field money number
---@alias tdBag2ForeverRealm table<string, tdBag2ForeverCharacter>
---@alias tdBag2ForeverDB table<string, tdBag2ForeverRealm>
---@class tdBag2Forever
---@field player tdBag2ForeverCharacter
---@field realm tdBag2ForeverRealm
---@field db tdBag2ForeverDB
---@field owners string[]
---@class tdBag2GlobalSearchBagItem
---@field title string
---@field bags string[]
---@class tdBag2GlobalSearch
---@field lastSearch string
---@field thread tdBag2Thread
---@class tdBag2AutoDisplay
---@field private frameKeys table<Frame, string>
---@field private profile table
---@class tdBag2Counter
---@class Events
---@field private bagSizes number[]
---@class tdBag2FrameClass
---@field Item tdBag2ItemBase
---@field Frame tdBag2Frame
---@field Container tdBag2Container
---@class tdBag2FrameMeta
---@field bagId number
---@field owner string
---@field bags number[]
---@field frame tdBag2Frame
---@field profile tdBag2FrameProfile
---@field sets tdBag2Profile
---@field character tdBag2CharacterProfile
---@field class tdBag2FrameClass
---@field title string
---@field icon string
---@class tdBag2Tooltip
---@class tdBag2MenuButton: Button
---@field private EnterBlocker Frame
---@class tdBag2Bag: Button
---@field private meta tdBag2FrameMeta
---@field private bag number
---@class tdBag2BagFrame
---@field protected meta tdBag2FrameMeta
---@class tdBag2GlobalSearchBox: EditBox
---@class tdBag2Item: tdBag2ItemBase
---@field private newitemglowAnim AnimationGroup
---@field private flashAnim AnimationGroup
---@class tdBag2ItemBase: Button
---@field protected meta tdBag2FrameMeta
---@field protected bag number
---@field protected slot number
---@field protected hasItem boolean
---@field protected notMatched boolean
---@field protected info tdBag2CacheItemData
---@field protected Overlay Frame
---@field protected Timeout FontString
---@field protected QuestBorder Texture
---@field protected JunkIcon Texture
---@class tdBag2MoneyFrame: Button
---@field private meta tdBag2FrameMeta
---@class tdBag2OwnerSelector: tdBag2MenuButton
---@field private meta tdBag2FrameMeta
---@class tdBag2SearchBox: EditBox
---@field private meta tdBag2FrameMeta
---@class tdBag2TitleFrame: Button
---@field private meta tdBag2FrameMeta
---@class tdBag2Token: Frame
---@field private Icon Texture
---@field private Count FontString
---@field private itemId number
---@class tdBag2TokenFrame: tdBag2MenuButton
---@field private meta tdBag2FrameMeta
---@field private buttons tdBag2Token[]
---@class tdBag2Container: Frame
---@field private meta tdBag2FrameMeta
---@field private itemButtons table<number, table<number, tdBag2Item>>
---@field private bagSizes table<number, number>
---@field private bagOrdered number[]
---@class tdBag2GlobalSearchContainer: tdBag2TitleContainer
---@field thread tdBag2Thread
---@class tdBag2TitleContainer: tdBag2Container
---@field alwaysShowTitle boolean
---@class tdBag2Bank: tdBag2ContainerFrame
---@class tdBag2ContainerFrame: tdBag2Frame
---@field protected Container tdBag2Container
---@field protected BagFrame tdBag2BagFrame
---@field protected TokenFrame tdBag2TokenFrame
---@field protected PluginFrame tdBag2PluginFrame
---@class tdBag2Frame: Frame
---@field protected meta tdBag2FrameMeta
---@field protected fixedHeight number
---@field protected portrait Texture
---@field protected TitleFrame tdBag2TitleFrame
---@field protected Container tdBag2Container
---@class tdBag2GlobalSearchFrame: tdBag2Frame
---@field protected Container tdBag2TitleContainer
---@field protected SearchBox tdBag2GlobalSearchBox
---@class tdBag2Inventory: tdBag2ContainerFrame
---@class tdBag2SimpleFrame: tdBag2Frame
---@field protected OwnerSelector tdBag2OwnerSelector
---@field protected SearchBox tdBag2SearchBox
---@class tdBag2BagToggle: tdBag2MenuButton
---@field private meta tdBag2FrameMeta
---@class tdBag2PluginFrame: Frame
---@field meta tdBag2FrameMeta
---@field menuButtons Button[]
---@field pluginButtons table<string, Button>
---@class tdBag2SearchToggle: tdBag2MenuButton
---@field private meta tdBag2FrameMeta
---@class Addon
| 26.816949 | 79 | 0.762356 |
7576ebdefce224e587be53d7268a5acd8d5152ee | 842 | css | CSS | css/nav.css | SedaxMx/School-Agenda | 49a3da412716870f30027c1842ba4f579f6cd5f0 | [
"MIT"
] | null | null | null | css/nav.css | SedaxMx/School-Agenda | 49a3da412716870f30027c1842ba4f579f6cd5f0 | [
"MIT"
] | null | null | null | css/nav.css | SedaxMx/School-Agenda | 49a3da412716870f30027c1842ba4f579f6cd5f0 | [
"MIT"
] | null | null | null | .switch-tema {
position: relative;
height: 35px;
width: 65px;
border-radius: 50px;
overflow: hidden;
margin-top: 1.2em;
}
.switch-tema label{
display: inline-block;
width: 100%;
height: 100%;
}
.input-tema + label {
transition: background 1s ease-in-out;
background: #1083D6;
}
.switch-tema > input {
display: none;
}
.label-tema:before {
content: '';
background-color: #FDD835;
position: absolute;
border-radius: 100%;
width: 30px;
height: 30px;
display: inline-block;
top: 0px;
left: 0px;
transition: transform 1s;
border: 3px solid rgba(0,0,0,0.10);
}
.input-tema[type=checkbox]:checked + label:before {
background-color: #ECEFF1;
transform: translateX(30px);
}
.input-tema[type=checkbox]:checked + label {
background: #2A3B47;
} | 18.304348 | 51 | 0.624703 |
387b744dc0711970d3f390e86001c6f8aa5943fd | 2,053 | php | PHP | src/Saver/SQLFile.php | Aldarien/backup | 5b6f7fa56fed8240b8b9f79a05be6c7e15960aba | [
"MIT"
] | null | null | null | src/Saver/SQLFile.php | Aldarien/backup | 5b6f7fa56fed8240b8b9f79a05be6c7e15960aba | [
"MIT"
] | null | null | null | src/Saver/SQLFile.php | Aldarien/backup | 5b6f7fa56fed8240b8b9f79a05be6c7e15960aba | [
"MIT"
] | null | null | null | <?php
namespace Backup\Saver;
class SQLFile extends Saver
{
public function __construct()
{
parent::__construct();
$this->extension = 'sql';
}
public function build()
{
$sql = [];
foreach ($this->data as $data) {
$sql []= $this->createTable($data);
$sql []= $this->inserts($data);
}
$this->file_data = implode(PHP_EOL, $sql);
}
protected function createTable($data)
{
$sql = ["CREATE TABLE IF NOT EXISTS `" . $data['name'] . "` ("];
foreach ($data['fields'] as $field) {
$str = "`" . $field['name'] . "` " . $field['type'];
if ($field['length'] != '') {
$str .= "(" . $field['length'] . ")";
}
if ($field['unsigned'] == true) {
$str .= " UNSIGNED";
}
if ($field['null'] == true) {
$str .= " NULL";
} else {
$str .= " NOT NULL";
}
if ($field['default'] != '') {
$str .= " DEFAULT ";
if ($field['type'] != 'int') {
$str .= "'";
}
$str .= $field['default'];
if ($field['type'] != 'int') {
$str .= "'";
}
}
if ($field['primary']) {
if ($field['type'] == 'int') {
$str .= " AUTO_INCREMENT";
}
$str .= " PRIMARY KEY";
}
$sql []= $str;
}
$sql []= ");";
return implode(PHP_EOL, $sql);
}
protected function inserts($data)
{
$sql = "INSERT INTO `" . $data['name'] . "` (";
$fields = [];
foreach ($data['fields'] as $field) {
$fields []= "`" . $field['name'] . "`";
}
$sql .= implode(', ', $fields) . ") VALUES ";
$values = [];
foreach ($data['values'] as $value) {
$vals = [];
foreach ($value as $v) {
$str = '';
if (!is_numeric($v)) {
$str .= '"';
}
$str .= $v;
if (!is_numeric($v)) {
$str .= '"';
}
$vals []= $str;
}
$values []= "(" . implode(', ', $vals) . ")";
}
$sql .= implode(', ', $values) . ';';
return $sql;
}
}
| 24.152941 | 68 | 0.407696 |
0575e56239eb2daaef27c6466a46cb1ea4a2c574 | 242 | asm | Assembly | libsrc/_DEVELOPMENT/compress/zx0/c/sccz80/dzx0_agile_rcs_callee.asm | w5Mike/z88dk | f5090488e1d74ead8c865afe6df48231cd5c70ba | [
"ClArtistic"
] | null | null | null | libsrc/_DEVELOPMENT/compress/zx0/c/sccz80/dzx0_agile_rcs_callee.asm | w5Mike/z88dk | f5090488e1d74ead8c865afe6df48231cd5c70ba | [
"ClArtistic"
] | null | null | null | libsrc/_DEVELOPMENT/compress/zx0/c/sccz80/dzx0_agile_rcs_callee.asm | w5Mike/z88dk | f5090488e1d74ead8c865afe6df48231cd5c70ba | [
"ClArtistic"
] | null | null | null |
; void dzx0_agile_rcs_callee(void *src, void *dst)
SECTION code_clib
SECTION code_compress_zx0
PUBLIC dzx0_agile_rcs_callee
EXTERN asm_dzx0_agile_rcs
dzx0_agile_rcs_callee:
pop hl
pop de
ex (sp),hl
jp asm_dzx0_agile_rcs
| 13.444444 | 50 | 0.772727 |
938747cffc10823328e66b95ceabca0eb68fe8ba | 507 | cs | C# | src/Channel_Nine/models/Shows/Show.cs | Xonshiz/Channel-9 | 2d10d792da220ce7b30a1806887db66e77576d16 | [
"MIT"
] | null | null | null | src/Channel_Nine/models/Shows/Show.cs | Xonshiz/Channel-9 | 2d10d792da220ce7b30a1806887db66e77576d16 | [
"MIT"
] | null | null | null | src/Channel_Nine/models/Shows/Show.cs | Xonshiz/Channel-9 | 2d10d792da220ce7b30a1806887db66e77576d16 | [
"MIT"
] | null | null | null | using System;
using System.Collections.Generic;
using System.Text;
namespace Channel_Nine.models.Shows
{
class Show
{
public string showID { get; set; }
public string showTitle { get; set; }
//Show URL will be just the part needed to go to /shows/{showURL} and get the details.
public string showUrl { get; set; }
public string showThumbnail { get; set; }
public string showLanguage { get; set; }
public int showNumber { get; set; }
}
}
| 28.166667 | 94 | 0.635108 |
46be5688a2ab1813b8393b2653ad1b87466e044f | 338 | swift | Swift | VisualRecognitionV3.playground/Pages/User Data.xcplaygroundpage/Contents.swift | kant/swift-playgrounds | 1b1e589586317005fef02423f770e624be2295dc | [
"Apache-2.0"
] | 1 | 2019-09-26T15:11:37.000Z | 2019-09-26T15:11:37.000Z | VisualRecognitionV3.playground/Pages/User Data.xcplaygroundpage/Contents.swift | kant/swift-playgrounds | 1b1e589586317005fef02423f770e624be2295dc | [
"Apache-2.0"
] | 5 | 2019-02-07T02:38:12.000Z | 2020-05-26T15:44:06.000Z | VisualRecognitionV3.playground/Pages/User Data.xcplaygroundpage/Contents.swift | kant/swift-playgrounds | 1b1e589586317005fef02423f770e624be2295dc | [
"Apache-2.0"
] | 2 | 2019-03-25T19:23:56.000Z | 2021-02-26T03:55:32.000Z | //:## User Data
import VisualRecognitionV3
let visualRecognition = setupVisualRecognitionV3()
//:### Delete labeled data
visualRecognition.deleteUserData(customerID: "my-customer-id") {
_, error in
if let error = error {
print(error.localizedDescription)
return
}
print("delete request submitted")
}
| 17.789474 | 64 | 0.689349 |
4b30963cb8404a0259545f4ca3fbf4bb0ff8c9f0 | 852 | rs | Rust | src/config.rs | TeFiLeDo/nimo | 5acdc0408028380e5cb34baa9875c40074c2dcae | [
"MIT"
] | 1 | 2021-11-26T05:58:48.000Z | 2021-11-26T05:58:48.000Z | src/config.rs | TeFiLeDo/nimo | 5acdc0408028380e5cb34baa9875c40074c2dcae | [
"MIT"
] | null | null | null | src/config.rs | TeFiLeDo/nimo | 5acdc0408028380e5cb34baa9875c40074c2dcae | [
"MIT"
] | null | null | null | use std::path::PathBuf;
use anyhow::{Context, Result};
use figment::{
providers::{Env, Format, Toml},
Figment,
};
#[derive(Debug, serde::Deserialize)]
pub struct Config {
#[serde(default = "default_data_path")]
pub data: PathBuf,
#[serde(default)]
pub ping: crate::ping::Config,
#[serde(default)]
pub speed_test: crate::speedtest::Config,
}
fn default_data_path() -> PathBuf {
PathBuf::from("/var/lib/nimo/data")
}
impl Config {
pub fn load() -> Result<Self> {
let mut cfg = Figment::new().merge(Toml::file("/etc/nimo.toml"));
if let Some(mut x) = home::home_dir() {
x.push(".config/nimo.toml");
cfg = cfg.merge(Toml::file(x));
}
cfg = cfg.merge(Env::prefixed("NIMO_").split("_"));
cfg.extract().context("failed to load configuration")
}
}
| 25.058824 | 73 | 0.591549 |
b07702c86548898ef633ce6d0cc0f13f210c5124 | 15,090 | py | Python | telnetbmc.py | spyd3rweb/pypmi | fe043ede5fb68a863586cbc5a991020a1f920add | [
"Apache-2.0"
] | 1 | 2020-07-23T10:21:37.000Z | 2020-07-23T10:21:37.000Z | telnetbmc.py | spyd3rweb/pypmi | fe043ede5fb68a863586cbc5a991020a1f920add | [
"Apache-2.0"
] | null | null | null | telnetbmc.py | spyd3rweb/pypmi | fe043ede5fb68a863586cbc5a991020a1f920add | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
import logging
import argparse
import sys
import re
import asyncio
import telnetlib3
import commandbmc
import asyncbmc
import pinbmc
from enum import IntEnum
from itertools import chain
COMMAND_TELNET_CONFIG = {
"host": '192.168.4.1',
"port": 24,
"baud": 115200,
"crlf" : '\r\n',
"response_timeout": 0.15,
"connection_timeout": 2.1,
"connection_retries": 1
}
SOL_TELNET_CONFIG = {
"host": '192.168.4.1',
"port": 23,
"baud": 115200,
"crlf" : '\r\n',
"response_timeout": 5,
"connection_timeout": 2.1,
"connection_retries": 1
}
# Receiver
class TelnetSession(asyncbmc.AsyncSession):
def __init__(self, host, port, baud, crlf, response_timeout, connection_timeout = 3, connection_retries=1, name=None, loop=None):
asyncbmc.AsyncSession.__init__(self, name=name, loop=loop)
self.host = host
self.port = port
self.baud = baud
self.crlf = crlf
self.response_timeout = response_timeout
self.connection_timeout = connection_timeout
self.connection_retries = connection_retries
self.reader = None
self.writer = None
self._waiter_connected = None
self._waiter_closed = None
async def is_connected(self):
await asyncio.sleep(0, loop=self.loop)
test1 = ((self._waiter_connected is not None and self._waiter_connected.done() and not self._waiter_connected.cancelled())
and (self._waiter_closed is not None and not self._waiter_closed.done()))
test2 = (self.reader is not None and not self.reader._eof and not self.reader._exception and
self.writer is not None and self.writer.protocol is not None)
connected = test1 and test2
return connected
async def connect(self):
# https://telnetlib3.readthedocs.io/en/latest/intro.html
# loop = asyncio.get_event_loop()
# coro = telnetlib3.open_connection(self.telnet_host, self.telnet_port, shell=self.shell) # , loop=self.loop
# https://stackoverflow.com/questions/36342899/asyncio-ensure-future-vs-baseeventloop-create-task-vs-simple-coroutine
# https://docs.python.org/3/library/asyncio-future.html#asyncio.ensure_future
# https://stackoverflow.com/questions/28609534/python-asyncio-force-timeout
#task = asyncio.ensure_future(coro) # asyncio.create_task(coro()) #
#reader, writer = loop.run_until_complete(asyncio.wait_for(task, 30))
#reader, writer = self.loop.run_until_complete(coro)
#self.loop.run_until_complete(writer.protocol.waiter_closed)
tries = 0
while (not await self.is_connected() and tries < self.connection_retries):
tries += 1
self._waiter_connected = self.loop.create_future() #asyncio.Future()
self._waiter_closed = self.loop.create_future() #asyncio.Future()
# https://stackoverflow.com/questions/50678184/how-to-pass-additional-parameters-to-handle-client-coroutine
# reader, writer = await telnetlib3.open_connection(self.telnet_host, self.telnet_port, shell=self.shell, loop=self.loop)
try:
#self.reader, self.writer = await telnetlib3.open_connection(self.host, self.port, loop=self.loop)
self.reader, self.writer = await asyncio.shield(asyncio.wait_for(telnetlib3.open_connection(self.host, self.port,
waiter_closed=self._waiter_closed,
_waiter_connected=self._waiter_connected,
loop=self.loop),
self.connection_timeout,
loop=self.loop))
except asyncio.TimeoutError as e:
#except Exception as e:
# self._waiter_connected = None
# self._waiter_closed = None
logging.warning("Connection attempt {} timed out after {}s".format(tries, self.connection_timeout))
#await self.shell(self.reader, self.writer)
# coro = telnetlib3.open_connection(self.telnet_host, self.telnet_port, shell=self.shell, loop=self.loop)
# task = asyncio.ensure_future(coro) # asyncio.create_task(coro()) #
# reader, writer = await asyncio.wait({task}, loop = self.loop)
return tries < self.connection_retries
async def disconnect(self):
is_connected = True
# disconnect
try:
self.writer.protocol.eof_received()
is_connected = await self.is_connected()
except Exception as e:
logging.error(e)
finally:
self._waiter_connected = None
self._waiter_closed = None
return is_connected
async def write(self, command_text):
is_connected = await self.connect()
if is_connected:
# print(command_text, end='', flush=True)
self.writer.write(command_text)
return await self.writer.drain()
async def read(self, num):
is_connected = await self.connect()
if is_connected:
response_line = await asyncio.wait_for(self.reader.read(num), self.response_timeout, loop = self.loop)
# print(response_line, end='', flush=True)
return response_line
async def readline(self):
is_connected = await self.connect()
if is_connected:
response_line = await asyncio.wait_for(self.reader.readline(), self.response_timeout, loop = self.loop)
# print(response_line, end='', flush=True)
return response_line
class TelnetCommand(commandbmc.GenericCommand):
class CommandEnum(IntEnum):
# Common
KEEP_ALIVE = 0x1000
# https://stackoverflow.com/questions/33679930/how-to-extend-python-enum
#CommandEnum = IntEnum('Idx', [(i.name, i.value) for i in chain(commandbmc.GenericCommand.CommandEnum, TelnetCommand.CommandEnum)])
def get_commands(self):
return {
commandbmc.GenericCommand.CommandEnum.NONE: "^]",
TelnetCommand.CommandEnum.KEEP_ALIVE: ""
}
def get_command_text(self, command_enum: CommandEnum = commandbmc.GenericCommand.CommandEnum.NONE):
commands = self.get_commands()
return commands.get(command_enum)
def get_responses(self):
return {
commandbmc.GenericCommand.CommandEnum.NONE: "",
TelnetCommand.CommandEnum.KEEP_ALIVE: ".+"
}
def get_response_regex(self, command_enum: CommandEnum = commandbmc.GenericCommand.CommandEnum.NONE):
responses = self.get_responses()
return responses.get(command_enum)
async def handle_response_match(self, match):
if match:
# handled
self.command_enum = commandbmc.GenericCommand.CommandEnum.HANDLED # CommandEnum.NONE
async def process_response_text(self, response_text, response_regex = None):
# raise NotImplementedError
receiver = self.receiver
command_enum = self.command_enum
if response_regex is None:
response_regex = self.get_response_regex(command_enum)
match = re.search(response_regex, response_text)
if match is not None or not response_text:
if match is not None:
await self.handle_response_match(match)
else:
logging.warning("Unexpected blank response for command {}, expected '{}'".format(command_enum.name, response_regex))
return True
else:
# retry
return False
async def execute(self):
receiver: TelnetCommandReceiver = self.receiver
command_enum = self.command_enum
command_text = self.get_command_text(command_enum)
response_regex = self.get_response_regex(command_enum)
response_text = ""
response_success = False
# send command
await receiver.command_telnet_session.write("{}{}".format(command_text, receiver.command_telnet_session.crlf))
# get response
while (True and not response_success):
try:
# response_line = yield from reader.read(1024)
# response_line = yield from reader.readuntil(separator=b'\n')
# https://stackoverflow.com/questions/28609534/python-asyncio-force-timeout
response_line = await receiver.command_telnet_session.readline()
if not response_line:
# EOF
break
else:
response_text += response_line
response_success = await self.process_response_text(response_text, response_regex)
except Exception as e:
logging.error(e)
break
logging.debug("Command {}:\n\tEnum: {}\n\tText: {}\n\tResponse: {}\tRegex:{}"
.format("Successful" if response_success else "Unsuccessful", command_enum.name, command_text, response_text, response_regex))
return response_success
class TelnetPinCommand(TelnetCommand, commandbmc.PinCommand):
class CommandEnum(IntEnum):
pass
# https://stackoverflow.com/questions/33679930/how-to-extend-python-enum
#CommandEnum = IntEnum('Idx', [(i.name, i.value) for i in chain(commandbmc.PinCommand.CommandEnum, TelnetCommand.CommandEnum, TelnetPinCommand.CommandEnum)])
async def handle_response_match(self, match):
pin: commandbmc.CommandPin = self.receiver
if self.command_enum in (commandbmc.PinCommand.CommandEnum.READ_STATE, commandbmc.PinCommand.CommandEnum.WRITE_STATE):
logic_level = match.group('logic_level')
# self.receiver.logic_level = int(logic_level)
pin.logic_level = int(logic_level)
await super().handle_response_match(match)
class TelnetSerialCommand(TelnetCommand, commandbmc.SerialCommand):
class CommandEnum(IntEnum):
pass
# https://stackoverflow.com/questions/33679930/how-to-extend-python-enum
#CommandEnum = IntEnum('Idx', [(i.name, i.value) for i in chain(commandbmc.SerialCommand.CommandEnum, TelnetCommand.CommandEnum, TelnetSerialCommand.CommandEnum)])
class TelnetCommandReceiver(object):
def __init__(self, command_telnet_session: TelnetSession):
self.command_telnet_session = command_telnet_session
class TelnetCommandPin(TelnetCommandReceiver, commandbmc.CommandPin):
def __init__(self, pin_command_telnet_session: TelnetSession, pin: int, is_output: bool = True, value: bool = False, invert_logic: bool = False, loop=None):
commandbmc.CommandPin.__init__(self, pin, is_output, value, invert_logic, loop=loop)
TelnetCommandReceiver.__init__(self, pin_command_telnet_session)
class TelnetCommandSerial(TelnetCommandReceiver, commandbmc.CommandSerial):
def __init__(self, serial_command_telnet_session: TelnetSession, name=None, loop=None):
commandbmc.CommandSerial.__init__(self, name=name, loop=loop)
TelnetCommandReceiver.__init__(self, serial_command_telnet_session)
class TelnetBmc(commandbmc.CommandBmc):
def __init__(self, authdata, button_config: dict, gpio_config: dict, command_telnet_config: dict, sol_telnet_config: dict, name=None, port=623, loop=None):
commandbmc.CommandBmc.__init__(self, authdata, button_config, gpio_config, name=name, port=port, loop=loop)
# Command Telnet Config
self.command_telnet_config = COMMAND_TELNET_CONFIG
if command_telnet_config is not None:
self.command_telnet_config.update(command_telnet_config)
self.command_telnet_host = self.command_telnet_config['host']
self.command_telnet_port = self.command_telnet_config['port']
self.command_telnet_baud = self.command_telnet_config['baud']
self.command_telnet_crlf = self.command_telnet_config['crlf']
self.command_telnet_response_timeout = self.command_telnet_config['response_timeout']
self.command_telnet_connection_timeout = self.command_telnet_config['connection_timeout']
self.command_telnet_connection_retries = self.command_telnet_config['connection_retries']
self.command_telnet_session = None
# Sol Telnet Config
self.sol_telnet_config = SOL_TELNET_CONFIG
if sol_telnet_config is not None:
self.sol_telnet_config.update(sol_telnet_config)
self.sol_telnet_host = self.sol_telnet_config['host']
self.sol_telnet_port = self.sol_telnet_config['port']
self.sol_telnet_baud = self.sol_telnet_config['baud']
self.sol_telnet_crlf = self.sol_telnet_config['crlf']
self.sol_telnet_response_timeout = self.sol_telnet_config['response_timeout']
self.sol_telnet_connection_timeout = self.sol_telnet_config['connection_timeout']
self.sol_telnet_connection_retries = self.sol_telnet_config['connection_retries']
async def setup_command_telnet_session(self):
await asyncio.sleep(0, loop=self.loop)
self.command_telnet_session = TelnetSession(self.command_telnet_host, self.command_telnet_port,
self.command_telnet_baud, self.command_telnet_crlf,
self.command_telnet_response_timeout, self.command_telnet_connection_timeout,
self.command_telnet_connection_retries, loop=self.loop)
async def setup_serial_session(self):
await asyncio.sleep(0, loop=self.loop)
self.serial_session = TelnetSession(self.sol_telnet_host, self.sol_telnet_port,
self.sol_telnet_baud, self.sol_telnet_crlf,
self.sol_telnet_response_timeout, self.sol_telnet_connection_timeout,
self.sol_telnet_connection_retries, loop=self.loop)
async def setup(self):
await self.setup_command_telnet_session()
await self.setup_serial_session()
return await super().setup()
def main():
parser = argparse.ArgumentParser(
prog='telnetbmc',
description='Generic Telnet Baseboard Management Controller',
conflict_handler='resolve'
)
parser.add_argument('--port',
dest='port',
type=int,
default=623,
help='Port to listen on; defaults to 623')
args = parser.parse_args()
mybmc = TelnetBmc({}, {}, {}, {}, {}, port=args.port)
mybmc.listen()
if __name__ == '__main__':
sys.exit(main()) | 44.910714 | 167 | 0.646587 |
f1ea8b5472f809e08a61f6ea4b9d8b5220a46671 | 1,179 | dart | Dart | lib/immutables.dart | google/dart-immutables | 4a09eaf827a94f98e071f7e9538f036cf2174866 | [
"Apache-2.0"
] | 4 | 2017-05-10T03:48:17.000Z | 2020-03-15T07:09:04.000Z | lib/immutables.dart | google/dart-immutables | 4a09eaf827a94f98e071f7e9538f036cf2174866 | [
"Apache-2.0"
] | null | null | null | lib/immutables.dart | google/dart-immutables | 4a09eaf827a94f98e071f7e9538f036cf2174866 | [
"Apache-2.0"
] | 5 | 2017-07-24T22:38:36.000Z | 2021-07-12T12:33:06.000Z | // Copyright 2015 Google 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.
library immutables;
/// The immutable library.
///
/// Wraps objects to make them immutable, propagating immutability
/// through values they return from their getters and non-mutating methods.
///
/// Returned values are wrapped using known default [Immutable] subclasses
/// (for instance [ImmutableList] for [List] return values), but this can be
/// customized by binding custom lightweight wrappers (see [ImmutablesModule]).
///
export 'src/default_immutable_wrappers.dart';
export 'src/immutable.dart';
export 'src/immutables.dart';
export 'src/module.dart';
| 39.3 | 79 | 0.751484 |
b349c67246b7d4fcd631374d26b62c856fe4ff64 | 15,382 | py | Python | anomaly_detection_time_series/MatrixProfileAD.py | Vincent-Vercruyssen/absent_pattern_detection | 58dba15a367a0a302756deeef34de73eb3dae8e6 | [
"Apache-2.0"
] | 4 | 2019-11-20T11:05:09.000Z | 2021-11-08T12:44:03.000Z | anomaly_detection_time_series/MatrixProfileAD.py | Vincent-Vercruyssen/absent_pattern_detection | 58dba15a367a0a302756deeef34de73eb3dae8e6 | [
"Apache-2.0"
] | null | null | null | anomaly_detection_time_series/MatrixProfileAD.py | Vincent-Vercruyssen/absent_pattern_detection | 58dba15a367a0a302756deeef34de73eb3dae8e6 | [
"Apache-2.0"
] | null | null | null | """ Matrix profile anomaly detection.
Reference:
Yeh, C. C. M., Zhu, Y., Ulanova, L., Begum, N., Ding, Y., Dau, H. A., Keogh, E. (2016, December).
Matrix profile I: all pairs similarity joins for time series: a unifying view that includes motifs, discords and shapelets.
In Data Mining (ICDM), 2016 IEEE 16th International Conference on (pp. 1317-1322). IEEE.
"""
# Authors: Vincent Vercruyssen, 2018.
import math
import numpy as np
import pandas as pd
import scipy.signal as sps
from tqdm import tqdm
from .BaseDetector import BaseDetector
# -------------
# CLASSES
# -------------
class MatrixProfileAD(BaseDetector):
""" Anomaly detection in time series using the matrix profile
Parameters
----------
m : int (default=10)
Window size.
contamination : float (default=0.1)
Estimate of the expected percentage of anomalies in the data.
Comments
--------
- This only works on time series data.
"""
def __init__(self, m=10, contamination=0.1,
tol=1e-8, verbose=False):
super(MatrixProfileAD, self).__init__()
self.m = int(m)
self.contamination = float(contamination)
self.tol = float(tol)
self.verbose = bool(verbose)
def ab_join(self, T, split):
""" Compute the ABjoin and BAjoin side-by-side,
where `split` determines the splitting point.
"""
# algorithm options
excZoneLen = int(np.round(self.m * 0.5))
radius = 1.1
dataLen = len(T)
proLen = dataLen - self.m + 1
# change Nan and Inf to zero
T = np.nan_to_num(T)
# precompute the mean, standard deviation
s = pd.Series(T)
dataMu = s.rolling(self.m).mean().values[self.m-1:dataLen]
dataSig = s.rolling(self.m).std().values[self.m-1:dataLen]
matrixProfile = np.ones(proLen) * np.inf
idxOrder = excZoneLen + np.arange(0, proLen, 1)
idxOrder = idxOrder[np.random.permutation(len(idxOrder))]
# construct the matrixprofile
for i, idx in enumerate(idxOrder):
# query
query = T[idx:idx+self.m-1]
# distance profile
distProfile = self._diagonal_dist(T, idx, dataLen, self.m, proLen, dataMu, dataSig)
distProfile = abs(distProfile)
distProfile = np.sqrt(distProfile)
# position magic
pos1 = np.arange(idx, proLen, 1)
pos2 = np.arange(0, proLen-idx+1, 1)
# split magic
distProfile = distProfile[np.where((pos2 <= split) & (pos1 > split))[0]]
pos1Split = pos1[np.where((pos2 <= split) & (pos1 > split))[0]]
pos2Split = pos2[np.where((pos2 <= split) & (pos1 > split))[0]]
pos1 = pos1Split
pos2 = pos2Split
# update magic
updatePos = np.where(matrixProfile[pos1] > distProfile)[0]
matrixProfile[pos1[updatePos]] = distProfile[updatePos]
updatePos = np.where(matrixProfile[pos2] > distProfile)[0]
matrixProfile[pos2[updatePos]] = distProfile[updatePos]
return matrixProfile
def fit_predict(self, T):
""" Fit the model to the time series T.
:param T : np.array(), shape (n_samples)
The time series data for which to compute the matrix profile.
:returns y_score : np.array(), shape (n_samples)
Anomaly score for the samples in T.
:returns y_pred : np.array(), shape (n_samples)
Returns -1 for inliers and +1 for anomalies/outliers.
"""
return self.fit(np.array([])).predict(T)
def fit(self, T=np.array([])):
""" Fit the model to the time series T.
:param T : np.array(), shape (n_samples)
The time series data for which to compute the matrix profile.
:returns self : object
"""
self.T_train = T
return self
def predict(self, T=np.array([])):
""" Compute the anomaly score + predict the label of each sample in T.
:returns y_score : np.array(), shape (n_samples)
Anomaly score for the samples in T.
:returns y_pred : np.array(), shape (n_samples)
Returns -1 for inliers and +1 for anomalies/outliers.
"""
# fuse T_train and T
nt = len(T)
nT = np.concatenate((self.T_train, T))
n = len(nT)
# compute the matrix profile
matrix_profile = self._compute_matrix_profile_stomp(nT, self.m)
# transform to an anomaly score (1NN distance)
# the largest distance = the largest anomaly
# rescale between 0 and 1, this yields the anomaly score
y_score = (matrix_profile - min(matrix_profile)) / (max(matrix_profile) - min(matrix_profile))
y_score = np.append(y_score, np.zeros(n-len(matrix_profile), dtype=float))
# prediction threshold + absolute predictions
self.threshold = np.sort(y_score)[int(n * (1.0 - self.contamination))]
y_pred = np.ones(n, dtype=float)
y_pred[y_score < self.threshold] = -1
# cut y_pred and y_score to match length of T
return y_score[-nt:], y_pred[-nt:]
def _compute_matrix_profile_stomp(self, T, m):
""" Compute the matrix profile and profile index for time series T using correct STOMP.
:param T : np.array(), shape (n_samples)
The time series data for which to compute the matrix profile.
:param m : int
Length of the query.
:returns matrix_profile : np.array(), shape (n_samples)
The matrix profile (distance) for the time series T.
comments
--------
- Includes a fix for straight line time series segments.
"""
n = len(T)
# precompute the mean, standard deviation
s = pd.Series(T)
data_m = s.rolling(m).mean().values[m-1:n]
data_s = s.rolling(m).std().values[m-1:n]
# where the data is zero
idxz = np.where(data_s < 1e-8)[0]
data_s[idxz] = 0.0
idxn = np.where(data_s > 0.0)[0]
zero_s = False
if len(idxz) > 0:
zero_s = True
# precompute distance to straight line segment of 0s
slD = np.zeros(n-m+1, dtype=float)
if zero_s:
for i in range(n-m+1):
Tsegm = T[i:i+m]
Tm = data_m[i]
Ts = data_s[i]
if Ts == 0.0: # data_s is effectively 0
slD[i] = 0.0
else:
Tn = (Tsegm - Tm) / Ts
slD[i] = np.sqrt(np.sum(Tn ** 2))
# compute the first dot product
q = T[:m]
QT = sps.convolve(T.copy(), q[::-1], 'valid', 'direct')
QT_first = QT.copy()
# compute the distance profile
D = self._compute_fixed_distance_profile(T[:m], QT, n, m, data_m, data_s, data_m[0], data_s[0], slD.copy(), idxz, idxn, zero_s)
# initialize matrix profile
matrix_profile = D
# in-order evaluation of the rest of the profile
for i in tqdm(range(1, n-m+1, 1), disable=not(self.verbose)):
# update the dot product
QT[1:] = QT[:-1] - (T[:n-m] * T[i-1]) + (T[m:n] * T[i+m-1])
QT[0] = QT_first[i]
# compute the distance profile: without function calls!
if data_s[i] == 0.0: # query_s is effectively 0
D = slD.copy()
elif zero_s:
D[idxn] = np.sqrt(2 * (m - (QT[idxn] - m * data_m[idxn] * data_m[i]) / (data_s[idxn] * data_s[i])))
nq = (q - data_m[i]) / data_s[i]
d = np.sqrt(np.sum(nq ** 2))
D[idxz] = d
else:
D = np.sqrt(2 * (m - (QT - m * data_m * data_m[i]) / (data_s * data_s[i])))
# update the matrix profile
exclusion_range = (int(max(0, round(i-m/2))), int(min(round(i+m/2+1), n-m+1)))
D[exclusion_range[0]:exclusion_range[1]] = np.inf
ix = np.where(D < matrix_profile)[0]
matrix_profile[ix] = D[ix]
# matrix_profile = np.minimum(matrix_profile, D)
return matrix_profile
def _compute_fixed_distance_profile(self, q, QT, n, m, data_m, data_s, query_m, query_s, slD, idxz, idxn, zero_s):
""" Compute the fixed distance profile """
D = np.zeros(n-m+1, dtype=float)
if query_s == 0.0: # query_s is effectively 0
return slD
if zero_s:
D[idxn] = np.sqrt(2 * (m - (QT[idxn] - m * data_m[idxn] * query_m) / (data_s[idxn] * query_s)))
nq = (q - query_m) / query_s
d = np.sqrt(np.sum(nq ** 2))
D[idxz] = d
else:
D = np.sqrt(2 * (m - (QT - m * data_m * query_m) / (data_s * query_s)))
return D
def _compute_matrix_profile_stamp(self, T, m):
""" Compute the matrix profile and profile index for time series T using STAMP.
:param T : np.array(), shape (n_samples)
The time series data for which to compute the matrix profile.
:param m : int
Length of the query.
:returns matrix_profile : np.array(), shape (n_samples)
The matrix profile (distance) for the time series T.
:returns profile_index : np.array(), shape (n_samples)
The matrix profile index accompanying the matrix profile.
comments
--------
- Uses the STAMP algorithm to compute the matrix profile.
- Includes a fix for straight line time series segments.
"""
n = len(T)
# initialize the empty profile and index
matrix_profile = np.ones(n-m+1) * np.inf
# precompute the mean, standard deviation
s = pd.Series(T)
data_m = s.rolling(m).mean().values[m-1:n]
data_s = s.rolling(m).std().values[m-1:n]
# where the data is zero
idxz = np.where(data_s < 1e-8)[0]
data_s[idxz] = 0.0
idxn = np.where(data_s > 0.0)[0]
zero_s = False
if len(idxz) > 0:
zero_s = True
# precompute distance to straight line segment of 0s
# brute force distance computation (because the dot_product is zero!)
# --> this is a structural issue with the MASS algorithm for fast distance computation
slD = np.zeros(n-m+1, dtype=float)
if zero_s:
for i in range(n-m+1):
Tsegm = T[i:i+m]
Tm = data_m[i]
Ts = data_s[i]
if Ts == 0.0: # data_s is effectively 0
slD[i] = 0.0
else:
Tn = (Tsegm - Tm) / Ts
slD[i] = np.sqrt(np.sum(Tn ** 2))
# random search order for the outer loop
indices = np.arange(0, n-m+1, 1)
np.random.shuffle(indices)
# compute the matrix profile
if self.verbose: print('Iterations:', len(indices))
for i, idx in tqdm(enumerate(indices), disable=not(self.verbose)):
# query for which to compute the distance profile
query = T[idx:idx+m]
# normalized distance profile (using MASS)
D = self._compute_MASS(query, T, n, m, data_m, data_s, data_m[idx], data_s[idx], slD.copy())
# update the matrix profile (keeping minimum distances)
# self-join is True! (we only look at constructing the matrix profile for a single time series)
exclusion_range = (int(max(0, round(idx-m/2))), int(min(round(idx+m/2+1), n-m+1)))
D[exclusion_range[0]:exclusion_range[1]] = np.inf
ix = np.where(D < matrix_profile)[0]
matrix_profile[ix] = D[ix]
return matrix_profile
def _compute_MASS(self, query, T, n, m, data_m, data_s, query_m, query_s, slD):
""" Compute the distance profile using the MASS algorithm.
:param query : np.array(), shape (self.m)
Query segment for which to compute the distance profile.
:param T : np.array(), shape (n_samples)
The time series data for which to compute the matrix profile.
:param n : int
Length of time series T.
:param m : int
Length of the query.
:param data_f : np.array, shape (n + m)
FFT transform of T.
:param data_m : np.array, shape (n - m + 1)
Mean of every segment of length m of T.
:param data_s : np.array, shape (n - m + 1)
STD of every segment of length m of T.
:param query_m : float
Mean of the query segment.
:param query_s : float
Standard deviation of the query segment.
:returns dist_profile : np.array(), shape (n_samples)
Distance profile of the query to time series T.
"""
# CASE 1: query is a straight line segment of 0s
if query_s < 1e-8:
return slD
# CASE 2: query is every other possible subsequence
# compute the sliding dot product
reverse_query = query[::-1]
dot_product = sps.fftconvolve(T, reverse_query, 'valid')
# compute the distance profile without correcting for standard deviation of the main signal being 0
# since this is numpy, it will result in np.inf if the data_sig is 0
dist_profile = np.sqrt(2 * (m - (dot_product - m * query_m * data_m) / (query_s * data_s)))
# correct for data_s being 0
zero_idxs = np.where(data_s < 1e-8)[0]
if len(zero_idxs) > 0:
n_query = (query - query_m) / query_s
d = np.linalg.norm(n_query - np.zeros(m, dtype=float))
dist_profile[zero_idxs] = d
return dist_profile
def _compute_brute_force_distance_profile(self, query, T, n, m, data_f, data_m, data_s, query_m, query_s):
""" Compute the brute force distance profile. """
dist_profile = np.zeros(n-m+1, dtype=float)
# normalize query
if query_m < 1e-8:
n_query = np.zeros(m, dtype=float)
else:
n_query = (query - query_m) / query_s
# compute the distance profile
for i in range(n-m+1):
T_segm = T[i:i+m]
Tm = data_m[i]
Ts = data_s[i]
# normalize time series segment
if Ts < 1e-8:
T_norm = np.zeros(m, dtype=float)
else:
T_norm = (T_segm - Tm) / Ts
# compute distance
dist_profile[i] = np.linalg.norm(T_norm - n_query)
return dist_profile
def _diagonal_dist(self, data, idx, dataLen, subLen, proLen, dataMu, dataSig):
""" Compute the diagonal distance (as in the original matrix profile code) """
xTerm = np.dot(np.ones(proLen-idx+1), np.dot(data[idx-1:idx+subLen-1], data[:subLen]))
mTerm = data[idx-1:proLen-1] * data[:proLen-idx]
aTerm = data[idx+subLen-1:] * data[subLen:dataLen-idx+1]
if proLen != idx:
xTerm[1:] = xTerm[1:] - np.cumsum(mTerm) + np.cumsum(aTerm)
distProfile = np.divide(xTerm - subLen * dataMu[idx-1:] * dataMu[:proLen-idx+1],
subLen * dataSig[idx-1:] * dataSig[:proLen-idx+1])
distProfile = 2 * subLen * (1 - distProfile)
| 36.192941 | 135 | 0.563191 |
20a7f168b064b7c93ea697daa790e550e1ae252e | 583 | py | Python | Python/basic/functools_test.py | InnoFang/misc-code | 561d0c5b02f81ad4978a97f7897b6c4c7b3b56ce | [
"MIT"
] | 4 | 2018-01-02T07:06:49.000Z | 2018-11-22T13:45:39.000Z | Python/basic/functools_test.py | InnoFang/playground | 2998c024a5834be3712734f43fe945f83c64f989 | [
"Apache-2.0"
] | 1 | 2020-02-20T10:08:58.000Z | 2020-02-20T10:08:58.000Z | Python/basic/functools_test.py | InnoFang/playground | 2998c024a5834be3712734f43fe945f83c64f989 | [
"Apache-2.0"
] | null | null | null | import time, functools
def performance(unit):
def perf_decorator(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
start = time.time()
res = f(*args, **kwargs)
end = time.time()
t = (start - end) * 1000 if unit == 'ms'else (start - end)
print 'call %s() in %f %s'%(f.__name__, t, unit)
return res
return wrapper
return perf_decorator
@performance('ms')
def factorial(n):
return reduce(lambda x, y : x * y, range(1, n + 1))
print factorial(10)
print factorial.__name__
| 26.5 | 70 | 0.557461 |
589d1ed2954ea915c22725e948603ddb015906f0 | 690 | css | CSS | css/global/main.css | danielrutter/Basic-Fixed-Width-Navbar | a8f939621a66025b9530b0fb542e3550804d398f | [
"Unlicense"
] | null | null | null | css/global/main.css | danielrutter/Basic-Fixed-Width-Navbar | a8f939621a66025b9530b0fb542e3550804d398f | [
"Unlicense"
] | null | null | null | css/global/main.css | danielrutter/Basic-Fixed-Width-Navbar | a8f939621a66025b9530b0fb542e3550804d398f | [
"Unlicense"
] | null | null | null | /* File Location: /css/global/main.css */
body {
font-family: 'Roboto', sans-serif;
margin: auto;
width: 667px;
}
nav {
box-shadow: 1px 1px 5px #CECECE;
border: 1px solid black;
}
ul {
list-style-type: none;
margin: 0;
padding: 0px;
overflow: hidden;
background-color: #EEE;
}
li {
float: left;
border-right: 1px solid #111;
}
li:last-child {
border-right: 10px solid #555;
}
li a {
display: block;
color: black;
text-align: center;
padding: 12px 17px;
text-decoration: none;
}
li a:hover:not(.active) {
background-color: #333;
color: white;
}
.active {
background-color: #333;
color: white;
}
| 14.375 | 41 | 0.594203 |
8d73c9fa5e9f01483df594765b6b22ea7ca811c2 | 1,375 | js | JavaScript | app-98-nippou/src/backend/fetchRecords.js | Lorenzras/kintone-customize | b875b3d7a27eba11243b9308ee052d65d4ba011d | [
"MIT"
] | null | null | null | app-98-nippou/src/backend/fetchRecords.js | Lorenzras/kintone-customize | b875b3d7a27eba11243b9308ee052d65d4ba011d | [
"MIT"
] | null | null | null | app-98-nippou/src/backend/fetchRecords.js | Lorenzras/kintone-customize | b875b3d7a27eba11243b9308ee052d65d4ba011d | [
"MIT"
] | null | null | null | import { getAppId } from '../../../kintone-api/api';
import { endOfMonth, startOfMonth } from '../helpers/Time';
import { getEmployeeNumber } from './user';
// const ownRecordFilter = `employeeNumber = "${getEmployeeNumber()}"`;
const fetchRecords = (condition) => {
const body = {
app: getAppId(),
query: condition,
};
return kintone.api(
kintone.api.url('/k/v1/records', true),
'GET',
body,
);
};
export const fetchOnDate = (selectedDate) => fetchRecords(
`reportDate = "${selectedDate}" `,
);
export const fetchPlanOnDate = async (
selectedDate, employeeNumber = getEmployeeNumber(),
) => (fetchRecords(
`employeeNumber = "${employeeNumber}" and plansDate = "${selectedDate}" limit 1`,
));
export const fetchReportOnDate = async (
selectedDate, employeeNumber = getEmployeeNumber(),
) => (fetchRecords(
`employeeNumber = "${employeeNumber}" and reportDate = "${selectedDate}" limit 1`,
));
export const fetchMonthRecords = (date, employeeNumber = getEmployeeNumber()) => fetchRecords(
`employeeNumber = "${employeeNumber}"
and reportDate >= "${startOfMonth(date)}"
and reportDate <= "${endOfMonth(date)}"`,
);
export const fetchFields = () => {
const body = {
app: getAppId(),
};
return kintone.api(
kintone.api.url('/k/v1/app/form/fields', true),
'GET',
body,
);
};
export default fetchRecords;
| 25.943396 | 94 | 0.659636 |
ff5ee06aeacb21a9acd7fe5496e8ffa95107915e | 1,569 | py | Python | src/backend/tests/test_sort_record_by_date.py | sico/recordexpungPDX | c2f18322014add7c78b27736bde2d29d1d086aa8 | [
"MIT"
] | 38 | 2019-05-09T03:13:43.000Z | 2022-03-16T22:59:25.000Z | src/backend/tests/test_sort_record_by_date.py | sico/recordexpungPDX | c2f18322014add7c78b27736bde2d29d1d086aa8 | [
"MIT"
] | 938 | 2019-05-02T15:13:21.000Z | 2022-02-27T20:59:00.000Z | src/backend/tests/test_sort_record_by_date.py | kenichi/recordexpungPDX | 100d9249473a01953451b83a72ec1b74574acc43 | [
"MIT"
] | 65 | 2019-05-09T03:28:12.000Z | 2022-03-21T00:06:39.000Z | from expungeservice.record_creator import RecordCreator
from expungeservice.models.record import Record
from tests.factories.case_factory import CaseFactory
def test_sort_by_case_date():
case1 = CaseFactory.create(case_number="1", date_location=["1/1/2018", "Multnomah"])
case2 = CaseFactory.create(case_number="2", date_location=["1/1/2019", "Multnomah"])
case3 = CaseFactory.create(case_number="3", date_location=["1/1/2020", "Multnomah"])
record = Record(tuple([case1, case2, case3]))
assert record.cases[0].summary.case_number == "1"
assert record.cases[1].summary.case_number == "2"
assert record.cases[2].summary.case_number == "3"
sorted_record = RecordCreator.sort_record_by_case_date(record)
assert sorted_record.cases[0].summary.case_number == "3"
assert sorted_record.cases[1].summary.case_number == "2"
assert sorted_record.cases[2].summary.case_number == "1"
def test_sort_if_all_dates_are_same():
case1 = CaseFactory.create(case_number="1")
case2 = CaseFactory.create(case_number="2")
case3 = CaseFactory.create(case_number="3")
record = Record(tuple([case1, case2, case3]))
assert record.cases[0].summary.case_number == "1"
assert record.cases[1].summary.case_number == "2"
assert record.cases[2].summary.case_number == "3"
sorted_record = RecordCreator.sort_record_by_case_date(record)
assert sorted_record.cases[0].summary.case_number == "1"
assert sorted_record.cases[1].summary.case_number == "2"
assert sorted_record.cases[2].summary.case_number == "3"
| 43.583333 | 88 | 0.732314 |
72f11c2afa4568c1087115d32f802eb84e60d7ac | 2,429 | cs | C# | AstroHelper/StockQuote/TurningPoint.cs | Cruisoring/Astroder | 700b6301aa3b978b57fa825785bfa08025ed6437 | [
"MIT"
] | 1 | 2021-03-25T11:21:23.000Z | 2021-03-25T11:21:23.000Z | AstroHelper/StockQuote/TurningPoint.cs | Cruisoring/Astroder | 700b6301aa3b978b57fa825785bfa08025ed6437 | [
"MIT"
] | null | null | null | AstroHelper/StockQuote/TurningPoint.cs | Cruisoring/Astroder | 700b6301aa3b978b57fa825785bfa08025ed6437 | [
"MIT"
] | 1 | 2021-03-01T11:51:50.000Z | 2021-03-01T11:51:50.000Z | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StockQuote
{
public enum TypeOfTurning
{
Bottom,
Top
}
public class TurningPoint<T> : IComparable<TurningPoint<T>>
where T : RecordBase
{
public TypeOfTurning Kind { get; private set; }
public T Record { get; set; }
public DateTime Date { get { return Record.Date; } }
public double Value { get { return (Kind == TypeOfTurning.Top) ? Record.High : Record.Low; } }
public TurningPoint(TypeOfTurning kind, T record)
{
Kind = kind;
Record = record;
}
public override string ToString()
{
return String.Format("{0}({1}): {2}", Date.ToString(Record.TimeFormat), Kind, Value);
}
#region IComparable<TurningPoint<T>> 成员
public int CompareTo(TurningPoint<T> other)
{
return Record.CompareTo(other.Record);
}
#endregion
public static string SummaryOf(List<TurningPoint<T>> turnings)
{
turnings.Sort();
int count = turnings.Count;
if (count < 2)
Console.WriteLine("Only {0} turnings are included in the list." ) ;
int highestIndex = -1, lowestIndex = -1, bottomCount = 0, topCount = 0;
double highest = double.MinValue, lowest = double.MaxValue;
for (int i = 0; i < count; i++)
{
if (turnings[i].Kind == TypeOfTurning.Bottom)
{
bottomCount++;
if (lowest > turnings[i].Value)
{
lowestIndex = i;
lowest = turnings[i].Value;
}
}
else // if (turnings[currentIndex].Kind == TypeOfTurning.Top)
{
topCount++;
if (highest < turnings[i].Value)
{
highest = turnings[i].Value;
highestIndex = i;
}
}
}
return String.Format("{0} turnings, {1} tops, {2} bottoms, highest={3}@{4}, lowest={5}@{6}",
count, topCount, bottomCount, highest, turnings[highestIndex].Date, lowest, turnings[lowestIndex].Date);
}
}
}
| 28.576471 | 120 | 0.495266 |
71af52630a5dea2ea991926815bed625c7aeb5ef | 7,737 | rs | Rust | api/src/dao/user_dao.rs | bpowers1215/money_map | 8b175d76df14f23d9987b6d557adfcc776a7165b | [
"Apache-2.0"
] | 1 | 2018-06-27T16:51:38.000Z | 2018-06-27T16:51:38.000Z | api/src/dao/user_dao.rs | bpowers1215/MoneyMap | 8b175d76df14f23d9987b6d557adfcc776a7165b | [
"Apache-2.0"
] | null | null | null | api/src/dao/user_dao.rs | bpowers1215/MoneyMap | 8b175d76df14f23d9987b6d557adfcc776a7165b | [
"Apache-2.0"
] | null | null | null | // src/dao/user_dao.rs
/// User DAO
/// Handle all database interaction for Users collection
//import
extern crate mongodb;
// Import Modules
// Common Utilities
use ::bson::{Bson, Document};
use ::bson::oid::ObjectId;
use ::mongodb::coll::options::FindOptions;
use ::mongodb::db::ThreadedDatabase;
use ::common::mm_result::{MMResult, MMError, MMErrorKind};
//Models
use ::models::user_model::{UserModel, OutUserModel};
// Constants
static USERS_COLLECTION: &'static str = "users";
/// User DAO
pub struct UserDAO{
db: mongodb::db::Database
}
// User DAO Methods
impl UserDAO{
/// Create UserDAO
///
/// # Arguments
/// db - mongodb::db::Database Cloned database connection
///
/// # Returns
/// `UserDAO`
pub fn new(db: mongodb::db::Database) -> UserDAO{
UserDAO{
db: db
}
}
/// Find All Users
///
/// # Arguments
/// self
/// filter - Option<Document> The find filter
///
/// # Returns
/// `Vec<OutUserModel>`
pub fn find(&self, filter: Option<Document>) -> Vec<OutUserModel>{
let coll = self.db.collection(USERS_COLLECTION);
let mut users = Vec::new();
//Set Find Options and retrieve cursor
let mut find_options = FindOptions::new();
find_options.projection = Some(doc!{
"password" => 0//exclude password
});
match coll.find(filter, Some(find_options)){
Ok(cursor) => {
for result in cursor {
if let Ok(item) = result {
let user = OutUserModel{
id: match item.get("_id"){
Some(obj_id) => match obj_id{ &Bson::ObjectId(ref id) => Some(id.clone().to_hex()), _ => None},
_ => None
},
first_name: match item.get("first_name"){
Some(&Bson::String(ref first_name)) => Some(first_name.clone()),
_ => None
},
last_name: match item.get("last_name"){
Some(&Bson::String(ref last_name)) => Some(last_name.clone()),
_ => None
},
email: match item.get("email"){
Some(&Bson::String(ref email)) => Some(email.clone()),
_ => None
}
};
users.push(user);
}
}
},
Err(e) => {
error!("Find All Users failed: {}", e)
}
}
users
}// end find
/// Find a single User
///
/// # Arguments
/// self
/// filter - Option<Document> The find filter
/// options - Option<FindOptions> The find options
///
/// # Returns
/// `Option<UserModel>` Some UserModel if found, None otherwise
pub fn find_one(self, filter: Option<Document>, options: Option<FindOptions>) -> Option<UserModel>{
let coll = self.db.collection(USERS_COLLECTION);
match coll.find_one(filter, options){
Ok(result) => {
if let Some(document) = result{
Some(UserModel{
id: match document.get("_id"){
Some(obj_id) => match obj_id{ &Bson::ObjectId(ref id) => Some(id.clone()), _ => None},
_ => None
},
first_name: match document.get("first_name"){
Some(&Bson::String(ref first_name)) => Some(first_name.clone()),
_ => None
},
last_name: match document.get("last_name"){
Some(&Bson::String(ref last_name)) => Some(last_name.clone()),
_ => None
},
email: match document.get("email"){
Some(&Bson::String(ref email)) => Some(email.clone()),
_ => None
},
password: match document.get("password"){
Some(&Bson::String(ref password)) => Some(password.clone()),
_ => None
}
})
}else{
None
}
},
Err(e) => {
error!("Find User failed: {}", e);
None
}
}
}// end find_one
/// Create User
/// Save new user to the users collection
///
/// # Arguments
/// self
/// &user - models::user_model::UserModel The user
///
/// # Returns
/// `MMResult<()>`
pub fn create(self, user: &UserModel) -> MMResult<mongodb::coll::results::InsertOneResult>{
let coll = self.db.collection(USERS_COLLECTION);
let doc = doc! {
"first_name" => (match user.get_first_name(){Some(val) => val, None => "".to_string()}),
"last_name" => (match user.get_last_name(){Some(val) => val, None => "".to_string()}),
"email" => (match user.get_email(){Some(val) => val, None => "".to_string()}),
"password" => (match user.get_password(){Some(val) => val, None => "".to_string()})
};
// Insert document into `users` collection
match coll.insert_one(doc.clone(), None){
Ok(result) => Ok(result),
Err(e) => {
warn!("{}", e);
Err(MMError::new("Failed to insert user", MMErrorKind::DAO))
}
}
}// end create
/// Save an existing User
///
/// # Arguments
/// self
/// user_id - String User identifier
/// &user - models::user_model::UserModel The user
///
/// # Returns
/// `MMResult<()>`
pub fn update(self, user_id: String, user: &UserModel) -> MMResult<mongodb::coll::results::UpdateResult>{
let coll = self.db.collection(USERS_COLLECTION);
match ObjectId::with_string(user_id.as_str()){
Ok(id) => {
let filter = doc! {
"_id" => id
};
// Build `$set` document to update document
let mut set_doc = doc!{};
if let Some(first_name) = user.get_first_name(){
set_doc.insert_bson("first_name".to_string(), Bson::String(first_name));
}
if let Some(last_name) = user.get_last_name(){
set_doc.insert_bson("last_name".to_string(), Bson::String(last_name));
}
if let Some(password) = user.get_password(){
set_doc.insert_bson("password".to_string(), Bson::String(password));
}
let update_doc = doc! {"$set" => set_doc};
// Update the user
match coll.update_one(filter.clone(), update_doc.clone(), None){
Ok(result) => Ok(result),
Err(e) => {
error!("{}", e);
Err(MMError::new("Failed to update user.", MMErrorKind::DAO))
}
}
},
Err(e) => {
error!("{}", e);
Err(MMError::new("Failed to update user.", MMErrorKind::DAO))
}
}
}// end update
}
| 35.654378 | 127 | 0.450433 |
11b26db0bed4d32f540bab56106c495b44aec34a | 811 | kt | Kotlin | app/src/main/java/com/example/shinelon/lianqin/model/CourseClassDetails.kt | HB-pencil/lianqin | d7876605647920c59a6bea2bfb6581b60091823e | [
"Apache-2.0"
] | 2 | 2018-02-18T14:54:35.000Z | 2018-03-21T07:12:21.000Z | app/src/main/java/com/example/shinelon/lianqin/model/CourseClassDetails.kt | HB-pencil/lianqin | d7876605647920c59a6bea2bfb6581b60091823e | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/shinelon/lianqin/model/CourseClassDetails.kt | HB-pencil/lianqin | d7876605647920c59a6bea2bfb6581b60091823e | [
"Apache-2.0"
] | null | null | null | package com.example.shinelon.lianqin.model
import java.io.Serializable
/**
* Created by Shinelon on 2018/3/4.
*/
data class CourseClassDetails(val code: Int,val data: DataBeanR,val success: Boolean,val message: String)
data class DataBeanR(val classTotal: ClassTotalBean,val lateStudentList: ArrayList<StudentBean>,val leaveStudentList: ArrayList<StudentBean>,
val absenceStudentList: ArrayList<StudentBean>)
data class ClassTotalBean(val courseClassId: Int,val teacherCourseId: Int,val studentNum: Int,val attendanceNum: Int,
val lateNum: Int,val leaveNum: Int,val absenceNum: Int,val attendanceStatus: Int,
val classOrder: Int,val createTime: String)
data class StudentBean(val name: String,val studentNumber: String): Serializable | 54.066667 | 141 | 0.739827 |
9fe625f50dffc1408e4e691f6448288f446c9cf1 | 1,112 | py | Python | robot/migrations/0011_auto_20200105_1702.py | Misschl/wechat | 8ce76dae32b1086bb83ee6e3fe64cf84845012c0 | [
"Apache-2.0"
] | 1 | 2020-01-07T06:51:19.000Z | 2020-01-07T06:51:19.000Z | robot/migrations/0011_auto_20200105_1702.py | Misschl/wechat | 8ce76dae32b1086bb83ee6e3fe64cf84845012c0 | [
"Apache-2.0"
] | null | null | null | robot/migrations/0011_auto_20200105_1702.py | Misschl/wechat | 8ce76dae32b1086bb83ee6e3fe64cf84845012c0 | [
"Apache-2.0"
] | null | null | null | # Generated by Django 2.1.5 on 2020-01-05 17:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('robot', '0010_auto_20200105_1342'),
]
operations = [
migrations.AlterModelOptions(
name='appmodel',
options={'verbose_name': '对接应用', 'verbose_name_plural': '对接应用'},
),
migrations.AlterField(
model_name='message',
name='is_at',
field=models.BooleanField(default=False, null=True),
),
migrations.AlterField(
model_name='wxuser',
name='friend',
field=models.BooleanField(null=True, verbose_name='我的好友'),
),
migrations.AlterField(
model_name='wxuser',
name='is_friend',
field=models.BooleanField(null=True, verbose_name='和我有好友关系'),
),
migrations.AlterField(
model_name='wxuser',
name='puid',
field=models.CharField(help_text='微信用户的外键', max_length=15, primary_key=True, serialize=False),
),
]
| 29.263158 | 106 | 0.573741 |
e060c6f95aa6b50358ca303c54b868b8bfbf521a | 2,228 | h | C | src/game/ghost.h | teerace/racemod | 5a4ed8c062deb855e5786cd6e3f499601cc200d5 | [
"Zlib"
] | 1 | 2020-05-27T00:07:05.000Z | 2020-05-27T00:07:05.000Z | src/game/ghost.h | teerace/racemod | 5a4ed8c062deb855e5786cd6e3f499601cc200d5 | [
"Zlib"
] | null | null | null | src/game/ghost.h | teerace/racemod | 5a4ed8c062deb855e5786cd6e3f499601cc200d5 | [
"Zlib"
] | null | null | null | #ifndef GAME_GHOST_H
#define GAME_GHOST_H
#include <game/generated/protocol.h>
enum
{
GHOSTDATA_TYPE_SKIN = 0,
GHOSTDATA_TYPE_CHARACTER_NO_TICK,
GHOSTDATA_TYPE_CHARACTER,
GHOSTDATA_TYPE_START_TICK
};
struct CGhostSkin
{
int m_Skin0;
int m_Skin1;
int m_Skin2;
int m_Skin3;
int m_Skin4;
int m_Skin5;
int m_UseCustomColor;
int m_ColorBody;
int m_ColorFeet;
};
struct CGhostCharacter_NoTick
{
int m_X;
int m_Y;
int m_VelX;
int m_VelY;
int m_Angle;
int m_Direction;
int m_Weapon;
int m_HookState;
int m_HookX;
int m_HookY;
int m_AttackTick;
};
struct CGhostCharacter : public CGhostCharacter_NoTick
{
int m_Tick;
};
class CGhostTools
{
public:
static void GetGhostSkin(CGhostSkin *pSkin, const char *pSkinName, int UseCustomColor, int ColorBody, int ColorFeet)
{
StrToInts(&pSkin->m_Skin0, 6, pSkinName);
pSkin->m_UseCustomColor = UseCustomColor;
pSkin->m_ColorBody = ColorBody;
pSkin->m_ColorFeet = ColorFeet;
}
static void GetGhostCharacter(CGhostCharacter *pGhostChar, const CNetObj_Character *pChar)
{
pGhostChar->m_X = pChar->m_X;
pGhostChar->m_Y = pChar->m_Y;
pGhostChar->m_VelX = pChar->m_VelX;
pGhostChar->m_VelY = 0;
pGhostChar->m_Angle = pChar->m_Angle;
pGhostChar->m_Direction = pChar->m_Direction;
pGhostChar->m_Weapon = pChar->m_Weapon;
pGhostChar->m_HookState = pChar->m_HookState;
pGhostChar->m_HookX = pChar->m_HookX;
pGhostChar->m_HookY = pChar->m_HookY;
pGhostChar->m_AttackTick = pChar->m_AttackTick;
pGhostChar->m_Tick = pChar->m_Tick;
}
static void GetNetObjCharacter(CNetObj_Character *pChar, const CGhostCharacter *pGhostChar)
{
mem_zero(pChar, sizeof(CNetObj_Character));
pChar->m_X = pGhostChar->m_X;
pChar->m_Y = pGhostChar->m_Y;
pChar->m_VelX = pGhostChar->m_VelX;
pChar->m_VelY = 0;
pChar->m_Angle = pGhostChar->m_Angle;
pChar->m_Direction = pGhostChar->m_Direction;
pChar->m_Weapon = pGhostChar->m_Weapon == WEAPON_GRENADE ? WEAPON_GRENADE : WEAPON_GUN;
pChar->m_HookState = pGhostChar->m_HookState;
pChar->m_HookX = pGhostChar->m_HookX;
pChar->m_HookY = pGhostChar->m_HookY;
pChar->m_AttackTick = pGhostChar->m_AttackTick;
pChar->m_HookedPlayer = -1;
pChar->m_Tick = pGhostChar->m_Tick;
}
};
#endif
| 23.452632 | 117 | 0.748654 |
143988e9e1c1db943115a4d44e39208172d59a5f | 4,317 | tsx | TypeScript | sites/x6-sites-demos/packages/tutorial/advanced/animation/football/src/app.tsx | avrinfly/X6 | 9637a254e0a5e9beb5a11546fd3208855d1e5f29 | [
"MIT"
] | 3,182 | 2020-06-15T04:04:23.000Z | 2022-03-31T21:52:40.000Z | sites/x6-sites-demos/packages/tutorial/advanced/animation/football/src/app.tsx | avrinfly/X6 | 9637a254e0a5e9beb5a11546fd3208855d1e5f29 | [
"MIT"
] | 1,766 | 2020-06-16T08:11:53.000Z | 2022-03-31T09:58:42.000Z | sites/x6-sites-demos/packages/tutorial/advanced/animation/football/src/app.tsx | avrinfly/X6 | 9637a254e0a5e9beb5a11546fd3208855d1e5f29 | [
"MIT"
] | 867 | 2020-06-17T12:04:47.000Z | 2022-03-31T07:52:16.000Z | import React from 'react'
import { Graph } from '@antv/x6'
import './reg'
import './app.css'
export default class Example extends React.Component {
private container: HTMLDivElement
componentDidMount() {
const graph = new Graph({
container: this.container,
grid: true,
})
graph.addNode({
shape: 'ball',
x: 400,
y: 270,
width: 50,
height: 50,
bounciness: 1.5,
attrs: {
image: {
'xlink:href':
'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB3aWR0aD0iODAwIiBoZWlnaHQ9IjgwMCIgdmlld0JveD0iLTEwNSAtMTA1IDIxMCAyMTAiPgogICA8ZGVmcz4KICAgICAgPGNsaXBQYXRoIGlkPSJiYWxsIj4KICAgICAgICAgPGNpcmNsZSByPSIxMDAiIHN0cm9rZS13aWR0aD0iMCIvPgogICAgICA8L2NsaXBQYXRoPgogICAgICA8cmFkaWFsR3JhZGllbnQgaWQ9InNoYWRvdzEiIGN4PSIuNCIgY3k9Ii4zIiByPSIuOCI+CiAgICAgICAgPHN0b3Agb2Zmc2V0PSIwIiBzdG9wLWNvbG9yPSJ3aGl0ZSIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICAgICAgPHN0b3Agb2Zmc2V0PSIuNCIgc3RvcC1jb2xvcj0id2hpdGUiIHN0b3Atb3BhY2l0eT0iMSIvPgogICAgICAgIDxzdG9wIG9mZnNldD0iLjgiIHN0b3AtY29sb3I9IiNFRUVFRUUiIHN0b3Atb3BhY2l0eT0iMSIvPgogICAgICA8L3JhZGlhbEdyYWRpZW50PgogICAgICA8cmFkaWFsR3JhZGllbnQgaWQ9InNoYWRvdzIiIGN4PSIuNSIgY3k9Ii41IiByPSIuNSI+CiAgICAgICAgPHN0b3Agb2Zmc2V0PSIwIiBzdG9wLWNvbG9yPSJ3aGl0ZSIgc3RvcC1vcGFjaXR5PSIwIi8+CiAgICAgICAgPHN0b3Agb2Zmc2V0PSIuOCIgc3RvcC1jb2xvcj0id2hpdGUiIHN0b3Atb3BhY2l0eT0iMCIvPgogICAgICAgIDxzdG9wIG9mZnNldD0iLjk5IiBzdG9wLWNvbG9yPSJibGFjayIgc3RvcC1vcGFjaXR5PSIuMyIvPgogICAgICAgIDxzdG9wIG9mZnNldD0iMSIgc3RvcC1jb2xvcj0iYmxhY2siIHN0b3Atb3BhY2l0eT0iMSIvPgogICAgICA8L3JhZGlhbEdyYWRpZW50PgogICAgICA8ZyBpZD0iYmxhY2tfc3R1ZmYiIHN0cm9rZS1saW5lam9pbj0icm91bmQiIGNsaXAtcGF0aD0idXJsKCNiYWxsKSI+CiAgICAgICAgIDxnIGZpbGw9ImJsYWNrIj4KICAgICAgICAgICAgPHBhdGggZD0iTSA2LC0zMiBRIDI2LC0yOCA0NiwtMTkgUSA1NywtMzUgNjQsLTQ3IFEgNTAsLTY4IDM3LC03NiBRIDE3LC03NSAxLC02OCBRIDQsLTUxIDYsLTMyIi8+CiAgICAgICAgICAgIDxwYXRoIGQ9Ik0gLTI2LC0yIFEgLTQ1LC04IC02MiwtMTEgUSAtNzQsNSAtNzYsMjIgUSAtNjksNDAgLTUwLDU0IFEgLTMyLDQ3IC0xNywzOSBRIC0yMywxNSAtMjYsLTIiLz4KICAgICAgICAgICAgPHBhdGggZD0iTSAtOTUsMjIgUSAtMTAyLDEyIC0xMDIsLTggViA4MCBIIC04NSBRIC05NSw0NSAtOTUsMjIiLz4KICAgICAgICAgICAgPHBhdGggZD0iTSA1NSwyNCBRIDQxLDQxIDI0LDUyIFEgMjgsNjUgMzEsNzkgUSA1NSw3OCA2OCw2NyBRIDc4LDUwIDgwLDM1IFEgNjUsMjggNTUsMjQiLz4KICAgICAgICAgICAgPHBhdGggZD0iTSAwLDEyMCBMIC0zLDk1IFEgLTI1LDkzIC00Miw4MiBRIC01MCw4NCAtNjAsODEiLz4KICAgICAgICAgICAgPHBhdGggZD0iTSAtOTAsLTQ4IFEgLTgwLC01MiAtNjgsLTQ5IFEgLTUyLC03MSAtMzUsLTc3IFEgLTM1LC0xMDAgLTQwLC0xMDAgSCAtMTAwIi8+CiAgICAgICAgICAgIDxwYXRoIGQ9Ik0gMTAwLC01NSBMIDg3LC0zNyBRIDk4LC0xMCA5Nyw1IEwgMTAwLDYiLz4KICAgICAgICAgPC9nPgogICAgICAgICA8ZyBmaWxsPSJub25lIj4KICAgICAgICAgICAgPHBhdGggZD0iTSA2LC0zMiBRIC0xOCwtMTIgLTI2LC0yICAgICAgICAgICAgICAgICAgICAgIE0gNDYsLTE5IFEgNTQsNSA1NSwyNCAgICAgICAgICAgICAgICAgICAgICBNIDY0LC00NyBRIDc3LC00NCA4NywtMzcgICAgICAgICAgICAgICAgICAgICAgTSAzNywtNzYgUSAzOSwtOTAgMzYsLTEwMCAgICAgICAgICAgICAgICAgICAgICBNIDEsLTY4IFEgLTEzLC03NyAtMzUsLTc3ICAgICAgICAgICAgICAgICAgICAgIE0gLTYyLC0xMSBRIC02NywtMjUgLTY4LC00OSAgICAgICAgICAgICAgICAgICAgICBNIC03NiwyMiBRIC04NSwyNCAtOTUsMjIgICAgICAgICAgICAgICAgICAgICAgTSAtNTAsNTQgUSAtNDksNzAgLTQyLDgyICAgICAgICAgICAgICAgICAgICAgIE0gLTE3LDM5IFEgMCw0OCAyNCw1MiAgICAgICAgICAgICAgICAgICAgICBNIDMxLDc5IFEgMjAsOTIgLTMsOTUgICAgICAgICAgICAgICAgICAgICAgTSA2OCw2NyBMIDgwLDgwICAgICAgICAgICAgICAgICAgICAgIE0gODAsMzUgUSA5MCwyNSA5Nyw1ICAgICAgICAgICAgICIvPgogICAgICAgICA8L2c+CiAgICAgIDwvZz4KICAgPC9kZWZzPgogICA8Y2lyY2xlIHI9IjEwMCIgZmlsbD0id2hpdGUiIHN0cm9rZT0ibm9uZSIvPgogICA8Y2lyY2xlIHI9IjEwMCIgZmlsbD0idXJsKCNzaGFkb3cxKSIgc3Ryb2tlPSJub25lIi8+CiAgIDx1c2UgeGxpbms6aHJlZj0iI2JsYWNrX3N0dWZmIiBzdHJva2U9IiNFRUUiIHN0cm9rZS13aWR0aD0iNyIvPgogICA8dXNlIHhsaW5rOmhyZWY9IiNibGFja19zdHVmZiIgc3Ryb2tlPSIjREREIiBzdHJva2Utd2lkdGg9IjQiLz4KICAgPHVzZSB4bGluazpocmVmPSIjYmxhY2tfc3R1ZmYiIHN0cm9rZT0iIzk5OSIgc3Ryb2tlLXdpZHRoPSIyIi8+CiAgIDx1c2UgeGxpbms6aHJlZj0iI2JsYWNrX3N0dWZmIiBzdHJva2U9ImJsYWNrIiBzdHJva2Utd2lkdGg9IjEiLz4KICAgPGNpcmNsZSByPSIxMDAiIGZpbGw9InVybCgjc2hhZG93MikiIHN0cm9rZT0ibm9uZSIvPgo8L3N2Zz4=',
},
},
})
}
refContainer = (container: HTMLDivElement) => {
this.container = container
}
render() {
return (
<div className="app">
<div className="app-content" ref={this.refContainer} />
</div>
)
}
}
| 100.395349 | 3,573 | 0.914524 |
6b3f6b15e1b6dd6f1c366c67f44d69c38f25b459 | 410 | hpp | C++ | source/platform/windows/input_impl_win.hpp | Kostu96/k2d-engine | 8150230034cf4afc862fcc1a3c262c27d544feed | [
"MIT"
] | null | null | null | source/platform/windows/input_impl_win.hpp | Kostu96/k2d-engine | 8150230034cf4afc862fcc1a3c262c27d544feed | [
"MIT"
] | null | null | null | source/platform/windows/input_impl_win.hpp | Kostu96/k2d-engine | 8150230034cf4afc862fcc1a3c262c27d544feed | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2021-2022 Konstanty Misiak
*
* SPDX-License-Identifier: MIT
*/
#pragma once
#include "platform/input.hpp"
namespace k2d {
class InputImpl
{
public:
InputImpl() = default;
bool isKeyPressed(Key::KeyCode key) const;
bool isMouseButtonPressed(Mouse::MouseCode button) const;
glm::vec2 getMousePosition() const;
};
} // namespace k2d
| 17.826087 | 65 | 0.636585 |
da48af35535eabcd638c85e3909ea87d9f0d5f05 | 73 | sql | SQL | src/test/resources/sql/drop_function/62a3d7a1.sql | Shuttl-Tech/antlr_psql | fcf83192300abe723f3fd3709aff5b0c8118ad12 | [
"MIT"
] | 66 | 2018-06-15T11:34:03.000Z | 2022-03-16T09:24:49.000Z | src/test/resources/sql/drop_function/62a3d7a1.sql | Shuttl-Tech/antlr_psql | fcf83192300abe723f3fd3709aff5b0c8118ad12 | [
"MIT"
] | 13 | 2019-03-19T11:56:28.000Z | 2020-08-05T04:20:50.000Z | src/test/resources/sql/drop_function/62a3d7a1.sql | Shuttl-Tech/antlr_psql | fcf83192300abe723f3fd3709aff5b0c8118ad12 | [
"MIT"
] | 28 | 2019-01-05T19:59:02.000Z | 2022-03-24T11:55:50.000Z | -- file:rangefuncs.sql ln:323 expect:true
DROP FUNCTION foo_mat(int,int)
| 24.333333 | 41 | 0.780822 |
d6221407daee4ac3bc397c81af5c629b3c975f6d | 2,868 | cs | C# | src/Cosmos.Logging.Sinks.File/Cosmos/Logging/Sinks/File/Filters/Navigators/NamespaceNavigationMatcher.cs | CosmosProgramme/Cosmos.Standard | 67b9ef4008cd29242bdbd8ddbd7ba31d555eeca4 | [
"Apache-2.0"
] | 21 | 2017-11-05T01:13:37.000Z | 2018-03-21T03:18:55.000Z | src/Cosmos.Logging.Sinks.File/Cosmos/Logging/Sinks/File/Filters/Navigators/NamespaceNavigationMatcher.cs | CosmosProgramme/Cosmos.Standard | 67b9ef4008cd29242bdbd8ddbd7ba31d555eeca4 | [
"Apache-2.0"
] | 19 | 2019-09-16T08:59:08.000Z | 2019-12-18T07:02:21.000Z | src/Cosmos.Logging.Sinks.File/Cosmos/Logging/Sinks/File/Filters/Navigators/NamespaceNavigationMatcher.cs | CosmosProgramme/Cosmos.Core | 67b9ef4008cd29242bdbd8ddbd7ba31d555eeca4 | [
"Apache-2.0"
] | 5 | 2018-04-03T13:44:54.000Z | 2018-09-04T01:13:26.000Z | using System;
using System.Collections.Generic;
using System.Linq;
namespace Cosmos.Logging.Sinks.File.Filters.Navigators {
internal static class NamespaceNavigationMatcher {
public static bool Match(string @namespace, out IEnumerable<EndValueNamespaceNavigationNode> valueList) {
var root = RootNamespaceNavigation.GetInstance();
var defaultValueList = valueList = root.HasAllValue() ? root.GetStarValues() : root.GetDefaultValues();
if (string.IsNullOrWhiteSpace(@namespace)) return false;
if (string.Compare(@namespace, "Default", StringComparison.OrdinalIgnoreCase) == 0) return true;
var globalValueList = root.GetStarValues();
if (@namespace.IndexOf('.') < 0) {
valueList = MergedOrDefault(root.GetFirstLevelNavValues(@namespace));
return HasValue(valueList);
}
var nss = @namespace.Split('.');
var currentNav = root.GetFirstLevelNavNode(nss[0]);
var index = 0;
do {
if (string.CompareOrdinal(currentNav.NamespaceFragment, "*") == 0) {
valueList = MergedOrDefault(currentNav.GetValues());
return HasValue(valueList);
}
if (string.CompareOrdinal(nss[index], currentNav.NamespaceFragment) != 0) {
valueList = defaultValueList;
return HasValue(valueList);
}
if (index + 1 < nss.Length && !currentNav.HasNextNav()) {
valueList = MergedOrDefault(currentNav.GetValues());
return HasValue(valueList);
}
currentNav = currentNav.GetNextNav(nss[++index]);
} while (index < nss.Length);
valueList = defaultValueList;
return HasValue(valueList);
bool HasGlobaltValueList() => globalValueList != null && globalValueList.Any();
bool HasValue(IEnumerable<EndValueNamespaceNavigationNode> targetValueList) => targetValueList.Any();
IEnumerable<EndValueNamespaceNavigationNode> TouchValueList(IEnumerable<EndValueNamespaceNavigationNode> targetValueList) {
foreach (var value in targetValueList) {
yield return value;
}
if (HasGlobaltValueList()) {
foreach (var value in globalValueList) {
yield return value;
}
}
}
IEnumerable<EndValueNamespaceNavigationNode> MergedOrDefault(IEnumerable<EndValueNamespaceNavigationNode> targetValueList) {
var merged = TouchValueList(targetValueList);
return HasValue(merged) ? merged : root.GetDefaultValues();
}
}
}
} | 40.971429 | 136 | 0.590307 |
57dac26f586a058789085077cb1d5dfa1c7cdaa2 | 2,373 | go | Go | token/core/fabtoken/driver/driver.go | adecaro/fabric-token-sdk | 236b47ac02c6a86ca1dd792c7e65fec890f07522 | [
"Apache-2.0"
] | null | null | null | token/core/fabtoken/driver/driver.go | adecaro/fabric-token-sdk | 236b47ac02c6a86ca1dd792c7e65fec890f07522 | [
"Apache-2.0"
] | null | null | null | token/core/fabtoken/driver/driver.go | adecaro/fabric-token-sdk | 236b47ac02c6a86ca1dd792c7e65fec890f07522 | [
"Apache-2.0"
] | null | null | null | /*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package driver
import (
fabric2 "github.com/hyperledger-labs/fabric-smart-client/platform/fabric"
view2 "github.com/hyperledger-labs/fabric-smart-client/platform/view"
"github.com/hyperledger-labs/fabric-token-sdk/token/core"
"github.com/hyperledger-labs/fabric-token-sdk/token/core/fabtoken"
"github.com/hyperledger-labs/fabric-token-sdk/token/core/identity"
"github.com/hyperledger-labs/fabric-token-sdk/token/core/identity/fabric"
"github.com/hyperledger-labs/fabric-token-sdk/token/driver"
"github.com/hyperledger-labs/fabric-token-sdk/token/services/vault"
)
type Driver struct {
}
func (d *Driver) PublicParametersFromBytes(params []byte) (driver.PublicParameters, error) {
pp, err := fabtoken.NewPublicParamsFromBytes(params)
if err != nil {
return nil, err
}
return pp, nil
}
func (d *Driver) NewTokenService(sp view2.ServiceProvider, publicParamsFetcher driver.PublicParamsFetcher, network string, channel driver.Channel, namespace string) (driver.TokenManagerService, error) {
qe := vault.NewVault(sp, channel, namespace).QueryEngine()
nodeIdentity := view2.GetIdentityProvider(sp).DefaultIdentity()
return fabtoken.NewService(
sp,
channel,
namespace,
publicParamsFetcher,
&fabtoken.VaultPublicParamsLoader{
TokenVault: qe,
PublicParamsFetcher: publicParamsFetcher,
},
qe,
identity.NewProvider(
sp,
map[driver.IdentityUsage]identity.Mapper{
driver.IssuerRole: fabric.NewMapper(fabric.X509MSPIdentity, nodeIdentity, fabric2.GetFabricNetworkService(sp, network).LocalMembership()),
driver.AuditorRole: fabric.NewMapper(fabric.X509MSPIdentity, nodeIdentity, fabric2.GetFabricNetworkService(sp, network).LocalMembership()),
driver.OwnerRole: fabric.NewMapper(fabric.X509MSPIdentity, nodeIdentity, fabric2.GetFabricNetworkService(sp, network).LocalMembership()),
},
),
), nil
}
func (d *Driver) NewValidator(params driver.PublicParameters) (driver.Validator, error) {
return fabtoken.NewValidator(params.(*fabtoken.PublicParams)), nil
}
func (d *Driver) NewPublicParametersManager(params driver.PublicParameters) (driver.PublicParamsManager, error) {
return fabtoken.NewPublicParamsManager(params.(*fabtoken.PublicParams)), nil
}
func init() {
core.Register(fabtoken.PublicParameters, &Driver{})
}
| 35.954545 | 202 | 0.778761 |
bea436cae216af9484e549cecd77880356669e9b | 45 | ts | TypeScript | node_modules/@coreui/icons/js/brand/cib-powershell.d.ts | FranckPharel/ProjetAdminLotto | 2fa93a5bb0e8538e4dca923fd134abf54d66c3ad | [
"MIT"
] | 1 | 2020-09-10T06:53:53.000Z | 2020-09-10T06:53:53.000Z | node_modules/@coreui/icons/js/brand/cib-powershell.d.ts | FranckPharel/ProjetAdminLotto | 2fa93a5bb0e8538e4dca923fd134abf54d66c3ad | [
"MIT"
] | 4 | 2020-04-07T07:15:09.000Z | 2022-03-26T08:25:27.000Z | public/node_modules/@coreui/icons/js/brand/cib-powershell.d.ts | k1000p/sistema | 338fb61009569523436ee45dd4731e0e28e0266a | [
"MIT"
] | null | null | null | export declare const cibPowershell: string[]; | 45 | 45 | 0.822222 |
256428241ef4b2c59348349bd3d5fcaafe2d4447 | 3,380 | cs | C# | Ix.NET/Source/System.Interactive.Tests/ShareTest.cs | tralivali1234/reactive | dfaebe3407db5f6454ec21fcdf6e22e2f1481676 | [
"Apache-2.0"
] | 1 | 2019-01-10T18:54:48.000Z | 2019-01-10T18:54:48.000Z | Ix.NET/Source/System.Interactive.Tests/ShareTest.cs | tralivali1234/reactive | dfaebe3407db5f6454ec21fcdf6e22e2f1481676 | [
"Apache-2.0"
] | null | null | null | Ix.NET/Source/System.Interactive.Tests/ShareTest.cs | tralivali1234/reactive | dfaebe3407db5f6454ec21fcdf6e22e2f1481676 | [
"Apache-2.0"
] | 1 | 2019-01-10T10:11:10.000Z | 2019-01-10T10:11:10.000Z | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Xunit;
using System.Collections;
namespace Tests
{
public class ShareTest : Tests
{
[Fact]
public void Share_Arguments()
{
AssertThrows<ArgumentNullException>(() => EnumerableEx.Share<int>(null));
}
[Fact]
public void Share1()
{
var rng = Enumerable.Range(0, 5).Share();
var e1 = rng.GetEnumerator();
HasNext(e1, 0);
HasNext(e1, 1);
HasNext(e1, 2);
HasNext(e1, 3);
HasNext(e1, 4);
NoNext(e1);
}
[Fact]
public void Share2()
{
var rng = Enumerable.Range(0, 5).Share();
var e1 = rng.GetEnumerator();
var e2 = rng.GetEnumerator();
HasNext(e1, 0);
HasNext(e2, 1);
HasNext(e1, 2);
HasNext(e2, 3);
HasNext(e1, 4);
NoNext(e2);
NoNext(e1);
}
[Fact]
public void Share3()
{
var rng = Enumerable.Range(0, 5).Share();
var e1 = rng.GetEnumerator();
HasNext(e1, 0);
HasNext(e1, 1);
HasNext(e1, 2);
var e2 = rng.GetEnumerator();
HasNext(e2, 3);
HasNext(e2, 4);
NoNext(e2);
NoNext(e1);
}
[Fact]
public void Share4()
{
var rng = Enumerable.Range(0, 5).Share();
var e1 = rng.GetEnumerator();
HasNext(e1, 0);
HasNext(e1, 1);
HasNext(e1, 2);
e1.Dispose();
Assert.False(e1.MoveNext());
}
[Fact]
public void Share5()
{
var rng = Enumerable.Range(0, 5).Share();
var e1 = rng.GetEnumerator();
HasNext(e1, 0);
HasNext(e1, 1);
HasNext(e1, 2);
rng.Dispose();
AssertThrows<ObjectDisposedException>(() => e1.MoveNext());
AssertThrows<ObjectDisposedException>(() => rng.GetEnumerator());
AssertThrows<ObjectDisposedException>(() => ((IEnumerable)rng).GetEnumerator());
}
[Fact]
public void Share6()
{
var rng = Enumerable.Range(0, 5).Share();
var e1 = ((IEnumerable)rng).GetEnumerator();
Assert.True(e1.MoveNext());
Assert.Equal(0, (int)e1.Current);
}
[Fact]
public void ShareLambda_Arguments()
{
AssertThrows<ArgumentNullException>(() => EnumerableEx.Share<int, int>(null, xs => xs));
AssertThrows<ArgumentNullException>(() => EnumerableEx.Share<int, int>(new[] { 1 }, null));
}
[Fact]
public void ShareLambda()
{
var n = 0;
var res = Enumerable.Range(0, 10).Do(_ => n++).Share(xs => xs.Zip(xs, (l, r) => l + r).Take(4)).ToList();
Assert.True(res.SequenceEqual(new[] { 0 + 1, 2 + 3, 4 + 5, 6 + 7 }));
Assert.Equal(8, n);
}
}
}
| 26.825397 | 117 | 0.487278 |
374edb646e698b6df92722875b5f4c6fdc75a575 | 1,322 | lua | Lua | lib/3d/utils/draw_2d.lua | p3r7/ovni | e7cfcc0de370956744a688d7ee5a758e044f59e2 | [
"MIT"
] | 3 | 2020-12-22T16:30:20.000Z | 2021-02-14T13:44:49.000Z | lib/3d/utils/draw_2d.lua | p3r7/ovni | e7cfcc0de370956744a688d7ee5a758e044f59e2 | [
"MIT"
] | null | null | null | lib/3d/utils/draw_2d.lua | p3r7/ovni | e7cfcc0de370956744a688d7ee5a758e044f59e2 | [
"MIT"
] | 1 | 2021-03-07T09:43:31.000Z | 2021-03-07T09:43:31.000Z |
local inspect = include('lib/inspect')
-- ------------------------------------------------------------------------
local draw_2d = {}
-- ------------------------------------------------------------------------
-- POINT
function draw_2d.point(x, y, l)
if l then
screen.level(l)
end
screen.pixel(x, y)
screen.fill()
end
-- ------------------------------------------------------------------------
-- CIRCLE
function draw_2d.circle(x, y, r, l)
if l then
screen.level(l)
end
screen.move(x + r, y)
screen.circle(x, y, r)
screen.fill()
end
-- ------------------------------------------------------------------------
-- LINE
function draw_2d.line(x0, y0, x1, y1, l)
if l then
screen.level(l)
end
screen.move(x0, y0)
screen.line(x1, y1)
screen.stroke()
end
-- ------------------------------------------------------------------------
-- POLYGON
function draw_2d.polygon(lines, l, filled)
if l then
screen.level(l)
end
commit_fn = (filled and screen.fill) or screen.stroke
for i, line in ipairs(lines) do
local p1, p2 = line[1], line[2]
if i == 1 then
screen.move(p1[1], p1[2])
end
screen.line_rel(p2[1]-p1[1], p2[2]-p1[2])
end
commit_fn()
end
-- ------------------------------------------------------------------------
return draw_2d
| 18.619718 | 75 | 0.405446 |
c556b44c00019bf6b97a57bdb2eec796508e14f9 | 577 | swift | Swift | Example/Example/Feature/Next/NextViewModel.swift | siam-biswas/Engine | 9a0efd1e59b393e5007608ff3e2ca13c89f54a95 | [
"MIT"
] | 12 | 2020-08-08T11:21:19.000Z | 2020-11-18T07:12:05.000Z | Example/Example/Feature/Next/NextViewModel.swift | siam-biswas/Engine | 9a0efd1e59b393e5007608ff3e2ca13c89f54a95 | [
"MIT"
] | null | null | null | Example/Example/Feature/Next/NextViewModel.swift | siam-biswas/Engine | 9a0efd1e59b393e5007608ff3e2ca13c89f54a95 | [
"MIT"
] | null | null | null | //
// NextViewModel.swift
// Example
//
// Created by Md. Siam Biswas on 27/7/20.
// Copyright © 2020 siambiswas. All rights reserved.
//
import Foundation
import Engine
protocol NextViewModelProtocol: ViewModel<NextCoordinatorProtocol,NextDependencyProtocol,NextAction,NextState> {
}
class NextViewModel: ViewModel<NextCoordinatorProtocol,NextDependencyProtocol,NextAction,NextState>, NextViewModelProtocol {
override func initialize() {
super.initialize()
}
override func setupReactive() {
super.setupReactive()
}
}
| 21.37037 | 124 | 0.719237 |
43b5df3d323748a94bf4887ccf6b4d95b72d1d59 | 967 | swift | Swift | GamerSky/Classes/Module/Game/GameDetail/Model/GameDetail.swift | game-platform-awaresome/GamerSky | 11f55ffdb876d9057483d4e2f974180456943d66 | [
"Apache-2.0"
] | 3 | 2019-03-16T06:18:03.000Z | 2021-07-03T19:38:43.000Z | GamerSky/Classes/Module/Game/GameDetail/Model/GameDetail.swift | game-platform-awaresome/GamerSky | 11f55ffdb876d9057483d4e2f974180456943d66 | [
"Apache-2.0"
] | null | null | null | GamerSky/Classes/Module/Game/GameDetail/Model/GameDetail.swift | game-platform-awaresome/GamerSky | 11f55ffdb876d9057483d4e2f974180456943d66 | [
"Apache-2.0"
] | null | null | null | //
// GameDetail.swift
// GamerSky
//
// Created by insect_qy on 2018/7/13.
// Copyright © 2018年 engic. All rights reserved.
//
import Foundation
struct GameDetail: Codable {
/// 背景图片
let backgroundURL: String
/// 是否有中文
let chinese: Int
/// 游戏介绍
let description: String
/// 开发者
let developer: String
/// 游戏时长
let gameLength: String
/// 游戏标签
let gameTag: [GameTag]
/// 游戏类型
let gameType: String
/// GS评分
let gsScore: Float
/// 是否发售
let market: Bool
/// 我的评分
let myScore : Float
/// 游戏登陆的平台
let platform: String
/// 玩过的人数
let playedCount: Int
/// 制作厂商
let producer: String
/// 打分的人数
let scoreUserCount: Int
/// 发售时间
let sellTime: String
/// 小图
let thumbnailURL: String
/// 中文游戏名
let title : String
/// 英文游戏名
let englishTitle: String
/// 用户打分
let userScore: Float
/// 想玩的人数
let wantplayCount: Int
}
| 17.907407 | 49 | 0.579111 |
4b735d80b365f4d2664e4cc049e18481dfc5751f | 1,333 | hpp | C++ | irohad/model/commands/transfer_asset.hpp | akshatkarani/iroha | 5acef9dd74720c6185360d951e9b11be4ef73260 | [
"Apache-2.0"
] | 1,467 | 2016-10-25T12:27:19.000Z | 2022-03-28T04:32:05.000Z | irohad/model/commands/transfer_asset.hpp | akshatkarani/iroha | 5acef9dd74720c6185360d951e9b11be4ef73260 | [
"Apache-2.0"
] | 2,366 | 2016-10-25T10:07:57.000Z | 2022-03-31T22:03:24.000Z | irohad/model/commands/transfer_asset.hpp | akshatkarani/iroha | 5acef9dd74720c6185360d951e9b11be4ef73260 | [
"Apache-2.0"
] | 662 | 2016-10-26T04:41:22.000Z | 2022-03-31T04:15:02.000Z | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef IROHA_TRANSFER_ASSET_HPP
#define IROHA_TRANSFER_ASSET_HPP
#include <string>
#include "model/command.hpp"
namespace iroha {
namespace model {
/**
* Transfer asset from one account to another
*/
struct TransferAsset : public Command {
/**
* Source account
*/
std::string src_account_id;
/**
* Destination account
*/
std::string dest_account_id;
/**
* Asset to transfer. Identifier is asset_id
*/
std::string asset_id;
/**
* Transfer description
*/
std::string description;
/**
* Amount of transferred asset
*/
std::string amount;
bool operator==(const Command &command) const override;
TransferAsset() {}
TransferAsset(const std::string &src_account_id,
const std::string &dest_account_id,
const std::string &asset_id,
const std::string &amount)
: src_account_id(src_account_id),
dest_account_id(dest_account_id),
asset_id(asset_id),
amount(amount) {}
};
} // namespace model
} // namespace iroha
#endif // IROHA_TRANSFER_ASSET_HPP
| 22.216667 | 61 | 0.585146 |
9723ab4d2bd4388c9fbdf99da227654f3168104d | 70 | ts | TypeScript | src/components/Table/Row/TableWithRows/index.ts | Huzzky/starwars_fors_tt | 7e2de937e95eafb3a17e577bdc4210eb4353cd86 | [
"MIT"
] | null | null | null | src/components/Table/Row/TableWithRows/index.ts | Huzzky/starwars_fors_tt | 7e2de937e95eafb3a17e577bdc4210eb4353cd86 | [
"MIT"
] | null | null | null | src/components/Table/Row/TableWithRows/index.ts | Huzzky/starwars_fors_tt | 7e2de937e95eafb3a17e577bdc4210eb4353cd86 | [
"MIT"
] | null | null | null | import TableWithRows from './TableWithRows'
export { TableWithRows }
| 17.5 | 43 | 0.785714 |
2542f7eb2a1241655c08e0f69e9f6d737b0b1c16 | 2,039 | js | JavaScript | venn_diagram/js/vcf-parser.js | dillonl/kaleidoscope | 283d30ce307e417fce5e40cf6ff1ee4e1a10a89a | [
"MIT"
] | null | null | null | venn_diagram/js/vcf-parser.js | dillonl/kaleidoscope | 283d30ce307e417fce5e40cf6ff1ee4e1a10a89a | [
"MIT"
] | null | null | null | venn_diagram/js/vcf-parser.js | dillonl/kaleidoscope | 283d30ce307e417fce5e40cf6ff1ee4e1a10a89a | [
"MIT"
] | null | null | null | var variants1 = [];
var variants2 = [];
var analysisCallbacks = [];
$(document).ready(function() {
addVCFFileListener('first-vcf', function (variants) {
variants1 = variants;
});
addVCFFileListener('second-vcf', function (variants) {
variants2 = variants;
});
});
function addVCFFileListener(vcfFileID, callback) {
var vcf = document.getElementById(vcfFileID);
$('#' + vcfFileID).on('change', function(e) {
var file = vcf.files[0];
parseVCF(file, function (variants) {
callback(variants);
runAnalysis();
});
});
}
function variant(chrom, position, ref, alts, info) {
this.chrom = chrom;
this.position = position;
this.ref = ref;
this.alts = alts;
this.info = info;
this.generateVariantKey = function () {
return this.chrom + "\t" + this.position + "\t" + this.ref + "\t" + this.alts.join();
};
}
function parseVariant(variantLine) {
variantSplit = variantLine.split('\t');
var chrom = variantSplit[0];
var position = variantSplit[1];
var ref = variantSplit[3];
var alts = (variantSplit[4].indexOf(',') > -1) ? variantSplit[4].split(',') : [variantSplit[4]];
var info = {};
var infoSplit = variantSplit[7].split(';');
$.each(infoSplit, function(index, infoField) {
var keyValue = infoField.split('=');
info[keyValue[0]] = keyValue[1];
});
return new variant(chrom, position, ref, alts, info);
}
function parseVCF(vcf, callback) {
var fr = new FileReader();
fr.onload = function() {
var vcfLines = fr.result.split('\n');
var variants = [];
$.each(vcfLines, function (index, variantLine) {
if (variantLine.startsWith('#') || variantLine.indexOf('\t') == -1) { return; }
var variant = parseVariant(variantLine);
variants.push(variant);
});
callback(variants);
};
fr.readAsText(vcf);
}
function registerAnalysis(analysisCallback) {
analysisCallbacks.push(analysisCallback);
}
function runAnalysis() {
if (variants1.length == 0 || variants2.length == 0) {
return;
}
$.each(analysisCallbacks, function(index, callback) {
callback(variants1, variants2);
});
}
| 25.4875 | 97 | 0.666013 |
d6378d67a84db7be93d19999a849023a8ed61733 | 1,218 | cs | C# | 01. Stacks and Queues/07. BalancedParenthesis/BalancedParenthesis.cs | Gandjurov/C-Advanced | 9cea524926cf9dc4c813bf6cc2e6a8af5e7a567c | [
"MIT"
] | 1 | 2019-04-09T11:27:26.000Z | 2019-04-09T11:27:26.000Z | 01. Stacks and Queues/07. BalancedParenthesis/BalancedParenthesis.cs | Gandjurov/C-Advanced | 9cea524926cf9dc4c813bf6cc2e6a8af5e7a567c | [
"MIT"
] | null | null | null | 01. Stacks and Queues/07. BalancedParenthesis/BalancedParenthesis.cs | Gandjurov/C-Advanced | 9cea524926cf9dc4c813bf6cc2e6a8af5e7a567c | [
"MIT"
] | null | null | null | using System;
using System.Collections.Generic;
namespace BalancedParenthesis
{
class BalancedParenthesis
{
static void Main(string[] args)
{
var parantheses = Console.ReadLine()
.Trim()
.ToCharArray();
var stack = new Stack<char>();
var paranthesesPair = new Dictionary<char, char>();
paranthesesPair['{'] = '}';
paranthesesPair['['] = ']';
paranthesesPair['('] = ')';
if (parantheses.Length % 2 != 0 || parantheses.Length == 0)
{
Console.WriteLine("NO");
return;
}
foreach (var p in parantheses)
{
if (paranthesesPair.ContainsKey(p))
{
stack.Push(p);
}
else
{
var openParantheses = stack.Pop();
if (paranthesesPair[openParantheses] != p)
{
Console.WriteLine("NO");
return;
}
}
}
Console.WriteLine("YES");
}
}
}
| 26.478261 | 71 | 0.407225 |
8f2a5e4eeaffb751953563f7e7fffebd70a45f52 | 6,955 | lua | Lua | func/player.lua | BEN1JEN/extra-credits-game-jam | 9184c01859c2ece7957f9433363d2dea08a9e539 | [
"MIT"
] | 1 | 2018-08-25T16:07:25.000Z | 2018-08-25T16:07:25.000Z | func/player.lua | BEN1JEN/beat-dungeon | 9184c01859c2ece7957f9433363d2dea08a9e539 | [
"MIT"
] | null | null | null | func/player.lua | BEN1JEN/beat-dungeon | 9184c01859c2ece7957f9433363d2dea08a9e539 | [
"MIT"
] | null | null | null | local player = {}
local playerX
local playerY
local playerWidth = 64
local playerHeight = 64
local heart = tiles.loadImage("assets/heart.png")
local health = 4
local moveTime = 0
local hurtCooldown = 0
local lastHit
local weaponCooldown = 1
local weaponPhase = 0
local axe = tiles.loadImage("assets/tools/axe1.png")
local dagger = tiles.loadImage("assets/tools/dagger.png")
local axeOut = 0
local daggerOut = 0
local playerDirection = "up"
local playerImages = {
up = {
tiles.loadImage("assets/character/characterUp1.png"),
tiles.loadImage("assets/character/characterUp2.png")
},
down = {
tiles.loadImage("assets/character/characterDown1.png"),
tiles.loadImage("assets/character/characterDown2.png")
},
left = {
tiles.loadImage("assets/character/characterLeft1.png"),
tiles.loadImage("assets/character/characterLeft2.png")
},
right = {
tiles.loadImage("assets/character/characterRight1.png"),
tiles.loadImage("assets/character/characterRight2.png")
}
}
function player.getPosition()
return playerX, playerY
end
function player.getScore()
return math.floor(playerY - 32)
end
function player.resetPosition(width)
playerX = (width / 2) + 1
playerY = 32
health = 4
lastHit = nil
hurtCooldown = 0
return player.getPosition()
end
function player.update(delta)
hurtCooldown = hurtCooldown - delta * 2
if hurtCooldown < 0 then
hurtCooldown = 0
end
weaponCooldown = weaponCooldown - delta * 1
if weaponCooldown < 0 then
weaponCooldown = 0
end
axeOut = axeOut - delta * 5
if axeOut < 0 then
axeOut = 0
end
daggerOut = daggerOut - delta * 5
if daggerOut < 0 then
daggerOut = 0
end
local newPlayerX = playerX
local newPlayerY = playerY
local moved = false
local yAmount = math.abs(joystick.getVerticalAxis())
local xAmount = math.abs(joystick.getHorizontalAxis())
if yAmount > 0.1 then
moved = true
newPlayerY = playerY - joystick.getVerticalAxis() * delta * 4
if joystick.getVerticalAxis() < 0 then
playerDirection = "up"
else
playerDirection = "down"
end
end
if xAmount > 0.1 then
moved = true
newPlayerX = playerX + joystick:getHorizontalAxis() * delta * 4
if xAmount > yAmount then
if joystick:getHorizontalAxis() < 0 then
playerDirection = "left"
else
playerDirection = "right"
end
end
end
if joystick.getRightBumper() then
player.attack("axe")
end
if joystick.getLeftBumper() then
player.attack("dagger")
end
if love.keyboard.isDown("up") then
moved = true
newPlayerY = playerY + delta * 4
playerDirection = "up"
elseif love.keyboard.isDown("down") then
moved = true
newPlayerY = playerY - delta * 4
playerDirection = "down"
end
if love.keyboard.isDown("right") then
moved = true
newPlayerX = playerX + delta * 4
playerDirection = "right"
elseif love.keyboard.isDown("left") then
moved = true
newPlayerX = playerX - delta * 4
playerDirection = "left"
end
if love.keyboard.isDown("z") then
player.attack("axe")
end
if love.keyboard.isDown("x") then
player.attack("dagger")
end
if moved then
moveTime = moveTime + delta
else
moveTime = 0
end
playerX, playerY = world.limitMovement(playerX, playerY, newPlayerX, newPlayerY)
-- print("player: " .. playerX .. ", " .. playerY)
end
function player.draw()
local width, height = love.window.getMode()
local frame = math.floor(moveTime / 0.2) % 2 + 1
if daggerOut ~= 0 then
local xDagger, yDagger, rot = 0, 0, 0
local xOffset, yOffset = 8, -80
if playerDirection == "down" then
yOffset = 48
xOffset = -24
end
if playerDirection == "right" then
yOffset = 0
xOffset = 32
end
if playerDirection == "left" then
yOffset = -32
xOffset = -32
end
yDagger = math.abs(daggerOut-0.5)*32
if playerDirection == "down" or playerDirection == "right" then
yDagger = yDagger * -1
rot = math.pi
end
if playerDirection == "left" or playerDirection == "right" then
xDagger = yDagger
yDagger = 0
rot = rot - math.pi/2
end
love.graphics.draw(dagger, width / 2 + xOffset + xDagger, height / 2 + yOffset + yDagger, rot, 2, 2, 16, 16)
end
if axeOut ~= 0 then
local rot = axeOut + math.pi * 1.75
local xOffset, yOffset = -8, -64
if playerDirection == "down" then
yOffset = 32
xOffset = -8
end
if playerDirection == "right" then
yOffset = -32
xOffset = 32
end
if playerDirection == "left" then
yOffset = -32
xOffset = -32
end
if playerDirection == "down" or playerDirection == "right" then
rot = rot + math.pi
end
if playerDirection == "left" or playerDirection == "right" then
rot = rot - math.pi/2
end
love.graphics.draw(axe, width / 2 + xOffset, height / 2 + yOffset, rot, 1, 1, 16, 32)
end
love.graphics.draw(playerImages[playerDirection][frame], width / 2 - playerWidth / 2, height / 2 - playerHeight * 1.5, 0, 2, 2)
end
function player.changeHealth(by, damageSource)
health = health + by
hurtCooldown = 1
lastHit = damageSource
joystick.vibrate(0.5)
if health < 1 then
mode = "end"
song.stop()
end
end
function player.getEndReason()
if health > 0 then
return "Ran out of time!"
else
return "Killed by " .. lastHit
end
end
function player.drawHUD()
local width, height = love.window.getMode()
love.graphics.print("Score: " .. math.floor(playerY - 32), 15, 10)
for i = 1, health do
love.graphics.draw(heart, 1280-20*i-15, 15, 0, 2, 2)
end
local minuets = math.floor(song.getSongRemaining()/60)
local seconds = math.floor(song.getSongRemaining()%60)
if seconds < 10 then
seconds = "0" .. seconds
end
love.graphics.print(minuets .. ":" .. seconds, 15, 669)
if hurtCooldown > 0 then
love.graphics.setColor(231/256, 76/256, 60/256, hurtCooldown)
love.graphics.rectangle("fill", 0, 0, width, height)
love.graphics.setColor(1, 1, 1, 1)
end
love.graphics.rectangle("fill", 1265-weaponCooldown*64, 689, weaponCooldown*64, 16)
end
function player.attack(weapon)
if weaponCooldown == 0 then
local damage, areaOfEffect = 0, 0
if weapon == "dagger" then
daggerOut = 1
weaponCooldown = 0.5
if math.random(1, 5) == 1 then
local xOffset, yOffset = 1, 0
if playerDirection == "left" or playerDirection == "down" then
xOffset = xOffset * -1
end
if playerDirection == "up" or playerDirection == "down" then
yOffset = xOffset
xOffset = 0
end
world.unset(math.floor(playerX+xOffset), math.floor(playerY+yOffset))
end
elseif weapon == "axe" then
axeOut = math.pi / 2
weaponCooldown = 2
for i = -1, 1 do
if math.random(1, 2) == 1 then
local xOffset, yOffset = 1, i
if playerDirection == "left" or playerDirection == "down" then
xOffset = xOffset * -1
yOffset = yOffset * -1
end
if playerDirection == "up" or playerDirection == "down" then
local tmp = yOffset
yOffset = xOffset
xOffset = tmp
end
world.unset(math.floor(playerX+xOffset), math.floor(playerY+yOffset))
end
end
end
end
end
return player
| 25.759259 | 128 | 0.683968 |
977d89dd218d6b212d11b31156e8ced10a83c44b | 934 | swift | Swift | Housing/JinModel.swift | Nandalu/Housing | cc6f615a272c56b850506f1e1e6bd3b294622313 | [
"MIT"
] | 3 | 2018-10-08T04:15:48.000Z | 2021-04-07T16:37:40.000Z | Housing/JinModel.swift | Nandalu/Housing | cc6f615a272c56b850506f1e1e6bd3b294622313 | [
"MIT"
] | 2 | 2018-02-21T12:16:48.000Z | 2018-02-21T12:21:13.000Z | Housing/JinModel.swift | Nandalu/Housing | cc6f615a272c56b850506f1e1e6bd3b294622313 | [
"MIT"
] | null | null | null | //
// JinModel.swift
// Housing
//
// Created by denkeni on 01/11/2017.
// Copyright © 2017 Nandalu. All rights reserved.
//
import Foundation
import MapKit
struct JinModel : Codable {
let Msgs : [MsgModel]
struct MsgModel : Codable {
let ID : String
let Time : TimeInterval
let Body : String
let Lat : CLLocationDegrees
let Lng : CLLocationDegrees
let SKF64 : Double
let User : UserModel
let App : AppModel
struct UserModel : Codable {
let ID : String
let Name : String
let Picture : String
let ThirdPartyID : String
let Privacy : String
}
struct AppModel : Codable {
let ID : String
let Name : String
let Icon : String
let MarketingURI : String
}
}
}
struct JinErrorModel : Codable {
let Error : String
}
| 22.238095 | 50 | 0.555675 |
57068c868a6773ccf475313730e8b7085f35e655 | 416 | js | JavaScript | html/search/variables_78.js | mive93/AngryTom | 4fe67f48fbea2053c26bf51fdb62026e4bde73bc | [
"Apache-2.0"
] | null | null | null | html/search/variables_78.js | mive93/AngryTom | 4fe67f48fbea2053c26bf51fdb62026e4bde73bc | [
"Apache-2.0"
] | null | null | null | html/search/variables_78.js | mive93/AngryTom | 4fe67f48fbea2053c26bf51fdb62026e4bde73bc | [
"Apache-2.0"
] | null | null | null | var searchData=
[
['x',['x',['../structGiocatore.html#ae3cd96fd365828a2aa0056db133db15a',1,'Giocatore::x()'],['../structColpo.html#a48413e32744aa1c695cf8101ed719be5',1,'Colpo::x()'],['../structNemici.html#abc8df94b28bade640027ed5020731e3d',1,'Nemici::x()'],['../structImpatti.html#a7a515775bd6eca2ded13b6ce51554fb4',1,'Impatti::x()'],['../structSfondo.html#ad67a51ec529a9ab1bae350d236c8c317',1,'Sfondo::x()']]]
];
| 83.2 | 394 | 0.735577 |
c80b89f6676c036a2f4be4611edba4e1b0ad511b | 319 | sql | SQL | posda/posdatools/queries/sql/AddFilterToTab.sql | UAMS-DBMI/PosdaTools | 7d33605da1b88e4787a1368dbecaffda1df95e5b | [
"Apache-2.0"
] | 6 | 2019-01-17T15:47:44.000Z | 2022-02-02T16:47:25.000Z | posda/posdatools/queries/sql/AddFilterToTab.sql | UAMS-DBMI/PosdaTools | 7d33605da1b88e4787a1368dbecaffda1df95e5b | [
"Apache-2.0"
] | 23 | 2016-06-08T21:51:36.000Z | 2022-03-02T08:11:44.000Z | posda/posdatools/queries/sql/AddFilterToTab.sql | UAMS-DBMI/PosdaTools | 7d33605da1b88e4787a1368dbecaffda1df95e5b | [
"Apache-2.0"
] | null | null | null | -- Name: AddFilterToTab
-- Schema: posda_queries
-- Columns: []
-- Args: ['query_tab_name', 'filter_name', 'sort_order']
-- Tags: ['meta', 'test', 'hello', 'query_tabs', 'bills_test']
-- Description: Add a filter to a tab
insert into query_tabs_query_tag_filter(query_tab_name, filter_name, sort_order)
values(?, ?, ?) | 35.444444 | 80 | 0.705329 |
c675b74078fdc8567ea2be181c76fee78293a249 | 333 | py | Python | Course_2/Week_4/streams.py | internetworksio/Google-ITAutomation-Python | 6027750a33e8df883d762223bb0c4a5a95395bc0 | [
"MIT"
] | 2 | 2021-03-23T16:02:32.000Z | 2022-03-13T09:32:56.000Z | Course_2/Week_4/streams.py | internetworksio/Google-ITAutomation-Python | 6027750a33e8df883d762223bb0c4a5a95395bc0 | [
"MIT"
] | null | null | null | Course_2/Week_4/streams.py | internetworksio/Google-ITAutomation-Python | 6027750a33e8df883d762223bb0c4a5a95395bc0 | [
"MIT"
] | 7 | 2021-01-14T05:39:54.000Z | 2022-03-13T09:33:01.000Z | #!/usr/bin/env python3
"""
This script is used for course notes.
Author: Erick Marin
Date: 12/19/2020
"""
data = input("This will come from STDIN: ")
print("Now we write it to STDOUT: " + data)
# Generating a standard error (type) by concatenating a string with an integer
print("Now we generate an error to STDERR: " + data + 1)
| 23.785714 | 78 | 0.702703 |
13c175d494a8be84997081955566063181109dcb | 1,216 | ps1 | PowerShell | Diagnostics/ExchangeLogCollector/extern/Import-ScriptConfigFile.ps1 | dpaulson45/CSS-Exchange | 16154ff8217a61694b56c8d46a136aa09e03187c | [
"MIT"
] | 1 | 2021-06-23T12:28:47.000Z | 2021-06-23T12:28:47.000Z | Diagnostics/ExchangeLogCollector/extern/Import-ScriptConfigFile.ps1 | paulvill76/CSS-Exchange | 824886e13761ddf2f237855564b76a66ab2e29c6 | [
"MIT"
] | null | null | null | Diagnostics/ExchangeLogCollector/extern/Import-ScriptConfigFile.ps1 | paulvill76/CSS-Exchange | 824886e13761ddf2f237855564b76a66ab2e29c6 | [
"MIT"
] | null | null | null | #https://github.com/dpaulson45/PublicPowerShellFunctions/blob/master/src/Common/Import-ScriptConfigFile/Import-ScriptConfigFile.ps1
#v21.02.07.1240
Function Import-ScriptConfigFile {
[CmdletBinding()]
param(
[Parameter(
Mandatory = $true
)]
[string]$ScriptConfigFileLocation
)
#Function Version #v21.02.07.1240
Write-VerboseWriter("Calling: Import-ScriptConfigFile")
Write-VerboseWriter("Passed: [string]ScriptConfigFileLocation: '$ScriptConfigFileLocation'")
if (!(Test-Path $ScriptConfigFileLocation)) {
throw [System.Management.Automation.ParameterBindingException] "Failed to provide valid ScriptConfigFileLocation"
}
try {
$content = Get-Content $ScriptConfigFileLocation -ErrorAction Stop
$jsonContent = $content | ConvertFrom-Json
} catch {
throw "Failed to convert ScriptConfigFileLocation from a json type object."
}
$jsonContent |
Get-Member |
Where-Object { $_.Name -ne "Method" } |
ForEach-Object {
Write-VerboseWriter("Adding variable $($_.Name)")
Set-Variable -Name $_.Name -Value ($jsonContent.$($_.Name)) -Scope Script
}
}
| 34.742857 | 132 | 0.671875 |
73cb3547fd6831812a22348dd418b35c74798cd6 | 130 | sql | SQL | bin/apache-hive-3.1.2-bin/scripts/metastore/upgrade/derby/hive-schema-0.11.0.derby.sql | ptrick/hdfs-hive-sql-playground | 83f2aaa79f022a3c320939eace1fd2d06583187f | [
"Apache-2.0"
] | null | null | null | bin/apache-hive-3.1.2-bin/scripts/metastore/upgrade/derby/hive-schema-0.11.0.derby.sql | ptrick/hdfs-hive-sql-playground | 83f2aaa79f022a3c320939eace1fd2d06583187f | [
"Apache-2.0"
] | null | null | null | bin/apache-hive-3.1.2-bin/scripts/metastore/upgrade/derby/hive-schema-0.11.0.derby.sql | ptrick/hdfs-hive-sql-playground | 83f2aaa79f022a3c320939eace1fd2d06583187f | [
"Apache-2.0"
] | null | null | null | version https://git-lfs.github.com/spec/v1
oid sha256:7c866e86c270100dc904dac809983b68286014dbe3fce1864d8511376e429de8
size 21180
| 32.5 | 75 | 0.884615 |
1bf7c3308a90ebfd05d7f8c8425e2e8aa256b824 | 1,003 | rb | Ruby | db/migrate/20110818141205_create_nodes.rb | tanordheim/adapt-cms | e1e828b25945daa6182f653eae3047523f36a409 | [
"MIT"
] | null | null | null | db/migrate/20110818141205_create_nodes.rb | tanordheim/adapt-cms | e1e828b25945daa6182f653eae3047523f36a409 | [
"MIT"
] | null | null | null | db/migrate/20110818141205_create_nodes.rb | tanordheim/adapt-cms | e1e828b25945daa6182f653eae3047523f36a409 | [
"MIT"
] | null | null | null | class CreateNodes < ActiveRecord::Migration
def change
create_table :nodes do |t|
t.references :site, :null => false
t.string :type
t.string :ancestry
t.integer :position, :null => false
t.string :slug, :null => false
t.string :uri, :null => false
t.boolean :published, :null => false, :default => true
t.date :published_on
t.boolean :show_in_navigation, :null => false, :default => true
t.references :variant
t.string :name, :null => false
# Link attributes
t.string :href
t.integer :creator_id, :null => false
t.integer :updater_id, :null => false
t.timestamps :null => false
end
add_index :nodes, :site_id
add_index :nodes, :type
add_index :nodes, [:site_id, :ancestry]
add_index :nodes, :position
add_index :nodes, [:site_id, :uri], :unique => true
add_index :nodes, :published
add_index :nodes, :show_in_navigation
add_index :nodes, :variant_id
end
end
| 27.861111 | 69 | 0.627119 |
12bdd7f72e719e39c561b75c7d450efa8b71590a | 4,291 | cs | C# | Net45/Mature.Socket.Server.DotNetty/TCPServer.cs | AelousDing/Mature.WPF | 7b01d84f34803b037707098c7ceee87df0cb963d | [
"MIT"
] | null | null | null | Net45/Mature.Socket.Server.DotNetty/TCPServer.cs | AelousDing/Mature.WPF | 7b01d84f34803b037707098c7ceee87df0cb963d | [
"MIT"
] | null | null | null | Net45/Mature.Socket.Server.DotNetty/TCPServer.cs | AelousDing/Mature.WPF | 7b01d84f34803b037707098c7ceee87df0cb963d | [
"MIT"
] | 1 | 2021-06-16T07:28:47.000Z | 2021-06-16T07:28:47.000Z | using DotNetty.Codecs;
using DotNetty.Handlers.Logging;
using DotNetty.Handlers.Timeout;
using DotNetty.Transport.Bootstrapping;
using DotNetty.Transport.Channels;
using DotNetty.Transport.Channels.Sockets;
using Mature.Socket.Common.DotNetty;
using Mature.Socket.Compression;
using Mature.Socket.Config;
using Mature.Socket.ContentBuilder;
using Mature.Socket.DataFormat;
using Mature.Socket.Validation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace Mature.Socket.Server.DotNetty
{
public class TCPServer : ITCPServer
{
private const int CmdByteCount = 20;
private const int CompressionByteCount = 1;
private const int LengthByteCount = 4;
private const int MessageIdCount = 32;
private const int ValidationIdCount = 8;
public event EventHandler<SessionInfo> NewSessionConnected;
public event Action<ISessionWrapper, StringPackageInfo> NewRequestReceived;
public event EventHandler<SessionInfo> SessionClosed;
IDataValidation dataValidation;
ICompression compression;
public TCPServer(IDataValidation dataValidation, ICompression compression)
{
this.dataValidation = dataValidation;
this.compression = compression;
DotNettyChannelManager.Instance.NewSessionConnected += (s, e) => NewSessionConnected?.Invoke(this, e);
DotNettyChannelManager.Instance.SessionClosed += (s, e) => SessionClosed?.Invoke(this, e);
}
public IEnumerable<ISessionWrapper> GetAllSession()
{
return DotNettyChannelManager.Instance.Channels?.Select(p => new SessionWrapper(p.Value));
}
public ISessionWrapper GetSessionByID(string sessionID)
{
var channel = DotNettyChannelManager.Instance.Channels?.FirstOrDefault(p => p.Value.Id.AsLongText() == sessionID).Value;
return channel == null ? null : new SessionWrapper(channel);
}
IEventLoopGroup bossGroup = new MultithreadEventLoopGroup();
IEventLoopGroup workerGroup = new MultithreadEventLoopGroup();
ServerBootstrap bootstrap;
IChannel boundChannel;
public bool Start(IServerConfig serverConfig)
{
var handler = new FrameHandler(dataValidation, compression);
handler.Handler += Handler_Handler;
bootstrap = new ServerBootstrap();
bootstrap.Group(bossGroup, workerGroup);
bootstrap.Channel<TcpServerSocketChannel>();
bootstrap
.Option(ChannelOption.SoBacklog, 100)
.Handler(new LoggingHandler("SRV-LSTN"))
.ChildHandler(new ActionChannelInitializer<IChannel>(channel =>
{
IChannelPipeline pipeline = channel.Pipeline;
pipeline.AddLast(new LoggingHandler("SRV-CONN"));
pipeline.AddLast(new IdleStateHandler(70, 0, 0));
pipeline.AddLast(new ChannelManagerHandler());
pipeline.AddLast(new HeatBeatHandler());
pipeline.AddLast(new LengthFieldBasedFrameDecoder(64 * 1024, CmdByteCount + CompressionByteCount, LengthByteCount, MessageIdCount + ValidationIdCount, 0));
pipeline.AddLast(handler);
pipeline.AddLast(new ByteArrayEncoder());
}));
boundChannel = bootstrap.BindAsync(serverConfig.Port).Result;
Console.WriteLine(boundChannel != null ? "Start successfully" : "Failed to start");
return boundChannel != null;
}
private void Handler_Handler(IChannel channel, StringPackageInfo e)
{
NewRequestReceived?.Invoke(new SessionWrapper(channel), e);
}
public void Stop()
{
try
{
boundChannel.CloseAsync().Wait();
}
finally
{
Task.WaitAll(bossGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)),
workerGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)));
}
}
}
}
| 42.068627 | 175 | 0.655791 |
40966d07d00bf6c2d9e1aa10e191d7a0ceb93b79 | 2,771 | tsx | TypeScript | src/pages/categories.tsx | leejy001/leeblog | 8a4985d8e99c3479f4d33e98761785c76a8b6d8d | [
"RSA-MD"
] | 4 | 2021-07-11T13:35:53.000Z | 2021-12-13T06:53:02.000Z | src/pages/categories.tsx | leejy001/leeblog | 8a4985d8e99c3479f4d33e98761785c76a8b6d8d | [
"RSA-MD"
] | null | null | null | src/pages/categories.tsx | leejy001/leeblog | 8a4985d8e99c3479f4d33e98761785c76a8b6d8d | [
"RSA-MD"
] | 1 | 2021-07-14T06:16:18.000Z | 2021-07-14T06:16:18.000Z | import React, { useMemo } from 'react'
import { graphql } from 'gatsby'
import queryString, { ParsedQuery } from 'query-string'
import Container from 'components/Common/Container'
import CategoryList, { CategoryListTypes } from 'components/Main/CategoryList'
import PostList from 'components/Main/PostList'
import { PostItemType } from 'types/PostItem.types'
type CategoriesType = {
location: {
search: string
}
data: {
site: {
siteMetadata: {
title: string
description: string
siteUrl: string
}
}
allMarkdownRemark: {
edges: PostItemType[]
}
file: {
publicURL: string
}
}
}
function CategoriesPage({
location: { search },
data: {
site: {
siteMetadata: { title, description, siteUrl },
},
allMarkdownRemark: { edges },
file: { publicURL },
},
}: CategoriesType) {
const parsed: ParsedQuery<string> = queryString.parse(search)
const selectedCategory: string =
typeof parsed.category !== 'string' || !parsed.category
? 'All'
: parsed.category
const categoryList = useMemo(
() =>
edges.reduce(
(
list: CategoryListTypes['categoryList'],
{
node: {
frontmatter: { categories },
},
}: PostItemType,
) => {
categories.forEach(category => {
if (list[category] === undefined) list[category] = 1
else list[category]++
})
list['All']++
return list
},
{ All: 0 },
),
[],
)
return (
<Container
title={title}
description={description}
url={siteUrl}
image={publicURL}
>
<CategoryList
selectedCategory={selectedCategory}
categoryList={categoryList}
/>
<PostList selectedCategory={selectedCategory} posts={edges} />
</Container>
)
}
export default CategoriesPage
export const getCategories = graphql`
query getCategories {
site {
siteMetadata {
title
description
siteUrl
}
}
allMarkdownRemark(
sort: { order: DESC, fields: [frontmatter___date, frontmatter___title] }
filter: { frontmatter: { categories: { ne: null } } }
) {
edges {
node {
id
fields {
slug
}
frontmatter {
title
summary
date(formatString: "YYYY.MM.DD.")
categories
showThumbnail
thumbnail {
childImageSharp {
gatsbyImageData(width: 768, height: 400)
}
}
}
}
}
}
file(name: { eq: "profile-image" }) {
publicURL
}
}
`
| 21.818898 | 78 | 0.539877 |
af4f02a81fc1282bc7553a8a3ea160e7f02efbc5 | 6,008 | py | Python | tests/unit/test_auto_deploy_task.py | mrnicegyu11/osparc-deployment-agent | e38508836ed7637595b152f8a1cb1c0e0b62f42f | [
"MIT"
] | 1 | 2021-11-15T12:26:26.000Z | 2021-11-15T12:26:26.000Z | tests/unit/test_auto_deploy_task.py | ITISFoundation/osparc-deployment-agent | 54a8d5b3d1cdbcc71bbfa93c96fce6b770b2050b | [
"MIT"
] | 44 | 2020-12-23T14:50:00.000Z | 2022-03-30T09:31:31.000Z | tests/unit/test_auto_deploy_task.py | mrnicegyu11/osparc-deployment-agent | e38508836ed7637595b152f8a1cb1c0e0b62f42f | [
"MIT"
] | 2 | 2020-12-16T14:24:08.000Z | 2021-11-15T12:26:40.000Z | # pylint:disable=wildcard-import
# pylint:disable=unused-import
# pylint:disable=unused-variable
# pylint:disable=unused-argument
# pylint:disable=redefined-outer-name
# pylint:disable=bare-except
import asyncio
from asyncio import Future
from pathlib import Path
from typing import Any, Awaitable, Callable, Dict, Iterator
import aioresponses
import pytest
import yaml
from aiohttp.test_utils import TestClient
from aioresponses import aioresponses
# Monkeypatch the tenacity wait time https://stackoverflow.com/questions/47906671/python-retry-with-tenacity-disable-wait-for-unittest
from tenacity.wait import wait_none
from simcore_service_deployment_agent import auto_deploy_task, portainer
from simcore_service_deployment_agent.app_state import State
from simcore_service_deployment_agent.application import create
from simcore_service_deployment_agent.git_url_watcher import GitUrlWatcher
portainer._portainer_request.retry.wait = wait_none()
@pytest.fixture()
def mocked_docker_registries_watcher(mocker) -> Dict[str, Any]:
mock_docker_watcher = {
"init": mocker.patch.object(
auto_deploy_task.DockerRegistriesWatcher, "init", return_value={}
),
"check_for_changes": mocker.patch.object(
auto_deploy_task.DockerRegistriesWatcher,
"check_for_changes",
return_value={},
),
}
return mock_docker_watcher
@pytest.fixture()
def mocked_git_url_watcher(mocker) -> Dict[str, Any]:
mock_git_changes = {
"init": mocker.patch.object(GitUrlWatcher, "init", return_value={}),
"check_for_changes": mocker.patch.object(
GitUrlWatcher, "check_for_changes", return_value={}
),
}
return mock_git_changes
@pytest.fixture(scope="session")
def mock_stack_config() -> Dict[str, Any]:
cfg = {
"version": "3.7",
"services": {
"fake_service": {"image": "fake_image"},
"fake_service2": {"image": "fake_image"},
},
}
return cfg
@pytest.fixture()
def mocked_stack_file(
valid_config: Dict[str, Any], mock_stack_config: Dict[str, Any]
) -> Iterator[Path]:
file_name = Path(valid_config["main"]["docker_stack_recipe"]["stack_file"])
with file_name.open("w", encoding="utf-8") as fp:
yaml.safe_dump(mock_stack_config, fp)
yield file_name
file_name.unlink()
@pytest.fixture
def client(
loop: asyncio.AbstractEventLoop,
aiohttp_unused_port: Callable[[], int],
aiohttp_client: Callable[..., Awaitable[TestClient]],
valid_config: Dict[str, Any],
monkeypatch,
) -> Iterator[TestClient]:
# increase the speed to fail
monkeypatch.setattr(auto_deploy_task, "RETRY_COUNT", 2)
monkeypatch.setattr(auto_deploy_task, "RETRY_WAIT_SECS", 1)
app = create(valid_config)
server_kwargs = {"port": aiohttp_unused_port(), "host": "localhost"}
client = loop.run_until_complete(aiohttp_client(app, server_kwargs=server_kwargs))
yield client
def test_client(portainer_service_mock: aioresponses, client: TestClient):
# check that the client starts/stops correctly
pass
async def test_wait_for_dependencies_no_portainer_up(client: TestClient):
assert client.app # nosec
# wait for the app to start
while client.app["state"][auto_deploy_task.TASK_NAME] == State.STARTING:
await asyncio.sleep(1)
assert client.app["state"][auto_deploy_task.TASK_NAME] == State.FAILED
async def test_filter_services(
valid_config: Dict[str, Any], valid_docker_stack_file: Path
):
stack_cfg = await auto_deploy_task.filter_services(
valid_config, valid_docker_stack_file
)
assert "app" not in stack_cfg["services"]
assert "some_volume" not in stack_cfg["volumes"]
assert "build" not in stack_cfg["services"]["anotherapp"]
async def test_add_parameters(
valid_config: Dict[str, Any], valid_docker_stack: Dict[str, Any]
):
stack_cfg = await auto_deploy_task.add_parameters(valid_config, valid_docker_stack)
assert "extra_hosts" in stack_cfg["services"]["app"]
hosts = stack_cfg["services"]["app"]["extra_hosts"]
assert "original_host:243.23.23.44" in hosts
assert "some_test_host:123.43.23.44" in hosts
assert "another_test_host:332.4.234.12" in hosts
assert "environment" in stack_cfg["services"]["app"]
envs = stack_cfg["services"]["app"]["environment"]
assert "ORIGINAL_ENV" in envs
assert envs["ORIGINAL_ENV"] == "the original env"
assert "YET_ANOTHER_ENV" in envs
assert envs["YET_ANOTHER_ENV"] == "this one is replaced"
assert "TEST_ENV" in envs
assert envs["TEST_ENV"] == "some test"
assert "ANOTHER_TEST_ENV" in envs
assert envs["ANOTHER_TEST_ENV"] == "some other test"
assert "extra_hosts" in stack_cfg["services"]["anotherapp"]
hosts = stack_cfg["services"]["anotherapp"]["extra_hosts"]
assert "some_test_host:123.43.23.44" in hosts
assert "another_test_host:332.4.234.12" in hosts
assert "environment" in stack_cfg["services"]["app"]
envs = stack_cfg["services"]["app"]["environment"]
assert "TEST_ENV" in envs
assert envs["TEST_ENV"] == "some test"
assert "ANOTHER_TEST_ENV" in envs
assert envs["ANOTHER_TEST_ENV"] == "some other test"
assert "image" in stack_cfg["services"]["app"]
assert "jenkins:latest" in stack_cfg["services"]["app"]["image"]
assert "image" in stack_cfg["services"]["anotherapp"]
assert "ubuntu" in stack_cfg["services"]["anotherapp"]["image"]
async def test_setup_task(
mocked_docker_registries_watcher,
mocked_git_url_watcher,
mocked_cmd_utils,
mocked_stack_file,
portainer_service_mock: aioresponses,
mattermost_service_mock: aioresponses,
client: TestClient,
):
assert client.app
assert auto_deploy_task.TASK_NAME in client.app
while client.app["state"][auto_deploy_task.TASK_NAME] == State.STARTING:
await asyncio.sleep(1)
assert client.app["state"][auto_deploy_task.TASK_NAME] == State.RUNNING
| 34.528736 | 134 | 0.717876 |
df7c6869542bffd7b730fb1d80e10490a3d43ae0 | 313 | cs | C# | src/Day06/CustomsSheetGroup.cs | david1995/AdventOfCode2020 | 912e9e04727347e542b1d9ae6011103b5e883ed0 | [
"MIT"
] | null | null | null | src/Day06/CustomsSheetGroup.cs | david1995/AdventOfCode2020 | 912e9e04727347e542b1d9ae6011103b5e883ed0 | [
"MIT"
] | null | null | null | src/Day06/CustomsSheetGroup.cs | david1995/AdventOfCode2020 | 912e9e04727347e542b1d9ae6011103b5e883ed0 | [
"MIT"
] | null | null | null | using System.Collections.Immutable;
namespace Day06
{
public class CustomsSheetGroup
{
public CustomsSheetGroup(IImmutableList<CustomsSheet> customsSheets)
{
CustomsSheets = customsSheets;
}
public IImmutableList<CustomsSheet> CustomsSheets { get; }
}
}
| 20.866667 | 76 | 0.667732 |
15af0d45edb6943c277ff9f6829462f3d9e25e16 | 742 | rb | Ruby | app/models/manageiq/providers/redhat/discovery.rb | dsatsura/manageiq-providers-ovirt | ed34bfcf8113703a09f32fc53d43c9606d4b4d85 | [
"Apache-2.0"
] | 7 | 2017-04-06T21:16:57.000Z | 2020-10-08T20:52:00.000Z | app/models/manageiq/providers/redhat/discovery.rb | dsatsura/manageiq-providers-ovirt | ed34bfcf8113703a09f32fc53d43c9606d4b4d85 | [
"Apache-2.0"
] | 572 | 2017-04-07T11:29:18.000Z | 2022-02-25T21:11:09.000Z | app/models/manageiq/providers/redhat/discovery.rb | dsatsura/manageiq-providers-ovirt | ed34bfcf8113703a09f32fc53d43c9606d4b4d85 | [
"Apache-2.0"
] | 65 | 2017-04-06T19:41:29.000Z | 2022-03-30T06:31:57.000Z | require 'manageiq/network_discovery/port'
require 'ovirtsdk4'
module ManageIQ
module Providers
module Redhat
class Discovery
OVIRT_DEFAULT_PORT = 443
class << self
def probe(ost)
if ManageIQ::NetworkDiscovery::Port.open?(ost, OVIRT_DEFAULT_PORT) &&
ovirt_exists?(ost.ipaddr, $rhevm_log)
ost.hypervisor << :rhevm
end
end
private
def ovirt_exists?(host, logger = nil)
opts = {
:host => host,
:log => logger
}.compact
OvirtSDK4::Probe.exists?(opts)
rescue OvirtSDK4::Error
false
end
end
end
end
end
end
| 21.823529 | 81 | 0.521563 |
179bc29f6439a459e0b74015be3406fa96f076da | 3,538 | swift | Swift | animation/Transition/AniObjct.swift | MChainZhou/animation | d6cd6875bfd783b7af01e983046aa7ab3fa0ba55 | [
"MIT"
] | null | null | null | animation/Transition/AniObjct.swift | MChainZhou/animation | d6cd6875bfd783b7af01e983046aa7ab3fa0ba55 | [
"MIT"
] | null | null | null | animation/Transition/AniObjct.swift | MChainZhou/animation | d6cd6875bfd783b7af01e983046aa7ab3fa0ba55 | [
"MIT"
] | null | null | null | //
// AniObjct.swift
// animation
//
// Created by USER on 2018/10/23.
// Copyright © 2018年 USER. All rights reserved.
//
import UIKit
class AniObjct: NSObject {
}
extension AniObjct: UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.3
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView
guard let formVc = transitionContext.viewController(forKey: .from), let toVc = transitionContext.viewController(forKey: .to) else {
return
}
let duration = transitionDuration(using: transitionContext)
if let toView = toVc.view, let fromView = formVc.view {
if toVc.isBeingPresented {
containerView.addSubview(toView)
let toViewWidth = containerView.frame.width * 2 / 3, toViewHeight = containerView.frame.height * 2 / 3
toView.center = containerView.center
toView.bounds = CGRect(x: 0, y: 0, width: 1, height: toViewHeight)
UIView.animate(withDuration: duration, delay: 0, options: .curveEaseInOut, animations: {
toView.bounds = CGRect(x: 0, y: 0, width: toViewWidth, height: toViewHeight)
}) { _ in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
if formVc.isBeingDismissed {
let fromViewHeight = fromView.frame.height
UIView.animate(withDuration: duration, animations: {
fromView.bounds = CGRect(x: 0, y: 0, width: 1, height: fromViewHeight)
}, completion: { _ in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
}
// //跳转的界面
// let toVc = transitionContext.viewController(forKey: .to)
// let fromVc = transitionContext.viewController(forKey: .from)
// let duration = transitionDuration(using: transitionContext)
//
// if let toVc = toVc, let fromVc = fromVc {
// if toVc.isBeingPresented {
// //最终的位置
// let finalRect = transitionContext.finalFrame(for: toVc)
// //起始位置
// toVc.view.frame = finalRect.offsetBy(dx: UIScreen.main.bounds.width, dy: 0)
// //添加到内容视图
// transitionContext.containerView.addSubview(toVc.view)
// UIView.animate(withDuration: duration, animations: {
// toVc.view.frame = finalRect
// }) { _ in
// transitionContext.completeTransition(true)
// }
// }
// if fromVc.isBeingDismissed {
//// transitionContext.containerView.insertSubview(toVc.view, belowSubview: fromVc.view)
//// UIView.animate(withDuration: duration, animations: {
//// fromVc.view.frame = CGRect(x: UIScreen.main.bounds.width, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
//// }) { _ in
//// transitionContext.completeTransition(true)
//// }
// }
// }
}
}
| 38.456522 | 159 | 0.566704 |
da50bdfc3191486800293513965c4fa9b00eb6d7 | 3,193 | php | PHP | app/Views/usuario/login.php | vallejosArmando/codeinter-proyecto-web | 134372bad7a79075b469f8c737ac8a574ec0138d | [
"MIT"
] | null | null | null | app/Views/usuario/login.php | vallejosArmando/codeinter-proyecto-web | 134372bad7a79075b469f8c737ac8a574ec0138d | [
"MIT"
] | null | null | null | app/Views/usuario/login.php | vallejosArmando/codeinter-proyecto-web | 134372bad7a79075b469f8c737ac8a574ec0138d | [
"MIT"
] | null | null | null |
<!doctype html>
<html lang="es">
<head>
<link rel="shortcut icon" href="#" />
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Login con PHP - Bootstrap 4</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href=" <?php echo base_url()?>/inicioLog/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href=" <?php echo base_url()?>/inicioLog/estilos.css">
<link rel="stylesheet" href="<?php echo base_url()?>/inicioLog/plugins/sweet_alert2/sweetalert2.min.css">
</head>
<body>
<div id="login">
<h3 class="text-center text-white display-4">Login con PHP</h3>
<div class="container">
<div id="login-row" class="row justify-content-center align-items-center">
<div id="login-column" class="col-md-6">
<div id="login-box" class="col-md-12 bg-light text-dark">
<form id="formLogin" class="form" action="" method="post">
<h3 class="text-center text-dark">Iniciar Sesión</h3>
<div class="form-group">
<label for="nom_usuario" class="text-dark">Usuario</label><br>
<input type="text" name="nom_usuario" id="nom_usuario" class="form-control">
</div>
<div class="form-group">
<label for="clave" class="text-dark">Password</label><br>
<input type="password" name="clave" id="clave" class="form-control">
</div>
<div class="form-group text-center">
<input type="submit" name="submit" class="btn btn-dark btn-lg btn-block" value="Conectar">
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="<?php echo base_url()?>/inicioLog/jquery/jquery-3.3.1.min.js"></script>
<script src="<?php echo base_url()?>/inicioLog/popper/popper.min.js"></script>
<script src="<?php echo base_url()?>/inicioLog/bootstrap/js/bootstrap.min.js"></script>
<script src="<?php echo base_url()?>/inicioLog/plugins/sweet_alert2/sweetalert2.all.min.js"></script>
<script src="<?php echo base_url()?>/js/main.js"></script>
<?php if (isset($_SESSION['error'])) : ?>
<script>
mostrarAlerta('error' , 'Oops...' , 'Parece que hubo un error en el registro vuelve a intentarlo nuevamente')
</script>
<?php unset($_SESSION['error']);
endif ?>
<?php if (isset($_SESSION['exito'])) : ?>
<script>
mostrarAlerta('success', 'Buen trabajo', 'La materia ha sido eliminada correctamente')
</script>
<?php unset($_SESSION['exito']);
endif ?>
</body>
</html>
| 43.739726 | 122 | 0.518008 |
5450cbfadf78fb5289ee512826b06aca69e67226 | 5,982 | css | CSS | css/resource/reset.css | qingbing/ui | 1a4ebc7cc98a44c76f15a4f51b572779a48e56ae | [
"MIT"
] | null | null | null | css/resource/reset.css | qingbing/ui | 1a4ebc7cc98a44c76f15a4f51b572779a48e56ae | [
"MIT"
] | null | null | null | css/resource/reset.css | qingbing/ui | 1a4ebc7cc98a44c76f15a4f51b572779a48e56ae | [
"MIT"
] | null | null | null | @charset "utf-8";
@import url("font-awesome/css/font-awesome.min.css");
html{font-family:sans-serif;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}
body{margin:0}
article,aside,details,figcaption,figure,footer,header,hgroup,main,menu,nav,section,summary{display:block}
audio,canvas,progress,video{display:inline-block;vertical-align:baseline}
audio:not([controls]){display:none;height:0}
[hidden],template{display:none}
a{background-color:transparent}
a:active,a:hover{outline:0}
abbr[title]{border-bottom:1px dotted}
b,strong{font-weight:700}
dfn{font-style:italic}
h1{font-size:2em}
mark{color:#000;background:#ff0}
small{font-size:80%}
sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}
sup{top:-.5em}
sub{bottom:-.25em}
img{border:0}
svg:not(:root){overflow:hidden}
hr{height:0;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box}
pre{overflow:auto}
code,kbd,pre,samp{font-family:monospace,monospace;font-size:1em}
button,input,optgroup,select,textarea{margin:0;font:inherit;color:inherit}
button{overflow:visible}
button,select{text-transform:none}
button,html input[type=button],input[type=reset],input[type=submit]{-webkit-appearance:button;cursor:pointer}
button[disabled],html input[disabled]{cursor:default}
button::-moz-focus-inner,input::-moz-focus-inner{padding:0;border:0}
input{line-height:normal}
input[type=checkbox],input[type=radio]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:0}
input[type=number]::-webkit-inner-spin-button,input[type=number]::-webkit-outer-spin-button{height:auto}
input[type=search]{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-webkit-appearance:textfield}
input[type=search]::-webkit-search-cancel-button,input[type=search]::-webkit-search-decoration{-webkit-appearance:none}
fieldset{padding:.35em .625em .75em;margin:0;border:1px solid silver}
legend{padding:0;border:0}
textarea{overflow:auto}
optgroup{font-weight:700}
table{border-spacing:0;border-collapse:collapse}
td,th{padding:0}
@media print{
*,:after,:before{color:#000!important;text-shadow:none!important;background:0 0!important;-webkit-box-shadow:none!important;box-shadow:none!important}
a,a:visited{text-decoration:underline}
a[href]:after{content:" (" attr(href) ")"}
abbr[title]:after{content:" (" attr(title) ")"}
a[href^="javascript:"]:after,a[href^="#"]:after{content:""}
blockquote,pre{border:1px solid #999;page-break-inside:avoid}
thead{display:table-header-group}
img,tr{page-break-inside:avoid}
img{max-width:100%!important}
h2,h3,p{orphans:3;widows:3}
h2,h3{page-break-after:avoid}
/*.navbar{display:none}
.btn>.caret,.dropup>.btn>.caret{border-top-color:#000!important}
.label{border:1px solid #000}
.table{border-collapse:collapse!important}
.table td,.table th{background-color:#fff!important}
.table-bordered td,.table-bordered th{border:1px solid #ddd!important}*/
}
*{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}
:after,:before{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}
html{font-size:10px;-webkit-tap-highlight-color:rgba(0,0,0,0)}
body{font-family:"微软雅黑",Tahoma,"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:1.42857143;color:#333;background-color:#fff}
button,input,select,textarea{font-family:inherit;font-size:inherit;line-height:inherit}
a{color:#2a2730;text-decoration:none}
a:focus,a:hover{color:#23527c;text-decoration:underline}
a:focus{outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}
figure{margin:0}
img{vertical-align:middle}
hr{border:0;border-top:1px solid #eee}
[role=button]{cursor:pointer}
.h1,.h2,.h3,.h4,.h5,.h6,h1,h2,h3,h4,h5,h6{font-family:inherit;font-weight:500;line-height:1.1;color:inherit}
.h1 .small,.h1 small,.h2 .small,.h2 small,.h3 .small,.h3 small,.h4 .small,.h4 small,.h5 .small,.h5 small,.h6 .small,.h6 small,h1 .small,h1 small,h2 .small,h2 small,h3 .small,h3 small,h4 .small,h4 small,h5 .small,h5 small,h6 .small,h6 small{font-weight:400;line-height:1;color:#777}
.h1 .small,.h1 small,.h2 .small,.h2 small,.h3 .small,.h3 small,h1 .small,h1 small,h2 .small,h2 small,h3 .small,h3 small{font-size:65%}
.h4 .small,.h4 small,.h5 .small,.h5 small,.h6 .small,.h6 small,h4 .small,h4 small,h5 .small,h5 small,h6 .small,h6 small{font-size:75%}
.h1,h1{font-size:36px}
.h2,h2{font-size:30px}
.h3,h3{font-size:24px}
.h4,h4{font-size:18px}
.h5,h5{font-size:14px}
.h6,h6{font-size:12px}
.small,small{font-size:85%}
.mark,mark{padding:.2em;background-color:#fcf8e3}
abbr[data-original-title],abbr[title]{cursor:help;border-bottom:1px dotted #777}
address{margin-bottom:20px;font-style:normal;line-height:1.42857143}
code,kbd,pre,samp{font-family:Menlo,Monaco,Consolas,"Courier New",monospace}
code{padding:2px 4px;font-size:90%;color:#c7254e;background-color:#f9f2f4;border-radius:4px}
kbd{padding:2px 4px;font-size:90%;color:#fff;background-color:#333;border-radius:3px;-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,.25);box-shadow:inset 0 -1px 0 rgba(0,0,0,.25)}
kbd kbd{padding:0;font-size:100%;font-weight:700;-webkit-box-shadow:none;box-shadow:none}
pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:1.42857143;color:#333;word-break:break-all;word-wrap:break-word;background-color:#f5f5f5;border:1px solid #ccc;border-radius:4px}
pre code{padding:0;font-size:inherit;color:inherit;white-space:pre-wrap;background-color:transparent;border-radius:0}
.btn-group-vertical>.btn-group:after,
.btn-group-vertical>.btn-group:before,
.clearfix:after,
.clearfix:before,
.container-fluid:after,
.container-fluid:before,
.container:after,
.container:before,
.pager:after,
.pager:before,
.row:after,
.row:before{display:table;content:" "}
.btn-group-vertical>.btn-group:after,
.btn-toolbar:after,
.clearfix:after,
.container-fluid:after,
.container:after,
.pager:after,
.row:after{clear:both}
| 52.938053 | 281 | 0.76095 |
7d4c3441170388ed7f42d67edb9499d8f82b39cd | 20,365 | rb | Ruby | spec/requests/api/v1/api_profiles_spec.rb | Zooip/ProfileDirectoryAPI | bf523451e0de976e830436f377e92edc220309b7 | [
"MIT"
] | 1 | 2016-03-29T08:29:52.000Z | 2016-03-29T08:29:52.000Z | spec/requests/api/v1/api_profiles_spec.rb | Zooip/ProfileDirectoryAPI | bf523451e0de976e830436f377e92edc220309b7 | [
"MIT"
] | null | null | null | spec/requests/api/v1/api_profiles_spec.rb | Zooip/ProfileDirectoryAPI | bf523451e0de976e830436f377e92edc220309b7 | [
"MIT"
] | null | null | null | require 'rails_helper'
include OauthHelpers
RSpec.describe "Api::V1::Profiles", type: :request do
describe "GET /api/v1/profiles" do
it_behaves_like 'a Oauth protected endpoint', :get, :api_v1_profiles_path,nil ,nil,JSONAPI_HEADERS
context "As an authentified Application with admin scope", :valid_oauth do
let (:scopes){'scopes.admin'}
it "it respond with sucess" do
get api_v1_profiles_path,nil, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(response).to have_http_status(:success)
end
it "it return a list of profiles" do
get api_v1_profiles_path,nil, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
response_data=JSON.parse(response.body)['data']
expect(response_data.class).to eq(Array)
response_data.each do |oa|
expect(oa["type"]).to eq("profiles")
end
end
it "doesn't expose passwords" do
get api_v1_profiles_path,nil, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(JSON.parse(response.body)['data'].any? {|x| x['attributes']['password']}).to eq(false)
expect(JSON.parse(response.body)['data'].any? {|x| x['attributes']['encrypted_password']}).to eq(false)
end
end
context "As an authentified Application with profiles.list", :valid_oauth do
let (:scopes){'scopes.profiles.list.readonly'}
it "it respond with sucess" do
get api_v1_profiles_path,nil, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(response).to have_http_status(:success)
end
describe "it display only public attributes" do
it "display public attributes" do
get api_v1_profiles_path,nil, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(JSON.parse(response.body)['data'].all? {|x| (['first_name', 'last_name', 'full_name']-x['attributes'].keys).empty?}).to eq(true)
end
it "doesn't display private attributes" do
get api_v1_profiles_path,nil, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(JSON.parse(response.body)['data'].all? {|x| (x['attributes'].keys.exclude?('birth_date'))}).to eq(true)
end
end
end
end
describe "GET /api/v1/profiles/:id" do
let!(:profile) { FactoryGirl.create(:master_data_profile) }
it_behaves_like 'a Oauth protected endpoint', :get, :api_v1_profile_path,100 ,nil,JSONAPI_HEADERS
context "When requesting the resource owner's profile", :valid_oauth do
let!(:resource_owner_profile) {profile}
context "As an authentified Application with admin scope" do
let (:scopes){'scopes.admin'}
it "it respond with sucess" do
get api_v1_profile_path(profile),nil, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(response).to have_http_status(:success)
end
it "it return a single Profile record" do
get api_v1_profile_path(profile),nil, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(JSON.parse(response.body)['data']['type']).to eq('profiles')
end
it "doesn't expose passwords" do
get api_v1_profile_path(profile),nil, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(JSON.parse(response.body)['data']['attributes']['password']).to eq(nil)
expect(JSON.parse(response.body)['data']['attributes']['encrypted_password']).to eq(nil)
end
end
context "As an authentified Application with profile.public.readonly", :valid_oauth do
let (:scopes){'scopes.profile.public.readonly'}
it "it respond with sucess" do
get api_v1_profile_path(profile),nil, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(response).to have_http_status(:success)
end
describe "it display only public attributes" do
it "display public attributes" do
get api_v1_profile_path(profile),nil, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
['first_name', 'last_name', 'full_name'].each do |attribute|
expect(JSON.parse(response.body)['data']['attributes']).to include(attribute)
end
end
it "doesn't display private attributes" do
get api_v1_profile_path(profile),nil, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(JSON.parse(response.body)['data']['attributes']).not_to include('birth_date')
end
end
end
context "As an authentified Application with profiles.phones", :valid_oauth do
let (:scopes){'scopes.profile.public.readonly scopes.profile.phones.readonly'}
let!(:phone) { FactoryGirl.create(:master_data_phone_number, profile_id: resource_owner_profile.id) }
it "it respond with sucess" do
get api_v1_profile_path(profile),nil, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(response).to have_http_status(:success)
end
describe "it display only public attributes" do
it "display public attributes" do
get api_v1_profile_path(profile),nil, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
['first_name', 'last_name', 'full_name'].each do |attribute|
expect(JSON.parse(response.body)['data']['attributes']).to include(attribute)
end
end
it "display phone relations" do
get api_v1_profile_path(profile),nil, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(JSON.parse(response.body)['data']['relationships']).to include('phone_numbers')
end
it "doesn't display private attributes" do
get api_v1_profile_path(profile),nil, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(JSON.parse(response.body)['data']['attributes']).not_to include('birth_date')
end
end
end
end
context "When requesting an other profile than resource owner's profile", :valid_oauth do
let!(:resource_owner_profile) {FactoryGirl.create(:master_data_profile)}
context "As an authentified Application with admin scope" do
let (:scopes){'scopes.admin'}
it "it respond with sucess" do
get api_v1_profile_path(profile),nil, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(response).to have_http_status(:success)
end
it "it return a single Profile record" do
get api_v1_profile_path(profile),nil, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(JSON.parse(response.body)['data']['type']).to eq('profiles')
end
it "doesn't expose passwords" do
get api_v1_profile_path(profile),nil, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(JSON.parse(response.body)['data']['attributes']['password']).to eq(nil)
expect(JSON.parse(response.body)['data']['attributes']['encrypted_password']).to eq(nil)
end
end
context "As an authentified Application with profile.public.readonly", :valid_oauth do
let (:scopes){'scopes.profile.public.readonly'}
it "it respond with sucess" do
get api_v1_profile_path(profile),nil, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(response).to have_http_status(:success)
end
describe "it display only public attributes" do
it "display public attributes" do
get api_v1_profile_path(profile),nil, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
['first_name', 'last_name', 'full_name'].each do |attribute|
expect(JSON.parse(response.body)['data']['attributes']).to include(attribute)
end
end
it "doesn't display private attributes" do
get api_v1_profile_path(profile),nil, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(JSON.parse(response.body)['data']['attributes']).not_to include('birth_date')
end
end
end
context "As an authentified Application with profiles.phones", :valid_oauth do
let (:scopes){'scopes.profile.public.readonly scopes.profile.phones.readonly'}
let!(:phone) { FactoryGirl.create(:master_data_phone_number, profile_id: resource_owner_profile.id) }
it "it respond with sucess" do
get api_v1_profile_path(profile),nil, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(response).to have_http_status(:success)
end
describe "it display only public attributes" do
it "display public attributes" do
get api_v1_profile_path(profile),nil, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
['first_name', 'last_name', 'full_name'].each do |attribute|
expect(JSON.parse(response.body)['data']['attributes']).to include(attribute)
end
end
it "doesn't display phone relations" do
get api_v1_profile_path(profile),nil, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(JSON.parse(response.body)['data']['relationships'].to_h).not_to include('phone_numbers')
end
it "doesn't display private attributes" do
get api_v1_profile_path(profile),nil, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(JSON.parse(response.body)['data']['attributes']).not_to include('birth_date')
end
end
end
end
end
describe "POST /api/v1/profiles" do
let(:profile_data) { FactoryGirl.json_api_attributes_for(:master_data_profile).to_json }
let(:invalid_profile_data) { FactoryGirl.json_api_attributes_for(:invalid_master_data_profile).to_json }
it_behaves_like 'a Oauth protected endpoint', :post, :api_v1_profiles_path,nil ,nil,JSONAPI_HEADERS
context "When there is no resource owner", :valid_oauth do
let!(:resource_owner_profile) {nil}
context "As an authentified Application with admin scope" do
let (:scopes){'scopes.admin'}
context 'with valid data' do
it "it respond with sucess" do
post api_v1_profiles_path, profile_data, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(response).to have_http_status(:success)
end
it "it return a single Profile record" do
post api_v1_profiles_path, profile_data, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(JSON.parse(response.body)['data']['type']).to eq('profiles')
end
it "create a new profile" do
expect {
post api_v1_profiles_path, profile_data, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
}.to change(MasterData::Profile, :count).by(1)
end
end
context 'with invalid data' do
it "it respond with 422" do
post api_v1_profiles_path, invalid_profile_data, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(response).to have_http_status(:unprocessable_entity)
end
it "it return errors" do
post api_v1_profiles_path, invalid_profile_data, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(JSON.parse(response.body)).to include("errors")
end
it "doesn't create a new profile" do
expect {
post api_v1_profiles_path, invalid_profile_data, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
}.to change(MasterData::Profile, :count).by(0)
end
end
end
context "As an authentified Application with scopes.profiles.create scope" do
let (:scopes){'scopes.profiles.create'}
context 'with valid data' do
it "it respond with success" do
post api_v1_profiles_path, profile_data, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(response).to have_http_status(:success)
end
it "it return a single Profile record" do
post api_v1_profiles_path, profile_data, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(JSON.parse(response.body)['data']['type']).to eq('profiles')
end
it "create a new profile" do
expect {
post api_v1_profiles_path, profile_data, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
}.to change(MasterData::Profile, :count).by(1)
end
end
context 'with invalid data' do
it "it respond with 422" do
post api_v1_profiles_path, invalid_profile_data, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(response).to have_http_status(:unprocessable_entity)
end
it "it return errors" do
post api_v1_profiles_path, invalid_profile_data, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(JSON.parse(response.body)).to include("errors")
end
it "doesn't create a new profile" do
expect {
post api_v1_profiles_path, invalid_profile_data, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
}.to change(MasterData::Profile, :count).by(0)
end
end
end
end
end
describe "DELETE /api/v1/profiles/:id" do
let!(:profile) { FactoryGirl.create(:master_data_profile)}
it_behaves_like 'a Oauth protected endpoint', :delete, :api_v1_profile_path,100 ,nil,JSONAPI_HEADERS
context "When there is no resource owner", :valid_oauth do
let!(:resource_owner_profile) {nil}
context "As an authentified Application with admin scope" do
let (:scopes){'scopes.admin'}
it "it respond with sucess" do
delete api_v1_profile_path(profile), nil, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(response).to have_http_status(:no_content)
end
it "it return nothing" do
delete api_v1_profile_path(profile), nil, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(response.body).to eq('')
end
it "create a delete a profile" do
expect {
delete api_v1_profile_path(profile), nil, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
}.to change(MasterData::Profile, :count).by(-1)
end
end
context "As an authentified Application with scopes.profiles.create scope" do
let (:scopes){'scopes.profiles.delete'}
it "it respond with sucess" do
delete api_v1_profile_path(profile), nil, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(response).to have_http_status(:no_content)
end
it "it return nothing" do
delete api_v1_profile_path(profile), nil, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(response.body).to eq('')
end
it "create a delete a profile" do
expect {
delete api_v1_profile_path(profile), nil, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
}.to change(MasterData::Profile, :count).by(-1)
end
end
end
end
describe "PUT /api/v1/profiles/:id" do
let(:profile_attributes) {{first_name: "Claude", gender: 'male'}}
let!(:profile) {FactoryGirl.create(:master_data_profile,profile_attributes)}
let(:profile_data) { FactoryGirl.json_api_attributes_for(:master_data_profile,profile_attributes.merge({first_name: "Paul"})).deep_merge({data:{id:profile.id.to_s}}).to_json }
let(:invalid_profile_data) { FactoryGirl.json_api_attributes_for(:invalid_master_data_profile, profile_attributes.merge({gender: 'cat'}) ).deep_merge( {data: {id: profile.id.to_s}} ).to_json }
it_behaves_like 'a Oauth protected endpoint', :put, :api_v1_profile_path,100 ,nil,JSONAPI_HEADERS
context "When requesting the resource owner's profile", :valid_oauth do
let!(:resource_owner_profile) {profile}
context "As an authentified Application with admin scope" do
let (:scopes){'scopes.admin'}
context 'with valid data' do
it "it respond with sucess" do
put api_v1_profile_path(profile), profile_data, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(response).to have_http_status(:success)
end
it "it return a single Profile record" do
put api_v1_profile_path(profile), profile_data, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(JSON.parse(response.body)['data']['type']).to eq('profiles')
end
it "update profile's attributes" do
put api_v1_profile_path(profile), profile_data, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
profile.reload
expect(profile.first_name).to eq("Paul")
end
end
context 'with invalid data' do
it "it respond with 422" do
put api_v1_profile_path(profile), invalid_profile_data, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(response).to have_http_status(:unprocessable_entity)
end
it "it return errors" do
put api_v1_profile_path(profile), invalid_profile_data, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(JSON.parse(response.body)).to include("errors")
end
it "doesn't update profile" do
put api_v1_profile_path(profile), invalid_profile_data, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
profile.reload
expect(profile.gender).to eq("male")
end
end
end
context "As an authentified Application with scopes.profiles.create scope" do
let (:scopes){'scopes.profile.basic.readwrite'}
context 'with valid data' do
it "it respond with success" do
put api_v1_profile_path(profile), profile_data, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(response).to have_http_status(:success)
end
it "it return a single Profile record" do
put api_v1_profile_path(profile), profile_data, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(JSON.parse(response.body)['data']['type']).to eq('profiles')
end
it "update profile's attributes" do
put api_v1_profile_path(profile), profile_data, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
profile.reload
expect(profile.first_name).to eq("Paul")
end
end
context 'with invalid data' do
it "it respond with 422" do
put api_v1_profile_path(profile), invalid_profile_data, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(response).to have_http_status(:unprocessable_entity)
end
it "it return errors" do
put api_v1_profile_path(profile), invalid_profile_data, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
expect(JSON.parse(response.body)).to include("errors")
end
it "doesn't update profile" do
put api_v1_profile_path(profile), invalid_profile_data, JSONAPI_HEADERS.merge({"Authorization" => "Bearer #{token.token}"})
profile.reload
expect(profile.gender).to eq("male")
end
end
end
end
end
end
| 46.074661 | 196 | 0.647827 |
2cbb6db6f5a6a942f82ef4654acf37431d0cd2ab | 1,865 | py | Python | bollards_api/api/routes.py | JeanmarieAlder/bollards-api | 39c82a53575ecd2fbd7f98864512a5494b800836 | [
"MIT"
] | 1 | 2021-07-26T06:40:04.000Z | 2021-07-26T06:40:04.000Z | bollards_api/api/routes.py | JeanmarieAlder/bollards-api | 39c82a53575ecd2fbd7f98864512a5494b800836 | [
"MIT"
] | null | null | null | bollards_api/api/routes.py | JeanmarieAlder/bollards-api | 39c82a53575ecd2fbd7f98864512a5494b800836 | [
"MIT"
] | null | null | null |
import json
from os import name
from flask_cors import CORS
from bollards_api.models import Bollard
from flask import Blueprint, jsonify
from bollards_api.api.utils import get_neighbours_by_number
api = Blueprint('api', __name__, url_prefix='/api/v1')
CORS(api)
@api.route('/bollards/list')
def bollards_list():
bollards = Bollard.query.all()
resp = []
for bollard in bollards:
resp.append({
"id": bollard.id,
"b_number": bollard.b_number,
"b_letter": bollard.b_letter,
"b_name": bollard.b_name,
"image_icon": bollard.image_icon
})
return jsonify(resp)
@api.route('/bollards/markers')
def bollards_markers():
bollards = Bollard.query.all()
resp = []
for bollard in bollards:
resp.append({
"id": bollard.id,
"b_number": bollard.b_number,
"b_letter": bollard.b_letter,
"b_name": bollard.b_name,
"b_type": bollard.b_type,
"image_icon": bollard.image_icon,
"b_lat": str(bollard.b_lat),
"b_lng": str(bollard.b_lng)
})
return jsonify(resp)
@api.route('/bollards/details/<int:bollard_id>')
def bollards_details(bollard_id):
bollard = Bollard.query.filter_by(id=bollard_id).first_or_404()
images = []
for img in bollard.images:
images.append(img.uri)
neighbours = get_neighbours_by_number(bollard)
return jsonify({
'id': bollard.id,
'b_number': bollard.b_number,
'b_letter': bollard.b_letter,
'b_type': bollard.b_type,
'b_name': bollard.b_name,
'comment': bollard.comment,
'b_lat': str(bollard.b_lat),
'b_lng': str(bollard.b_lng),
'image_icon': bollard.image_icon,
'images': images,
'neighbours': neighbours
})
| 25.902778 | 67 | 0.609651 |
da7b8992400a6a84697b805c02f14ee5d09e2470 | 353 | php | PHP | app/Rinventarios2.php | juansg3701/sisVentasPUBLICIDAD | acd733130ff8f1a5b0227cbfdab3cff93516fea0 | [
"MIT"
] | null | null | null | app/Rinventarios2.php | juansg3701/sisVentasPUBLICIDAD | acd733130ff8f1a5b0227cbfdab3cff93516fea0 | [
"MIT"
] | null | null | null | app/Rinventarios2.php | juansg3701/sisVentasPUBLICIDAD | acd733130ff8f1a5b0227cbfdab3cff93516fea0 | [
"MIT"
] | null | null | null | <?php
namespace sisVentas;
use Illuminate\Database\Eloquent\Model;
class RInventarios2 extends Model
{
protected $table = 'reporteinventarios2';
protected $primaryKey='id_rInventarios';
public $timestamps =false;
protected $fillable=['fechaInicial','fechaFinal','fechaActual','noProductos','total'];
protected $guarded=[];
}
| 22.0625 | 90 | 0.72238 |
902f2b8e899d1e34ac6e93ff17f47153a26df9cc | 2,779 | go | Go | terraform/providers/ibm/vendor/github.com/IBM-Cloud/terraform-provider-ibm/ibm/service/appid/data_source_ibm_appid_role.go | HuijingHei/installer | fa0c02493524b60064d09772ca0f3961d1c2f8ac | [
"Apache-2.0"
] | null | null | null | terraform/providers/ibm/vendor/github.com/IBM-Cloud/terraform-provider-ibm/ibm/service/appid/data_source_ibm_appid_role.go | HuijingHei/installer | fa0c02493524b60064d09772ca0f3961d1c2f8ac | [
"Apache-2.0"
] | 2 | 2022-02-03T16:01:09.000Z | 2022-03-31T16:44:21.000Z | terraform/providers/ibm/vendor/github.com/IBM-Cloud/terraform-provider-ibm/ibm/service/appid/data_source_ibm_appid_role.go | HuijingHei/installer | fa0c02493524b60064d09772ca0f3961d1c2f8ac | [
"Apache-2.0"
] | 1 | 2022-02-18T15:53:46.000Z | 2022-02-18T15:53:46.000Z | package appid
import (
"context"
"fmt"
"github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns"
"github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex"
appid "github.com/IBM/appid-management-go-sdk/appidmanagementv4"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func DataSourceIBMAppIDRole() *schema.Resource {
return &schema.Resource{
Description: "A role is a collection of `scopes` that allow varying permissions to different types of app users",
ReadContext: dataSourceIBMAppIDRoleRead,
Schema: map[string]*schema.Schema{
"role_id": {
Description: "Role ID",
Type: schema.TypeString,
Required: true,
},
"tenant_id": {
Description: "The service `tenantId`",
Type: schema.TypeString,
Required: true,
},
"name": {
Description: "Unique role name",
Type: schema.TypeString,
Computed: true,
},
"description": {
Description: "Optional role description",
Type: schema.TypeString,
Computed: true,
},
"access": {
Type: schema.TypeSet,
Computed: true,
Description: "A set of access policies that bind specific application scopes to the role",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"application_id": {
Type: schema.TypeString,
Computed: true,
},
"scopes": {
Type: schema.TypeList,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Computed: true,
},
},
},
},
},
}
}
func dataSourceIBMAppIDRoleRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
appIDClient, err := meta.(conns.ClientSession).AppIDAPI()
if err != nil {
return diag.FromErr(err)
}
tenantID := d.Get("tenant_id").(string)
id := d.Get("role_id").(string)
role, resp, err := appIDClient.GetRoleWithContext(ctx, &appid.GetRoleOptions{
RoleID: &id,
TenantID: &tenantID,
})
if err != nil {
return diag.Errorf("Error loading AppID role: %s\n%s", err, resp)
}
d.Set("name", *role.Name)
if role.Description != nil {
d.Set("description", *role.Description)
}
if err := d.Set("access", flattenAppIDRoleAccess(role.Access)); err != nil {
return diag.Errorf("Error setting AppID role access: %s", err)
}
d.SetId(fmt.Sprintf("%s/%s", tenantID, *role.ID))
return nil
}
func flattenAppIDRoleAccess(ra []appid.RoleAccessItem) []interface{} {
var result []interface{}
for _, a := range ra {
access := map[string]interface{}{
"scopes": flex.FlattenStringList(a.Scopes),
}
if a.ApplicationID != nil {
access["application_id"] = *a.ApplicationID
}
result = append(result, access)
}
return result
}
| 24.377193 | 115 | 0.649514 |
a45c129456c43320ac4a8a9c77bdc5c39e2fe93a | 2,802 | php | PHP | functions.php | wp-kitten/cp-newspaper-feed-reader | e090288176dbe0d4648caa89728953d5080bee4f | [
"MIT"
] | null | null | null | functions.php | wp-kitten/cp-newspaper-feed-reader | e090288176dbe0d4648caa89728953d5080bee4f | [
"MIT"
] | null | null | null | functions.php | wp-kitten/cp-newspaper-feed-reader | e090288176dbe0d4648caa89728953d5080bee4f | [
"MIT"
] | null | null | null | <?php
use App\Models\Category;
use App\Helpers\VPML;
use App\Http\Controllers\Admin\AdminControllerBase;
use App\Models\Options;
use App\Models\PostType;
use Illuminate\Support\Arr;
if ( !defined( 'NPFR_PLUGIN_DIR_NAME' ) ) {
exit;
}
/**
* Check to see whether the import process has started
* @return bool
*/
function npfrImportingContent()
{
//#! Check to see whether or not we're already importing
$options = ( new Options() );
$option = $options->where( 'name', NPFR_PROCESS_OPT_NAME )->first();
return ( $option && $option->value >= time() );
}
/**
* Retrieve the top categories (categories without parent) excluding the custom ones: Public & Private
* @return mixed
*/
function npfrGetTopCategories()
{
$query = Category::where( 'category_id', null );
$publicCat = npfrGetCategoryPublic();
$privateCat = npfrGetCategoryPrivate();
if ( $publicCat && $privateCat ) {
$query = $query->where( function ( $q ) use ( $publicCat, $privateCat ) {
return $q->whereNotIn( 'id', [ $publicCat->id, $privateCat->id ] );
} );
}
return $query
->where( 'language_id', VPML::getDefaultLanguageID() )
->where( 'post_type_id', PostType::where( 'name', 'post' )->first()->id )
->orderBy( 'name', 'ASC' )
->get();
}
/**
* Retrieve the subcategories, 1 level deep of the specified $category
* @param Category $category
* @return array
*/
function npfrGetSubCategoriesTree( Category $category )
{
static $out = [];
if ( !$category ) {
return $out;
}
if ( $subcategories = $category->childrenCategories()->get() ) {
$out[ $category->id ] = Arr::pluck( $subcategories, 'id' );
}
return $out;
}
function npfrGetCategoriesTree()
{
$categories = npfrGetTopCategories();
$out = [];
if ( !$categories || $categories->count() == 0 ) {
return $out;
}
foreach ( $categories as $category ) {
$out = npfrGetSubCategoriesTree( $category );
}
return $out;
}
function npfrGetAdminBaseController()
{
return new AdminControllerBase();
}
/**
* Retrieve the Model for the special category: public
* @return mixed
*/
function npfrGetCategoryPublic()
{
return Category::where( 'slug', NPFR_CATEGORY_PUBLIC )
->where( 'language_id', VPML::getDefaultLanguageID() )
->where( 'post_type_id', PostType::where( 'name', 'post' )->first()->id )
->first();
}
/**
* Retrieve the Model for the special category: private
* @return mixed
*/
function npfrGetCategoryPrivate()
{
return Category::where( 'slug', NPFR_CATEGORY_PRIVATE )
->where( 'language_id', VPML::getDefaultLanguageID() )
->where( 'post_type_id', PostType::where( 'name', 'post' )->first()->id )
->first();
}
| 25.472727 | 102 | 0.625625 |
03d2ecfa53cc6e37677744474812306175b2201a | 2,038 | sql | SQL | db/src/libs/pgjwt/pgjwt--001.sql | orthodoc/jdbapi | c0b5961cbdbadd7b88f5b10b0e5859ee6012f5b0 | [
"MIT"
] | 12 | 2018-01-24T16:51:35.000Z | 2020-01-09T15:51:49.000Z | db/src/libs/pgjwt/pgjwt--001.sql | orthodoc/jdbapi | c0b5961cbdbadd7b88f5b10b0e5859ee6012f5b0 | [
"MIT"
] | null | null | null | db/src/libs/pgjwt/pgjwt--001.sql | orthodoc/jdbapi | c0b5961cbdbadd7b88f5b10b0e5859ee6012f5b0 | [
"MIT"
] | 2 | 2020-01-09T15:51:51.000Z | 2020-12-23T17:15:47.000Z | \echo Use "CREATE EXTENSION pgjwt" to load this file. \quit
CREATE OR REPLACE FUNCTION url_encode(data bytea) RETURNS text LANGUAGE sql AS $$
SELECT translate(encode(data, 'base64'), E'+/=\n', '-_');
$$;
CREATE OR REPLACE FUNCTION url_decode(data text) RETURNS bytea LANGUAGE sql AS $$
WITH t AS (SELECT translate(data, '-_', '+/')),
rem AS (SELECT length((SELECT * FROM t)) % 4) -- compute padding size
SELECT decode(
(SELECT * FROM t) ||
CASE WHEN (SELECT * FROM rem) > 0
THEN repeat('=', (4 - (SELECT * FROM rem)))
ELSE '' END,
'base64');
$$;
CREATE OR REPLACE FUNCTION algorithm_sign(signables text, secret text, algorithm text)
RETURNS text LANGUAGE sql AS $$
WITH
alg AS (
SELECT CASE
WHEN algorithm = 'HS256' THEN 'sha256'
WHEN algorithm = 'HS384' THEN 'sha384'
WHEN algorithm = 'HS512' THEN 'sha512'
ELSE '' END) -- hmac throws error
SELECT @[email protected]_encode(hmac(signables, secret, (select * FROM alg)));
$$;
CREATE OR REPLACE FUNCTION sign(payload json, secret text, algorithm text DEFAULT 'HS256')
RETURNS text LANGUAGE sql AS $$
WITH
header AS (
SELECT @[email protected]_encode(convert_to('{"alg":"' || algorithm || '","typ":"JWT"}', 'utf8'))
),
payload AS (
SELECT @[email protected]_encode(convert_to(payload::text, 'utf8'))
),
signables AS (
SELECT (SELECT * FROM header) || '.' || (SELECT * FROM payload)
)
SELECT
(SELECT * FROM signables)
|| '.' ||
@[email protected]_sign((SELECT * FROM signables), secret, algorithm);
$$;
CREATE OR REPLACE FUNCTION verify(token text, secret text, algorithm text DEFAULT 'HS256')
RETURNS table(header json, payload json, valid boolean) LANGUAGE sql AS $$
SELECT
convert_from(@[email protected]_decode(r[1]), 'utf8')::json AS header,
convert_from(@[email protected]_decode(r[2]), 'utf8')::json AS payload,
r[3] = @[email protected]_sign(r[1] || '.' || r[2], secret, algorithm) AS valid
FROM regexp_split_to_array(token, '\.') r;
$$;
| 33.409836 | 98 | 0.648184 |
e717eedb39f57325e1b13bf37869b309a3517272 | 48,691 | php | PHP | resources/views/frontend/lease-application.blade.php | talktojoegee/plusrentalsv2 | 8d30cda480c30f0bffdd77405e3d216bf727d85e | [
"MIT"
] | null | null | null | resources/views/frontend/lease-application.blade.php | talktojoegee/plusrentalsv2 | 8d30cda480c30f0bffdd77405e3d216bf727d85e | [
"MIT"
] | null | null | null | resources/views/frontend/lease-application.blade.php | talktojoegee/plusrentalsv2 | 8d30cda480c30f0bffdd77405e3d216bf727d85e | [
"MIT"
] | null | null | null | @extends('layouts.tenant-layout')
@section('title')
Lease Application
@endsection
@section('meta-title')
Property Details
@endsection
@section('meta-keywords')
Property Details
@endsection
@section('extra-styles')
<link rel="stylesheet" href="/css/custom/rightbar-details.css">
@endsection
@section('main-content')
<section class="ad-details-part">
<div class="container">
<div class="row">
@if(session()->has('message-success'))
<div class="col-md-12 mt-4">
<div class="alert alert-success">
{!! session()->get('message-success') !!}
</div>
</div>
@endif
<div class="col-lg-8">
<div class="ad-details-card">
<div class="ad-details-breadcrumb">
<ol class="breadcrumb">
<li>
<span class="flat-badge sale">
@switch($property->property_type)
@case(1)
Apartment
@break
@case(2)
House
@break
@case(3)
Land
@break
@case(4)
Townhouse
@break
@case(5)
Garden Cottage
@break
@case(6)
Farm
@break
@endswitch
</span>
</li>
<li class="breadcrumb-item">
<a href="javascript:void(0);">{{$property->getLocation->location_name ?? ''}}</a>
</li>
<li class="breadcrumb-item active" aria-current="page">{{$property->getArea->area_name ?? ''}}</li>
</ol>
</div>
<div class="ad-details-heading">
<h2>
<a href="{{url()->current()}}">{{ucfirst(strtolower($property->property_name))}}</a>
</h2>
</div>
<div class="ad-details-title">
<h5>Interior View</h5>
</div>
<div class="ad-details-slider slider-arrow">
@foreach($property->getInteriorGallery as $interior)
<div>
<img src="/assets/images/property/interior/{{$interior->directory ?? ''}}" alt="{{$property->property_name ?? '' }}">
</div>
@endforeach
</div>
<div class="ad-thumb-slider">
@foreach ($property->getInteriorGallery as $image)
<div>
<img src="/assets/images/property/interior/{{$image->directory ?? ''}}" alt="{{$property->property_name ?? '' }}">
</div>
@endforeach
</div>
<div class="ad-details-title">
<h5>External View</h5>
</div>
<div class="ad-details-slider slider-arrow">
@foreach($property->getExteriorGallery as $exterior)
<div>
<img src="/assets/images/property/exterior/{{$exterior->directory ?? ''}}" alt="{{$property->property_name ?? '' }}">
</div>
@endforeach
</div>
<div class="ad-thumb-slider">
@foreach ($property->getExteriorGallery as $ex_image)
<div>
<img src="/assets/images/property/exterior/{{$ex_image->directory ?? ''}}" alt="{{$property->property_name ?? '' }}">
</div>
@endforeach
</div>
</div>
<div class="ad-details-card">
<div class="ad-details-title">
<h5>Schedule Property Inspection</h5>
</div>
<div class="ad-details-specific">
<form action="" class="ad-review-form">
@csrf
<div class="row mb-3">
<div class="col-md-6 col-sm-6 col-lg-6">
<label for="">Full Name</label>
<input type="text" value="{{old('full_name')}}" placeholder="Full Name" name="full_name" class="form-control">
@error('full_name')
<i class="text-danger mt-2">{{$message}}</i>
@enderror
</div>
<div class="col-md-6 col-sm-6 col-lg-6">
<label for="">Email Address</label>
<input type="text" value="{{old('email_address')}}" placeholder="Email Address" name="email_address" class="form-control">
@error('email_address')
<i class="text-danger mt-2">{{$message}}</i>
@enderror
</div>
</div>
<div class="row mb-3">
<div class="col-md-6 col-sm-6 col-lg-6">
<label for="">Mobile No.</label>
<input type="text" value="{{old('mobile_no')}}" placeholder="Mobile No." name="mobile_no" class="form-control">
@error('mobile_no')
<i class="text-danger mt-2">{{$message}}</i>
@enderror
</div>
<div class="col-md-6 col-sm-6 col-lg-6">
<label for="">Date & Time</label>
<input type="datetime-local" value="{{old('date_time')}}" placeholder="Date & Time" name="date_time" class="form-control">
@error('date_time')
<i class="text-danger mt-2">{{$message}}</i>
@enderror
</div>
</div>
<div class="row mb-3">
<div class="col-md-12 col-sm-12 col-lg-12">
<label for="">Message</label>
<textarea name="message" id="message" style="resize: none;" placeholder="I'm interested in {{$property->property_name ?? '...'}}" class="form-control">{{old('message')}}</textarea>
@error('message')
<i class="text-danger mt-2">{{$message}}</i>
@enderror
</div>
</div>
<div class="row ">
<div class="col-md-12 col-sm-12 col-lg-12 d-flex justify-content-center">
<button class="btn btn-inline"><i class="fas fa-check"></i><span>Submit</span></button>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="col-lg-4">
<div class="form-group">
<a href="submit" class="btn btn-inline btn-outline"><i class="fa fa-check"></i><span>Submit Lease Application</span></a>
</div>
<div class="ad-details-price">
<h5>{{'₦'.number_format($property->rental_price,2)}}</h5>
<i class="flaticon-bargain"></i>
</div>
<button class="ad-details-number">
<i class="fas fa-phone-alt"></i>
<span>Click to show the number</span>
</button>
<div class="ad-details-card">
<div class="ad-details-title">
<h5>Realtor</h5>
</div>
<div class="ad-details-profile">
<div class="author-img">
<a href="#">
<img src="/images/avatar/01.jpg" alt="avatar">
<span class="author-status"></span>
</a>
</div>
<div class="author-intro">
<h4>
<a href="#">{{$property->getRentalOwner->ownership_type == 1 ? $property->getRentalOwner->first_name .' '.$property->getRentalOwner->surname : $property->getRentalOwner->company_name }} </a>
</h4>
</div>
<hr>
<ul class="author-widget">
<li>
<a href="tel:{{$property->getRentalOwner->mobile_no ?? '' }}">
<i class="fas fa-phone-alt"></i>
</a>
</li>
@if(!Auth::check())
<li>
<a href="javascript:void(0);" data-toggle="modal" data-target="#exampleModal">
<i class="fas fa-envelope"></i>
</a>
</li>
@endif
</ul>
</div>
</div>
<div class="ad-details-card">
<div class="ad-details-title">
<h5>Property Features</h5>
</div>
<div class="ad-details-safety">
<ul>
<li>
{!! $property->getPropertyFeatures->bedrooms == 1 ? "<i class='fas fa-check text-success'></i>" : "<i class='fas fa-times text-danger'></i>" !!}
<p><strong>Bedrooms: </strong> {{$property->getPropertyFeatures->bedrooms_comment ?? ''}}</p>
</li>
<li>
{!! $property->getPropertyFeatures->bathrooms == 1 ? "<i class='fas fa-check text-success'></i>" : "<i class='fas fa-times text-danger'></i>" !!}
<p><strong>Bathrooms: </strong> {{$property->getPropertyFeatures->bathrooms_comment ?? ''}}</p>
</li>
<li>
{!! $property->getPropertyFeatures->study_room == 1 ? "<i class='fas fa-check text-success'></i>" : "<i class='fas fa-times text-danger'></i>" !!}
<p><strong>Study room: </strong> {{$property->getPropertyFeatures->study_room_comment ?? ''}}</p>
</li>
<li>
{!! $property->getPropertyFeatures->dinning_room == 1 ? "<i class='fas fa-check text-success'></i>" : "<i class='fas fa-times text-danger'></i>" !!}
<p><strong>Dinning room: </strong> {{$property->getPropertyFeatures->dinning_room_comment ?? ''}}</p>
</li>
<li>
{!! $property->getPropertyFeatures->carports == 1 ? "<i class='fas fa-check text-success'></i>" : "<i class='fas fa-times text-danger'></i>" !!}
<p><strong>Carports: </strong> {{$property->getPropertyFeatures->carports_comment ?? ''}}</p>
</li>
<li>
{!! $property->getPropertyFeatures->kitchens == 1 ? "<i class='fas fa-check text-success'></i>" : "<i class='fas fa-times text-danger'></i>" !!}
<p><strong>Kitchens: </strong> {{$property->getPropertyFeatures->kitchens_comment ?? ''}}</p>
</li>
<li>
{!! $property->getPropertyFeatures->garages == 1 ? "<i class='fas fa-check text-success'></i>" : "<i class='fas fa-times text-danger'></i>" !!}
<p><strong>Garages: </strong> {{$property->getPropertyFeatures->garages_comment ?? ''}}</p>
</li>
<li>
{!! $property->getPropertyFeatures->flooring == 1 ? "<i class='fas fa-check text-success'></i>" : "<i class='fas fa-times text-danger'></i>" !!}
<p><strong>Flooring: </strong> {{$property->getPropertyFeatures->flooring_type ?? ''}}</p>
</li>
<li>
{!! $property->getPropertyFeatures->laundry == 1 ? "<i class='fas fa-check text-success'></i>" : "<i class='fas fa-times text-danger'></i>" !!}
<p><strong>Laundry: </strong> {{$property->getPropertyFeatures->laundry_comment ?? ''}}</p>
</li>
<li>
{!! $property->getPropertyFeatures->balcony == 1 ? "<i class='fas fa-check text-success'></i>" : "<i class='fas fa-times text-danger'></i>" !!}
<p><strong>Balcony: </strong> {{$property->getPropertyFeatures->balcony_comment ?? ''}}</p>
</li>
<li>
{!! $property->getPropertyFeatures->pool == 1 ? "<i class='fas fa-check text-success'></i>" : "<i class='fas fa-times text-danger'></i>" !!}
<p><strong>Pool: </strong> {{$property->getPropertyFeatures->pool_comment ?? ''}}</p>
</li>
<li>
{!! $property->getPropertyFeatures->garden == 1 ? "<i class='fas fa-check text-success'></i>" : "<i class='fas fa-times text-danger'></i>" !!}
<p><strong>Garden: </strong> {{$property->getPropertyFeatures->garden_comment ?? ''}}</p>
</li>
<li>
{!! $property->getPropertyFeatures->views == 1 ? "<i class='fas fa-check text-success'></i>" : "<i class='fas fa-times text-danger'></i>" !!}
<p><strong>Views: </strong> {{$property->getPropertyFeatures->views_comment ?? ''}}</p>
</li>
<li>
{!! $property->getPropertyFeatures->security == 1 ? "<i class='fas fa-check text-success'></i>" : "<i class='fas fa-times text-danger'></i>" !!}
<p><strong>Security: </strong> {{$property->getPropertyFeatures->security_comment ?? ''}}</p>
</li>
<li>
{!! $property->getPropertyFeatures->store_room == 1 ? "<i class='fas fa-check text-success'></i>" : "<i class='fas fa-times text-danger'></i>" !!}
<p><strong>Store room: </strong> {{$property->getPropertyFeatures->store_room_comment ?? ''}}</p>
</li>
<li>
{!! $property->getPropertyFeatures->lounges == 1 ? "<i class='fas fa-check text-success'></i>" : "<i class='fas fa-times text-danger'></i>" !!}
<p><strong>Lounges: </strong> {{$property->getPropertyFeatures->lounges_comment ?? ''}}</p>
</li>
</ul>
</div>
</div>
<div class="ad-details-card">
<div class="ad-details-title">
<h5>featured ads</h5>
</div>
<div class="ad-details-feature slider-arrow">
<div class="feature-card">
<div class="feature-img">
<a href="#">
<img src="/images/product/10.jpg" alt="feature">
</a>
</div>
<div class="feature-badge">
<p>Featured</p>
</div>
<div class="feature-bookmark">
<button type="button">
<i class="fas fa-heart"></i>
</button>
</div>
<div class="feature-content">
<ol class="breadcrumb">
<li>
<span class="feature-cate rent">Rent</span>
</li>
<li class="breadcrumb-item">
<a href="#">automobile</a>
</li>
<li class="breadcrumb-item active" aria-current="page">Private Car</li>
</ol>
<div class="feature-title">
<h3>
<a href="#">Unde eveniet ducimus nostrum maiores soluta temporibus ipsum dolor sit amet.</a>
</h3>
</div>
<ul class="feature-meta">
<li>
<span>$1200
<small>/Monthly</small>
</span>
</li>
<li>
<i class="fas fa-clock"></i>
<span>56 minute ago!</span>
</li>
</ul>
</div>
</div>
<div class="feature-card">
<div class="feature-img">
<a href="#">
<img src="/images/product/01.jpg" alt="feature">
</a>
</div>
<div class="feature-badge">
<p>Featured</p>
</div>
<div class="feature-bookmark">
<button type="button">
<i class="fas fa-heart"></i>
</button>
</div>
<div class="feature-content">
<ol class="breadcrumb">
<li>
<span class="feature-cate booking">Booking</span>
</li>
<li class="breadcrumb-item">
<a href="#">Property</a>
</li>
<li class="breadcrumb-item active" aria-current="page">House</li>
</ol>
<div class="feature-title">
<h3>
<a href="#">Unde eveniet ducimus nostrum maiores soluta temporibus ipsum dolor sit amet.</a>
</h3>
</div>
<ul class="feature-meta">
<li>
<span>$800
<small>/Per Day</small>
</span>
</li>
<li>
<i class="fas fa-clock"></i>
<span>56 minute ago!</span>
</li>
</ul>
</div>
</div>
<div class="feature-card">
<div class="feature-img">
<a href="#">
<img src="/images/product/08.jpg" alt="feature">
</a>
</div>
<div class="feature-badge">
<p>Featured</p>
</div>
<div class="feature-bookmark">
<button type="button">
<i class="fas fa-heart"></i>
</button>
</div>
<div class="feature-content">
<ol class="breadcrumb">
<li>
<span class="feature-cate sale">sale</span>
</li>
<li class="breadcrumb-item">
<a href="#">Gadget</a>
</li>
<li class="breadcrumb-item active" aria-current="page">Iphone</li>
</ol>
<div class="feature-title">
<h3>
<a href="#">Unde eveniet ducimus nostrum maiores soluta temporibus ipsum dolor sit amet.</a>
</h3>
</div>
<ul class="feature-meta">
<li>
<span>$1150
<small>/Negotiable</small>
</span>
</li>
<li>
<i class="fas fa-clock"></i>
<span>56 minute ago!</span>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<section class="related-part">
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="section-center-heading">
<h2>Similar
<span>Listings</span>
</h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit aspernatur illum vel sunt libero voluptatum repudiandae veniam maxime tenetur.</p>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="related-slider slider-arrow">
<div class="product-card">
<div class="product-head">
<div class="product-img" style="background:url(images/product/01.jpg) no-repeat center; background-size:cover;">
<i class="cross-badge fas fa-bolt"></i>
<span class="flat-badge booking">booking</span>
<ul class="product-meta">
<li>
<i class="fas fa-eye"></i>
<p>264</p>
</li>
<li>
<i class="fas fa-mouse"></i>
<p>134</p>
</li>
<li>
<i class="fas fa-star"></i>
<p>4.5/7</p>
</li>
</ul>
</div>
</div>
<div class="product-info">
<div class="product-tag">
<i class="fas fa-tags"></i>
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="#">Luxury</a>
</li>
<li class="breadcrumb-item active" aria-current="page">Duplex House</li>
</ol>
</div>
<div class="product-title">
<h5>
<a href="rightbar-details.html">Lorem ipsum dolor sit amet consect adipisicing elit</a>
</h5>
<ul class="product-location">
<li>
<i class="fas fa-map-marker-alt"></i>
<p>Uttara, Dhaka</p>
</li>
<li>
<i class="fas fa-clock"></i>
<p>30 min ago!</p>
</li>
</ul>
</div>
<div class="product-details">
<div class="product-price">
<h5>$1500</h5>
<span>/Per Day</span>
</div>
<ul class="product-widget">
<li>
<a href="compare.html" class="tooltip">
<i class="fas fa-compress"></i>
<span class="tooltext top">compare</span>
</a>
</li>
<li>
<button class="tooltip">
<i class="far fa-heart"></i>
<span class="tooltext top">bookmark</span>
</button>
</li>
</ul>
</div>
</div>
</div>
<div class="product-card">
<div class="product-head">
<div class="product-img" style="background:url(images/product/03.jpg) no-repeat center; background-size:cover;">
<i class="cross-badge fas fa-bolt"></i>
<span class="flat-badge sale">sale</span>
<ul class="product-meta">
<li>
<i class="fas fa-eye"></i>
<p>264</p>
</li>
<li>
<i class="fas fa-mouse"></i>
<p>134</p>
</li>
<li>
<i class="fas fa-star"></i>
<p>4.5/7</p>
</li>
</ul>
</div>
</div>
<div class="product-info">
<div class="product-tag">
<i class="fas fa-tags"></i>
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="#">Stationary</a>
</li>
<li class="breadcrumb-item active" aria-current="page">books</li>
</ol>
</div>
<div class="product-title">
<h5>
<a href="rightbar-details.html">Lorem ipsum dolor sit amet consect adipisicing elit</a>
</h5>
<ul class="product-location">
<li>
<i class="fas fa-map-marker-alt"></i>
<p>Uttara, Dhaka</p>
</li>
<li>
<i class="fas fa-clock"></i>
<p>30 min ago!</p>
</li>
</ul>
</div>
<div class="product-details">
<div class="product-price">
<h5>$470</h5>
<span>/fixed</span>
</div>
<ul class="product-widget">
<li>
<a href="compare.html" class="tooltip">
<i class="fas fa-compress"></i>
<span class="tooltext top">compare</span>
</a>
</li>
<li>
<button class="tooltip">
<i class="far fa-heart"></i>
<span class="tooltext top">bookmark</span>
</button>
</li>
</ul>
</div>
</div>
</div>
<div class="product-card">
<div class="product-head">
<div class="product-img" style="background:url(images/product/10.jpg) no-repeat center; background-size:cover;">
<i class="cross-badge fas fa-bolt"></i>
<span class="flat-badge rent">rent</span>
<ul class="product-meta">
<li>
<i class="fas fa-eye"></i>
<p>264</p>
</li>
<li>
<i class="fas fa-mouse"></i>
<p>134</p>
</li>
<li>
<i class="fas fa-star"></i>
<p>4.5/7</p>
</li>
</ul>
</div>
</div>
<div class="product-info">
<div class="product-tag">
<i class="fas fa-tags"></i>
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="#">automobile</a>
</li>
<li class="breadcrumb-item active" aria-current="page">private car</li>
</ol>
</div>
<div class="product-title">
<h5>
<a href="rightbar-details.html">Lorem ipsum dolor sit amet consect adipisicing elit</a>
</h5>
<ul class="product-location">
<li>
<i class="fas fa-map-marker-alt"></i>
<p>Uttara, Dhaka</p>
</li>
<li>
<i class="fas fa-clock"></i>
<p>30 min ago!</p>
</li>
</ul>
</div>
<div class="product-details">
<div class="product-price">
<h5>$3300</h5>
<span>/per month</span>
</div>
<ul class="product-widget">
<li>
<a href="compare.html" class="tooltip">
<i class="fas fa-compress"></i>
<span class="tooltext top">compare</span>
</a>
</li>
<li>
<button class="tooltip">
<i class="far fa-heart"></i>
<span class="tooltext top">bookmark</span>
</button>
</li>
</ul>
</div>
</div>
</div>
<div class="product-card">
<div class="product-head">
<div class="product-img" style="background:url(images/product/09.jpg) no-repeat center; background-size:cover;">
<i class="cross-badge fas fa-bolt"></i>
<span class="flat-badge sale">sale</span>
<ul class="product-meta">
<li>
<i class="fas fa-eye"></i>
<p>264</p>
</li>
<li>
<i class="fas fa-mouse"></i>
<p>134</p>
</li>
<li>
<i class="fas fa-star"></i>
<p>4.5/7</p>
</li>
</ul>
</div>
</div>
<div class="product-info">
<div class="product-tag">
<i class="fas fa-tags"></i>
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="#">animals</a>
</li>
<li class="breadcrumb-item active" aria-current="page">cat</li>
</ol>
</div>
<div class="product-title">
<h5>
<a href="rightbar-details.html">Lorem ipsum dolor sit amet consect adipisicing elit</a>
</h5>
<ul class="product-location">
<li>
<i class="fas fa-map-marker-alt"></i>
<p>Uttara, Dhaka</p>
</li>
<li>
<i class="fas fa-clock"></i>
<p>30 min ago!</p>
</li>
</ul>
</div>
<div class="product-details">
<div class="product-price">
<h5>$900</h5>
<span>/Negotiable</span>
</div>
<ul class="product-widget">
<li>
<a href="compare.html" class="tooltip">
<i class="fas fa-compress"></i>
<span class="tooltext top">compare</span>
</a>
</li>
<li>
<button class="tooltip">
<i class="far fa-heart"></i>
<span class="tooltext top">bookmark</span>
</button>
</li>
</ul>
</div>
</div>
</div>
<div class="product-card">
<div class="product-head">
<div class="product-img" style="background:url(images/product/02.jpg) no-repeat center; background-size:cover;">
<i class="cross-badge fas fa-bolt"></i>
<span class="flat-badge sale">sale</span>
<ul class="product-meta">
<li>
<i class="fas fa-eye"></i>
<p>264</p>
</li>
<li>
<i class="fas fa-mouse"></i>
<p>134</p>
</li>
<li>
<i class="fas fa-star"></i>
<p>4.5/7</p>
</li>
</ul>
</div>
</div>
<div class="product-info">
<div class="product-tag">
<i class="fas fa-tags"></i>
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="#">fashion</a>
</li>
<li class="breadcrumb-item active" aria-current="page">shoes</li>
</ol>
</div>
<div class="product-title">
<h5>
<a href="rightbar-details.html">Lorem ipsum dolor sit amet consect adipisicing elit</a>
</h5>
<ul class="product-location">
<li>
<i class="fas fa-map-marker-alt"></i>
<p>Uttara, Dhaka</p>
</li>
<li>
<i class="fas fa-clock"></i>
<p>30 min ago!</p>
</li>
</ul>
</div>
<div class="product-details">
<div class="product-price">
<h5>$460</h5>
<span>/fixed</span>
</div>
<ul class="product-widget">
<li>
<a href="compare.html" class="tooltip">
<i class="fas fa-compress"></i>
<span class="tooltext top">compare</span>
</a>
</li>
<li>
<button class="tooltip">
<i class="far fa-heart"></i>
<span class="tooltext top">bookmark</span>
</button>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="center-50">
<a href="rightbar-list.html" class="btn btn-inline">
<i class="fas fa-eye"></i>
<span>view all related</span>
</a>
</div>
</div>
</div>
</div>
</section>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Message {{$property->getRentalOwner->ownership_type == 1 ? $property->getRentalOwner->first_name .' '.$property->getRentalOwner->surname : $property->getRentalOwner->company_name}}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form class="ad-review-form" method="post" action="route('message-seller')}}">
@csrf
<div class="form-group">
<textarea class="form-control" placeholder="Type message here..." name="message" style="resize: none;"></textarea>
</div>
<input type="hidden" name="to" value="{{$property->getRentalOwner->id}}">
<div class="btn-group">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button class="btn btn-inline" type="submit">
<i class="fas fa-tint"></i>
<span>submit</span>
</button>
</div>
</form>
</div>
</div>
</div>
</div>
@endsection
@section('extra-scripts')
<script src="/js/custom/price-range.js"></script>
@endsection
| 59.597307 | 252 | 0.286254 |
393736277959993aca35785733ea38468ef7ec00 | 487 | py | Python | server/database_connection.py | osteele/matrix-photo-gallery | 2eecff1833aa09350a8a19553352c24a1691e639 | [
"MIT"
] | 1 | 2018-07-24T20:19:52.000Z | 2018-07-24T20:19:52.000Z | server/database_connection.py | osteele/tidal-memories | afcd3c8900814577374bfd847ba05c12ca88f397 | [
"MIT"
] | 2 | 2021-03-09T09:59:44.000Z | 2021-05-09T17:29:22.000Z | server/database_connection.py | osteele/matrix-photo-gallery | 2eecff1833aa09350a8a19553352c24a1691e639 | [
"MIT"
] | null | null | null | import os
import re
from mongoengine import connect
MONGODB_URI = os.getenv('MONGODB_URI')
MONGO_CONNECTION_RE = re.compile(
r'mongodb://'
r'(?P<username>.+?)'
r':(?P<password>.+?)'
r'@(?P<host>(?:.+?):(?:\d+))'
r'/(?P<db>.+)')
def parse_mongo_connection_uri(uri):
return MONGO_CONNECTION_RE.match(uri).groupdict()
if MONGODB_URI:
print(f"Connecting to {MONGODB_URI}")
connect(**parse_mongo_connection_uri(MONGODB_URI))
else:
connect('dinacon')
| 20.291667 | 54 | 0.655031 |
4cd74a4ec11457564c379d8c97e82889cc58345b | 582 | py | Python | bootstrap.py | onecodex/docker-sentry | 31ad3e6bb8ecae071c3916f091b9e0547f16bf89 | [
"MIT"
] | 6 | 2015-06-03T09:38:27.000Z | 2017-09-16T11:47:29.000Z | bootstrap.py | onecodex/docker-sentry | 31ad3e6bb8ecae071c3916f091b9e0547f16bf89 | [
"MIT"
] | 10 | 2015-04-20T00:02:23.000Z | 2017-05-22T15:26:44.000Z | bootstrap.py | onecodex/docker-sentry | 31ad3e6bb8ecae071c3916f091b9e0547f16bf89 | [
"MIT"
] | 12 | 2015-04-19T22:51:23.000Z | 2019-10-16T14:49:27.000Z | # Bootstrap the Sentry environment
from sentry.utils.runner import configure
configure()
import os
from sentry.models import Team, Project, ProjectKey, User
username = os.environ.get('ADMIN_USERNAME', 'aptible')
user, created = User.objects.get_or_create(username=username, defaults={
'email': os.environ.get('ADMIN_EMAIL', 'root@localhost'),
'is_superuser': True
})
user.set_password(os.environ['ADMIN_PASSWORD'])
user.save()
team_name = os.environ.get('TEAM_NAME', 'Aptible')
team, created = Team.objects.get_or_create(name=team_name, defaults={
'owner': user
})
| 26.454545 | 72 | 0.747423 |
c9d706c63bb1bae4e82822c85322e7cad2e2a451 | 4,870 | ts | TypeScript | core/templates/pages/collection-editor-page/modals/collection-editor-pre-publish-modal.component.spec.ts | swyuan27/oppia | da4c733659b8813eccf738ff8be19123ebcdeb15 | [
"Apache-2.0"
] | 5,422 | 2015-08-14T01:56:44.000Z | 2022-03-31T23:31:56.000Z | core/templates/pages/collection-editor-page/modals/collection-editor-pre-publish-modal.component.spec.ts | swyuan27/oppia | da4c733659b8813eccf738ff8be19123ebcdeb15 | [
"Apache-2.0"
] | 14,178 | 2015-08-14T05:21:45.000Z | 2022-03-31T23:54:10.000Z | core/templates/pages/collection-editor-page/modals/collection-editor-pre-publish-modal.component.spec.ts | swyuan27/oppia | da4c733659b8813eccf738ff8be19123ebcdeb15 | [
"Apache-2.0"
] | 3,574 | 2015-08-14T04:20:06.000Z | 2022-03-29T01:52:37.000Z | // Copyright 2020 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Unit tests for collection editor pre publish modal.
*/
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { NgbActiveModal, NgbModalModule } from '@ng-bootstrap/ng-bootstrap';
import { CollectionUpdateService } from 'domain/collection/collection-update.service';
import { Collection } from 'domain/collection/collection.model';
import { AlertsService } from 'services/alerts.service';
import { CollectionEditorStateService } from '../services/collection-editor-state.service';
import { CollectionEditorPrePublishModalComponent } from './collection-editor-pre-publish-modal.component';
describe('Collection editor pre publish modal component', () => {
let fixture: ComponentFixture<CollectionEditorPrePublishModalComponent>;
let componentInstance: CollectionEditorPrePublishModalComponent;
let collectionEditorStateService: CollectionEditorStateService;
let collectionUpdateService: CollectionUpdateService;
let ngbActiveModal: NgbActiveModal;
let alertsService: AlertsService;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [
HttpClientTestingModule,
NgbModalModule
],
declarations: [
CollectionEditorPrePublishModalComponent
],
providers: [
AlertsService,
CollectionEditorStateService,
CollectionUpdateService,
NgbActiveModal
],
schemas: [NO_ERRORS_SCHEMA]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(CollectionEditorPrePublishModalComponent);
componentInstance = fixture.componentInstance;
collectionEditorStateService = TestBed.inject(CollectionEditorStateService);
collectionUpdateService = TestBed.inject(CollectionUpdateService);
ngbActiveModal = TestBed.inject(NgbActiveModal);
alertsService = TestBed.inject(AlertsService);
});
it('should initialize', () => {
let collectionTitle = 'collection_title';
let collectionObjective = 'collection_objective';
let mockCollection = new Collection(
'collection_id', collectionTitle, collectionObjective, 'en', [],
null, '', 2, 3, []);
spyOn(collectionEditorStateService, 'getCollection')
.and.returnValue(mockCollection);
componentInstance.ngOnInit();
expect(componentInstance.newTitle).toEqual(collectionTitle);
expect(componentInstance.newObjective).toEqual(collectionObjective);
});
it('should tell if saving is allowed', () => {
componentInstance.newTitle = 'valid title';
componentInstance.newObjective = 'valid objective';
componentInstance.newCategory = '';
expect(componentInstance.isSavingAllowed()).toBeFalse();
});
it('should cancel publish', () => {
spyOn(ngbActiveModal, 'dismiss');
componentInstance.cancel();
expect(ngbActiveModal.dismiss).toHaveBeenCalled();
});
it('should publish', () => {
let collectionTitle = 'collection_title';
let collectionObjective = 'collection_objective';
let mockCollection = new Collection(
'collection_id', collectionTitle, collectionObjective, 'en', [],
null, '', 2, 3, []);
spyOn(collectionEditorStateService, 'getCollection')
.and.returnValue(mockCollection);
componentInstance.ngOnInit();
spyOn(alertsService, 'addWarning');
componentInstance.newTitle = '';
componentInstance.save();
expect(alertsService.addWarning).toHaveBeenCalledWith(
'Please specify a title');
componentInstance.newTitle = 'valid title';
componentInstance.newObjective = '';
componentInstance.save();
expect(alertsService.addWarning).toHaveBeenCalledWith(
'Please specify an objective');
componentInstance.newObjective = 'learn';
componentInstance.save();
expect(alertsService.addWarning).toHaveBeenCalledWith(
'Please specify a category');
componentInstance.newCategory = 'ALGEBRA';
spyOn(collectionUpdateService, 'setCollectionObjective');
spyOn(collectionUpdateService, 'setCollectionCategory');
spyOn(ngbActiveModal, 'close');
componentInstance.save();
});
});
| 39.593496 | 107 | 0.734086 |
572aa2e1e4b8edb5bd040be0ba74c1d257ae8ca6 | 710 | js | JavaScript | src/backend/mailer.js | DMartinBGL/MakersBnB-DJBT | 7ac90183a619f52a1846ac3765ffe7234cebfd86 | [
"MIT"
] | null | null | null | src/backend/mailer.js | DMartinBGL/MakersBnB-DJBT | 7ac90183a619f52a1846ac3765ffe7234cebfd86 | [
"MIT"
] | 10 | 2019-11-18T10:05:49.000Z | 2019-11-22T11:08:42.000Z | src/backend/mailer.js | DMartinBGL/MakersBnB-DJBT | 7ac90183a619f52a1846ac3765ffe7234cebfd86 | [
"MIT"
] | 1 | 2019-11-26T15:50:10.000Z | 2019-11-26T15:50:10.000Z | const cryptoRandomString = require('crypto-random-string');
const sgMail = require('@sendgrid/mail');
const emailVerification = require('./emailVerification');
const apiKey = process.env.SG_KEY;
const tokenLength = 40;
const baseUrl = "http://makers-project.xyz";
sgMail.setApiKey(apiKey);
async function sendVerificationEmail(email) {
const token = cryptoRandomString( { length: tokenLength, type: 'url-safe'} );
await emailVerification.add(email, token);
sgMail.send({
to: email,
from: "[email protected]",
subject: "Verify Email",
html: `<a href="${baseUrl}/verify-email/${token}">Click here to verify your email</a>`
})
}
module.exports = {
sendVerificationEmail,
} | 26.296296 | 90 | 0.708451 |
e018dd3705f992b3ebf524f6922cff12cf62e9ae | 17,365 | c | C | ext/yiot-core/iotkit/sdk/modules/protocols/snap/src/generated/snap_cvt.c | andr13/yiot-yocto-test | 1a0942318a2fb244c2a5a2ff086be7d0b7ea0deb | [
"BSD-2-Clause"
] | null | null | null | ext/yiot-core/iotkit/sdk/modules/protocols/snap/src/generated/snap_cvt.c | andr13/yiot-yocto-test | 1a0942318a2fb244c2a5a2ff086be7d0b7ea0deb | [
"BSD-2-Clause"
] | null | null | null | ext/yiot-core/iotkit/sdk/modules/protocols/snap/src/generated/snap_cvt.c | andr13/yiot-yocto-test | 1a0942318a2fb244c2a5a2ff086be7d0b7ea0deb | [
"BSD-2-Clause"
] | null | null | null | // Copyright (C) 2015-2020 Virgil Security, Inc.
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// (1) Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// (2) Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// (3) Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
// IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Lead Maintainer: Virgil Security Inc. <[email protected]>
#include <virgil/iot/protocols/snap/generated/snap_cvt.h>
/******************************************************************************/
// Converting encode function for (vs_pubkey_dated_t)
void
vs_pubkey_dated_t_encode(vs_pubkey_dated_t *src_data) {
src_data->expire_date = VS_IOT_HTONL(src_data->expire_date);
vs_pubkey_t_encode(&src_data->pubkey);
src_data->start_date = VS_IOT_HTONL(src_data->start_date);
}
/******************************************************************************/
// Converting decode function for (vs_pubkey_dated_t)
void
vs_pubkey_dated_t_decode(vs_pubkey_dated_t *src_data) {
src_data->expire_date = VS_IOT_NTOHL(src_data->expire_date);
vs_pubkey_t_decode(&src_data->pubkey);
src_data->start_date = VS_IOT_NTOHL(src_data->start_date);
}
/******************************************************************************/
// Converting encode function for (vs_fldt_gnff_footer_request_t)
void
vs_fldt_gnff_footer_request_t_encode(vs_fldt_gnff_footer_request_t *src_data) {
vs_update_file_type_t_encode(&src_data->type);
}
/******************************************************************************/
// Converting decode function for (vs_fldt_gnff_footer_request_t)
void
vs_fldt_gnff_footer_request_t_decode(vs_fldt_gnff_footer_request_t *src_data) {
vs_update_file_type_t_decode(&src_data->type);
}
/******************************************************************************/
// Converting encode function for (vs_update_file_type_t)
void
vs_update_file_type_t_encode(vs_update_file_type_t *src_data) {
vs_file_info_t_encode(&src_data->info);
src_data->type = VS_IOT_HTONS(src_data->type);
}
/******************************************************************************/
// Converting decode function for (vs_update_file_type_t)
void
vs_update_file_type_t_decode(vs_update_file_type_t *src_data) {
vs_file_info_t_decode(&src_data->info);
src_data->type = VS_IOT_NTOHS(src_data->type);
}
#if MSGR_SERVER
/******************************************************************************/
// Converting encode function for (vs_msgr_setd_request_t)
void
vs_msgr_setd_request_t_encode(vs_msgr_setd_request_t *src_data) {
src_data->data_sz = VS_IOT_HTONL(src_data->data_sz);
}
/******************************************************************************/
// Converting decode function for (vs_msgr_setd_request_t)
void
vs_msgr_setd_request_t_decode(vs_msgr_setd_request_t *src_data) {
src_data->data_sz = VS_IOT_NTOHL(src_data->data_sz);
}
#endif
/******************************************************************************/
// Converting encode function for (vs_info_stat_response_t)
void
vs_info_stat_response_t_encode(vs_info_stat_response_t *src_data) {
src_data->sent = VS_IOT_HTONL(src_data->sent);
src_data->received = VS_IOT_HTONL(src_data->received);
}
/******************************************************************************/
// Converting decode function for (vs_info_stat_response_t)
void
vs_info_stat_response_t_decode(vs_info_stat_response_t *src_data) {
src_data->sent = VS_IOT_NTOHL(src_data->sent);
src_data->received = VS_IOT_NTOHL(src_data->received);
}
/******************************************************************************/
// Converting encode function for (vs_info_ginf_response_t)
void
vs_info_ginf_response_t_encode(vs_info_ginf_response_t *src_data) {
vs_file_version_t_encode(&src_data->fw_version);
vs_file_version_t_encode(&src_data->tl_version);
src_data->device_roles = VS_IOT_HTONL(src_data->device_roles);
}
/******************************************************************************/
// Converting decode function for (vs_info_ginf_response_t)
void
vs_info_ginf_response_t_decode(vs_info_ginf_response_t *src_data) {
vs_file_version_t_decode(&src_data->fw_version);
vs_file_version_t_decode(&src_data->tl_version);
src_data->device_roles = VS_IOT_NTOHL(src_data->device_roles);
}
/******************************************************************************/
// Converting encode function for (vs_info_poll_request_t)
void
vs_info_poll_request_t_encode(vs_info_poll_request_t *src_data) {
src_data->period_seconds = VS_IOT_HTONS(src_data->period_seconds);
}
/******************************************************************************/
// Converting decode function for (vs_info_poll_request_t)
void
vs_info_poll_request_t_decode(vs_info_poll_request_t *src_data) {
src_data->period_seconds = VS_IOT_NTOHS(src_data->period_seconds);
}
/******************************************************************************/
// Converting encode function for (vs_cfg_user_config_request_t)
void
vs_cfg_user_config_request_t_encode(vs_cfg_user_config_request_t *src_data) {
src_data->data_sz = VS_IOT_HTONL(src_data->data_sz);
}
/******************************************************************************/
// Converting decode function for (vs_cfg_user_config_request_t)
void
vs_cfg_user_config_request_t_decode(vs_cfg_user_config_request_t *src_data) {
src_data->data_sz = VS_IOT_NTOHL(src_data->data_sz);
}
/******************************************************************************/
// Converting encode function for (vs_snap_prvs_set_data_t)
void
vs_snap_prvs_set_data_t_encode(vs_snap_prvs_set_data_t *src_data) {
src_data->request_id = VS_IOT_HTONS(src_data->request_id);
}
/******************************************************************************/
// Converting decode function for (vs_snap_prvs_set_data_t)
void
vs_snap_prvs_set_data_t_decode(vs_snap_prvs_set_data_t *src_data) {
src_data->request_id = VS_IOT_NTOHS(src_data->request_id);
}
/******************************************************************************/
// Converting encode function for (vs_ethernet_header_t)
void
vs_ethernet_header_t_encode(vs_ethernet_header_t *src_data) {
src_data->type = VS_IOT_HTONS(src_data->type);
}
/******************************************************************************/
// Converting decode function for (vs_ethernet_header_t)
void
vs_ethernet_header_t_decode(vs_ethernet_header_t *src_data) {
src_data->type = VS_IOT_NTOHS(src_data->type);
}
/******************************************************************************/
// Converting encode function for (vs_fldt_gnff_footer_response_t)
void
vs_fldt_gnff_footer_response_t_encode(vs_fldt_gnff_footer_response_t *src_data) {
vs_update_file_type_t_encode(&src_data->type);
src_data->footer_size = VS_IOT_HTONS(src_data->footer_size);
}
/******************************************************************************/
// Converting decode function for (vs_fldt_gnff_footer_response_t)
void
vs_fldt_gnff_footer_response_t_decode(vs_fldt_gnff_footer_response_t *src_data) {
vs_update_file_type_t_decode(&src_data->type);
src_data->footer_size = VS_IOT_NTOHS(src_data->footer_size);
}
/******************************************************************************/
// Converting encode function for (vs_file_info_t)
void
vs_file_info_t_encode(vs_file_info_t *src_data) {
vs_file_version_t_encode(&src_data->version);
}
/******************************************************************************/
// Converting decode function for (vs_file_info_t)
void
vs_file_info_t_decode(vs_file_info_t *src_data) {
vs_file_version_t_decode(&src_data->version);
}
/******************************************************************************/
// Converting encode function for (vs_snap_packet_t)
void
vs_snap_packet_t_encode(vs_snap_packet_t *src_data) {
vs_ethernet_header_t_encode(&src_data->eth_header);
vs_snap_header_t_encode(&src_data->header);
}
/******************************************************************************/
// Converting decode function for (vs_snap_packet_t)
void
vs_snap_packet_t_decode(vs_snap_packet_t *src_data) {
vs_ethernet_header_t_decode(&src_data->eth_header);
vs_snap_header_t_decode(&src_data->header);
}
/******************************************************************************/
// Converting encode function for (vs_fldt_gnfh_header_request_t)
void
vs_fldt_gnfh_header_request_t_encode(vs_fldt_gnfh_header_request_t *src_data) {
vs_update_file_type_t_encode(&src_data->type);
}
/******************************************************************************/
// Converting decode function for (vs_fldt_gnfh_header_request_t)
void
vs_fldt_gnfh_header_request_t_decode(vs_fldt_gnfh_header_request_t *src_data) {
vs_update_file_type_t_decode(&src_data->type);
}
/******************************************************************************/
// Converting encode function for (vs_fldt_gnfh_header_response_t)
void
vs_fldt_gnfh_header_response_t_encode(vs_fldt_gnfh_header_response_t *src_data) {
src_data->file_size = VS_IOT_HTONL(src_data->file_size);
src_data->header_size = VS_IOT_HTONS(src_data->header_size);
vs_fldt_file_info_t_encode(&src_data->fldt_info);
}
/******************************************************************************/
// Converting decode function for (vs_fldt_gnfh_header_response_t)
void
vs_fldt_gnfh_header_response_t_decode(vs_fldt_gnfh_header_response_t *src_data) {
src_data->file_size = VS_IOT_NTOHL(src_data->file_size);
src_data->header_size = VS_IOT_NTOHS(src_data->header_size);
vs_fldt_file_info_t_decode(&src_data->fldt_info);
}
/******************************************************************************/
// Converting encode function for (vs_fldt_gnfd_data_request_t)
void
vs_fldt_gnfd_data_request_t_encode(vs_fldt_gnfd_data_request_t *src_data) {
vs_update_file_type_t_encode(&src_data->type);
src_data->offset = VS_IOT_HTONL(src_data->offset);
}
/******************************************************************************/
// Converting decode function for (vs_fldt_gnfd_data_request_t)
void
vs_fldt_gnfd_data_request_t_decode(vs_fldt_gnfd_data_request_t *src_data) {
vs_update_file_type_t_decode(&src_data->type);
src_data->offset = VS_IOT_NTOHL(src_data->offset);
}
/******************************************************************************/
// Converting encode function for (vs_msgr_poll_request_t)
void
vs_msgr_poll_request_t_encode(vs_msgr_poll_request_t *src_data) {
src_data->period_seconds = VS_IOT_HTONS(src_data->period_seconds);
}
/******************************************************************************/
// Converting decode function for (vs_msgr_poll_request_t)
void
vs_msgr_poll_request_t_decode(vs_msgr_poll_request_t *src_data) {
src_data->period_seconds = VS_IOT_NTOHS(src_data->period_seconds);
}
/******************************************************************************/
// Converting encode function for (vs_msgr_getd_response_t)
void
vs_msgr_getd_response_t_encode(vs_msgr_getd_response_t *src_data) {
src_data->data_sz = VS_IOT_HTONL(src_data->data_sz);
}
/******************************************************************************/
// Converting decode function for (vs_msgr_getd_response_t)
void
vs_msgr_getd_response_t_decode(vs_msgr_getd_response_t *src_data) {
src_data->data_sz = VS_IOT_NTOHL(src_data->data_sz);
}
/******************************************************************************/
// Converting encode function for (vs_snap_header_t)
void
vs_snap_header_t_encode(vs_snap_header_t *src_data) {
src_data->transaction_id = VS_IOT_HTONS(src_data->transaction_id);
src_data->padding = VS_IOT_HTONS(src_data->padding);
src_data->content_size = VS_IOT_HTONS(src_data->content_size);
}
/******************************************************************************/
// Converting decode function for (vs_snap_header_t)
void
vs_snap_header_t_decode(vs_snap_header_t *src_data) {
src_data->transaction_id = VS_IOT_NTOHS(src_data->transaction_id);
src_data->padding = VS_IOT_NTOHS(src_data->padding);
src_data->content_size = VS_IOT_NTOHS(src_data->content_size);
}
/******************************************************************************/
// Converting encode function for (vs_pubkey_t)
void
vs_pubkey_t_encode(vs_pubkey_t *src_data) {
src_data->meta_data_sz = VS_IOT_HTONS(src_data->meta_data_sz);
}
/******************************************************************************/
// Converting decode function for (vs_pubkey_t)
void
vs_pubkey_t_decode(vs_pubkey_t *src_data) {
src_data->meta_data_sz = VS_IOT_NTOHS(src_data->meta_data_sz);
}
/******************************************************************************/
// Converting encode function for (vs_snap_prvs_devi_t)
void
vs_snap_prvs_devi_t_encode(vs_snap_prvs_devi_t *src_data) {
src_data->data_sz = VS_IOT_HTONS(src_data->data_sz);
}
/******************************************************************************/
// Converting decode function for (vs_snap_prvs_devi_t)
void
vs_snap_prvs_devi_t_decode(vs_snap_prvs_devi_t *src_data) {
src_data->data_sz = VS_IOT_NTOHS(src_data->data_sz);
}
/******************************************************************************/
// Converting encode function for (vs_fldt_file_info_t)
void
vs_fldt_file_info_t_encode(vs_fldt_file_info_t *src_data) {
vs_update_file_type_t_encode(&src_data->type);
}
/******************************************************************************/
// Converting decode function for (vs_fldt_file_info_t)
void
vs_fldt_file_info_t_decode(vs_fldt_file_info_t *src_data) {
vs_update_file_type_t_decode(&src_data->type);
}
/******************************************************************************/
// Converting encode function for (vs_fldt_gnfd_data_response_t)
void
vs_fldt_gnfd_data_response_t_encode(vs_fldt_gnfd_data_response_t *src_data) {
src_data->data_size = VS_IOT_HTONS(src_data->data_size);
vs_update_file_type_t_encode(&src_data->type);
src_data->offset = VS_IOT_HTONL(src_data->offset);
src_data->next_offset = VS_IOT_HTONL(src_data->next_offset);
}
/******************************************************************************/
// Converting decode function for (vs_fldt_gnfd_data_response_t)
void
vs_fldt_gnfd_data_response_t_decode(vs_fldt_gnfd_data_response_t *src_data) {
src_data->data_size = VS_IOT_NTOHS(src_data->data_size);
vs_update_file_type_t_decode(&src_data->type);
src_data->offset = VS_IOT_NTOHL(src_data->offset);
src_data->next_offset = VS_IOT_NTOHL(src_data->next_offset);
}
/******************************************************************************/
// Converting encode function for (vs_cfg_messenger_config_request_t)
void
vs_cfg_messenger_config_request_t_encode(vs_cfg_messenger_config_request_t *src_data) {
src_data->enjabberd_port = VS_IOT_HTONS(src_data->enjabberd_port);
}
/******************************************************************************/
// Converting decode function for (vs_cfg_messenger_config_request_t)
void
vs_cfg_messenger_config_request_t_decode(vs_cfg_messenger_config_request_t *src_data) {
src_data->enjabberd_port = VS_IOT_NTOHS(src_data->enjabberd_port);
}
/******************************************************************************/
// Converting encode function for (vs_file_version_t)
void
vs_file_version_t_encode(vs_file_version_t *src_data) {
src_data->build = VS_IOT_HTONL(src_data->build);
src_data->timestamp = VS_IOT_HTONL(src_data->timestamp);
}
/******************************************************************************/
// Converting decode function for (vs_file_version_t)
void
vs_file_version_t_decode(vs_file_version_t *src_data) {
src_data->build = VS_IOT_NTOHL(src_data->build);
src_data->timestamp = VS_IOT_NTOHL(src_data->timestamp);
} | 41.247031 | 87 | 0.613878 |
0d470a3e0297f718b91240e88af0de4ee5fe3120 | 4,083 | rb | Ruby | test/functional/test_matchers.rb | coupler/coupler | 52625c9ca823367723cfe2e6ab6c7af97d430be2 | [
"MIT"
] | null | null | null | test/functional/test_matchers.rb | coupler/coupler | 52625c9ca823367723cfe2e6ab6c7af97d430be2 | [
"MIT"
] | null | null | null | test/functional/test_matchers.rb | coupler/coupler | 52625c9ca823367723cfe2e6ab6c7af97d430be2 | [
"MIT"
] | null | null | null | require 'helper'
module CouplerFunctionalTests
class TestMatchers < Coupler::Test::FunctionalTest
def self.startup
super
conn = new_connection('h2', :name => 'foo')
conn.database do |db|
db.create_table!(:foo) do
primary_key :id
String :foo
String :bar
end
db[:foo].insert({:foo => 'foo', :bar => 'bar'})
db[:foo].insert({:foo => 'bar', :bar => 'foo'})
end
end
def setup
super
@connection = new_connection('h2', :name => 'foo').save!
@project = Project.create!(:name => 'foo')
@resource = Resource.create!(:name => 'foo', :project => @project, :table_name => 'foo', :connection => @connection)
@scenario = Scenario.create!(:name => 'foo', :project => @project, :resource_1 => @resource)
end
test "new" do
visit "/projects/#{@project.id}/scenarios/#{@scenario.id}/matchers/new"
assert_equal 200, page.status_code
end
test "new with non existant project" do
visit "/projects/8675309/scenarios/#{@scenario.id}/matchers/new"
assert_equal "/projects", page.current_path
assert page.has_content?("The project you were looking for doesn't exist")
end
test "new with non existant scenario" do
visit "/projects/#{@project.id}/scenarios/8675309/matchers/new"
assert_equal "/projects/#{@project.id}/scenarios", page.current_path
assert page.has_content?("The scenario you were looking for doesn't exist")
end
attribute(:javascript, true)
test "successfully creating matcher for self-linkage" do
visit "/projects/#{@project.id}/scenarios/#{@scenario.id}/matchers/new"
click_link("Add comparison")
select('foo', :from => "lhs_value_select")
find('span.ui-button-text', :text => 'Add').click
click_button('Submit')
assert_equal "/projects/#{@project.id}/scenarios/#{@scenario.id}", page.current_path
assert @scenario.matcher
end
attribute(:javascript, true)
test "edit" do
foo = @resource.fields_dataset[:name => 'foo']
bar = @resource.fields_dataset[:name => 'bar']
matcher = Matcher.create!({
:scenario => @scenario,
:comparisons_attributes => [{
'lhs_type' => 'field', 'raw_lhs_value' => foo.id, 'lhs_which' => 1,
'rhs_type' => 'field', 'raw_rhs_value' => bar.id, 'rhs_which' => 2,
'operator' => 'equals'
}]
})
visit "/projects/#{@project.id}/scenarios/#{@scenario.id}/matchers/#{matcher.id}/edit"
click_link("Delete")
click_link("Add comparison")
find("#lhs_value_select").select("bar")
find("#rhs_value_select").select("foo")
find('span.ui-button-text', :text => 'Add').click
click_button('Submit')
assert_equal "/projects/#{@project.id}/scenarios/#{@scenario.id}", page.current_path
assert_equal 1, @scenario.matcher.comparisons_dataset.count
end
test "edit with non existant matcher" do
visit "/projects/#{@project.id}/scenarios/#{@scenario.id}/matchers/8675309/edit"
assert_equal "/projects/#{@project.id}/scenarios/#{@scenario.id}", page.current_path
assert page.has_content?("The matcher you were looking for doesn't exist")
end
attribute(:javascript, true)
test "delete" do
field = @resource.fields_dataset[:name => 'foo']
matcher = Matcher.create!({
:scenario => @scenario,
:comparisons_attributes => [{
'lhs_type' => 'field', 'raw_lhs_value' => field.id, 'lhs_which' => 1,
'rhs_type' => 'field', 'raw_rhs_value' => field.id, 'rhs_which' => 2,
'operator' => 'equals'
}]
})
visit "/projects/#{@project.id}/scenarios/#{@scenario.id}"
link = page.driver.browser.find_element(:link_text, "Delete")
link.click
a = page.driver.browser.switch_to.alert
a.accept
assert_equal 0, Models::Matcher.filter(:id => matcher.id).count
assert_equal "/projects/#{@project.id}/scenarios/#{@scenario.id}", page.current_path
end
end
end
| 37.805556 | 122 | 0.620132 |
7f07c03a071e6af23c0899b2dc57e7ec200d03bf | 6,515 | cs | C# | src/Tests/Aggregations/WritingAggregations.doc.cs | RossLieberman/NEST | ba9182ca1ea386644e4dc6546d462e424875cb85 | [
"Apache-2.0"
] | null | null | null | src/Tests/Aggregations/WritingAggregations.doc.cs | RossLieberman/NEST | ba9182ca1ea386644e4dc6546d462e424875cb85 | [
"Apache-2.0"
] | null | null | null | src/Tests/Aggregations/WritingAggregations.doc.cs | RossLieberman/NEST | ba9182ca1ea386644e4dc6546d462e424875cb85 | [
"Apache-2.0"
] | null | null | null | using System;
using Nest;
using Tests.Framework;
using Tests.Framework.MockData;
using static Nest.Infer;
using System.Collections.Generic;
using System.Linq;
using Tests.Aggregations.Bucket.Children;
using Tests.Framework.Integration;
using FluentAssertions;
namespace Tests.Aggregations
{
/**
*== Writing Aggregations
* NEST allows you to write your aggregations using
*
* - a strict fluent DSL
* - a verbatim object initializer syntax that maps verbatim to the Elasticsearch API
* - a more terse object initializer aggregation DSL
*
* Three different ways, yikes that's a lot to take in! Lets go over them one by one and explain when you might
* want to use each.
*/
public class Usage : UsageTestBase<ISearchRequest, SearchDescriptor<Project>, SearchRequest<Project>>
{
/**
* This is the json output for each example
**/
protected override object ExpectJson => new
{
aggs = new
{
name_of_child_agg = new
{
children = new
{
type = "commits"
},
aggs = new
{
average_per_child = new
{
avg = new
{
field = "confidenceFactor"
}
},
max_per_child = new
{
max = new
{
field = "confidenceFactor"
}
}
}
}
}
};
/** === Fluent DSL
* The fluent lambda syntax is the most terse way to write aggregations.
* It benefits from types that are carried over to sub aggregations
*/
protected override Func<SearchDescriptor<Project>, ISearchRequest> Fluent => s => s
.Aggregations(aggs => aggs
.Children<CommitActivity>("name_of_child_agg", child => child
.Aggregations(childAggs => childAggs
.Average("average_per_child", avg => avg.Field(p => p.ConfidenceFactor))
.Max("max_per_child", avg => avg.Field(p => p.ConfidenceFactor))
)
)
);
/** === Object Initializer syntax
* The object initializer syntax (OIS) is a one-to-one mapping with how aggregations
* have to be represented in the Elasticsearch API. While it has the benefit of being a one-to-one
* mapping, being dictionary based in C# means it can grow exponentially in complexity rather quickly.
*/
protected override SearchRequest<Project> Initializer =>
new SearchRequest<Project>
{
Aggregations = new ChildrenAggregation("name_of_child_agg", typeof(CommitActivity))
{
Aggregations =
new AverageAggregation("average_per_child", "confidenceFactor")
&& new MaxAggregation("max_per_child", "confidenceFactor")
}
};
}
public class AggregationDslUsage : Usage
{
/** === Terse Object Initializer DSL
* For this reason the OIS syntax can be shortened dramatically by using `*Agg` related family,
* These allow you to forego introducing intermediary Dictionaries to represent the aggregation DSL.
* It also allows you to combine multiple aggregations using bitwise AND (`&&`) operator.
*
* Compare the following example with the previous vanilla OIS syntax
*/
protected override SearchRequest<Project> Initializer =>
new SearchRequest<Project>
{
Aggregations = new ChildrenAggregation("name_of_child_agg", typeof(CommitActivity))
{
Aggregations =
new AverageAggregation("average_per_child", Field<CommitActivity>(p => p.ConfidenceFactor))
&& new MaxAggregation("max_per_child", Field<CommitActivity>(p => p.ConfidenceFactor))
}
};
}
public class AdvancedAggregationDslUsage : Usage
{
/** === Aggregating over a collection of aggregations
* An advanced scenario may involve an existing collection of aggregation functions that should be set as aggregations
* on the request. Using LINQ's `.Aggregate()` method, each function can be applied to the aggregation descriptor
* (`childAggs` below) in turn, returning the descriptor after each function application.
*
*/
protected override Func<SearchDescriptor<Project>, ISearchRequest> Fluent
{
get
{
var aggregations = new List<Func<AggregationContainerDescriptor<CommitActivity>, IAggregationContainer>> //<1> a list of aggregation functions to apply
{
a => a.Average("average_per_child", avg => avg.Field(p => p.ConfidenceFactor)),
a => a.Max("max_per_child", avg => avg.Field(p => p.ConfidenceFactor))
};
return s => s
.Aggregations(aggs => aggs
.Children<CommitActivity>("name_of_child_agg", child => child
.Aggregations(childAggs =>
aggregations.Aggregate(childAggs, (acc, agg) => { agg(acc); return acc; }) // <2> Using LINQ's `Aggregate()` function to accumulate/apply all of the aggregation functions
)
)
);
}
}
}
/**[[aggs-vs-aggregations]]
*=== Aggs vs. Aggregations
*
* The response exposes both `.Aggregations` and `.Aggs` properties for handling aggregations. Why two properties you ask?
* Well, the former is a dictionary of aggregation names to `IAggregate` types, a common interface for
* aggregation responses (termed __Aggregates__ in NEST), and the latter is a convenience helper to get the right type
* of aggregation response out of the dictionary based on a key name.
*
* This is better illustrated with an example
*/
public class AggsUsage : ChildrenAggregationUsageTests
{
public AggsUsage(ReadOnlyCluster i, EndpointUsage usage) : base(i, usage) { }
/** Let's imagine we make the following request. */
protected override Func<SearchDescriptor<Project>, ISearchRequest> Fluent => s => s
.Aggregations(aggs => aggs
.Children<CommitActivity>("name_of_child_agg", child => child
.Aggregations(childAggs => childAggs
.Average("average_per_child", avg => avg.Field(p => p.ConfidenceFactor))
.Max("max_per_child", avg => avg.Field(p => p.ConfidenceFactor))
)
)
);
/**=== Aggs usage
* Now, using `.Aggs`, we can easily get the `Children` aggregation response out and from that,
* the `Average` and `Max` sub aggregations.
*/
protected override void ExpectResponse(ISearchResponse<Project> response)
{
response.IsValid.Should().BeTrue();
var childAggregation = response.Aggs.Children("name_of_child_agg");
var averagePerChild = childAggregation.Average("average_per_child");
averagePerChild.Should().NotBeNull(); //<1> Do something with the average per child. Here we just assert it's not null
var maxPerChild = childAggregation.Max("max_per_child");
maxPerChild.Should().NotBeNull(); //<2> Do something with the max per child. Here we just assert it's not null
}
}
}
| 34.654255 | 178 | 0.697314 |
e534d15a0f556f0050838312c1c77e33814b8e3b | 156 | swift | Swift | SimpleFunctionalWeather/Pure/Utils.swift | viralplatipuss/SimpleFunctionalWeather | a77746f8d8446ef4f2ed6364d746d97a43d1f1ee | [
"MIT"
] | 1 | 2020-06-08T19:46:46.000Z | 2020-06-08T19:46:46.000Z | SimpleFunctionalWeather/Pure/Utils.swift | viralplatipuss/SimpleFunctionalWeather | a77746f8d8446ef4f2ed6364d746d97a43d1f1ee | [
"MIT"
] | null | null | null | SimpleFunctionalWeather/Pure/Utils.swift | viralplatipuss/SimpleFunctionalWeather | a77746f8d8446ef4f2ed6364d746d97a43d1f1ee | [
"MIT"
] | null | null | null | import Foundation
extension Optional where Wrapped == Data {
var asUtf8String: String? {
flatMap { String(data: $0, encoding: .utf8) }
}
}
| 19.5 | 53 | 0.641026 |
261e3ef9e00eb0bfbfb83b37ca54fe9a0bc5912e | 2,892 | dart | Dart | packages/pdfx/lib/src/renderer/interfaces/page.dart | victorshx/packages.flutter | e5f53c24e8a1da078110a024883d17a138754bb6 | [
"MIT"
] | 37 | 2019-03-01T20:19:16.000Z | 2019-11-30T19:20:12.000Z | packages/pdfx/lib/src/renderer/interfaces/page.dart | victorshx/packages.flutter | e5f53c24e8a1da078110a024883d17a138754bb6 | [
"MIT"
] | 13 | 2019-03-28T21:04:54.000Z | 2019-12-05T11:34:54.000Z | packages/pdfx/lib/src/renderer/interfaces/page.dart | victorshx/packages.flutter | e5f53c24e8a1da078110a024883d17a138754bb6 | [
"MIT"
] | 11 | 2019-04-09T14:01:03.000Z | 2019-11-26T16:49:32.000Z | import 'dart:async';
import 'dart:typed_data' show Uint8List;
import 'dart:ui';
import 'package:extension/extension.dart';
import 'package:meta/meta.dart';
import 'document.dart';
part 'page_image.dart';
part 'page_texture.dart';
/// Image compression format
class PdfPageImageFormat extends Enum<int> {
const PdfPageImageFormat(int val) : super(val);
static const PdfPageImageFormat jpeg = PdfPageImageFormat(0);
static const PdfPageImageFormat png = PdfPageImageFormat(1);
/// ***Attention!*** Works only on android
static const PdfPageImageFormat webp = PdfPageImageFormat(2);
}
/// An integral part of a document is its page,
/// which contains a method [render] for rendering into an image
abstract class PdfPage {
PdfPage({
required this.document,
required this.id,
required this.pageNumber,
required this.width,
required this.height,
required this.autoCloseAndroid,
});
final PdfDocument document;
/// Page unique id. Needed for rendering and closing page.
/// Generated when opening page.
final String? id;
/// Page number in document.
/// Starts from 1.
final int pageNumber;
/// Page source width in pixels
final double width;
/// Page source height in pixels
final double height;
final bool autoCloseAndroid;
/// Is the page closed
bool isClosed = false;
/// Render a full image of specified PDF file.
///
/// [width], [height] specify resolution to render in pixels.
/// As default PNG uses transparent background. For change it you can set
/// [backgroundColor] property like a hex string ('#FFFFFF')
/// [format] - image type, all types can be seen here [PdfPageImageFormat]
/// [cropRect] - render only the necessary part of the image
/// [quality] - hint to the JPEG and WebP compression algorithms (0-100)
Future<PdfPageImage?> render({
required double width,
required double height,
PdfPageImageFormat format = PdfPageImageFormat.jpeg,
String? backgroundColor,
Rect? cropRect,
int quality = 100,
@visibleForTesting bool removeTempFile = true,
});
/// Create a new Flutter `Texture`. The object should be released by
/// calling `dispose` method after use it.
Future<PdfPageTexture> createTexture();
/// Before open another page it is necessary to close the previous.
///
/// The android platform does not allow parallel rendering.
Future<void> close();
@override
bool operator ==(Object other);
@override
int get hashCode;
@override
String toString() => '$runtimeType{'
'document: $document, '
'page: $pageNumber, '
'width: $width, '
'height: $height}';
}
class PdfPageAlreadyClosedException implements Exception {
@override
String toString() => '$runtimeType: Page already closed';
}
| 28.633663 | 77 | 0.679461 |
ebc43a0c56d553facc0e73447c42e8ae5b175dca | 302 | css | CSS | 01 React Concepts/01 Properties/src/css/styles.css | Lemoncode/react-training-es6 | 6105dd8eeff71963dfbde5881426d1d4a926f142 | [
"MIT"
] | 13 | 2017-02-21T21:42:23.000Z | 2021-11-06T01:55:33.000Z | 01 React Concepts/01 Properties/src/css/styles.css | Lemoncode/react-training-ts | ac5587e873d84e6940e410774b5b195d74450b5c | [
"MIT"
] | 22 | 2017-02-09T14:53:45.000Z | 2017-02-21T16:53:05.000Z | 01 React Concepts/01 Properties/src/css/styles.css | Lemoncode/react-training-es6 | 6105dd8eeff71963dfbde5881426d1d4a926f142 | [
"MIT"
] | 8 | 2017-02-22T11:17:11.000Z | 2021-11-09T17:03:37.000Z | .container {
margin-top: 50px;
}
.animated {
-webkit-transition: opacity .15s ease-out, visibility .3s ease-out;
transition: opacity .15s ease-out, visibility .3s ease-out;
}
.modal {
display: block;
}
.modal .modal-dialog {
cursor: pointer;
}
.borderless {
border-color: transparent;
}
| 15.1 | 69 | 0.682119 |
b0f92973ac5b228d853c6dc53d5b6bb8bbc50be3 | 120 | py | Python | GPopt/utils/__init__.py | Techtonique/GPopt | 37eb7cbd55679b67b0f0f39dddb310309531e5ca | [
"BSD-3-Clause-Clear"
] | 1 | 2021-07-14T11:56:32.000Z | 2021-07-14T11:56:32.000Z | GPopt/utils/__init__.py | Techtonique/GPopt | 37eb7cbd55679b67b0f0f39dddb310309531e5ca | [
"BSD-3-Clause-Clear"
] | null | null | null | GPopt/utils/__init__.py | Techtonique/GPopt | 37eb7cbd55679b67b0f0f39dddb310309531e5ca | [
"BSD-3-Clause-Clear"
] | null | null | null | from .progress_bar import Progbar
from .nodesimulation import generate_sobol2
__all__ = ["Progbar", "generate_sobol2"]
| 24 | 43 | 0.808333 |
e0942dbdcd5ac5efe431ba45d9532144b2aef31f | 1,155 | c | C | src/lin/fix_utils.c | srsem/fix_parser | 91b19abf724c854bf2f7f5b03b412f6c7c69a536 | [
"BSD-3-Clause"
] | 26 | 2015-02-11T22:20:45.000Z | 2021-12-19T20:33:04.000Z | src/lin/fix_utils.c | srsem/fix_parser | 91b19abf724c854bf2f7f5b03b412f6c7c69a536 | [
"BSD-3-Clause"
] | null | null | null | src/lin/fix_utils.c | srsem/fix_parser | 91b19abf724c854bf2f7f5b03b412f6c7c69a536 | [
"BSD-3-Clause"
] | 12 | 2015-01-24T16:37:03.000Z | 2020-06-25T14:48:29.000Z | /* @file fix_utils_lin.c
@author Dmitry S. Melnikov, [email protected]
@date Created on: 12/28/2012 04:58:17 PM
*/
#include "fix_utils.h"
#include "fix_types.h"
#include <libgen.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/*------------------------------------------------------------------------------------------------------------------------*/
FIXErrCode fix_utils_make_path(char const* protocolFile, char const* transpFile, char* path, uint32_t buffLen)
{
FIXErrCode ret = FIX_SUCCESS;
char* transpFileDup = strdup(transpFile);
char* protocolFileDup = strdup(protocolFile);
if (!strcmp(basename(transpFileDup), transpFile) &&
strcmp(basename(protocolFileDup), protocolFile)) // make sure no dir(even ./) set for transpFile and protocolFile has a dir
{
if (snprintf(path, buffLen, "%s/%s", dirname(protocolFileDup), basename(transpFileDup)) >= buffLen)
{
ret = FIX_FAILED;
}
}
else
{
if (snprintf(path, buffLen, "%s", transpFile) >= buffLen)
{
ret = FIX_FAILED;
}
}
free(transpFileDup);
free(protocolFileDup);
return ret;
}
| 30.394737 | 130 | 0.58961 |
2f4b599c3d96ec21fd1ef1dde0c7ebe0c34199ea | 1,028 | js | JavaScript | test/btrz-label.spec.js | Betterez/btrz-vue-components | 3d6491f94cea30a99c2162df8b00c75e687289ca | [
"MIT"
] | null | null | null | test/btrz-label.spec.js | Betterez/btrz-vue-components | 3d6491f94cea30a99c2162df8b00c75e687289ca | [
"MIT"
] | 8 | 2017-02-23T18:49:28.000Z | 2020-09-10T17:30:25.000Z | test/btrz-label.spec.js | Betterez/btrz-vue-components | 3d6491f94cea30a99c2162df8b00c75e687289ca | [
"MIT"
] | null | null | null | import "./setup";
import {expect} from "chai";
import {insertHTML} from "./utils";
import BtrzInput from "../src/btrz-input";
import BtrzToggle from "../src/btrz-toggle";
describe("BtrzLabel", () => {
it("btrz-input should render a label with a given text", () => {
insertHTML(`<div id="app">
<btrz-input type='text' class="form-control" label="test label"></btrz-input>
</div>`);
const app = new Vue({
el: "#app",
components: {BtrzInput}
}),
label = $(".form-control label");
expect(label.text()).to.equal("test label");
});
it("btrz-toggle should render a label with a given text", () => {
insertHTML(`<div id="app">
<btrz-toggle class="form-control" label="Activate this" value="false"></btrz-toggle>
</div>`);
const app = new Vue({
el: "#app",
components: {BtrzToggle}
}),
label = $(".form-control label");
expect(label.text()).to.equal("Activate this");
});
});
| 29.371429 | 102 | 0.553502 |
7e65c06d40f9a3459a26a8b3d245c0b586846d9f | 7,614 | rs | Rust | src/parser/lexer.rs | kirbycool/rust-monkey | 235d8be81092e6a74e7f1aa09acab9e33bd669f7 | [
"MIT"
] | null | null | null | src/parser/lexer.rs | kirbycool/rust-monkey | 235d8be81092e6a74e7f1aa09acab9e33bd669f7 | [
"MIT"
] | null | null | null | src/parser/lexer.rs | kirbycool/rust-monkey | 235d8be81092e6a74e7f1aa09acab9e33bd669f7 | [
"MIT"
] | null | null | null | use crate::parser::token::Token;
use crate::parser::token::Token::*;
pub struct Lexer {
input: Vec<char>,
position: usize,
read_position: usize,
}
impl Lexer {
pub fn new(input: String) -> Self {
Lexer {
input: input.chars().collect(),
position: 0,
read_position: 0,
}
}
fn peek_char(&self) -> Option<char> {
if self.read_position >= self.input.len() {
return None;
}
Some(self.input[self.read_position])
}
fn read_char(&mut self) -> Option<char> {
self.peek_char().map(|c| {
self.position = self.read_position;
self.read_position += 1;
c
})
}
fn consume_whitespace(&mut self) {
while self.peek_char().map_or(false, |c| c.is_whitespace()) {
self.read_char();
}
}
fn read_identifier(&mut self) -> String {
let start = self.position;
while self.peek_char().map_or(false, |c| is_identifier(c)) {
self.read_char();
}
self.input[start..self.read_position].iter().collect()
}
fn read_number(&mut self) -> String {
let start = self.position;
while self.peek_char().map_or(false, |c| c.is_ascii_digit()) {
self.read_char();
}
self.input[start..self.read_position].iter().collect()
}
fn read_string(&mut self) -> String {
let start = self.read_position;
while self.peek_char().map_or(false, |c| c != '"') {
self.read_char();
}
let result = self.input[start..self.read_position].iter().collect();
self.read_char();
result
}
}
impl Iterator for Lexer {
type Item = Token;
fn next(&mut self) -> Option<Token> {
self.consume_whitespace();
let next_char = self.read_char();
next_char.map(|c| match c {
'=' => match self.peek_char() {
Some('=') => {
self.read_char();
Equal
}
_ => Assign,
},
'+' => Plus,
'-' => Minus,
'!' => match self.peek_char() {
Some('=') => {
self.read_char();
NotEqual
}
_ => Bang,
},
'*' => Asterisk,
'/' => Slash,
'<' => LessThan,
'>' => GreaterThan,
'(' => LParen,
')' => RParen,
'{' => LBrace,
'}' => RBrace,
'[' => LBracket,
']' => RBracket,
',' => Comma,
';' => Semicolon,
':' => Colon,
'"' => Str(self.read_string()),
c => {
if is_identifier_start(c) {
let literal = self.read_identifier();
lookup_identifier(literal)
} else if c.is_ascii_digit() {
let literal = self.read_number();
Int(literal)
} else {
Illegal(c.to_string())
}
}
})
}
}
fn is_identifier_start(c: char) -> bool {
c.is_ascii_alphabetic() || c == '_'
}
fn is_identifier(c: char) -> bool {
c.is_ascii_alphanumeric() || c == '_'
}
fn lookup_identifier(identifier: String) -> Token {
match &identifier[..] {
"fn" => Function,
"let" => Let,
"true" => True,
"false" => False,
"if" => If,
"else" => Else,
"return" => Return,
_ => Ident(identifier),
}
}
#[cfg(test)]
mod tests {
use crate::parser::token::Token;
use crate::parser::token::Token::*;
use crate::parser::Lexer;
fn assert_tokens(input: String, tokens: &[Token]) -> () {
let lexer = Lexer::new(input);
for (actual, expected) in lexer.zip(tokens.iter()) {
assert_eq!(actual, *expected)
}
}
#[test]
fn next_literals() {
let input = String::from("=+(){},;");
let tokens = [
Assign, Plus, LParen, RParen, LBrace, RBrace, Comma, Semicolon,
];
assert_tokens(input, &tokens)
}
#[test]
fn string_literal() {
let cases = vec![
("\"foobar\"".to_string(), [Str("foobar".to_string())]),
("\"\"".to_string(), [Str("".to_string())]),
];
for (input, output) in cases.into_iter() {
assert_tokens(input, &output)
}
}
#[test]
fn array() {
let cases = vec![(
"[1, 2]".to_string(),
[
LBracket,
Int("1".to_string()),
Comma,
Int("2".to_string()),
RBracket,
],
)];
for (input, output) in cases.into_iter() {
assert_tokens(input, &output)
}
}
#[test]
fn hash() {
let cases = vec![(
"{1: 2}".to_string(),
[
LBrace,
Int("1".to_string()),
Colon,
Int("2".to_string()),
RBrace,
],
)];
for (input, output) in cases.into_iter() {
assert_tokens(input, &output)
}
}
#[test]
fn next_kitchen_sink() {
let input = String::from(
"
let five = 5;
let ten = 10;
let add = fn(x, y) {
x + y;
};
let result = add(five, ten);
!-/*5;
5 < 10 > 5;
1 != 2;
2 == 2;
if (5 < 10) {
return true;
} else {
return false;
}
",
);
let tokens = [
Let,
Ident(String::from("five")),
Assign,
Int(String::from("5")),
Semicolon,
Let,
Ident(String::from("ten")),
Assign,
Int(String::from("10")),
Semicolon,
Let,
Ident(String::from("add")),
Assign,
Function,
LParen,
Ident(String::from("x")),
Comma,
Ident(String::from("y")),
RParen,
LBrace,
Ident(String::from("x")),
Plus,
Ident(String::from("y")),
Semicolon,
RBrace,
Semicolon,
Let,
Ident(String::from("result")),
Assign,
Ident(String::from("add")),
LParen,
Ident(String::from("five")),
Comma,
Ident(String::from("ten")),
RParen,
Semicolon,
Bang,
Minus,
Slash,
Asterisk,
Int(String::from("5")),
Semicolon,
Int(String::from("5")),
LessThan,
Int(String::from("10")),
GreaterThan,
Int(String::from("5")),
Semicolon,
Int(String::from("1")),
NotEqual,
Int(String::from("2")),
Semicolon,
Int(String::from("2")),
Equal,
Int(String::from("2")),
Semicolon,
If,
LParen,
Int(String::from("5")),
LessThan,
Int(String::from("10")),
RParen,
LBrace,
Return,
True,
Semicolon,
RBrace,
Else,
LBrace,
Return,
False,
Semicolon,
RBrace,
];
assert_tokens(input, &tokens)
}
}
| 24.325879 | 76 | 0.420541 |
fa82b6e764767ec297ffd9060a087f242751acf1 | 8,957 | cpp | C++ | src/XspfDateTime.cpp | ezdev128/libxspf | ba71431e24293510c44d6581e2c05b901a372880 | [
"BSD-3-Clause"
] | null | null | null | src/XspfDateTime.cpp | ezdev128/libxspf | ba71431e24293510c44d6581e2c05b901a372880 | [
"BSD-3-Clause"
] | null | null | null | src/XspfDateTime.cpp | ezdev128/libxspf | ba71431e24293510c44d6581e2c05b901a372880 | [
"BSD-3-Clause"
] | null | null | null | /*
* libxspf - XSPF playlist handling library
*
* Copyright (C) 2006-2008, Sebastian Pipping / Xiph.Org Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* * Neither the name of the Xiph.Org Foundation nor the names of
* its contributors may be used to endorse or promote products
* derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Sebastian Pipping, [email protected]
*/
/**
* @file XspfDateTime.cpp
* Implementation of XspfDateTime.
*/
#include <xspf/XspfDateTime.h>
#include <cstring>
#if defined(sun) || defined(__sun)
# include <strings.h> // for strncmp()
#endif
namespace Xspf {
/// @cond DOXYGEN_NON_API
/**
* D object for XspfDateTime.
*/
class XspfDateTimePrivate {
friend class XspfDateTime;
int year; ///< Year [-9999..+9999] but not zero
int month; ///< Month [1..12]
int day; ///< Day [1..31]
int hour; ///< Hour [0..23]
int minutes; ///< Minutes [0..59]
int seconds; ///< Seconds [0..59]
int distHours; ///< Time shift hours [-14..+14]
int distMinutes; ///< Time shift minutes [-59..+59]
/**
* Creates a new D object.
*
* @param year Year [-9999..+9999] but not zero
* @param month Month [1..12]
* @param day Day [1..31]
* @param hour Hour [0..23]
* @param minutes Minutes [0..59]
* @param seconds Seconds [0..59]
* @param distHours Time shift hours [-14..+14]
* @param distMinutes Time shift minutes [-59..+59]
*/
XspfDateTimePrivate(int year, int month, int day, int hour,
int minutes, int seconds, int distHours, int distMinutes)
: year(year),
month(month),
day(day),
hour(hour),
minutes(minutes),
seconds(seconds),
distHours(distHours),
distMinutes(distMinutes) {
}
/**
* Destroys this D object.
*/
~XspfDateTimePrivate() {
}
};
/// @endcond
XspfDateTime::XspfDateTime(int year, int month, int day,
int hour, int minutes, int seconds, int distHours,
int distMinutes)
: d(new XspfDateTimePrivate(year, month, day, hour,
minutes, seconds, distHours, distMinutes)) {
}
XspfDateTime::XspfDateTime()
: d(new XspfDateTimePrivate(0, 0, 0, -1, -1, -1, 0, 0)) {
}
XspfDateTime::XspfDateTime(XspfDateTime const & source)
: d(new XspfDateTimePrivate(*(source.d))) {
}
XspfDateTime & XspfDateTime::operator=(XspfDateTime const & source) {
if (this != &source) {
*(this->d) = *(source.d);
}
return *this;
}
XspfDateTime::~XspfDateTime() {
delete this->d;
}
XspfDateTime * XspfDateTime::clone() const {
return new XspfDateTime(this->d->year, this->d->month, this->d->day,
this->d->hour, this->d->minutes, this->d->seconds, this->d->distHours,
this->d->distMinutes);
}
int XspfDateTime::getYear() const {
return this->d->year;
}
int XspfDateTime::getMonth() const {
return this->d->month;
}
int XspfDateTime::getDay() const {
return this->d->day;
}
int XspfDateTime::getHour() const {
return this->d->hour;
}
int XspfDateTime::getMinutes() const {
return this->d->minutes;
}
int XspfDateTime::getSeconds() const {
return this->d->seconds;
}
int XspfDateTime::getDistHours() const {
return this->d->distHours;
}
int XspfDateTime::getDistMinutes() const {
return this->d->distMinutes;
}
void XspfDateTime::setYear(int year) {
this->d->year = year;
}
void XspfDateTime::setMonth(int month) {
this->d->month = month;
}
void XspfDateTime::setDay(int day) {
this->d->day = day;
}
void XspfDateTime::setHour(int hour) {
this->d->hour = hour;
}
void XspfDateTime::setMinutes(int minutes) {
this->d->minutes = minutes;
}
void XspfDateTime::setSeconds(int seconds) {
this->d->seconds = seconds;
}
void XspfDateTime::setDistHours(int distHours) {
this->d->distHours = distHours;
}
void XspfDateTime::setDistMinutes(int distMinutes) {
this->d->distMinutes = distMinutes;
}
namespace {
/**
* Calls atoi() on a limited number of characters.
*
* @param text Text
* @param len Number of characters to read
* @return Result of atoi()
* @since 1.0.0rc1
*/
int PORT_ANTOI(XML_Char const * text, int len) {
XML_Char * final = new XML_Char[len + 1];
::PORT_STRNCPY(final, text, len);
final[len] = _PT('\0');
int const res = ::PORT_ATOI(final);
delete [] final;
return res;
}
} // anon namespace
/*static*/ bool
XspfDateTime::extractDateTime(XML_Char const * text,
XspfDateTime * output) {
// http://www.w3.org/TR/xmlschema-2/#dateTime-lexical-representation
// '-'? yyyy '-' mm '-' dd 'T' hh ':' mm ':' ss ('.' s+)? (zzzzzz)?
// '-'?
bool const leadingMinus = (*text == _PT('-'));
if (leadingMinus) {
text++;
}
// yyyy
if ((::PORT_STRNCMP(text, _PT("0001"), 4) < 0) || (::PORT_STRNCMP(_PT("9999"), text, 4) < 0)) {
return false;
}
int const year = PORT_ANTOI(text, 4);
output->setYear(year);
text += 4;
// '-' mm
if ((::PORT_STRNCMP(text, _PT("-01"), 3) < 0) || (::PORT_STRNCMP(_PT("-12"), text, 3) < 0)) {
return false;
}
int const month = PORT_ANTOI(text + 1, 2);
output->setMonth(month);
text += 3;
// '-' dd
if ((::PORT_STRNCMP(text, _PT("-01"), 3) < 0) || (::PORT_STRNCMP(_PT("-31"), text, 3) < 0)) {
return false;
}
int const day = PORT_ANTOI(text + 1, 2);
output->setDay(day);
text += 3;
// Month specific day check
switch (month) {
case 2:
switch (day) {
case 31:
case 30:
return false;
case 29:
if (((year % 400) != 0) && (((year % 4) != 0)
|| ((year % 100) == 0))) {
// Not a leap year
return false;
}
break;
case 28:
break;
}
break;
case 4:
case 6:
case 9:
case 11:
if (day > 30) {
return false;
}
break;
}
// 'T' hh
if ((::PORT_STRNCMP(text, _PT("T00"), 3) < 0) || (::PORT_STRNCMP(_PT("T23"), text, 3) < 0)) {
return false;
}
output->setHour(PORT_ANTOI(text + 1, 2));
text += 3;
// ':' mm
if ((::PORT_STRNCMP(text, _PT(":00"), 3) < 0) || (::PORT_STRNCMP(_PT(":59"), text, 3) < 0)) {
return false;
}
output->setMinutes(PORT_ANTOI(text + 1, 2));
text += 3;
// ':' ss
if ((::PORT_STRNCMP(text, _PT(":00"), 2) < 0) || (::PORT_STRNCMP(_PT(":59"), text, 2) < 0)) {
return false;
}
output->setSeconds(PORT_ANTOI(text + 1, 2));
text += 3;
// ('.' s+)?
if (*text == _PT('.')) {
text++;
int counter = 0;
while ((*text >= _PT('0')) && (*text <= _PT('9'))) {
text++;
counter++;
}
if (counter == 0) {
return false;
} else {
// The fractional second string, if present, must not end in '0'
if (*(text - 1) == _PT('0')) {
return false;
}
}
}
// (zzzzzz)? := (('+' | '-') hh ':' mm) | 'Z'
XML_Char const * const timeZoneStart = text;
switch (*text) {
case _PT('+'):
case _PT('-'):
{
text++;
if ((::PORT_STRNCMP(text, _PT("00"), 2) < 0) || (::PORT_STRNCMP(_PT("14"), text, 2) < 0)) {
return false;
}
int const distHours = PORT_ANTOI(text, 2);
output->setDistHours(distHours);
text += 2;
if ((::PORT_STRNCMP(text, _PT(":00"), 3) < 0) || (::PORT_STRNCMP(_PT(":59"), text, 3) < 0)) {
return false;
}
int const distMinutes = PORT_ANTOI(text + 1, 2);
output->setDistMinutes(distMinutes);
if ((distHours == 14) && (distMinutes != 0)) {
return false;
}
text += 3;
if (*text != _PT('\0')) {
return false;
}
if (*timeZoneStart == _PT('-')) {
output->setDistHours(-distHours);
output->setDistMinutes(-distMinutes);
}
}
break;
case _PT('Z'):
text++;
if (*text != _PT('\0')) {
return false;
}
// NO BREAK
case _PT('\0'):
output->setDistHours(0);
output->setDistMinutes(0);
break;
default:
return false;
}
return true;
}
} // namespace Xspf
| 21.275534 | 96 | 0.620744 |
a35fcd4f53c5d44b5abb0e4a92f8c947937daca7 | 1,823 | java | Java | marathon-manage/marathon-manage-web/src/main/java/com/marathon/manage/controller/volunteer/qvo/QueryVolunteerInfoVO.java | xiaocui123/marathon | d44b2699236616b58e7dbe63cdcb603aa6bece21 | [
"Apache-2.0"
] | null | null | null | marathon-manage/marathon-manage-web/src/main/java/com/marathon/manage/controller/volunteer/qvo/QueryVolunteerInfoVO.java | xiaocui123/marathon | d44b2699236616b58e7dbe63cdcb603aa6bece21 | [
"Apache-2.0"
] | null | null | null | marathon-manage/marathon-manage-web/src/main/java/com/marathon/manage/controller/volunteer/qvo/QueryVolunteerInfoVO.java | xiaocui123/marathon | d44b2699236616b58e7dbe63cdcb603aa6bece21 | [
"Apache-2.0"
] | 2 | 2017-07-26T01:05:09.000Z | 2020-02-28T02:14:16.000Z | package com.marathon.manage.controller.volunteer.qvo;
import com.marathon.manage.vo.BaseTreeGridVO;
/**
* 志愿者需求树形结构
* Created by cui on 2018/5/22.
*/
public class QueryVolunteerInfoVO extends BaseTreeGridVO<QueryVolunteerInfoVO> {
//分组名称
private String groupName;
//位置名称
private String locationName;
//数量
private Integer total;
//男/女/不限
private String genderRequire;
//职责要求
private String jobRequire;
//志愿者要求
private String volunteerRequire;
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public String getLocationName() {
return locationName;
}
public void setLocationName(String locationName) {
this.locationName = locationName;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
public String getGenderRequire() {
return genderRequire;
}
public void setGenderRequire(String genderRequire) {
this.genderRequire = genderRequire;
}
public String getJobRequire() {
return jobRequire;
}
public void setJobRequire(String jobRequire) {
this.jobRequire = jobRequire;
}
public String getVolunteerRequire() {
return volunteerRequire;
}
public void setVolunteerRequire(String volunteerRequire) {
this.volunteerRequire = volunteerRequire;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof QueryVolunteerInfoVO) {
QueryVolunteerInfoVO objExt = (QueryVolunteerInfoVO) obj;
return this.getId().equals(objExt.getId());
} else {
return false;
}
}
}
| 20.715909 | 80 | 0.645639 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.