hexsha stringlengths 40 40 | size int64 5 1.05M | ext stringclasses 98
values | lang stringclasses 21
values | max_stars_repo_path stringlengths 3 945 | max_stars_repo_name stringlengths 4 118 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 368k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 945 | max_issues_repo_name stringlengths 4 118 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 134k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 945 | max_forks_repo_name stringlengths 4 135 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 5 1.05M | avg_line_length float64 1 1.03M | max_line_length int64 2 1.03M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
040edf2db10f804c46cfba08c0e1a64a636e6b36 | 2,499 | js | JavaScript | lulc.js | amruthkiran94/Openlayers-Guwahati | 26d658adc91b13b1bab8f2a95663aca22131fee6 | [
"MIT"
] | null | null | null | lulc.js | amruthkiran94/Openlayers-Guwahati | 26d658adc91b13b1bab8f2a95663aca22131fee6 | [
"MIT"
] | null | null | null | lulc.js | amruthkiran94/Openlayers-Guwahati | 26d658adc91b13b1bab8f2a95663aca22131fee6 | [
"MIT"
] | null | null | null |
// A group layer for base layers
var baseLayers = new ol.layer.Group({
title: 'Base Layers',
openInLayerSwitcher: true,
layers: [
new ol.layer.Tile({
title: "Toner",
baseLayer: true,
visible: false,
source: new ol.source.Stamen({ layer: 'toner' })
}),
new ol.layer.Tile({
title: "OSM",
baseLayer: true,
source: new ol.source.OSM(),
visible: true
})
]
});
//Overlays - WMS and GeoJSON
// list of layers
var lulc_2001 = new ol.layer.Tile(
{ source: new ol.source.TileWMS({url: 'http://odisha.spatialdata.in/geoserver/Guwahati/wms?',params: {
'LAYERS': 'Guwahati:Reproject53_GAU_LandCover_2001',
'VERSION': '1.1.1',
'FORMAT': 'image/png',
'TILED': true,
},
}),
title:'LULC 2001',
visible:true
});
var lulc_2011 = new ol.layer.Tile(
{ source: new ol.source.TileWMS({url: 'http://odisha.spatialdata.in/geoserver/Guwahati/wms?',params: {
'LAYERS': 'Guwahati:Reproject53_GAU_LandCover_2011',
'VERSION': '1.1.1',
'FORMAT': 'image/png',
'TILED': true,
},
}),
title:'LULC 2011',
visible:false
});
var lulc_2016 = new ol.layer.Tile(
{ source: new ol.source.TileWMS({url: 'http://odisha.spatialdata.in/geoserver/Guwahati/wms?',params: {
'LAYERS': 'Guwahati:Reproject53_GAU_LandCover_2016.tif',
'VERSION': '1.1.1',
'FORMAT': 'image/png',
'TILED': true,
},
}),
title:'LULC 2016',
visible:true
});
// The Map
var map = new ol.Map({
target: 'map',
view: new ol.View({
zoom: 12,
minZoom: 4,
center: [10214968.0230,3016785.0392]
}),
layers: [ baseLayers,lulc_2016,lulc_2011,lulc_2001],
controls: ol.control.defaults({
zoom: false,
attribution: true,
rotate: false
}),
});
// Add control inside the map
var ctrl = new ol.control.LayerSwitcher({
show_progress:true,
mouseover:true,
collapsed:false
});
map.addControl(ctrl);
// CanvasScaleLine control
var scaleLineControl = new ol.control.CanvasScaleLine();
map.addControl(scaleLineControl);
// Control
var ctrl = new ol.control.Swipe();
map.addControl(ctrl);
// Set stamen on left
ctrl.addLayer(lulc_2001);
// OSM on right
ctrl.addLayer(lulc_2011, true);
| 24.028846 | 106 | 0.563826 |
d2e4d5759a5e41e5a6230b9ca39d129af82fe587 | 997 | php | PHP | src/Models/DescribeNatGatewaysResponseBody/natGateways/natGateway/fullNatTableIds.php | alibabacloud-sdk-php/Vpc-20160428 | a0f4b36da6656e046bdd020e0f71240029fdfe9f | [
"Apache-2.0"
] | null | null | null | src/Models/DescribeNatGatewaysResponseBody/natGateways/natGateway/fullNatTableIds.php | alibabacloud-sdk-php/Vpc-20160428 | a0f4b36da6656e046bdd020e0f71240029fdfe9f | [
"Apache-2.0"
] | null | null | null | src/Models/DescribeNatGatewaysResponseBody/natGateways/natGateway/fullNatTableIds.php | alibabacloud-sdk-php/Vpc-20160428 | a0f4b36da6656e046bdd020e0f71240029fdfe9f | [
"Apache-2.0"
] | null | null | null | <?php
// This file is auto-generated, don't edit it. Thanks.
namespace AlibabaCloud\SDK\Vpc\V20160428\Models\DescribeNatGatewaysResponseBody\natGateways\natGateway;
use AlibabaCloud\Tea\Model;
class fullNatTableIds extends Model
{
/**
* @var string[]
*/
public $fullNatTableId;
protected $_name = [
'fullNatTableId' => 'FullNatTableId',
];
public function validate()
{
}
public function toMap()
{
$res = [];
if (null !== $this->fullNatTableId) {
$res['FullNatTableId'] = $this->fullNatTableId;
}
return $res;
}
/**
* @param array $map
*
* @return fullNatTableIds
*/
public static function fromMap($map = [])
{
$model = new self();
if (isset($map['FullNatTableId'])) {
if (!empty($map['FullNatTableId'])) {
$model->fullNatTableId = $map['FullNatTableId'];
}
}
return $model;
}
}
| 19.94 | 103 | 0.54664 |
b6c0be74be1cf12801eef42fca4e6be51accae1c | 8,933 | rb | Ruby | app/controllers/leaves_controller.rb | hansraj/leave_management | 287f4740a8a948d6fae072ffad42c9b89ef3b5eb | [
"MIT"
] | 1 | 2015-11-05T01:31:35.000Z | 2015-11-05T01:31:35.000Z | app/controllers/leaves_controller.rb | hansraj/leave_management | 287f4740a8a948d6fae072ffad42c9b89ef3b5eb | [
"MIT"
] | null | null | null | app/controllers/leaves_controller.rb | hansraj/leave_management | 287f4740a8a948d6fae072ffad42c9b89ef3b5eb | [
"MIT"
] | null | null | null | class LeavesController < ApplicationController
# GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
layout "layouts/plugins"
before_filter :login_required
def index
#if session[:rolename] == "admin" and session[:department] == "Admin"
if current_user.role.title == 'Admin'
@emp_leaves = Leave.find(:all, :conditions =>['status =?',"Pending" ])
else
@leaves = Leave.paginate(:all, :conditions =>['employee_id =?', current_user.employee ], :page => params[:page], :per_page => 10 )
@employee_leave_status = EmployeeLeaveStatus.find(:first, :conditions =>["employee_id = ? and year = ?", current_user.employee ,Time.now.strftime("%Y").to_i])
end
end
def new
@leave = Leave.new
@employee = User.find( session[:user_id] ).employee
#@employee = Employee.find( session[:user_id] )
end
def show
@leave = Leave.find(params[:id])
end
def create
@leave = Leave.new(params[:leave])
@employee = current_user.employee
@leave.employee = @employee
@leave.status = "Pending"
@leave.date = Time.now.strftime("%m/%d/%Y")
p @leave.date
p params[:leave]
#if validate_emp_leave(@leave)
#
if @leave.save
@link = url_for :controller => 'leaves', :action => 'edit', :id => @leave.id
#LeaveNotifier.deliver_leave_details( @leave, @employee, @link )
emp_lev_status = EmployeeLeaveStatus.find_by_employee_id_and_year( @employee, Time.now.strftime("%Y").to_i )
if emp_lev_status.remain_privilege < @leave.no_of_days and @leave.type_of_leave == "privilege"
flash[:notice] = " Leave has been successfully applied and your #{@leave.no_of_days - emp_lev_status.remain_privilege } day's are Without pay "
else
flash[:notice] = 'Leave has been successfully applied.'
end
redirect_to leafe_path(@leave)
# redirect_to( :action => 'index', :id =>)
else
p @leave.errors
@employee.current_address = params[:leave][:address]
@employee.mobile = params[:leave][:contact_no]
render :action => 'new'
end
#end
end
def edit
@leave = Leave.find(params[:id])
@employee = User.find( session[:user_id] ).employee
end
def update
@leave = Leave.find(params[:id])
@employee = current_user.employee
if @leave.update_attributes(params[:leave])
if session[:rolename] == "admin" and session[:department] == "Admin"
@leave.status = params[:status]
@leave.save
#LeaveNotifier.deliver_leave_status_updated( @leave, @leave.employee )
if @leave.status == "Approved" or @leave.status == "Rejected"
update_employee_leave_status( @leave )
end
else
@link = url_for :controller => 'leaves', :action => 'edit', :id => @leave.id
# LeaveNotifier.deliver_leave_details( @leave, @employee, @link )
end
emp_lev_status = EmployeeLeaveStatus.find_by_employee_id_and_year( @employee, Time.now.strftime("%Y").to_i )
if emp_lev_status.remain_privilege < @leave.no_of_days and @leave.type_of_leave == "privilege" and session[:rolename] != "admin"
flash[:notice] = " Leave has been successfully updated and your #{@leave.no_of_days - emp_lev_status.remain_privilege } day's are Without pay "
else
flash[:notice] = 'Leave has been successfully updated.'
end
redirect_to leafe_path(@leave)
else
render :action => 'edit'
end
end
def destroy
@leave = Leave.find(params[:id])
@leave.destroy
flash[:notice] = 'Leave was successfully deleted.'
redirect_to :action => 'index', :id=>session[:user_id]
end
def print
@leave = Leave.find(params[:id])
render :layout => false
end
def update_employee_leave_status( leave )
employee_leave_status = EmployeeLeaveStatus.find_by_employee_id(leave.employee_id)
if employee_leave_status
employee_leave_status.remain_privilege -= leave.no_of_days if leave.type_of_leave == "privilege"
employee_leave_status.remain_casual -= leave.no_of_days if leave.type_of_leave == "casual"
employee_leave_status.remain_sick -= leave.no_of_days if leave.type_of_leave == "sick"
employee_leave_status.save!
end
end
def validate_emp_leave( leave )
emp_leave_status = EmployeeLeaveStatus.find_by_employee_id_and_year( @employee, Time.now.strftime("%Y").to_i )
if emp_leave_status
return ( emp_leave_status.remain_privilege >= leave.no_of_days ) if leave.type_of_leave == "privilege"
return ( emp_leave_status.remain_casual >= leave.no_of_days ) if leave.type_of_leave == "casual"
return ( emp_leave_status.remain_sick >= leave.no_of_days ) if leave.type_of_leave == "sick"
end
end
def emp_leave_status
if params[:status_year]
@employee_leave_status = EmployeeLeaveStatus.order_by_employee.paginate(:conditions =>["year = ?", params[:status_year].to_i] , :page => params[:page], :per_page => 10)
session[:current_year] = params[:status_year]
else
session[:current_year] = Time.now.strftime("%Y")
@employee_leave_status = EmployeeLeaveStatus.order_by_employee.paginate(:conditions =>["year = ?", Time.now.strftime("%Y").to_i] , :page => params[:page], :per_page => 10)
end
if request.xhr?
render :update do |page|
page.replace_html 'change_year', :partial =>'emp_leave_status', :locals => { :employee_leave_status => @employee_leave_status }
end
end
end
def edit_emp_leave_status
@employee_leave_status = EmployeeLeaveStatus.find( params[:id] )
session[:emp_leave_id] = @employee_leave_status.employee_id
end
def change_year
invalid_year = 0
if params[:status_year]
@employee_leave_status = EmployeeLeaveStatus.find(:first, :conditions =>["employee_id = ? and year = ?", session[:emp_leave_id], params[:status_year] ] )
if @employee_leave_status.blank?
invalid_year = 1
#~ @employee_leave_status = EmployeeLeaveStatus.new
#~ @employee_leave_status.employee_id = session[:emp_leave_id]
#~ @employee_leave_status.year = params[:status_year]
#~ @employee_leave_status.save
@employee_leave_status = EmployeeLeaveStatus.find(:first, :conditions =>["employee_id = ? and year = ?", session[:emp_leave_id], Time.now.strftime("%Y").to_i ] )
end
session[:current_year] = @employee_leave_status.year.to_s
end
if request.xhr?
render :update do |page|
flash[:notice] = "Selected year's leaves are not available." if invalid_year == 1
page.replace_html 'change_year', :partial =>'edit_emp_leave_status', :locals => { :employee_leave_status => @employee_leave_status }
end
end
end
def update_emp_leave_status
@employee_leave_status = EmployeeLeaveStatus.find( params[:id] )
@employee_leave_status = EmployeeLeaveStatus.find( :first, :conditions => ["employee_id =? and year = ? ", @employee_leave_status.employee_id,session[:current_year].to_i ] )
@employee_leave_status.year = params[:status_year]
if @employee_leave_status.update_attributes(params[:employee_leave_status])
flash[:notice] = 'Employee Leave status was successfully updated.'
redirect_to :action => 'emp_leave_status'
else
render :action=> "edit_emp_leave_status"
end
end
def delete_emp_leave_status
@employee_leave_status = EmployeeLeaveStatus.find( params[:id] )
@employee_leave_status.destroy
flash[:notice] = 'Employee Leave Status was successfully deleted.'
redirect_to :action => 'emp_leave_status'
end
def leave_details
@employee = Employee.find( params[:id] )
@leaves = Leave.find(:all, :conditions =>['employee_id =? and status =?', params[:id], "Approved" ], :order =>"date DESC")
end
def policy
end
def accept
leave = Leave.find(params[:id])
leave.status = 'Approved'
update_employee_leave_status( leave ) if leave.save!
if request.xhr?
render :update do |page|
page.replace_html "accept_reject_#{leave.id}", "<strong> Approved</strong>"
end
end
end
def reject
leave = Leave.find(params[:id])
leave.status = 'Rejected'
leave.save!
if request.xhr?
render :update do |page|
page.replace_html "accept_reject_#{leave.id}", "<strong> Rejected </strong>"
end
end
end
def new_emp_leave_status
@employee_leave_status = EmployeeLeaveStatus.new
end
def create_emp_leave_status
@employee_leave_status = EmployeeLeaveStatus.new(params[:employee_leave_status])
@employee_leave_status.year = params[:status_year]
@employee_leave_status.save!
redirect_to emp_leave_status_leaves_path
end
end
| 40.238739 | 179 | 0.66842 |
9a2fefe9c248d722a7141257ad5c04cf7a160c7f | 606 | css | CSS | weatherapi/static/css/style.css | ernstki/cs5165-weather-api | 04f255a505bcec363ef785e99750e3132303dedd | [
"MIT"
] | null | null | null | weatherapi/static/css/style.css | ernstki/cs5165-weather-api | 04f255a505bcec363ef785e99750e3132303dedd | [
"MIT"
] | null | null | null | weatherapi/static/css/style.css | ernstki/cs5165-weather-api | 04f255a505bcec363ef785e99750e3132303dedd | [
"MIT"
] | null | null | null | /* Sticky footer styles
source: https://getbootstrap.com/examples/sticky-footer-navbar/
-------------------------------------------------- */
html {
position: relative;
min-height: 100%;
}
body {
/* Margin bottom by footer height */
padding-top: 80px;
margin-bottom: 100px;
}
.starter-template {
padding: 40px 15px;
text-align: center;
}
.footer {
position: absolute;
bottom: 0;
width: 100%;
/* Set the fixed height of the footer here */
height: 60px;
background-color: #f5f5f5;
}
/* source: https://stackoverflow.com/a/26495054 */
.label-round {
border-radius: 1em;
}
| 18.363636 | 66 | 0.608911 |
5a205eff58d5af9cbaa4a870fc1b704b0e943ea3 | 1,402 | sql | SQL | user_profile.sql | alditofaisal/userapp | 01d96a00810e533f217b56ce3c07f8a1b7ab5acb | [
"MIT"
] | null | null | null | user_profile.sql | alditofaisal/userapp | 01d96a00810e533f217b56ce3c07f8a1b7ab5acb | [
"MIT"
] | null | null | null | user_profile.sql | alditofaisal/userapp | 01d96a00810e533f217b56ce3c07f8a1b7ab5acb | [
"MIT"
] | null | null | null | -- phpMyAdmin SQL Dump
-- version 5.0.2
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Sep 08, 2021 at 02:54 PM
-- Server version: 10.4.11-MariaDB
-- PHP Version: 7.4.5
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `user_profile`
--
-- --------------------------------------------------------
--
-- Table structure for table `user`
--
CREATE TABLE `user` (
`id_user` varchar(64) NOT NULL,
`nama` varchar(25) NOT NULL,
`email` varchar(50) NOT NULL,
`password` varchar(15) NOT NULL,
`picture` varchar(64) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `user`
--
INSERT INTO `user` (`id_user`, `nama`, `email`, `password`, `picture`) VALUES
('61389c61da938', 'user1', 'user1@gmail.com', '12345', '61389c61da938.png');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `user`
--
ALTER TABLE `user`
ADD PRIMARY KEY (`id_user`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| 23.762712 | 77 | 0.669757 |
8970a867f104ea9b19051dee11c42bc37f164a33 | 4,620 | swift | Swift | NetworkOperationTests/NetworkOperationTests.swift | alasdairlaw/network-operation | 20db0a1d13bf58c725c508dc6e9cb187134659c8 | [
"MIT"
] | 1 | 2017-08-04T07:37:46.000Z | 2017-08-04T07:37:46.000Z | NetworkOperationTests/NetworkOperationTests.swift | alasdairlaw/network-operation | 20db0a1d13bf58c725c508dc6e9cb187134659c8 | [
"MIT"
] | 1 | 2017-08-04T10:21:11.000Z | 2017-08-04T10:21:11.000Z | NetworkOperationTests/NetworkOperationTests.swift | alasdairlaw/network-operation | 20db0a1d13bf58c725c508dc6e9cb187134659c8 | [
"MIT"
] | null | null | null | //
// NetworkOperationTests.swift
// NetworkOperationTests
//
// Created by Alasdair Law on 17/12/2016.
// Copyright © 2016 Alasdair Law. All rights reserved.
//
import XCTest
@testable import NetworkOperation
private let mockJSONURL = URL(string: "https://json.test")!
internal class NetworkOperationTests: XCTestCase {
private var operationQueue = OperationQueue()
private var mockSession = MockSession()
override internal func setUp() {
super.setUp()
self.mockSession = MockSession()
self.mockTestRequests(session: self.mockSession)
}
override internal func tearDown() {
super.tearDown()
self.mockSession.removeMocks()
}
// Mark: Tests
/**
Test performing a network request, receiving a JSON response.
Intended functionality:
- Network operation added to queue.
- Network operation completes with correct response.
- Operation queue is empty after completion.
*/
internal func testNetworkOperationFromRequest() {
let expectation = self.expectation(description: "JSON response")
let request = URLRequest(url: mockJSONURL)
let operation = NetworkOperation<JSONResponse>(session: self.mockSession, request: request) { (jsonResponse: JSONResponse?, error) in
XCTAssert(jsonResponse?.data is [String: Any])
XCTAssert(jsonResponse?.response is HTTPURLResponse)
expectation.fulfill()
}
XCTAssert(operation.isAsynchronous)
self.operationQueue.addOperation(operation)
self.waitForExpectations(timeout: 1.0) { (error) in
}
XCTAssert(self.operationQueue.operationCount == 0)
}
/**
Test performing a network request from a URL, receiving a JSON response.
Intended functionality:
- Network operation added to queue.
- Network operation completes with correct response.
- Operation queue is empty after completion.
*/
internal func testNetworkOperationFromURL() {
let expectation = self.expectation(description: "JSON response")
let operation = NetworkOperation<JSONResponse>(session: self.mockSession, url: mockJSONURL) { (jsonResponse: JSONResponse?, error) in
XCTAssert(jsonResponse?.data is [String: Any])
XCTAssert(jsonResponse?.response is HTTPURLResponse)
expectation.fulfill()
}
XCTAssert(operation.isAsynchronous)
self.operationQueue.addOperation(operation)
self.waitForExpectations(timeout: 1.0) { (error) in
}
XCTAssert(self.operationQueue.operationCount == 0)
}
/**
Test performing a network request, but cancelling before the network operation
has completed.
Intended functionality:
- Network operation added to queue.
- Network operation cancelled before responding.
- Operation queue is empty after cancelling all operations.
*/
internal func testCancellingNetworkOperation() {
let expectation = self.expectation(description: "JSON response")
let request = URLRequest(url: mockJSONURL)
let operation = NetworkOperation<JSONResponse>(session: self.mockSession, request: request) { (jsonResponse: JSONResponse?, error) in
XCTAssert(jsonResponse?.data == nil)
XCTAssert(jsonResponse?.response == nil)
XCTAssert(error is MockSessionDataTaskError)
guard let error = error as? MockSessionDataTaskError else {
return
}
XCTAssert(error == .cancelled)
expectation.fulfill()
}
self.operationQueue.addOperation(operation)
self.operationQueue.cancelAllOperations()
self.waitForExpectations(timeout: 1.0) { (error) in
}
XCTAssert(self.operationQueue.operationCount == 0)
}
// MARK: Private
private func mockTestRequests(session: MockSession) {
session.mock(url: mockJSONURL) { (url: URL) -> CompletionValues in
let jsonObject = [
"test": "success"
]
let data = try! JSONSerialization.data(withJSONObject: jsonObject, options: [])
let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "https", headerFields: nil)
return (data, response, nil)
}
}
}
| 34.222222 | 141 | 0.626623 |
39ff89fc7c948a032d427d9cdcb354e5e575553a | 1,822 | java | Java | buchladen-ejb-remote-interface/src/de/th/wildau/webapp/buchladen/facades/UserGroupEntityFacadeRemote.java | MalteSchwering/de.th.wildau.webapp.buchladen | 25b07782691583cec12ae05856644499c52be53f | [
"MIT"
] | null | null | null | buchladen-ejb-remote-interface/src/de/th/wildau/webapp/buchladen/facades/UserGroupEntityFacadeRemote.java | MalteSchwering/de.th.wildau.webapp.buchladen | 25b07782691583cec12ae05856644499c52be53f | [
"MIT"
] | null | null | null | buchladen-ejb-remote-interface/src/de/th/wildau/webapp/buchladen/facades/UserGroupEntityFacadeRemote.java | MalteSchwering/de.th.wildau.webapp.buchladen | 25b07782691583cec12ae05856644499c52be53f | [
"MIT"
] | null | null | null | package de.th.wildau.webapp.buchladen.facades;
import de.th.wildau.webapp.buchladen.entities.UserGroupEntity;
import java.util.List;
import javax.ejb.Remote;
/**
* @author Jan Gabler
* @author Malte Schwering
* @version 0.3
*/
@Remote
public interface UserGroupEntityFacadeRemote {
/**
* Erstellt eine Benutzer-Gruppen-Entität.
* @param userGroupEntity Benutzer-Gruppen-Entität
*/
void create(UserGroupEntity userGroupEntity);
/**
* Modifiziert eine Benutzer-Gruppen-Entität.
* @param userGroupEntity Benutzer-Gruppen-Entität
*/
void edit(UserGroupEntity userGroupEntity);
/**
* Löscht eine Benutzer-Gruppen-Entität.
* @param userGroupEntity Benutzer-Gruppen-Entität
*/
void remove(UserGroupEntity userGroupEntity);
/**
* Liefert eine bestimmte Benutzer-Gruppen-Entität zurück.
* @param id ID der Benutzer-Gruppen-Entität
* @return Benutzer-Gruppen-Entität
*/
UserGroupEntity find(Object id);
/**
* Liefert eine Liste aller Benutzer-Gruppen-Entitäten zurück.
* @return Liste von Benutzer-Gruppen-Entitäten
*/
List<UserGroupEntity> findAll();
/**
* Liefert eine Liste von Benutzer-Gruppen-Entitäten aus einem bestimmten Bereich zurück.
* @param range Bereich
* @return Liste von Benutzer-Gruppen-Entitäten
*/
List<UserGroupEntity> findRange(int[] range);
/**
* Liefert eine bestimmte Benutzer-Gruppen-Entität eines Gruppennamens zurück.
* @param groupName Gruppenname
* @return Benutzer-Gruppen-Entität
*/
UserGroupEntity findByGroupName(String groupName);
/**
* Liefert die Anzahl an gefundenen Benutzer-Gruppen-Entitäten zurück.
* @return Anzahl gefundender Benutzer-Gruppen-Entitäten
*/
int count();
}
| 27.19403 | 93 | 0.693743 |
bb96fd74f2736e31271b321d7176ef1abca75cd9 | 814 | swift | Swift | ios/Classes/Nodes/AudioEngineNode.swift | yangtianyan/audio_graph | a423a875ec462cd0cb3139bc4c31301f6ed6d610 | [
"MIT"
] | null | null | null | ios/Classes/Nodes/AudioEngineNode.swift | yangtianyan/audio_graph | a423a875ec462cd0cb3139bc4c31301f6ed6d610 | [
"MIT"
] | null | null | null | ios/Classes/Nodes/AudioEngineNode.swift | yangtianyan/audio_graph | a423a875ec462cd0cb3139bc4c31301f6ed6d610 | [
"MIT"
] | null | null | null | //
// AudioEngineNode.swift
// audio_graph
//
// Created by Kaisei Sunaga on 2020/01/24.
//
import Foundation
import AVFoundation
protocol AudioEngineNode: class {
static var nodeName: String { get }
var node: AudioNode { get }
var engineNode: AVAudioNode { get }
var inputConnections: [AudioNodeConnection] { get }
var outputConnections: [AudioNodeConnection] { get }
var shouldAttach: Bool { get }
func dispose()
}
extension AudioEngineNode {
func dispose() {
}
}
protocol AudioControllableNode: class {
func play()
func pause()
}
protocol AudioPreparableNode: class {
func prepare()
}
protocol AudioVolumeEditableNode: class {
var volume: Double { get set }
}
protocol AudioPositionableNode: class {
var position: Double { get set }
}
| 18.5 | 56 | 0.681818 |
c57af51cc20ad83418ff1e4f90327ab2b4cb39b2 | 495 | lua | Lua | config/nvim/lua/configs/colorschemes/moonfly.lua | TracerBuilt/dotfiles | 781678611f2effac5292b75b148cc382d3842014 | [
"MIT"
] | 2 | 2021-09-26T13:23:51.000Z | 2022-01-11T20:54:40.000Z | config/nvim/lua/configs/colorschemes/moonfly.lua | TracerBuilt/dotfiles | 781678611f2effac5292b75b148cc382d3842014 | [
"MIT"
] | null | null | null | config/nvim/lua/configs/colorschemes/moonfly.lua | TracerBuilt/dotfiles | 781678611f2effac5292b75b148cc382d3842014 | [
"MIT"
] | null | null | null | local g = vim.g
g.moonflyTransparent = 1
g.moonflyCursorColor = 1
g.moonflyNormalFloat = 1
vim.lsp.handlers['textDocument/hover'] = vim.lsp.with(vim.lsp.handlers.hover, {
border = 'single',
})
vim.lsp.handlers['textDocument/signatureHelp'] = vim.lsp.with(vim.lsp.handlers.signatureHelp, {
border = 'single',
})
vim.cmd 'colorscheme moonfly'
vim.cmd [[highlight VertSplit guibg=NONE]]
vim.cmd [[highlight EndOfBuffer guifg=#000000 guibg=NONE]]
vim.cmd [[highlight StatusLineNC guibg=NONE]]
| 26.052632 | 95 | 0.745455 |
4ab64c8168c08859a1d87eea955b758ab6495341 | 384 | swift | Swift | PersistenceProjectTests/_TestHelpers/NSManagedObjectContextExtensions.swift | benjmanning/PersistenceProject | 0e74831e7205aa78cd6c37fb21774dfaeb272069 | [
"MIT"
] | null | null | null | PersistenceProjectTests/_TestHelpers/NSManagedObjectContextExtensions.swift | benjmanning/PersistenceProject | 0e74831e7205aa78cd6c37fb21774dfaeb272069 | [
"MIT"
] | null | null | null | PersistenceProjectTests/_TestHelpers/NSManagedObjectContextExtensions.swift | benjmanning/PersistenceProject | 0e74831e7205aa78cd6c37fb21774dfaeb272069 | [
"MIT"
] | null | null | null | //
// NSManagedObjectContextExtensions.swift
// PersistenceProjectTests
//
// Created by Ben Manning on 02/08/2019.
// Copyright © 2019 Ben Manning. All rights reserved.
//
import XCTest
import CoreData
extension NSManagedObjectContext {
func xctestSave() {
do {
try save()
} catch {
XCTFail("Unable to save managed object context - \(error)")
}
}
}
| 18.285714 | 65 | 0.671875 |
9bc8448037971a60e4da19e32a464eddb4eae6da | 88 | js | JavaScript | src/screens/DashboardFeatured/index.js | iola-app/iola-app | e1262d345bfa2c464bfafd93b11788cc33b43377 | [
"MIT"
] | 1 | 2022-01-15T15:46:26.000Z | 2022-01-15T15:46:26.000Z | src/screens/DashboardFeatured/index.js | iola-team/iola-app | e1262d345bfa2c464bfafd93b11788cc33b43377 | [
"MIT"
] | null | null | null | src/screens/DashboardFeatured/index.js | iola-team/iola-app | e1262d345bfa2c464bfafd93b11788cc33b43377 | [
"MIT"
] | null | null | null | import DashboardFeatured from './DashboardFeatured';
export default DashboardFeatured;
| 22 | 52 | 0.840909 |
16432bf15b5af78267b1d793d9faebb7ecf1c3ab | 6,466 | ts | TypeScript | blingabc/src/app/services/conference.service.ts | Gozeon/code-collections | 7304e2b9c4c91a809125198d22cf40dcbb45a23b | [
"MIT"
] | null | null | null | blingabc/src/app/services/conference.service.ts | Gozeon/code-collections | 7304e2b9c4c91a809125198d22cf40dcbb45a23b | [
"MIT"
] | 1 | 2020-07-17T09:25:42.000Z | 2020-07-17T09:25:42.000Z | blingabc/src/app/services/conference.service.ts | Gozeon/code-collections | 7304e2b9c4c91a809125198d22cf40dcbb45a23b | [
"MIT"
] | null | null | null | import { Injectable } from '@angular/core';
import { Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { HttpInterceptorService, RESTService } from '@covalent/http';
import { API_V1 } from './api.config';
import { verifyMiddleWare } from './base.service';
const CONFERENCE_URL = `${API_V1}/conference/v1`;
/**
* API文档 --> 发布会 (http://120.27.11.200/)
*/
@Injectable()
export class ConferenceService extends RESTService<any> {
constructor(private _http: HttpInterceptorService) {
super(_http, {
baseUrl: API_V1, // NOTE: baseUrl not work
path: '/conference/v1',
});
}
// 发布会信息列表
getAllConferences(page: number, size: number): Observable<any> {
return this._http.get(`${CONFERENCE_URL}/conferences`, {params: {page: page, size: size}})
.map((res: Response) => verifyMiddleWare(res.json()) ? res.json()['data'] : {list: [], total: 0});
}
// 批量无效
cnacelConferences(ids: number[]): Observable<boolean> {
return this._http.post(`${CONFERENCE_URL}/invalidBatch`, ids)
.map((res: Response) => verifyMiddleWare(res.json()))
}
// 新增发布会信息
createConferences(data: any): Observable<any> {
return this._http.post(`${CONFERENCE_URL}/save`, data)
.map((res: Response) => verifyMiddleWare(res.json()) ? {code: 200} : res.json());
}
/**
* 发布会设置列表
* @link http://showdoc.blingabc.com/index.php?s=/2&page_id=238
* @returns {Observable<any>}
*/
getAllConferenceWithGrab(): Observable<any> {
return this._http.get(`${API_V1}/pro/v1/list`)
.map((res: Response) => verifyMiddleWare(res.json()) ? res.json()['data'] : []);
}
/**
* 添加发布会
* @link http://showdoc.blingabc.com/index.php?s=/2&page_id=239
* @param data
* @returns {Observable<any>}
*/
addConferenceWithGrab(data): Observable<any> {
return this._http.post(`${API_V1}/pro/v1/save`, data)
.map((res: Response) => res.json());
}
/**
* 更新发布会
* @link http://showdoc.blingabc.com/index.php?s=/2&page_id=240
* @param data
* @returns {Observable<any>}
*/
updateConferenceWithGrab(data): Observable<any> {
return this._http.post(`${API_V1}/pro/v1/update`, data)
.map((res: Response) => res.json());
}
/**
* 删除发布会设置
* @link http://showdoc.blingabc.com/index.php?s=/2&page_id=242
* @param data
* @returns {Observable<any>}
*/
deleteConferenceWithGrab(id): Observable<any> {
return this._http.get(`${API_V1}/pro/v1/delete/${id}`)
.map((res: Response) => res.json());
}
/**
* 续报配置列表
* @link http://showdoc.blingabc.com/index.php?s=/2&page_id=300
* @param data
* @returns {Observable<any>}
*/
getAllRenewal(data): Observable<any> {
return this._http.post(`${API_V1}/resubmit/v1/resubmits`, data)
.map((res: Response) => verifyMiddleWare(res.json()) ? res.json()['data'] : {list: [], total: 0});
}
/**
* 续报配置新增
* @link http://showdoc.blingabc.com/index.php?s=/2&page_id=298
* @param data
* @returns {Observable<any>}
*/
addRenewal(data): Observable<any> {
return this._http.post(`${API_V1}/resubmit/v1/save`, data)
.map((res: Response) => res.json());
}
/**
* 续报配置详情查询
* @link http://showdoc.blingabc.com/index.php?s=/2&page_id=299
* @param id
* @returns {Observable<any>}
*/
getRenewalById(id): Observable<any> {
return this._http.get(`${API_V1}/resubmit/v1/resubmit/${id}`)
.map((res: Response) => verifyMiddleWare(res.json()) ? res.json()['data'] : {});
}
/**
* 续班配置更新
* @link http://showdoc.blingabc.com/index.php?s=/2&page_id=302
* @param data
* @returns {Observable<any>}
*/
updateRenewal(data): Observable<any> {
return this._http.post(`${API_V1}/resubmit/v1/update`, data)
.map((res: Response) => res.json());
}
/**
* 续班配置发布
* @link http://showdoc.blingabc.com/index.php?s=/2&page_id=303
* @param id
* @param state
* @returns {Observable<any>}
*/
changeRenewalState(id, state): Observable<any> {
return this._http.post(`${API_V1}/resubmit/v1/state/update`, {
id: id,
state: state
})
.map((res: Response) => res.json());
}
/**
* 续报配置删除
* @link http://showdoc.blingabc.com/index.php?s=/2&page_id=317
* @param id
* @returns {Observable<any>}
*/
deleteRenewalById(id): Observable<any> {
return this._http.get(`${API_V1}/resubmit/v1/delete/${id}`)
.map((res: Response) => res.json());
}
/**
* 分销配置列表
* @link http://showdoc.blingabc.com/index.php?s=/2&page_id=327
* @param data
* @returns {Observable<any>}
*/
getAllDistribution(data): Observable<any> {
return this._http.post(`${API_V1}/distribution/config/v1/configs`, data)
.map((res: Response) => verifyMiddleWare(res.json()) ? res.json()['data'] : {list: [], total: 0});
}
/**
* 分销配置新增
* @link http://showdoc.blingabc.com/index.php?s=/2&page_id=322
* @param data
* @returns {Observable<any>}
*/
addDistribution(data): Observable<any> {
return this._http.post(`${API_V1}/distribution/config/v1/save`, data)
.map((res: Response) => res.json());
}
/**
* 分销配置发布
* @link http://showdoc.blingabc.com/index.php?s=/2&page_id=326
* @param id
* @param state
* @returns {Observable<any>}
*/
changeDistributionState(id): Observable<any> {
return this._http.get(`${API_V1}/distribution/config/v1/publish/${id}`)
.map((res: Response) => res.json());
}
/**
* 分销配置删除
* @link http://showdoc.blingabc.com/index.php?s=/2&page_id=323
* @param id
* @returns {Observable<any>}
*/
deleteDistributionById(id): Observable<any> {
return this._http.get(`${API_V1}/distribution/config/v1/delete/${id}`)
.map((res: Response) => res.json());
}
/**
* 分销配置详情
* @link http://showdoc.blingabc.com/index.php?s=/2&page_id=325
* @param id
* @returns {Observable<any>}
*/
getDistributionById(id): Observable<any> {
return this._http.get(`${API_V1}/distribution/config/v1/config/${id}`)
.map((res: Response) => verifyMiddleWare(res.json()) ? res.json()['data'] : {});
}
/**
* 分销配置更新
* @link http://showdoc.blingabc.com/index.php?s=/2&page_id=324
* @param data
* @returns {Observable<any>}
*/
updateDistribution(data): Observable<any> {
return this._http.post(`${API_V1}/distribution/config/v1/update`, data)
.map((res: Response) => res.json());
}
}
| 28.995516 | 104 | 0.617693 |
5de1db45dc329cd747999d7b667fc3dbafcb76ce | 930 | go | Go | go/vt/zktopo/agent.go | ngaut/vitess | 53eb94e5130965ea569d2f11e55b7c947e4494cf | [
"BSD-3-Clause"
] | 1 | 2015-09-16T04:46:41.000Z | 2015-09-16T04:46:41.000Z | go/vt/zktopo/agent.go | ngaut/vitess | 53eb94e5130965ea569d2f11e55b7c947e4494cf | [
"BSD-3-Clause"
] | null | null | null | go/vt/zktopo/agent.go | ngaut/vitess | 53eb94e5130965ea569d2f11e55b7c947e4494cf | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2013, Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package zktopo
import (
"path"
"github.com/youtube/vitess/go/vt/topo"
"github.com/youtube/vitess/go/zk"
)
/*
This file contains the code to support the local agent process for zktopo.Server
*/
func (zkts *Server) CreateTabletPidNode(tabletAlias topo.TabletAlias, contents string, done chan struct{}) error {
zkTabletPath := TabletPathForAlias(tabletAlias)
path := path.Join(zkTabletPath, "pid")
return zk.CreatePidNode(zkts.zconn, path, contents, done)
}
func (zkts *Server) ValidateTabletPidNode(tabletAlias topo.TabletAlias) error {
zkTabletPath := TabletPathForAlias(tabletAlias)
path := path.Join(zkTabletPath, "pid")
_, _, err := zkts.zconn.Get(path)
return err
}
func (zkts *Server) GetSubprocessFlags() []string {
return zk.GetZkSubprocessFlags()
}
| 27.352941 | 114 | 0.750538 |
e7143f88a989b05ff162abb77595ea67110d0aa3 | 267 | js | JavaScript | src/screens/splash/LogoApp.js | gersonmontenegro/dictionaryapp | 1353aa4738ac035772743dcb7487d02346da09d2 | [
"MIT"
] | null | null | null | src/screens/splash/LogoApp.js | gersonmontenegro/dictionaryapp | 1353aa4738ac035772743dcb7487d02346da09d2 | [
"MIT"
] | null | null | null | src/screens/splash/LogoApp.js | gersonmontenegro/dictionaryapp | 1353aa4738ac035772743dcb7487d02346da09d2 | [
"MIT"
] | null | null | null | import React, { memo } from 'react';
import { View, Image } from 'react-native';
const LogoComponent = () => {
return (
<View>
<Image source={require('src/assets/img/logo.png')} />
</View>
);
}
export default memo(LogoComponent); | 22.25 | 65 | 0.573034 |
8ea9babe9d449fd90fb05a0a05b20fe3d96f6bab | 88 | rb | Ruby | app/helpers/application_helper.rb | Flakster/Mountain-Style2 | 7ed858c0b10e62fc65daba64bbf848722a926d8f | [
"MIT"
] | 1 | 2020-09-14T20:43:27.000Z | 2020-09-14T20:43:27.000Z | app/helpers/application_helper.rb | Flakster/Mountain-Style2 | 7ed858c0b10e62fc65daba64bbf848722a926d8f | [
"MIT"
] | 6 | 2021-10-06T18:57:35.000Z | 2022-03-31T01:31:56.000Z | app/helpers/application_helper.rb | Flakster/Mountain-Style2 | 7ed858c0b10e62fc65daba64bbf848722a926d8f | [
"MIT"
] | 1 | 2021-04-30T17:17:02.000Z | 2021-04-30T17:17:02.000Z | # frozen_string_literal: true
# modules ApplicationHelper
module ApplicationHelper
end
| 14.666667 | 29 | 0.852273 |
75e4e5829c09bf7d978587158a77c647773f8692 | 4,370 | php | PHP | resources/views/savecart.blade.php | Jionsix-coder/zmh-laravel | 37cf1ded064e11bd1cdcf3efcd1c33f008f0ec52 | [
"MIT"
] | null | null | null | resources/views/savecart.blade.php | Jionsix-coder/zmh-laravel | 37cf1ded064e11bd1cdcf3efcd1c33f008f0ec52 | [
"MIT"
] | null | null | null | resources/views/savecart.blade.php | Jionsix-coder/zmh-laravel | 37cf1ded064e11bd1cdcf3efcd1c33f008f0ec52 | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<title>SaveCart | ZMH-OnlineShop</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/font-awesome.min.css" rel="stylesheet">
<link href="css/prettyPhoto.css" rel="stylesheet">
<link href="css/price-range.css" rel="stylesheet">
<link href="css/animate.css" rel="stylesheet">
<link href="css/main.css" rel="stylesheet">
<link href="css/responsive.css" rel="stylesheet">
<!--[if lt IE 9]>
<script src="js/html5shiv.js"></script>
<script src="js/respond.min.js"></script>
<![endif]-->
<link rel="shortcut icon" href="images/ico/favicon.ico">
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="images/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="images/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="images/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="images/ico/apple-touch-icon-57-precomposed.png">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
</head><!--/head-->
<body>
@include('partials.header')
<section id="cart_items">
<div class="container">
<div class="breadcrumbs">
<ol class="breadcrumb">
<li><a href="/home">ပင်မ</a></li>
<li style="font-weight: bolder;"><i class="fa fa-lg fa-shopping-cart"></i> စျေးခြင်း</li>
</ol>
</div>
@if (session()->has('success_message'))
<div class="alert alert-success">
{{ session()->get('success_message') }}
</div>
@endif
@if(count($errors) > 0)
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
@if(Cart::instance('saveCart')->count() > 0)
<h2>{{ Cart::instance('saveCart')->count() }} item(s) in Shopping Cart</h2>
<div class="table-responsive cart_info">
<table class="table table-condensed">
<thead>
<tr class="cart_menu">
<td class="image">ပစ္စည်း</td>
<td class="description">Name</td>
<td>switchToBasket</td>
<td class="price">စျေးနှုန်း</td>
<td class="total">စုစုပေါင်း</td>
<td></td>
</tr>
</thead>
<tbody>
@foreach (Cart::instance('saveCart')->content() as $item)
<tr>
<td class="cart_product">
<a href=""><img src="{{ productImage($item->model->image)}}" alt=""></a>
</td>
<td class="cart_description">
<h4><a href="{{ route('shop.show', $item->model->slug) }}">{{ $item->model->name }}</a></h4>
<p>{{ $item->model->details }}</p>
</td>
<td>
<form action="{{ route('saveCart.switchToCart', $item->rowId) }}" method="POST">
@csrf
<input type="hidden" name="id" value="{{ $item->rowId }}">
<button class="btn btn-default">ခြင်းသို့ထည့်ရန်</button>
</form>
</td>
<td class="cart_price">
<p>{{ $item->model->presentPrice() }}</p>
</td>
<td class="cart_total">
<p class="cart_total_price">12,000 Ks</p>
</td>
<td class="cart_delete">
<form action="{{ route('saveCart.destroy',$item->rowId) }}" method="POST">
@csrf
@method('DELETE')
<button type="submit" class="cart_quantity_delete"><i class="fa fa-times"></i></button>
</form>
</td>
</tr>
@endforeach
@else
<h3 class="no-item-h3">ဈေးလှည်းထဲတွင်ပစ္စည်းမရှိပါ။</h3>
<a href="{{ route('shop.index') }}" class="btn btn-primary btn-cs">Contine Shopping</a>
@endif
</tbody>
</table>
</div>
</div>
</section> <!--/#cart_items-->
@include('partials.footer') | 37.033898 | 218 | 0.55492 |
bf874f29a894febaa9b4cebcb0c8e88486f68358 | 2,365 | rs | Rust | src/lib.rs | rmanoka/geo-crossings | b1bfa2ab10735ed23ac6c4213662fc1d109cb066 | [
"Apache-2.0",
"MIT"
] | null | null | null | src/lib.rs | rmanoka/geo-crossings | b1bfa2ab10735ed23ac6c4213662fc1d109cb066 | [
"Apache-2.0",
"MIT"
] | null | null | null | src/lib.rs | rmanoka/geo-crossings | b1bfa2ab10735ed23ac6c4213662fc1d109cb066 | [
"Apache-2.0",
"MIT"
] | null | null | null | //! Implements a few plane-sweep / line-crossings flavored algorithms.
//!
//! 1. [Line Crossings](#line-crossings)
//! 1. [Monotone Decomposition](#monotone-decomposition)
//!
//! # Line Crossings
//!
//! This is an implementation of the [Bentley-Ottman] algorithm to
//! efficiently compute all intersections of a collection of line
//! segments and points. The simplest usage is using the
//! [`Intersections`] iterator which yields all intersections and
//! overlaps. This is essentially a drop-in replacement to using
//! [`line_intersection`] over all pairs, but is typically more
//! efficient.
//!
//! For a more advanced usage such as polygon clipping, use
//! [`CrossingsIter`] which iterates over all intersection points,
//! while also providing information about all segments that start or
//! end at the last yielded point.
//!
//! ## Usage
//!
//! Construct a [`Intersections`] from an iterator of any type
//! implementing the [`Crossable`] trait. The geo-type [`Line`]
//! implements this trait. See the trait documentation for more
//! information on usage with custom types.
//!
//! ```rust
//! use geo::Line;
//! use geo_crossings::Intersections;
//! use std::iter::FromIterator;
//! let input = vec![
//! Line::from([(1., 0.), (0., 1.)]),
//! Line::from([(0., 0.5), (1., 0.5)]),
//! Line::from([(0., 0.), (1., 1.)]),
//! ];
//! let iter = Intersections::<_>::from_iter(input);
//! // All pairs intersect
//! assert_eq!(iter.count(), 3);
//! ```
//!
//! # Monotone Decomposition
//!
//! Partitions a polygon into monotone pieces. See [`monotone_chains`].
//!
//! [Bentley-Ottman]: //en.wikipedia.org/wiki/Bentley%E2%80%93Ottmann_algorithm
//! [`Line`]: geo::Line
//! [`Point`]: geo::Point
//! [`Coordinate`]: geo::Coordinate
//! [`line_intersection`]: geo::algorithm::line_intersection::line_intersection
mod events;
pub use events::SweepPoint;
mod line_or_point;
pub use line_or_point::{LineOrPoint, Float};
mod active;
pub mod crossings;
pub use crossings::{Crossable, Crossing, CrossingsIter, Intersections};
pub mod monotone;
pub use monotone::{monotone_chains, Sweep as MonotoneSweep};
pub mod bops;
pub use bops::BooleanOp;
pub mod splay;
pub use splay::*;
#[cfg(test)]
#[path = "../benches/utils/random.rs"]
pub mod random;
#[cfg(test)]
#[path = "../benches/utils/bops.rs"]
pub mod bops_utils;
pub(crate) mod utils;
| 29.5625 | 79 | 0.679915 |
d5de800be3442230c75ab9643b7ca81abde96bee | 360 | h | C | src/fillediconlabel.h | ycashfoundation/YecLite | 3276280c7eb84f44abb9f04d8689fc983d0d0f4a | [
"MIT"
] | 19 | 2019-07-15T18:30:05.000Z | 2021-11-06T04:48:15.000Z | src/fillediconlabel.h | ycashfoundation/YecLite | 3276280c7eb84f44abb9f04d8689fc983d0d0f4a | [
"MIT"
] | 90 | 2021-04-09T14:39:52.000Z | 2022-03-23T03:49:44.000Z | src/fillediconlabel.h | ycashfoundation/YecLite | 3276280c7eb84f44abb9f04d8689fc983d0d0f4a | [
"MIT"
] | 9 | 2019-03-04T05:57:00.000Z | 2020-04-11T01:07:08.000Z | #ifndef FILLEDICONLABEL_H
#define FILLEDICONLABEL_H
#include "precompiled.h"
class FilledIconLabel : public QLabel
{
Q_OBJECT
public:
explicit FilledIconLabel(QWidget *parent = 0);
void setBasePixmap(QPixmap pm);
public slots:
void resizeEvent(QResizeEvent *);
private:
QPixmap basePm;
};
#endif // FILLEDICONLABEL_H | 17.142857 | 57 | 0.705556 |
a9cd80d9e1cb803cff0a72334f0145d2bf916f90 | 307 | html | HTML | templates/registration/registration_complete.html | monovertex/ygorganizer | 987a8de36b3864906ed499886e4c1a712d214310 | [
"MIT"
] | 11 | 2015-08-20T15:29:33.000Z | 2021-08-19T23:48:14.000Z | templates/registration/registration_complete.html | monovertex/ygorganizer | 987a8de36b3864906ed499886e4c1a712d214310 | [
"MIT"
] | 29 | 2015-08-20T13:25:59.000Z | 2015-08-24T13:28:52.000Z | templates/registration/registration_complete.html | monovertex/ygorganizer | 987a8de36b3864906ed499886e4c1a712d214310 | [
"MIT"
] | 4 | 2015-10-25T07:04:45.000Z | 2020-05-17T01:09:22.000Z | {% extends 'registration/registration_base.html' %}
{% block subtitle %}Registration{% endblock %}
{% block page_header %}
<strong>Activation email sent</strong>
{% endblock %}
{% block page_body %}
<p>
Please check your email to complete the registration process.
</p>
{% endblock %} | 23.615385 | 69 | 0.664495 |
d2da05cbafa8893fbdf623512fd642c07be52ece | 10,790 | php | PHP | modules/Kepegawaian/views/pegawai/view.php | hendabastian/hris | 14674aeb73ea23f88a3d7e3f62eeacd78eadff15 | [
"BSD-3-Clause"
] | null | null | null | modules/Kepegawaian/views/pegawai/view.php | hendabastian/hris | 14674aeb73ea23f88a3d7e3f62eeacd78eadff15 | [
"BSD-3-Clause"
] | null | null | null | modules/Kepegawaian/views/pegawai/view.php | hendabastian/hris | 14674aeb73ea23f88a3d7e3f62eeacd78eadff15 | [
"BSD-3-Clause"
] | null | null | null | <?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\widgets\Pjax;
use yii\bootstrap\Modal;
use yii\bootstrap\ButtonDropdown;
use yii\helpers\Url;
use app\components\AccessRole;
/* @var $this yii\web\View */
/* @var $model app\models\Pegawai */
$this->title = 'Profile Pegawai: '.$model->no_pegawai;
$this->params['breadcrumbs'][] = ['label' => 'Daftar Pegawai', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="row">
<div class="col-md-3">
<div class="box box-primary">
<div class="box-body box-profile">
<p style="text-align:center; font-size:10px">Foto Pegawai (100px x 120px)</p>
<img style="height: 120px; width:100px" class="profile-user-img img-responsive" src="<?= $model->photo;?>" alt="User profile picture">
<h4 class="text-center" style="line-height:20px"><?= $model->fullname;?></h4>
<p class="text-muted text-center">NPP: <code><?php echo $model->no_pegawai;?></code></p>
<p class="text-muted text-center">Grade: <code><?php echo $model->getGolonganPegawai($model->id);?></code></p>
<p style="text-align: center;">
<?= Html::button('<i class="fa fa-edit"></i> Ganti Foto', ['value' => Url::to(['pegawai/change-photo', 'id'=>$model->id]), 'title' => 'Ganti Foto Pegawai', 'class' => 'showModalButton btn btn-primary btn-xs']); ?>
<?= Html::a('<i class="fa fa-trash"></i> Hapus Foto', ['pegawai/delete-photo', 'id' => $model->id], [
'class' => 'btn btn-danger btn-xs',
'data' => [
'confirm' => 'Apakah anda yakin foto pegawai ini akan dihapus?',
'method' => 'post',
],
]) ?>
</p>
<div class="btn-group btn-block">
<button class="btn bg-maroon btn-block dropdown-toggle" data-toggle="dropdown"><i class="fa fa-download"></i> Download CV <span class="caret"></span></button>
<ul class="dropdown-menu" style="width:100%">
<li><a href="<?= Url::to(['pegawai/download-cv', 'id'=>$model->id]);?>" target="_blank" tabindex="-1"><i class="fa fa-download"></i> Download CV</a></li>
<li><a href="<?= Url::to(['pegawai/download-mini-cv', 'id'=>$model->id]);?>" target="_blank" tabindex="-1"><i class="fa fa-download"></i> Download Mini CV</a></li>
</ul>
</div>
</div>
<!-- /.box-body -->
</div>
</div>
<div class="col-md-9">
<div class="box box-primary">
<div class="box-body">
<?php if(in_array($model->id, $listPhk)): ?>
<?= Html::a('<i class="fa fa-list-alt"></i> Daftar Pegawai Lainnya', ['pegawai-nonaktif/index'], ['class' => 'btn btn-info btn-sm']) ?>
<?php else: ?>
<?= Html::a('<i class="fa fa-list-alt"></i> Daftar Pegawai Lainnya', ['pegawai/index'], ['class' => 'btn btn-info btn-sm']) ?>
<?php endif; ?>
<?php if(AccessRole::getAccessWrite(Yii::$app->controller->id) === 1){?>
<?= Html::a('<i class="fa fa-edit"></i> Update Data Pribadi Pegawai', ['update', 'id' => $model->id], ['class' => 'btn btn-primary btn-sm']) ?>
<?= Html::a('<i class="fa fa-trash"></i> Hapus Data Pegawai', ['delete', 'id' => $model->id], [
'class' => 'btn btn-danger btn-sm',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
<?= Html::a('<i class="fa fa-plus-circle"></i> Tambah Data Pegawai Baru', ['create'], ['class' => 'btn btn-success btn-sm']) ?>
<?php }?>
</div>
</div>
<div class="nav-tabs-custom">
<ul class="nav nav-tabs" style="font-size: 0.8em;">
<li class="active" style="padding-left: 2px; padding-right: 2px;"><a href="#data_pribadi" data-toggle="tab" aria-expanded="true">DATA PRIBADI</a></li>
<li class="" style="padding-left: 2px; padding-right: 2px;"><a href="#karir" data-toggle="tab" aria-expanded="false">RIWAYAT KARIR</a></li>
<!-- <li class="" style="padding-left: 2px; padding-right: 2px;"><a href="#sanksi" data-toggle="tab" aria-expanded="false">RIWAYAT SANKSI</a></li>-->
<!-- <li class="" style="padding-left: 2px; padding-right: 2px;"><a href="#penghargaan" data-toggle="tab" aria-expanded="false">RIWAYAT PENGHARGAAN</a></li>-->
</ul>
<div class="tab-content">
<div class="tab-pane active" id="data_pribadi">
<?php echo $this->render('_data_pribadi', ['model' => $model]); ?>
</div>
<!-- /.tab-pane -->
<div class="tab-pane" id="karir">
<?php echo $this->render('_riwayat_karir', ['model' => $model]); ?>
</div>
<!-- /.tab-pane -->
<div class="tab-pane" id="sanksi">
<?php echo $this->render('_riwayat_sanksi', ['model' => $model, 'sanksiPegawai' => $sanksiPegawai]); ?>
</div>
<div class="tab-pane" id="penghargaan">
<?php echo $this->render('_riwayat_penghargaan', ['model' => $model, 'penghargaanPegawai' => $penghargaanPegawai]); ?>
</div>
<!-- /.tab-pane -->
</div>
<!-- /.tab-content -->
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="nav-tabs-custom">
<ul class="nav nav-tabs" style="font-size: 0.8em;">
<li class="active" style="padding-left: 2px; padding-right: 2px;"><a href="#tab_1" data-toggle="tab" aria-expanded="true">ALAMAT</a></li>
<li class="" style="padding-left: 2px; padding-right: 2px;"><a href="#tab_2" data-toggle="tab" aria-expanded="false">PENDIDIKAN</a></li>
<li class="" style="padding-left: 2px; padding-right: 2px;"><a href="#tab_9" data-toggle="tab" aria-expanded="false">PERNIKAHAN</a></li>
<li class="" style="padding-left: 2px; padding-right: 2px;"><a href="#tab_3" data-toggle="tab" aria-expanded="false">KELUARGA</a></li>
<li class="" style="padding-left: 2px; padding-right: 2px;"><a href="#tab_4" data-toggle="tab" aria-expanded="false">SERTIFIKASI</a></li>
<li class="" style="padding-left: 2px; padding-right: 2px;"><a href="#tab_10" data-toggle="tab" aria-expanded="false">PELATIHAN</a></li>
<li class="" style="padding-left: 2px; padding-right: 2px;"><a href="#tab_5" data-toggle="tab" aria-expanded="false">REKENING BANK</a></li>
<li class="" style="padding-left: 2px; padding-right: 2px;"><a href="#tab_7" data-toggle="tab" aria-expanded="false">BPJS</a></li>
<li class="" style="padding-left: 2px; padding-right: 2px;"><a href="#tab_8" data-toggle="tab" aria-expanded="false">PENGALAMAN KERJA</a></li>
<li class="" style="padding-left: 2px; padding-right: 2px;"><a href="#tab_11" data-toggle="tab" aria-expanded="false">DOKUMEN LAINNYA</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="tab_1">
<?php echo $this->render('_alamat_pegawai', ['model' => $model, 'dataAlamat'=>$dataAlamat, 'searchAlamat'=>$searchAlamat]); ?>
</div>
<!-- /.tab-pane -->
<div class="tab-pane" id="tab_2">
<?php echo $this->render('_pendidikan_pegawai', ['model' => $model, 'searchPendidikan'=>$searchPendidikan, 'dataPendidikan'=>$dataPendidikan]); ?>
</div>
<!-- /.tab-pane -->
<div class="tab-pane" id="tab_3">
<?php echo $this->render('_keluarga_pegawai', ['model' => $model, 'searchKeluarga'=>$searchKeluarga, 'dataKeluarga'=>$dataKeluarga, 'searchKartuKeluarga'=>$searchKartuKeluarga, 'dataKartuKeluarga'=>$dataKartuKeluarga]); ?>
</div>
<div class="tab-pane" id="tab_4">
<?php echo $this->render('_sertifikasi_pegawai', ['model' => $model, 'searchSertifikasi'=>$searchSertifikasi, 'dataSertifikasi'=>$dataSertifikasi]); ?>
</div>
<div class="tab-pane" id="tab_5">
<?php echo $this->render('_rek_bank_pegawai', ['model' => $model, 'dataRekBank'=>$dataRekBank]); ?>
</div>
<?php /*
<div class="tab-pane" id="tab_6">
<?php echo $this->render('_npwp_pegawai', ['model' => $model, 'dataNpwp'=>$dataNpwp, 'kartuNpwp' => $kartuNpwp]); ?>
</div>
*/?>
<div class="tab-pane" id="tab_7">
<?php echo $this->render('_bpjs_pegawai', ['model' => $model, 'dataBpjs'=>$dataBpjs, 'kartuBpjsKtn' => $kartuBpjsKtn, 'kartuBpjsKsh' => $kartuBpjsKsh]); ?>
</div>
<div class="tab-pane" id="tab_8">
<?php echo $this->render('_pengalaman_kerja_pegawai', ['model' => $model, 'searchPengalamanKerja'=>$searchPengalamanKerja, 'dataPengalamanKerja'=>$dataPengalamanKerja]); ?>
</div>
<div class="tab-pane" id="tab_9">
<?php echo $this->render('_pernikahan_pegawai', ['model' => $model, 'dataPernikahan'=>$dataPernikahan, 'searchPernikahan' => $searchPernikahan]); ?>
</div>
<div class="tab-pane" id="tab_10">
<?php echo $this->render('_pelatihan_pegawai', ['model' => $model, 'searchPelatihan'=>$searchPelatihan, 'dataPelatihan'=>$dataPelatihan]); ?>
</div>
<div class="tab-pane" id="tab_11">
<?php echo $this->render('_dokumen_lainnya_pegawai', ['model' => $model, 'searchDokumenLainnya'=>$searchDokumenLainnya, 'dataDokumenLainnya'=>$dataDokumenLainnya]); ?>
</div>
<!-- /.tab-pane -->
</div>
<!-- /.tab-content -->
</div>
</div>
</div>
<?php
Modal::begin([
'headerOptions' => ['id' => 'modalHeader'],
'id' => 'modal',
'size' => 'modal-lg',
'options' => ['tabindex' => false],
'closeButton' =>['tag'=>'close', 'label'=> 'x'],
//keeps from closing modal with esc key or by clicking out of the modal.
// user must click cancel or X to close
'clientOptions' => ['backdrop' => 'static', 'keyboard' => false]
]);
echo "<div id='modalContent'></div>";
Modal::end();
?>
<?php
$script = "$('body').addClass('sidebar-collapse');";
$this->registerJs($script,yii\web\View::POS_END);
?>
| 55.906736 | 237 | 0.532901 |
6798bc4d4e881b23820e51dc8f3351d5293b11b4 | 468 | kt | Kotlin | app/src/main/java/com/unitbean/ubanalytics/MainActivity.kt | unitbean/UBAnalytics | 72293d6c991b7f27411a2b90201488dfdbba3134 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/unitbean/ubanalytics/MainActivity.kt | unitbean/UBAnalytics | 72293d6c991b7f27411a2b90201488dfdbba3134 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/unitbean/ubanalytics/MainActivity.kt | unitbean/UBAnalytics | 72293d6c991b7f27411a2b90201488dfdbba3134 | [
"Apache-2.0"
] | null | null | null | package com.unitbean.ubanalytics
import androidx.appcompat.app.AppCompatActivity
import android.content.Intent
import android.os.Bundle
import android.view.View
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun launchSecond(view: View) {
startActivity(Intent(this, SecondActivity::class.java))
}
}
| 24.631579 | 63 | 0.75 |
cb2151fda98bba9b6ac76785dbbc9ee12a0c1e73 | 181 | sql | SQL | database/init.sql | HaeckelK/language-learning | 0466ac8e904b60c5922c93695046fc7affa80ca4 | [
"MIT"
] | null | null | null | database/init.sql | HaeckelK/language-learning | 0466ac8e904b60c5922c93695046fc7affa80ca4 | [
"MIT"
] | null | null | null | database/init.sql | HaeckelK/language-learning | 0466ac8e904b60c5922c93695046fc7affa80ca4 | [
"MIT"
] | null | null | null | CREATE TABLE IF NOT EXISTS words (
id SERIAL PRIMARY KEY,
language text,
word text,
known boolean,
date_known int,
added int,
UNIQUE (language, word)
);
| 18.1 | 34 | 0.640884 |
56c14abf0bf63ce790be649ac9f1c80490fd63fe | 2,795 | ts | TypeScript | src/models/translation.ts | kentaro-m/honyaku-flag | 919a7e893f00cd856d988387c513acec700ad567 | [
"MIT"
] | 5 | 2019-08-05T19:15:08.000Z | 2020-03-16T10:02:09.000Z | src/models/translation.ts | kentaro-m/honyaku-flag | 919a7e893f00cd856d988387c513acec700ad567 | [
"MIT"
] | 2 | 2021-05-10T05:31:53.000Z | 2022-01-22T08:28:47.000Z | src/models/translation.ts | kentaro-m/honyaku-flag | 919a7e893f00cd856d988387c513acec700ad567 | [
"MIT"
] | null | null | null | import { App, ReactionAddedEvent, Context } from "@slack/bolt"
import { findLanguageCode } from "../utils/language"
import { isInvitedBot } from "../utils/bot"
import { langcodes } from "../constants/langcodes"
import { Translate } from "@google-cloud/translate"
class Translation {
private app: App
private event: ReactionAddedEvent
private context: Context
public constructor(app: App, event: ReactionAddedEvent, context: Context) {
this.app = app
this.event = event
this.context = context
}
public async translate(): Promise<void> {
try {
const langcode: string = findLanguageCode(this.event.reaction, langcodes)
if (!langcode) {
return
}
const item: any = this.event.item
const userId: string = process.env.SLACK_USER_ID || ""
/**
* INFO: A check for running the app only on the channel which the app was invited.
*/
if (userId) {
const members: any = await this.app.client.conversations.members({
token: process.env.SLACK_OAUTH_TOKEN,
channel: item.channel
})
if (!isInvitedBot(userId, members.members)) {
return
}
}
const messages: any = await this.app.client.conversations.replies({
token: process.env.SLACK_OAUTH_TOKEN,
channel: item.channel,
ts: item.ts,
limit: 1,
inclusive: true
})
const translate = new Translate({
key: process.env.TRANSLATION_API_TOKEN
})
const [translation] = await translate.translate(
messages.messages[0].text,
langcode
)
await this.app.client.chat.postMessage({
token: this.context.botToken,
channel: item.channel,
text: "",
attachments: [
{
color: "#1a73e8",
pretext: `The message is translated in :${this.event.reaction}: (${langcode}).`,
fields: [
{
title: "Translated Message",
value: translation,
short: false
},
{
title: "Original Message",
value: messages.messages[0].text,
short: false
}
]
}
],
// eslint-disable-next-line @typescript-eslint/camelcase
thread_ts: item.ts
})
} catch (error) {
const item: any = this.event.item
await this.app.client.chat.postMessage({
token: this.context.botToken,
channel: item.channel,
text: "Oops! Something Went Wrong :nauseated_face:\nPlease try again.",
// eslint-disable-next-line @typescript-eslint/camelcase
thread_ts: item.ts
})
throw error
}
}
}
export default Translation
| 27.401961 | 92 | 0.576386 |
c21a91f35eef46b8e93d014d56e2bfc2a5f45964 | 223,950 | go | Go | sdk/application/models.go | gofynd/fdk-client-golang | 10cf9432d8d7617d2ab239da2442a3d95b300e6c | [
"MIT"
] | null | null | null | sdk/application/models.go | gofynd/fdk-client-golang | 10cf9432d8d7617d2ab239da2442a3d95b300e6c | [
"MIT"
] | null | null | null | sdk/application/models.go | gofynd/fdk-client-golang | 10cf9432d8d7617d2ab239da2442a3d95b300e6c | [
"MIT"
] | 1 | 2021-08-09T10:42:19.000Z | 2021-08-09T10:42:19.000Z | package application
// Meta ...
type Meta struct {
Source string `json:"source"`
}
// Media ...
type Media struct {
Meta Meta `json:"meta"`
Type string `json:"type"`
URL string `json:"url"`
}
// ProductListingActionPage ...
type ProductListingActionPage struct {
Type string `json:"type"`
Query map[string]interface{} `json:"query"`
Params map[string]interface{} `json:"params"`
}
// ProductListingAction ...
type ProductListingAction struct {
Type string `json:"type"`
Page ProductListingActionPage `json:"page"`
}
// ProductBrand ...
type ProductBrand struct {
Logo Media `json:"logo"`
UID float64 `json:"uid"`
Name string `json:"name"`
Action ProductListingAction `json:"action"`
}
// Price ...
type Price struct {
CurrencySymbol string `json:"currency_symbol"`
Max float64 `json:"max"`
Min float64 `json:"min"`
CurrencyCode string `json:"currency_code"`
}
// ProductListingPrice ...
type ProductListingPrice struct {
Marked Price `json:"marked"`
Effective Price `json:"effective"`
}
// ProductDetailAttribute ...
type ProductDetailAttribute struct {
Key string `json:"key"`
Type string `json:"type"`
Value string `json:"value"`
}
// ProductDetailGroupedAttribute ...
type ProductDetailGroupedAttribute struct {
Details []ProductDetailAttribute `json:"details"`
Title string `json:"title"`
}
// ProductDetail ...
type ProductDetail struct {
ProductOnlineDate string `json:"product_online_date"`
Highlights []string `json:"highlights"`
TeaserTag string `json:"teaser_tag"`
Brand ProductBrand `json:"brand"`
ItemType string `json:"item_type"`
Discount string `json:"discount"`
Similars []string `json:"similars"`
Tryouts []string `json:"tryouts"`
ShortDescription string `json:"short_description"`
Price ProductListingPrice `json:"price"`
UID float64 `json:"uid"`
Type string `json:"type"`
Description string `json:"description"`
HasVariant bool `json:"has_variant"`
Action ProductListingAction `json:"action"`
Attributes map[string]interface{} `json:"attributes"`
ImageNature string `json:"image_nature"`
Categories []ProductBrand `json:"categories"`
Name string `json:"name"`
Color string `json:"color"`
RatingCount float64 `json:"rating_count"`
Medias []Media `json:"medias"`
GroupedAttributes []ProductDetailGroupedAttribute `json:"grouped_attributes"`
Slug string `json:"slug"`
Rating float64 `json:"rating"`
ItemCode string `json:"item_code"`
}
// ErrorResponse ...
type ErrorResponse struct {
Error string `json:"error"`
}
// ProductSizeStores ...
type ProductSizeStores struct {
Count float64 `json:"count"`
}
// SizeChartValues ...
type SizeChartValues struct {
Col6 string `json:"col_6"`
Col1 string `json:"col_1"`
Col5 string `json:"col_5"`
Col4 string `json:"col_4"`
Col2 string `json:"col_2"`
Col3 string `json:"col_3"`
}
// ColumnHeader ...
type ColumnHeader struct {
Convertable bool `json:"convertable"`
Value string `json:"value"`
}
// ColumnHeaders ...
type ColumnHeaders struct {
Col6 ColumnHeader `json:"col_6"`
Col1 ColumnHeader `json:"col_1"`
Col5 ColumnHeader `json:"col_5"`
Col4 ColumnHeader `json:"col_4"`
Col2 ColumnHeader `json:"col_2"`
Col3 ColumnHeader `json:"col_3"`
}
// SizeChart ...
type SizeChart struct {
Image string `json:"image"`
Title string `json:"title"`
Unit string `json:"unit"`
Sizes []SizeChartValues `json:"sizes"`
SizeTip string `json:"size_tip"`
Description string `json:"description"`
Headers ColumnHeaders `json:"headers"`
}
// ProductSize ...
type ProductSize struct {
Display string `json:"display"`
Quantity float64 `json:"quantity"`
Value string `json:"value"`
IsAvailable bool `json:"is_available"`
}
// ProductSizes ...
type ProductSizes struct {
Stores ProductSizeStores `json:"stores"`
Price ProductListingPrice `json:"price"`
SizeChart SizeChart `json:"size_chart"`
Sizes []ProductSize `json:"sizes"`
Sellable bool `json:"sellable"`
Discount string `json:"discount"`
}
// StrategyWiseListing ...
type StrategyWiseListing struct {
Quantity float64 `json:"quantity"`
Tat float64 `json:"tat"`
Distance float64 `json:"distance"`
Pincode float64 `json:"pincode"`
}
// Seller ...
type Seller struct {
UID float64 `json:"uid"`
Count float64 `json:"count"`
Name string `json:"name"`
}
// Store ...
type Store struct {
UID float64 `json:"uid"`
Count float64 `json:"count"`
Name string `json:"name"`
}
// ProductStockPrice ...
type ProductStockPrice struct {
Currency string `json:"currency"`
Marked float64 `json:"marked"`
Effective float64 `json:"effective"`
}
// ProductSetDistributionSize ...
type ProductSetDistributionSize struct {
Size string `json:"size"`
Pieces float64 `json:"pieces"`
}
// ProductSetDistribution ...
type ProductSetDistribution struct {
Sizes []ProductSetDistributionSize `json:"sizes"`
}
// ProductSet ...
type ProductSet struct {
SizeDistribution ProductSetDistribution `json:"size_distribution"`
Quantity float64 `json:"quantity"`
}
// ArticleAssignment ...
type ArticleAssignment struct {
Level string `json:"level"`
Strategy string `json:"strategy"`
}
// ReturnConfig ...
type ReturnConfig struct {
Unit string `json:"unit"`
Time float64 `json:"time"`
Returnable bool `json:"returnable"`
}
// Details ...
type Details struct {
Key string `json:"key"`
Type string `json:"type"`
Value string `json:"value"`
}
// MarketPlaceSttributes ...
type MarketPlaceSttributes struct {
Details []Details `json:"details"`
Title string `json:"title"`
}
// ProductSizePriceResponse ...
type ProductSizePriceResponse struct {
LongLat []float64 `json:"long_lat"`
StrategyWiseListing []StrategyWiseListing `json:"strategy_wise_listing"`
Quantity float64 `json:"quantity"`
SellerCount float64 `json:"seller_count"`
Seller Seller `json:"seller"`
ArticleID string `json:"article_id"`
Store Store `json:"store"`
Price ProductStockPrice `json:"price"`
Set ProductSet `json:"set"`
Pincode float64 `json:"pincode"`
ItemType string `json:"item_type"`
SpecialBadge string `json:"special_badge"`
PricePerPiece ProductStockPrice `json:"price_per_piece"`
Discount string `json:"discount"`
ArticleAssignment ArticleAssignment `json:"article_assignment"`
ReturnConfig ReturnConfig `json:"return_config"`
MarketplaceAttributes []MarketPlaceSttributes `json:"marketplace_attributes"`
}
// ProductSizeSellerFilter ...
type ProductSizeSellerFilter struct {
Value string `json:"value"`
Name string `json:"name"`
IsSelected bool `json:"is_selected"`
}
// ProductSizeSellersResponse ...
type ProductSizeSellersResponse struct {
Items []ProductSizePriceResponse `json:"items"`
SortOn []ProductSizeSellerFilter `json:"sort_on"`
Page Page `json:"page"`
}
// AttributeDetail ...
type AttributeDetail struct {
Key string `json:"key"`
Display string `json:"display"`
Logo string `json:"logo"`
Description string `json:"description"`
}
// AttributeMetadata ...
type AttributeMetadata struct {
Details []AttributeDetail `json:"details"`
Title string `json:"title"`
}
// ProductsComparisonResponse ...
type ProductsComparisonResponse struct {
Items []ProductDetail `json:"items"`
AttributesMetadata []AttributeMetadata `json:"attributes_metadata"`
}
// ProductCompareResponse ...
type ProductCompareResponse struct {
Subtitle string `json:"subtitle"`
Title string `json:"title"`
Items []ProductDetail `json:"items"`
AttributesMetadata []AttributeMetadata `json:"attributes_metadata"`
}
// ProductFrequentlyComparedSimilarResponse ...
type ProductFrequentlyComparedSimilarResponse struct {
Similars ProductCompareResponse `json:"similars"`
}
// ProductSimilarItem ...
type ProductSimilarItem struct {
Subtitle string `json:"subtitle"`
Title string `json:"title"`
Items []ProductDetail `json:"items"`
}
// SimilarProductByTypeResponse ...
type SimilarProductByTypeResponse struct {
Similars ProductSimilarItem `json:"similars"`
}
// ProductVariantItemResponse ...
type ProductVariantItemResponse struct {
Action ProductListingAction `json:"action"`
ColorName string `json:"color_name"`
IsAvailable bool `json:"is_available"`
UID float64 `json:"uid"`
Name string `json:"name"`
Color string `json:"color"`
Medias []Media `json:"medias"`
Slug string `json:"slug"`
Value string `json:"value"`
}
// ProductVariantResponse ...
type ProductVariantResponse struct {
Key string `json:"key"`
DisplayType string `json:"display_type"`
Items []ProductVariantItemResponse `json:"items"`
Header string `json:"header"`
}
// ProductVariantsResponse ...
type ProductVariantsResponse struct {
Variants []ProductVariantResponse `json:"variants"`
}
// StoreDetail ...
type StoreDetail struct {
Code string `json:"code"`
Name string `json:"name"`
City string `json:"city"`
ID float64 `json:"id"`
}
// CompanyDetail ...
type CompanyDetail struct {
Name string `json:"name"`
ID float64 `json:"id"`
}
// ProductStockStatusItem ...
type ProductStockStatusItem struct {
Quantity float64 `json:"quantity"`
Store StoreDetail `json:"store"`
Seller Seller `json:"seller"`
ItemID float64 `json:"item_id"`
Price ProductStockPrice `json:"price"`
UID string `json:"uid"`
Size string `json:"size"`
Identifier map[string]interface{} `json:"identifier"`
Company CompanyDetail `json:"company"`
}
// ProductStockStatusResponse ...
type ProductStockStatusResponse struct {
Items []ProductStockStatusItem `json:"items"`
}
// ProductStockPolling ...
type ProductStockPolling struct {
Items []ProductStockStatusItem `json:"items"`
Page Page `json:"page"`
}
// ProductListingDetail ...
type ProductListingDetail struct {
ProductOnlineDate string `json:"product_online_date"`
Highlights []string `json:"highlights"`
TeaserTag string `json:"teaser_tag"`
Brand ProductBrand `json:"brand"`
ItemType string `json:"item_type"`
Discount string `json:"discount"`
Similars []string `json:"similars"`
Tryouts []string `json:"tryouts"`
ShortDescription string `json:"short_description"`
Sellable bool `json:"sellable"`
Price ProductListingPrice `json:"price"`
UID float64 `json:"uid"`
Type string `json:"type"`
Description string `json:"description"`
HasVariant bool `json:"has_variant"`
Action ProductListingAction `json:"action"`
Attributes map[string]interface{} `json:"attributes"`
ImageNature string `json:"image_nature"`
Categories []ProductBrand `json:"categories"`
Name string `json:"name"`
Color string `json:"color"`
RatingCount float64 `json:"rating_count"`
Medias []Media `json:"medias"`
GroupedAttributes []ProductDetailGroupedAttribute `json:"grouped_attributes"`
Slug string `json:"slug"`
Rating float64 `json:"rating"`
ItemCode string `json:"item_code"`
}
// ProductSortOn ...
type ProductSortOn struct {
IsSelected bool `json:"is_selected"`
Name string `json:"name"`
Value string `json:"value"`
}
// ProductFiltersKey ...
type ProductFiltersKey struct {
Display string `json:"display"`
Kind string `json:"kind"`
Name string `json:"name"`
Logo string `json:"logo"`
}
// ProductFiltersValue ...
type ProductFiltersValue struct {
Display string `json:"display"`
Count float64 `json:"count"`
Min float64 `json:"min"`
IsSelected bool `json:"is_selected"`
CurrencyCode string `json:"currency_code"`
Max float64 `json:"max"`
SelectedMin float64 `json:"selected_min"`
DisplayFormat string `json:"display_format"`
CurrencySymbol string `json:"currency_symbol"`
SelectedMax float64 `json:"selected_max"`
Value string `json:"value"`
QueryFormat string `json:"query_format"`
}
// ProductFilters ...
type ProductFilters struct {
Key ProductFiltersKey `json:"key"`
Values []ProductFiltersValue `json:"values"`
}
// ProductListingResponse ...
type ProductListingResponse struct {
Items []ProductListingDetail `json:"items"`
SortOn []ProductSortOn `json:"sort_on"`
Filters []ProductFilters `json:"filters"`
Page Page `json:"page"`
}
// ImageUrls ...
type ImageUrls struct {
Landscape Media `json:"landscape"`
Portrait Media `json:"portrait"`
}
// BrandItem ...
type BrandItem struct {
Action ProductListingAction `json:"action"`
Logo Media `json:"logo"`
UID float64 `json:"uid"`
Name string `json:"name"`
Banners ImageUrls `json:"banners"`
Slug string `json:"slug"`
Discount string `json:"discount"`
Departments []string `json:"departments"`
}
// BrandListingResponse ...
type BrandListingResponse struct {
Items []BrandItem `json:"items"`
Page Page `json:"page"`
}
// BrandDetailResponse ...
type BrandDetailResponse struct {
Logo Media `json:"logo"`
UID float64 `json:"uid"`
Name string `json:"name"`
Banners ImageUrls `json:"banners"`
}
// DepartmentIdentifier ...
type DepartmentIdentifier struct {
UID float64 `json:"uid"`
Slug string `json:"slug"`
}
// ThirdLevelChild ...
type ThirdLevelChild struct {
CustomJson map[string]interface{} `json:"_custom_json"`
Action ProductListingAction `json:"action"`
UID float64 `json:"uid"`
Name string `json:"name"`
Banners ImageUrls `json:"banners"`
Childs []map[string]interface{} `json:"childs"`
Slug string `json:"slug"`
}
// SecondLevelChild ...
type SecondLevelChild struct {
CustomJson map[string]interface{} `json:"_custom_json"`
Action ProductListingAction `json:"action"`
UID float64 `json:"uid"`
Name string `json:"name"`
Banners ImageUrls `json:"banners"`
Childs []ThirdLevelChild `json:"childs"`
Slug string `json:"slug"`
}
// Child ...
type Child struct {
CustomJson map[string]interface{} `json:"_custom_json"`
Action ProductListingAction `json:"action"`
UID float64 `json:"uid"`
Name string `json:"name"`
Banners ImageUrls `json:"banners"`
Childs []SecondLevelChild `json:"childs"`
Slug string `json:"slug"`
}
// CategoryItems ...
type CategoryItems struct {
Action ProductListingAction `json:"action"`
UID float64 `json:"uid"`
Name string `json:"name"`
Banners ImageUrls `json:"banners"`
Childs []Child `json:"childs"`
Slug string `json:"slug"`
}
// DepartmentCategoryTree ...
type DepartmentCategoryTree struct {
Department string `json:"department"`
Items []CategoryItems `json:"items"`
}
// CategoryListingResponse ...
type CategoryListingResponse struct {
Departments []DepartmentIdentifier `json:"departments"`
Data []DepartmentCategoryTree `json:"data"`
}
// CategoryMetaResponse ...
type CategoryMetaResponse struct {
Logo Media `json:"logo"`
UID float64 `json:"uid"`
Name string `json:"name"`
Banners ImageUrls `json:"banners"`
}
// HomeListingResponse ...
type HomeListingResponse struct {
Items []ProductListingDetail `json:"items"`
Message string `json:"message"`
Page Page `json:"page"`
}
// Department ...
type Department struct {
Logo Media `json:"logo"`
UID float64 `json:"uid"`
Name string `json:"name"`
PriorityOrder float64 `json:"priority_order"`
Slug string `json:"slug"`
}
// DepartmentResponse ...
type DepartmentResponse struct {
Items []Department `json:"items"`
}
// AutocompleteItem ...
type AutocompleteItem struct {
Display string `json:"display"`
Type string `json:"type"`
Action ProductListingAction `json:"action"`
Logo Media `json:"logo"`
}
// AutoCompleteResponse ...
type AutoCompleteResponse struct {
Items []AutocompleteItem `json:"items"`
}
// GetCollectionDetailNest ...
type GetCollectionDetailNest struct {
Logo Media `json:"logo"`
Banners ImageUrls `json:"banners"`
Query map[string]interface{} `json:"query"`
Tag []string `json:"tag"`
AppID string `json:"app_id"`
VisibleFacetsKeys []string `json:"visible_facets_keys"`
AllowSort bool `json:"allow_sort"`
IsActive bool `json:"is_active"`
Badge map[string]interface{} `json:"badge"`
Type string `json:"type"`
UID string `json:"uid"`
AllowFacets bool `json:"allow_facets"`
Description string `json:"description"`
Schedule map[string]interface{} `json:"_schedule"`
Meta map[string]interface{} `json:"meta"`
Action ProductListingAction `json:"action"`
Cron map[string]interface{} `json:"cron"`
Name string `json:"name"`
Slug string `json:"slug"`
}
// CollectionListingFilterType ...
type CollectionListingFilterType struct {
Display string `json:"display"`
Name string `json:"name"`
IsSelected bool `json:"is_selected"`
}
// CollectionListingFilterTag ...
type CollectionListingFilterTag struct {
Display string `json:"display"`
Name string `json:"name"`
IsSelected bool `json:"is_selected"`
}
// CollectionListingFilter ...
type CollectionListingFilter struct {
Type []CollectionListingFilterType `json:"type"`
Tags []CollectionListingFilterTag `json:"tags"`
}
// GetCollectionListingResponse ...
type GetCollectionListingResponse struct {
Items []GetCollectionDetailNest `json:"items"`
Filters CollectionListingFilter `json:"filters"`
Page Page `json:"page"`
}
// CollectionDetailResponse ...
type CollectionDetailResponse struct {
Meta map[string]interface{} `json:"meta"`
AllowSort bool `json:"allow_sort"`
IsActive bool `json:"is_active"`
Badge map[string]interface{} `json:"badge"`
Cron map[string]interface{} `json:"cron"`
Logo Media `json:"logo"`
Type string `json:"type"`
Name string `json:"name"`
VisibleFacetsKeys []string `json:"visible_facets_keys"`
Banners ImageUrls `json:"banners"`
Query map[string]interface{} `json:"query"`
AllowFacets bool `json:"allow_facets"`
Tag []string `json:"tag"`
Description string `json:"description"`
Slug string `json:"slug"`
Schedule map[string]interface{} `json:"_schedule"`
AppID string `json:"app_id"`
}
// GetFollowListingResponse ...
type GetFollowListingResponse struct {
Items []ProductListingDetail `json:"items"`
Page Page `json:"page"`
}
// FollowPostResponse ...
type FollowPostResponse struct {
ID string `json:"id"`
Message string `json:"message"`
}
// FollowerCountResponse ...
type FollowerCountResponse struct {
Count float64 `json:"count"`
}
// FollowIdsData ...
type FollowIdsData struct {
Brands []float64 `json:"brands"`
Collections []float64 `json:"collections"`
Products []float64 `json:"products"`
}
// FollowIdsResponse ...
type FollowIdsResponse struct {
Data FollowIdsData `json:"data"`
}
// LatLong ...
type LatLong struct {
Type string `json:"type"`
Coordinates []float64 `json:"coordinates"`
}
// Store1 ...
type Store1 struct {
State string `json:"state"`
UID float64 `json:"uid"`
Name string `json:"name"`
Address string `json:"address"`
Pincode float64 `json:"pincode"`
StoreEmail string `json:"store_email"`
StoreCode string `json:"store_code"`
City string `json:"city"`
Country string `json:"country"`
LatLong LatLong `json:"lat_long"`
}
// StoreListingResponse ...
type StoreListingResponse struct {
Items []Store1 `json:"items"`
Page Page `json:"page"`
}
// CartCurrency ...
type CartCurrency struct {
Symbol string `json:"symbol"`
Code string `json:"code"`
}
// CouponBreakup ...
type CouponBreakup struct {
IsApplied bool `json:"is_applied"`
Message string `json:"message"`
Type string `json:"type"`
UID string `json:"uid"`
Value float64 `json:"value"`
Code string `json:"code"`
}
// DisplayBreakup ...
type DisplayBreakup struct {
CurrencySymbol string `json:"currency_symbol"`
Message []string `json:"message"`
Key string `json:"key"`
Value float64 `json:"value"`
Display string `json:"display"`
CurrencyCode string `json:"currency_code"`
}
// RawBreakup ...
type RawBreakup struct {
ConvenienceFee float64 `json:"convenience_fee"`
Vog float64 `json:"vog"`
DeliveryCharge float64 `json:"delivery_charge"`
YouSaved float64 `json:"you_saved"`
Subtotal float64 `json:"subtotal"`
CodCharge float64 `json:"cod_charge"`
GstCharges float64 `json:"gst_charges"`
MrpTotal string `json:"mrp_total"`
Coupon float64 `json:"coupon"`
Discount float64 `json:"discount"`
FyndCash float64 `json:"fynd_cash"`
Total float64 `json:"total"`
}
// LoyaltyPoints ...
type LoyaltyPoints struct {
Applicable float64 `json:"applicable"`
IsApplied bool `json:"is_applied"`
Total float64 `json:"total"`
Description string `json:"description"`
}
// CartBreakup ...
type CartBreakup struct {
Coupon CouponBreakup `json:"coupon"`
Display []DisplayBreakup `json:"display"`
Raw RawBreakup `json:"raw"`
LoyaltyPoints LoyaltyPoints `json:"loyalty_points"`
}
// PaymentSelectionLock ...
type PaymentSelectionLock struct {
Enabled bool `json:"enabled"`
DefaultOptions string `json:"default_options"`
PaymentIdentifier string `json:"payment_identifier"`
}
// ProductPrice ...
type ProductPrice struct {
CurrencySymbol string `json:"currency_symbol"`
Effective float64 `json:"effective"`
Marked float64 `json:"marked"`
Selling float64 `json:"selling"`
AddOn float64 `json:"add_on"`
CurrencyCode string `json:"currency_code"`
}
// ProductPriceInfo ...
type ProductPriceInfo struct {
Converted ProductPrice `json:"converted"`
Base ProductPrice `json:"base"`
}
// PromoMeta ...
type PromoMeta struct {
Message string `json:"message"`
}
// BaseInfo ...
type BaseInfo struct {
UID float64 `json:"uid"`
Name string `json:"name"`
}
// BasePrice ...
type BasePrice struct {
CurrencySymbol string `json:"currency_symbol"`
Effective float64 `json:"effective"`
Marked float64 `json:"marked"`
CurrencyCode string `json:"currency_code"`
}
// ArticlePriceInfo ...
type ArticlePriceInfo struct {
Converted BasePrice `json:"converted"`
Base BasePrice `json:"base"`
}
// ProductArticle ...
type ProductArticle struct {
Seller BaseInfo `json:"seller"`
Price ArticlePriceInfo `json:"price"`
Type string `json:"type"`
UID string `json:"uid"`
Size string `json:"size"`
ExtraMeta map[string]interface{} `json:"extra_meta"`
Store BaseInfo `json:"store"`
Quantity float64 `json:"quantity"`
}
// ProductAvailability ...
type ProductAvailability struct {
IsValid bool `json:"is_valid"`
OtherStoreQuantity float64 `json:"other_store_quantity"`
Sizes []string `json:"sizes"`
Deliverable bool `json:"deliverable"`
OutOfStock bool `json:"out_of_stock"`
}
// CartProductIdentifer ...
type CartProductIdentifer struct {
Identifier string `json:"identifier"`
}
// CategoryInfo ...
type CategoryInfo struct {
UID float64 `json:"uid"`
Name string `json:"name"`
}
// ActionQuery ...
type ActionQuery struct {
ProductSlug []string `json:"product_slug"`
}
// ProductAction ...
type ProductAction struct {
URL string `json:"url"`
Query ActionQuery `json:"query"`
Type string `json:"type"`
}
// Image ...
type Image struct {
SecureURL string `json:"secure_url"`
AspectRatio string `json:"aspect_ratio"`
URL string `json:"url"`
}
// Product ...
type Product struct {
Categories []CategoryInfo `json:"categories"`
Action ProductAction `json:"action"`
Type string `json:"type"`
UID float64 `json:"uid"`
Slug string `json:"slug"`
Images []Image `json:"images"`
Name string `json:"name"`
Brand BaseInfo `json:"brand"`
}
// CartProductInfo ...
type CartProductInfo struct {
Price ProductPriceInfo `json:"price"`
Message string `json:"message"`
BulkOffer map[string]interface{} `json:"bulk_offer"`
PromoMeta PromoMeta `json:"promo_meta"`
Article ProductArticle `json:"article"`
CouponMessage string `json:"coupon_message"`
Availability ProductAvailability `json:"availability"`
Key string `json:"key"`
Identifiers CartProductIdentifer `json:"identifiers"`
IsSet bool `json:"is_set"`
PricePerUnit ProductPriceInfo `json:"price_per_unit"`
Product Product `json:"product"`
Discount string `json:"discount"`
Quantity float64 `json:"quantity"`
}
// PromiseTimestamp ...
type PromiseTimestamp struct {
Min float64 `json:"min"`
Max float64 `json:"max"`
}
// PromiseFormatted ...
type PromiseFormatted struct {
Min string `json:"min"`
Max string `json:"max"`
}
// ShipmentPromise ...
type ShipmentPromise struct {
Timestamp PromiseTimestamp `json:"timestamp"`
Formatted PromiseFormatted `json:"formatted"`
}
// CartDetailResponse ...
type CartDetailResponse struct {
IsValid bool `json:"is_valid"`
CouponText string `json:"coupon_text"`
Message string `json:"message"`
Currency CartCurrency `json:"currency"`
BreakupValues CartBreakup `json:"breakup_values"`
ID string `json:"id"`
Gstin string `json:"gstin"`
LastModified string `json:"last_modified"`
CheckoutMode string `json:"checkout_mode"`
DeliveryChargeInfo string `json:"delivery_charge_info"`
RestrictCheckout bool `json:"restrict_checkout"`
PaymentSelectionLock PaymentSelectionLock `json:"payment_selection_lock"`
Comment string `json:"comment"`
Items []CartProductInfo `json:"items"`
DeliveryPromise ShipmentPromise `json:"delivery_promise"`
}
// AddProductCart ...
type AddProductCart struct {
ItemID float64 `json:"item_id"`
StoreID float64 `json:"store_id"`
ArticleAssignment map[string]interface{} `json:"article_assignment"`
SellerID float64 `json:"seller_id"`
ArticleID string `json:"article_id"`
Pos bool `json:"pos"`
ExtraMeta map[string]interface{} `json:"extra_meta"`
ItemSize string `json:"item_size"`
Quantity float64 `json:"quantity"`
Display string `json:"display"`
}
// AddCartRequest ...
type AddCartRequest struct {
Items []AddProductCart `json:"items"`
}
// AddCartDetailResponse ...
type AddCartDetailResponse struct {
Partial bool `json:"partial"`
Success bool `json:"success"`
Message string `json:"message"`
Cart CartDetailResponse `json:"cart"`
}
// UpdateProductCart ...
type UpdateProductCart struct {
ItemID float64 `json:"item_id"`
ArticleID string `json:"article_id"`
ExtraMeta map[string]interface{} `json:"extra_meta"`
ItemSize string `json:"item_size"`
ItemIndex float64 `json:"item_index"`
Identifiers CartProductIdentifer `json:"identifiers"`
Quantity float64 `json:"quantity"`
}
// UpdateCartRequest ...
type UpdateCartRequest struct {
Items []UpdateProductCart `json:"items"`
Operation string `json:"operation"`
}
// UpdateCartDetailResponse ...
type UpdateCartDetailResponse struct {
Success bool `json:"success"`
Message string `json:"message"`
Cart CartDetailResponse `json:"cart"`
}
// CartItemCountResponse ...
type CartItemCountResponse struct {
UserCartItemsCount float64 `json:"user_cart_items_count"`
}
// PageCoupon ...
type PageCoupon struct {
TotalItemCount float64 `json:"total_item_count"`
HasPrevious bool `json:"has_previous"`
HasNext bool `json:"has_next"`
Current float64 `json:"current"`
Total float64 `json:"total"`
}
// Coupon ...
type Coupon struct {
IsApplicable bool `json:"is_applicable"`
IsApplied bool `json:"is_applied"`
Message string `json:"message"`
Title string `json:"title"`
MaxDiscountValue float64 `json:"max_discount_value"`
CouponCode string `json:"coupon_code"`
SubTitle string `json:"sub_title"`
ExpiresOn string `json:"expires_on"`
CouponValue float64 `json:"coupon_value"`
MinimumCartValue float64 `json:"minimum_cart_value"`
}
// GetCouponResponse ...
type GetCouponResponse struct {
Page PageCoupon `json:"page"`
AvailableCouponList []Coupon `json:"available_coupon_list"`
}
// ApplyCouponRequest ...
type ApplyCouponRequest struct {
CouponCode string `json:"coupon_code"`
}
// OfferSeller ...
type OfferSeller struct {
UID float64 `json:"uid"`
Name string `json:"name"`
}
// OfferPrice ...
type OfferPrice struct {
CurrencySymbol string `json:"currency_symbol"`
Effective float64 `json:"effective"`
Marked float64 `json:"marked"`
BulkEffective float64 `json:"bulk_effective"`
CurrencyCode string `json:"currency_code"`
}
// OfferItem ...
type OfferItem struct {
Best bool `json:"best"`
Price OfferPrice `json:"price"`
Type string `json:"type"`
AutoApplied bool `json:"auto_applied"`
Margin float64 `json:"margin"`
Quantity float64 `json:"quantity"`
Total float64 `json:"total"`
}
// BulkPriceOffer ...
type BulkPriceOffer struct {
Seller OfferSeller `json:"seller"`
Offers []OfferItem `json:"offers"`
}
// BulkPriceResponse ...
type BulkPriceResponse struct {
Data []BulkPriceOffer `json:"data"`
}
// RewardPointRequest ...
type RewardPointRequest struct {
Points bool `json:"points"`
}
// GeoLocation ...
type GeoLocation struct {
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
}
// Address ...
type Address struct {
Area string `json:"area"`
State string `json:"state"`
Landmark string `json:"landmark"`
GeoLocation GeoLocation `json:"geo_location"`
AddressType string `json:"address_type"`
City string `json:"city"`
CountryCode string `json:"country_code"`
ID string `json:"id"`
GoogleMapPoint map[string]interface{} `json:"google_map_point"`
Phone string `json:"phone"`
Email string `json:"email"`
AreaCodeSlug string `json:"area_code_slug"`
IsDefaultAddress bool `json:"is_default_address"`
Country string `json:"country"`
CheckoutMode string `json:"checkout_mode"`
IsActive bool `json:"is_active"`
AreaCode string `json:"area_code"`
Address string `json:"address"`
Meta map[string]interface{} `json:"meta"`
Name string `json:"name"`
UserID string `json:"user_id"`
Tags []string `json:"tags"`
}
// GetAddressesResponse ...
type GetAddressesResponse struct {
Address []Address `json:"address"`
}
// SaveAddressResponse ...
type SaveAddressResponse struct {
Success bool `json:"success"`
ID string `json:"id"`
IsDefaultAddress bool `json:"is_default_address"`
}
// UpdateAddressResponse ...
type UpdateAddressResponse struct {
IsUpdated bool `json:"is_updated"`
Success bool `json:"success"`
ID string `json:"id"`
IsDefaultAddress bool `json:"is_default_address"`
}
// DeleteAddressResponse ...
type DeleteAddressResponse struct {
IsDeleted bool `json:"is_deleted"`
ID string `json:"id"`
}
// SelectCartAddressRequest ...
type SelectCartAddressRequest struct {
ID string `json:"id"`
CartID string `json:"cart_id"`
BillingAddressID string `json:"billing_address_id"`
}
// UpdateCartPaymentRequest ...
type UpdateCartPaymentRequest struct {
AggregatorName string `json:"aggregator_name"`
PaymentMode string `json:"payment_mode"`
PaymentIdentifier string `json:"payment_identifier"`
MerchantCode string `json:"merchant_code"`
ID string `json:"id"`
AddressID string `json:"address_id"`
}
// CouponValidity ...
type CouponValidity struct {
Valid bool `json:"valid"`
Title string `json:"title"`
DisplayMessageEn string `json:"display_message_en"`
Discount float64 `json:"discount"`
Code string `json:"code"`
}
// PaymentCouponValidate ...
type PaymentCouponValidate struct {
CouponValidity CouponValidity `json:"coupon_validity"`
Success bool `json:"success"`
Message string `json:"message"`
}
// ShipmentResponse ...
type ShipmentResponse struct {
DpOptions map[string]interface{} `json:"dp_options"`
ShipmentType string `json:"shipment_type"`
FulfillmentID float64 `json:"fulfillment_id"`
Shipments float64 `json:"shipments"`
Promise ShipmentPromise `json:"promise"`
DpID float64 `json:"dp_id"`
Items []CartProductInfo `json:"items"`
BoxType string `json:"box_type"`
FulfillmentType string `json:"fulfillment_type"`
OrderType string `json:"order_type"`
}
// CartShipmentsResponse ...
type CartShipmentsResponse struct {
Currency CartCurrency `json:"currency"`
LastModified string `json:"last_modified"`
DeliveryChargeInfo string `json:"delivery_charge_info"`
RestrictCheckout bool `json:"restrict_checkout"`
DeliveryPromise ShipmentPromise `json:"delivery_promise"`
IsValid bool `json:"is_valid"`
CouponText string `json:"coupon_text"`
ID string `json:"id"`
Gstin string `json:"gstin"`
PaymentSelectionLock PaymentSelectionLock `json:"payment_selection_lock"`
Comment string `json:"comment"`
Shipments []ShipmentResponse `json:"shipments"`
Message string `json:"message"`
UID string `json:"uid"`
BreakupValues CartBreakup `json:"breakup_values"`
CheckoutMode string `json:"checkout_mode"`
CartID float64 `json:"cart_id"`
Error bool `json:"error"`
}
// StaffCheckout ...
type StaffCheckout struct {
User string `json:"user"`
LastName string `json:"last_name"`
FirstName string `json:"first_name"`
ID string `json:"_id"`
}
// CartCheckoutDetailRequest ...
type CartCheckoutDetailRequest struct {
PaymentAutoConfirm bool `json:"payment_auto_confirm"`
DeliveryAddress map[string]interface{} `json:"delivery_address"`
PaymentMode string `json:"payment_mode"`
PaymentIdentifier string `json:"payment_identifier"`
MerchantCode string `json:"merchant_code"`
BillingAddressID string `json:"billing_address_id"`
Meta map[string]interface{} `json:"meta"`
FyndstoreEmpID string `json:"fyndstore_emp_id"`
Staff StaffCheckout `json:"staff"`
BillingAddress map[string]interface{} `json:"billing_address"`
ExtraMeta map[string]interface{} `json:"extra_meta"`
AddressID string `json:"address_id"`
PaymentParams map[string]interface{} `json:"payment_params"`
Aggregator string `json:"aggregator"`
OrderingStore float64 `json:"ordering_store"`
CallbackURL string `json:"callback_url"`
}
// CheckCart ...
type CheckCart struct {
Currency CartCurrency `json:"currency"`
LastModified string `json:"last_modified"`
DeliveryChargeInfo string `json:"delivery_charge_info"`
RestrictCheckout bool `json:"restrict_checkout"`
Success bool `json:"success"`
CodCharges float64 `json:"cod_charges"`
DeliveryPromise ShipmentPromise `json:"delivery_promise"`
UserType string `json:"user_type"`
IsValid bool `json:"is_valid"`
CouponText string `json:"coupon_text"`
OrderID string `json:"order_id"`
StoreEmps []map[string]interface{} `json:"store_emps"`
ID string `json:"id"`
Gstin string `json:"gstin"`
PaymentSelectionLock PaymentSelectionLock `json:"payment_selection_lock"`
Comment string `json:"comment"`
Message string `json:"message"`
UID string `json:"uid"`
BreakupValues CartBreakup `json:"breakup_values"`
StoreCode string `json:"store_code"`
ErrorMessage string `json:"error_message"`
CheckoutMode string `json:"checkout_mode"`
CartID float64 `json:"cart_id"`
CodMessage string `json:"cod_message"`
Items []CartProductInfo `json:"items"`
CodAvailable bool `json:"cod_available"`
DeliveryCharges float64 `json:"delivery_charges"`
DeliveryChargeOrderValue float64 `json:"delivery_charge_order_value"`
}
// CartCheckoutResponse ...
type CartCheckoutResponse struct {
Message string `json:"message"`
Cart CheckCart `json:"cart"`
OrderID string `json:"order_id"`
Success bool `json:"success"`
Data map[string]interface{} `json:"data"`
AppInterceptURL string `json:"app_intercept_url"`
CallbackURL string `json:"callback_url"`
}
// CartMetaRequest ...
type CartMetaRequest struct {
Comment string `json:"comment"`
PickUpCustomerDetails map[string]interface{} `json:"pick_up_customer_details"`
CheckoutMode string `json:"checkout_mode"`
Gstin string `json:"gstin"`
}
// CartMetaResponse ...
type CartMetaResponse struct {
Message string `json:"message"`
}
// CartMetaMissingResponse ...
type CartMetaMissingResponse struct {
Errors []string `json:"errors"`
}
// GetShareCartLinkRequest ...
type GetShareCartLinkRequest struct {
UID float64 `json:"uid"`
Meta map[string]interface{} `json:"meta"`
ID string `json:"id"`
}
// GetShareCartLinkResponse ...
type GetShareCartLinkResponse struct {
Token string `json:"token"`
ShareURL string `json:"share_url"`
}
// SharedCartDetails ...
type SharedCartDetails struct {
Meta map[string]interface{} `json:"meta"`
User map[string]interface{} `json:"user"`
CreatedOn string `json:"created_on"`
Token string `json:"token"`
Source map[string]interface{} `json:"source"`
}
// SharedCart ...
type SharedCart struct {
IsValid bool `json:"is_valid"`
CouponText string `json:"coupon_text"`
Message string `json:"message"`
Currency CartCurrency `json:"currency"`
UID string `json:"uid"`
SharedCartDetails SharedCartDetails `json:"shared_cart_details"`
BreakupValues CartBreakup `json:"breakup_values"`
ID string `json:"id"`
Gstin string `json:"gstin"`
LastModified string `json:"last_modified"`
CheckoutMode string `json:"checkout_mode"`
DeliveryChargeInfo string `json:"delivery_charge_info"`
RestrictCheckout bool `json:"restrict_checkout"`
CartID float64 `json:"cart_id"`
Comment string `json:"comment"`
PaymentSelectionLock PaymentSelectionLock `json:"payment_selection_lock"`
Items []CartProductInfo `json:"items"`
DeliveryPromise ShipmentPromise `json:"delivery_promise"`
}
// SharedCartResponse ...
type SharedCartResponse struct {
Error string `json:"error"`
Cart SharedCart `json:"cart"`
}
// LocationDefaultLanguage ...
type LocationDefaultLanguage struct {
Name string `json:"name"`
Code string `json:"code"`
}
// LocationDefaultCurrency ...
type LocationDefaultCurrency struct {
Name string `json:"name"`
Symbol string `json:"symbol"`
Code string `json:"code"`
}
// LocationCountry ...
type LocationCountry struct {
Capital string `json:"capital"`
Currency string `json:"currency"`
Iso2 string `json:"iso2"`
Iso3 string `json:"iso3"`
Name string `json:"name"`
Parent string `json:"parent"`
PhoneCode string `json:"phone_code"`
Type string `json:"type"`
UID float64 `json:"uid"`
V float64 `json:"__v"`
ID string `json:"_id"`
DefaultCurrency LocationDefaultCurrency `json:"default_currency"`
DefaultLanguage LocationDefaultLanguage `json:"default_language"`
}
// Locations ...
type Locations struct {
Items []LocationCountry `json:"items"`
}
// TicketList ...
type TicketList struct {
Items []Ticket `json:"items"`
Filters Filter `json:"filters"`
Page Page `json:"page"`
}
// Page ...
type Page struct {
ItemTotal float64 `json:"item_total"`
NextID string `json:"next_id"`
HasPrevious bool `json:"has_previous"`
HasNext bool `json:"has_next"`
Current float64 `json:"current"`
Type string `json:"type"`
Size float64 `json:"size"`
}
// TicketHistoryList ...
type TicketHistoryList struct {
Items []TicketHistory `json:"items"`
Page Page `json:"page"`
}
// CustomFormList ...
type CustomFormList struct {
Items []CustomForm `json:"items"`
Page Page `json:"page"`
}
// CreateCustomFormPayload ...
type CreateCustomFormPayload struct {
Slug string `json:"slug"`
Title string `json:"title"`
Inputs []map[string]interface{} `json:"inputs"`
Description string `json:"description"`
HeaderImage string `json:"header_image"`
Priority interface{} `json:"priority"`
ShouldNotify bool `json:"should_notify"`
SuccessMessage string `json:"success_message"`
PollForAssignment PollForAssignment `json:"poll_for_assignment"`
}
// EditCustomFormPayload ...
type EditCustomFormPayload struct {
Title string `json:"title"`
Inputs []map[string]interface{} `json:"inputs"`
Description string `json:"description"`
Priority interface{} `json:"priority"`
HeaderImage string `json:"header_image"`
ShouldNotify bool `json:"should_notify"`
LoginRequired bool `json:"login_required"`
SuccessMessage string `json:"success_message"`
PollForAssignment PollForAssignment `json:"poll_for_assignment"`
}
// EditTicketPayload ...
type EditTicketPayload struct {
Content TicketContent `json:"content"`
Category string `json:"category"`
SubCategory string `json:"sub_category"`
Source string `json:"source"`
Status string `json:"status"`
Priority interface{} `json:"priority"`
AssignedTo AgentChangePayload `json:"assigned_to"`
Tags []string `json:"tags"`
}
// AgentChangePayload ...
type AgentChangePayload struct {
AgentID string `json:"agent_id"`
}
// CreateVideoRoomResponse ...
type CreateVideoRoomResponse struct {
UniqueName string `json:"unique_name"`
}
// CloseVideoRoomResponse ...
type CloseVideoRoomResponse struct {
Success bool `json:"success"`
}
// CreateVideoRoomPayload ...
type CreateVideoRoomPayload struct {
UniqueName string `json:"unique_name"`
Notify []NotifyUser `json:"notify"`
}
// NotifyUser ...
type NotifyUser struct {
CountryCode string `json:"country_code"`
PhoneNumber string `json:"phone_number"`
}
// Filter ...
type Filter struct {
Priorities []Priority `json:"priorities"`
Categories []TicketCategory `json:"categories"`
Statuses []Status `json:"statuses"`
Assignees []map[string]interface{} `json:"assignees"`
}
// TicketHistoryPayload ...
type TicketHistoryPayload struct {
Value map[string]interface{} `json:"value"`
Type interface{} `json:"type"`
}
// CustomFormSubmissionPayload ...
type CustomFormSubmissionPayload struct {
Response []KeyValue `json:"response"`
Attachments []TicketAsset `json:"attachments"`
}
// KeyValue ...
type KeyValue struct {
Key string `json:"key"`
Value map[string]interface{} `json:"value"`
}
// GetTokenForVideoRoomResponse ...
type GetTokenForVideoRoomResponse struct {
AccessToken string `json:"access_token"`
}
// GetParticipantsInsideVideoRoomResponse ...
type GetParticipantsInsideVideoRoomResponse struct {
Participants []Participant `json:"participants"`
}
// Participant ...
type Participant struct {
User UserSchema `json:"user"`
Identity string `json:"identity"`
Status string `json:"status"`
}
// PhoneNumber ...
type PhoneNumber struct {
Active bool `json:"active"`
Primary bool `json:"primary"`
Verified bool `json:"verified"`
Phone string `json:"phone"`
CountryCode float64 `json:"country_code"`
}
// Email ...
type Email struct {
Primary bool `json:"primary"`
Verified bool `json:"verified"`
Email string `json:"email"`
Active bool `json:"active"`
}
// Debug ...
type Debug struct {
Source string `json:"source"`
Platform string `json:"platform"`
}
// SubmitCustomFormResponse ...
type SubmitCustomFormResponse struct {
Ticket Ticket `json:"ticket"`
}
// TicketContext ...
type TicketContext struct {
ApplicationID string `json:"application_id"`
CompanyID string `json:"company_id"`
}
// CreatedOn ...
type CreatedOn struct {
UserAgent string `json:"user_agent"`
}
// TicketAsset ...
type TicketAsset struct {
Display string `json:"display"`
Value string `json:"value"`
Type interface{} `json:"type"`
}
// TicketContent ...
type TicketContent struct {
Title string `json:"title"`
Description string `json:"description"`
Attachments []TicketAsset `json:"attachments"`
}
// AddTicketPayload ...
type AddTicketPayload struct {
CreatedBy map[string]interface{} `json:"created_by"`
Status string `json:"status"`
Priority interface{} `json:"priority"`
Category string `json:"category"`
Content TicketContent `json:"content"`
}
// Priority ...
type Priority struct {
Key PriorityEnum `json:"key"`
Display string `json:"display"`
Color string `json:"color"`
}
// Status ...
type Status struct {
Key string `json:"key"`
Display string `json:"display"`
Color string `json:"color"`
}
// TicketCategory ...
type TicketCategory struct {
Key string `json:"key"`
Display string `json:"display"`
Form CustomForm `json:"form"`
SubCategories []TicketSubCategory `json:"sub_categories"`
FeedbackForm TicketFeedbackForm `json:"feedback_form"`
}
// TicketSubCategory ...
type TicketSubCategory struct {
Key string `json:"key"`
Display string `json:"display"`
}
// TicketFeedbackForm ...
type TicketFeedbackForm struct {
Title string `json:"title"`
Display []map[string]interface{} `json:"display"`
}
// TicketFeedbackList ...
type TicketFeedbackList struct {
Items []TicketFeedback `json:"items"`
}
// TicketFeedbackPayload ...
type TicketFeedbackPayload struct {
FormResponse map[string]interface{} `json:"form_response"`
}
// SubmitButton ...
type SubmitButton struct {
Title string `json:"title"`
TitleColor string `json:"title_color"`
BackgroundColor string `json:"background_color"`
}
// PollForAssignment ...
type PollForAssignment struct {
Duration float64 `json:"duration"`
Message string `json:"message"`
SuccessMessage string `json:"success_message"`
FailureMessage string `json:"failure_message"`
}
// CustomForm ...
type CustomForm struct {
ApplicationID string `json:"application_id"`
Slug string `json:"slug"`
HeaderImage string `json:"header_image"`
Title string `json:"title"`
Description string `json:"description"`
Priority Priority `json:"priority"`
LoginRequired bool `json:"login_required"`
ShouldNotify bool `json:"should_notify"`
SuccessMessage string `json:"success_message"`
SubmitButton SubmitButton `json:"submit_button"`
Inputs []map[string]interface{} `json:"inputs"`
CreatedOn CreatedOn `json:"created_on"`
CreatedBy map[string]interface{} `json:"created_by"`
PollForAssignment PollForAssignment `json:"poll_for_assignment"`
ID string `json:"_id"`
}
// FeedbackResponseItem ...
type FeedbackResponseItem struct {
Display string `json:"display"`
Key string `json:"key"`
Value string `json:"value"`
}
// TicketFeedback ...
type TicketFeedback struct {
ID string `json:"_id"`
TicketID string `json:"ticket_id"`
CompanyID string `json:"company_id"`
Response []FeedbackResponseItem `json:"response"`
Category string `json:"category"`
User map[string]interface{} `json:"user"`
UpdatedAt string `json:"updated_at"`
CreatedAt string `json:"created_at"`
}
// TicketHistory ...
type TicketHistory struct {
Type string `json:"type"`
Value map[string]interface{} `json:"value"`
TicketID string `json:"ticket_id"`
CreatedOn CreatedOn `json:"created_on"`
CreatedBy map[string]interface{} `json:"created_by"`
ID string `json:"_id"`
UpdatedAt string `json:"updated_at"`
CreatedAt string `json:"created_at"`
}
// Ticket ...
type Ticket struct {
Context TicketContext `json:"context"`
CreatedOn CreatedOn `json:"created_on"`
ResponseID string `json:"response_id"`
Content TicketContent `json:"content"`
TicketID string `json:"ticket_id"`
Category TicketCategory `json:"category"`
SubCategory TicketSubCategory `json:"sub_category"`
Source interface{} `json:"source"`
Status Status `json:"status"`
Priority Priority `json:"priority"`
CreatedBy map[string]interface{} `json:"created_by"`
AssignedTo map[string]interface{} `json:"assigned_to"`
Tags []string `json:"tags"`
CustomJson map[string]interface{} `json:"_custom_json"`
IsFeedbackPending bool `json:"is_feedback_pending"`
ID string `json:"_id"`
UpdatedAt string `json:"updated_at"`
CreatedAt string `json:"created_at"`
}
// AvailablePageSchema ...
type AvailablePageSchema struct {
Value string `json:"value"`
Text string `json:"text"`
Path string `json:"path"`
Type string `json:"type"`
Sections []AvailablePageSchemaSections `json:"sections"`
SectionsMeta []AvailablePageSectionMetaAttributes `json:"sections_meta"`
Theme string `json:"theme"`
Seo AvailablePageSeo `json:"seo"`
Props []map[string]interface{} `json:"props"`
ID string `json:"_id"`
}
// AvailablePageSectionMetaAttributes ...
type AvailablePageSectionMetaAttributes struct {
Attributes map[string]interface{} `json:"attributes"`
}
// AvailablePageSeo ...
type AvailablePageSeo struct {
Title string `json:"title"`
Description string `json:"description"`
ID string `json:"_id"`
}
// AvailablePageSchemaSections ...
type AvailablePageSchemaSections struct {
Name string `json:"name"`
Label string `json:"label"`
Props map[string]interface{} `json:"props"`
Blocks []map[string]interface{} `json:"blocks"`
Preset map[string]interface{} `json:"preset"`
Predicate AvailablePagePredicate `json:"predicate"`
}
// AvailablePageScreenPredicate ...
type AvailablePageScreenPredicate struct {
Mobile bool `json:"mobile"`
Desktop bool `json:"desktop"`
Tablet bool `json:"tablet"`
}
// AvailablePageUserPredicate ...
type AvailablePageUserPredicate struct {
Authenticated bool `json:"authenticated"`
Anonymous bool `json:"anonymous"`
}
// AvailablePageRoutePredicate ...
type AvailablePageRoutePredicate struct {
Selected string `json:"selected"`
ExactURL string `json:"exact_url"`
Query map[string]interface{} `json:"query"`
}
// AvailablePagePredicate ...
type AvailablePagePredicate struct {
Screen AvailablePageScreenPredicate `json:"screen"`
User AvailablePageUserPredicate `json:"user"`
Route AvailablePageRoutePredicate `json:"route"`
}
// AllAvailablePageSchema ...
type AllAvailablePageSchema struct {
Pages []AvailablePageSchema `json:"pages"`
}
// PaginationSchema ...
type PaginationSchema struct {
Size float64 `json:"size"`
ItemTotal float64 `json:"item_total"`
HasNext bool `json:"has_next"`
Type string `json:"type"`
Current float64 `json:"current"`
}
// ThemesListingResponseSchema ...
type ThemesListingResponseSchema struct {
Items []ThemesSchema `json:"items"`
Page PaginationSchema `json:"page"`
}
// AddThemeRequestSchema ...
type AddThemeRequestSchema struct {
ThemeID string `json:"theme_id"`
}
// UpgradableThemeSchema ...
type UpgradableThemeSchema struct {
ParentTheme string `json:"parent_theme"`
AppliedTheme string `json:"applied_theme"`
Upgrade bool `json:"upgrade"`
}
// FontsSchema ...
type FontsSchema struct {
Items FontsSchemaItems `json:"items"`
Kind string `json:"kind"`
}
// BlitzkriegApiErrorSchema ...
type BlitzkriegApiErrorSchema struct {
Message string `json:"message"`
}
// BlitzkriegNotFoundSchema ...
type BlitzkriegNotFoundSchema struct {
Message string `json:"message"`
}
// BlitzkriegInternalServerErrorSchema ...
type BlitzkriegInternalServerErrorSchema struct {
Message string `json:"message"`
}
// FontsSchemaItems ...
type FontsSchemaItems struct {
Family string `json:"family"`
Variants []string `json:"variants"`
Subsets []string `json:"subsets"`
Version string `json:"version"`
LastModified string `json:"last_modified"`
Files FontsSchemaItemsFiles `json:"files"`
Category string `json:"category"`
Kind string `json:"kind"`
}
// FontsSchemaItemsFiles ...
type FontsSchemaItemsFiles struct {
Regular string `json:"regular"`
Italic string `json:"italic"`
Bold string `json:"bold"`
}
// ThemesSchema ...
type ThemesSchema struct {
Application string `json:"application"`
Applied bool `json:"applied"`
Customized bool `json:"customized"`
Published bool `json:"published"`
Archived bool `json:"archived"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
Version string `json:"version"`
ParentThemeVersion string `json:"parent_theme_version"`
ParentTheme string `json:"parent_theme"`
Information Information `json:"information"`
Tags []string `json:"tags"`
Src Src `json:"src"`
Assets AssetsSchema `json:"assets"`
AvailableSections []availableSectionSchema `json:"available_sections"`
Constants map[string]interface{} `json:"constants"`
Styles map[string]interface{} `json:"styles"`
Config Config `json:"config"`
Settings map[string]interface{} `json:"settings"`
Font Font `json:"font"`
ID string `json:"_id"`
V float64 `json:"__v"`
Colors Colors `json:"colors"`
}
// availableSectionSchema ...
type availableSectionSchema struct {
Blocks []Blocks `json:"blocks"`
Name string `json:"name"`
Label string `json:"label"`
Props []BlocksProps `json:"props"`
}
// Information ...
type Information struct {
Images Images `json:"images"`
Features []string `json:"features"`
Name string `json:"name"`
Description string `json:"description"`
}
// Images ...
type Images struct {
Desktop []string `json:"desktop"`
Android []string `json:"android"`
Ios []string `json:"ios"`
Thumbnail []string `json:"thumbnail"`
}
// Src ...
type Src struct {
Link string `json:"link"`
}
// AssetsSchema ...
type AssetsSchema struct {
UmdJs UmdJs `json:"umd_js"`
CommonJs CommonJs `json:"common_js"`
Css Css `json:"css"`
}
// UmdJs ...
type UmdJs struct {
Link string `json:"link"`
}
// CommonJs ...
type CommonJs struct {
Link string `json:"link"`
}
// Css ...
type Css struct {
Link string `json:"link"`
}
// Seo ...
type Seo struct {
Title string `json:"title"`
Description string `json:"description"`
}
// Sections ...
type Sections struct {
Attributes string `json:"attributes"`
}
// Config ...
type Config struct {
Preset Preset `json:"preset"`
GlobalSchema GlobalSchema `json:"global_schema"`
Current string `json:"current"`
List []ListSchemaItem `json:"list"`
}
// Preset ...
type Preset struct {
Pages []AvailablePageSchema `json:"pages"`
}
// GlobalSchema ...
type GlobalSchema struct {
Props []GlobalSchemaProps `json:"props"`
}
// ListSchemaItem ...
type ListSchemaItem struct {
Global map[string]interface{} `json:"global"`
Page []ConfigPage `json:"page"`
Name string `json:"name"`
}
// Colors ...
type Colors struct {
BgColor string `json:"bg_color"`
PrimaryColor string `json:"primary_color"`
SecondaryColor string `json:"secondary_color"`
AccentColor string `json:"accent_color"`
LinkColor string `json:"link_color"`
ButtonSecondaryColor string `json:"button_secondary_color"`
}
// Custom ...
type Custom struct {
Props map[string]interface{} `json:"props"`
}
// ConfigPage ...
type ConfigPage struct {
Settings map[string]interface{} `json:"settings"`
Page string `json:"page"`
}
// Font ...
type Font struct {
Family string `json:"family"`
Variants Variants `json:"variants"`
}
// Variants ...
type Variants struct {
Medium Medium `json:"medium"`
SemiBold SemiBold `json:"semi_bold"`
Bold Bold `json:"bold"`
Light Light `json:"light"`
Regular Regular `json:"regular"`
}
// Medium ...
type Medium struct {
Name string `json:"name"`
File string `json:"file"`
}
// SemiBold ...
type SemiBold struct {
Name string `json:"name"`
File string `json:"file"`
}
// Bold ...
type Bold struct {
Name string `json:"name"`
File string `json:"file"`
}
// Light ...
type Light struct {
Name string `json:"name"`
File string `json:"file"`
}
// Regular ...
type Regular struct {
Name string `json:"name"`
File string `json:"file"`
}
// Blocks ...
type Blocks struct {
Type string `json:"type"`
Name string `json:"name"`
Props []BlocksProps `json:"props"`
}
// GlobalSchemaProps ...
type GlobalSchemaProps struct {
ID string `json:"id"`
Label string `json:"label"`
Type string `json:"type"`
Category string `json:"category"`
}
// BlocksProps ...
type BlocksProps struct {
ID string `json:"id"`
Label string `json:"label"`
Type string `json:"type"`
}
// EditEmailRequestSchema ...
type EditEmailRequestSchema struct {
Email string `json:"email"`
}
// SendVerificationLinkMobileRequestSchema ...
type SendVerificationLinkMobileRequestSchema struct {
Verified bool `json:"verified"`
Active bool `json:"active"`
CountryCode string `json:"country_code"`
Phone string `json:"phone"`
Primary bool `json:"primary"`
}
// EditMobileRequestSchema ...
type EditMobileRequestSchema struct {
CountryCode string `json:"country_code"`
Phone string `json:"phone"`
}
// EditProfileRequestSchema ...
type EditProfileRequestSchema struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Mobile EditProfileMobileSchema `json:"mobile"`
CountryCode string `json:"country_code"`
Email string `json:"email"`
Gender string `json:"gender"`
Dob string `json:"dob"`
ProfilePicURL string `json:"profile_pic_url"`
AndroidHash string `json:"android_hash"`
Sender string `json:"sender"`
RegisterToken string `json:"register_token"`
}
// EditProfileMobileSchema ...
type EditProfileMobileSchema struct {
Phone string `json:"phone"`
CountryCode string `json:"country_code"`
}
// SendEmailOtpRequestSchema ...
type SendEmailOtpRequestSchema struct {
Email string `json:"email"`
Action string `json:"action"`
Token string `json:"token"`
RegisterToken string `json:"register_token"`
}
// VerifyEmailOtpRequestSchema ...
type VerifyEmailOtpRequestSchema struct {
Email string `json:"email"`
Action string `json:"action"`
RegisterToken string `json:"register_token"`
Otp string `json:"otp"`
}
// VerifyOtpRequestSchema ...
type VerifyOtpRequestSchema struct {
RequestID string `json:"request_id"`
RegisterToken string `json:"register_token"`
Otp string `json:"otp"`
}
// SendMobileOtpRequestSchema ...
type SendMobileOtpRequestSchema struct {
Mobile string `json:"mobile"`
CountryCode string `json:"country_code"`
Action string `json:"action"`
Token string `json:"token"`
AndroidHash string `json:"android_hash"`
Force string `json:"force"`
CaptchaCode string `json:"captcha_code"`
}
// UpdatePasswordRequestSchema ...
type UpdatePasswordRequestSchema struct {
OldPassword string `json:"old_password"`
NewPassword string `json:"new_password"`
}
// FormRegisterRequestSchema ...
type FormRegisterRequestSchema struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Gender string `json:"gender"`
Email string `json:"email"`
Password string `json:"password"`
Phone FormRegisterRequestSchemaPhone `json:"phone"`
RegisterToken string `json:"register_token"`
}
// TokenRequestBodySchema ...
type TokenRequestBodySchema struct {
Token string `json:"token"`
}
// ForgotPasswordRequestSchema ...
type ForgotPasswordRequestSchema struct {
Code string `json:"code"`
Password string `json:"password"`
}
// CodeRequestBodySchema ...
type CodeRequestBodySchema struct {
Code string `json:"code"`
}
// SendResetPasswordEmailRequestSchema ...
type SendResetPasswordEmailRequestSchema struct {
Email string `json:"email"`
CaptchaCode string `json:"captcha_code"`
}
// PasswordLoginRequestSchema ...
type PasswordLoginRequestSchema struct {
CaptchaCode string `json:"captcha_code"`
Password string `json:"password"`
Username string `json:"username"`
}
// SendOtpRequestSchema ...
type SendOtpRequestSchema struct {
CountryCode string `json:"country_code"`
CaptchaCode string `json:"captcha_code"`
Mobile string `json:"mobile"`
}
// OAuthRequestSchema ...
type OAuthRequestSchema struct {
IsSignedIn bool `json:"is_signed_in"`
Oauth2 OAuthRequestSchemaOauth2 `json:"oauth2"`
Profile OAuthRequestSchemaProfile `json:"profile"`
}
// UserObjectSchema ...
type UserObjectSchema struct {
User UserSchema `json:"user"`
}
// AuthSuccess ...
type AuthSuccess struct {
RegisterToken string `json:"register_token"`
UserExists bool `json:"user_exists"`
User UserSchema `json:"user"`
}
// SendOtpResponse ...
type SendOtpResponse struct {
ResendTimer float64 `json:"resend_timer"`
ResendToken string `json:"resend_token"`
Success bool `json:"success"`
RequestID string `json:"request_id"`
Message string `json:"message"`
Mobile string `json:"mobile"`
CountryCode string `json:"country_code"`
Email string `json:"email"`
ResendEmailToken string `json:"resend_email_token"`
RegisterToken string `json:"register_token"`
VerifyEmailOtp bool `json:"verify_email_otp"`
VerifyMobileOtp bool `json:"verify_mobile_otp"`
UserExists bool `json:"user_exists"`
}
// ProfileEditSuccess ...
type ProfileEditSuccess struct {
User UserSchema `json:"user"`
RegisterToken string `json:"register_token"`
UserExists bool `json:"user_exists"`
VerifyEmailLink bool `json:"verify_email_link"`
VerifyEmailOtp bool `json:"verify_email_otp"`
VerifyMobileOtp bool `json:"verify_mobile_otp"`
Email string `json:"email"`
}
// LoginSuccess ...
type LoginSuccess struct {
User UserSchema `json:"user"`
RequestID string `json:"request_id"`
RegisterToken string `json:"register_token"`
}
// VerifyOtpSuccess ...
type VerifyOtpSuccess struct {
User UserSchema `json:"user"`
UserExists bool `json:"user_exists"`
RegisterToken string `json:"register_token"`
}
// ResetPasswordSuccess ...
type ResetPasswordSuccess struct {
Status string `json:"status"`
}
// RegisterFormSuccess ...
type RegisterFormSuccess struct {
Email string `json:"email"`
ResendTimer float64 `json:"resend_timer"`
ResendToken string `json:"resend_token"`
ResendEmailToken string `json:"resend_email_token"`
RegisterToken string `json:"register_token"`
Success bool `json:"success"`
RequestID string `json:"request_id"`
Message string `json:"message"`
Mobile string `json:"mobile"`
CountryCode string `json:"country_code"`
VerifyEmailOtp bool `json:"verify_email_otp"`
VerifyMobileOtp bool `json:"verify_mobile_otp"`
UserExists bool `json:"user_exists"`
}
// VerifyEmailSuccess ...
type VerifyEmailSuccess struct {
Message string `json:"message"`
}
// HasPasswordSuccess ...
type HasPasswordSuccess struct {
Result bool `json:"result"`
}
// LogoutSuccess ...
type LogoutSuccess struct {
Logout bool `json:"logout"`
}
// OtpSuccess ...
type OtpSuccess struct {
ResendTimer float64 `json:"resend_timer"`
ResendToken string `json:"resend_token"`
RegisterToken string `json:"register_token"`
Success bool `json:"success"`
RequestID string `json:"request_id"`
Message string `json:"message"`
Mobile string `json:"mobile"`
CountryCode string `json:"country_code"`
}
// EmailOtpSuccess ...
type EmailOtpSuccess struct {
Success bool `json:"success"`
}
// SessionListSuccess ...
type SessionListSuccess struct {
Sessions []string `json:"sessions"`
}
// VerifyMobileOTPSuccess ...
type VerifyMobileOTPSuccess struct {
User UserSchema `json:"user"`
VerifyMobileLink bool `json:"verify_mobile_link"`
}
// VerifyEmailOTPSuccess ...
type VerifyEmailOTPSuccess struct {
User UserSchema `json:"user"`
VerifyEmailLink bool `json:"verify_email_link"`
}
// SendMobileVerifyLinkSuccess ...
type SendMobileVerifyLinkSuccess struct {
VerifyMobileLink bool `json:"verify_mobile_link"`
}
// SendEmailVerifyLinkSuccess ...
type SendEmailVerifyLinkSuccess struct {
VerifyEmailLink bool `json:"verify_email_link"`
}
// UserSearchResponseSchema ...
type UserSearchResponseSchema struct {
Users []UserSchema `json:"users"`
}
// CustomerListResponseSchema ...
type CustomerListResponseSchema struct {
Items []UserSchema `json:"items"`
Page PaginationSchema `json:"page"`
}
// UnauthorizedSchema ...
type UnauthorizedSchema struct {
Message string `json:"message"`
}
// UnauthenticatedSchema ...
type UnauthenticatedSchema struct {
Authenticated bool `json:"authenticated"`
}
// NotFoundSchema ...
type NotFoundSchema struct {
Message string `json:"message"`
}
// AuthenticationInternalServerErrorSchema ...
type AuthenticationInternalServerErrorSchema struct {
Message string `json:"message"`
}
// AuthenticationApiErrorSchema ...
type AuthenticationApiErrorSchema struct {
Message string `json:"message"`
}
// ProfileEditSuccessSchema ...
type ProfileEditSuccessSchema struct {
Email string `json:"email"`
VerifyEmailOtp bool `json:"verify_email_otp"`
VerifyEmailLink bool `json:"verify_email_link"`
VerifyMobileOtp bool `json:"verify_mobile_otp"`
User string `json:"user"`
RegisterToken string `json:"register_token"`
UserExists bool `json:"user_exists"`
}
// FormRegisterRequestSchemaPhone ...
type FormRegisterRequestSchemaPhone struct {
CountryCode string `json:"country_code"`
Mobile string `json:"mobile"`
}
// OAuthRequestSchemaOauth2 ...
type OAuthRequestSchemaOauth2 struct {
AccessToken string `json:"access_token"`
Expiry float64 `json:"expiry"`
RefreshToken string `json:"refresh_token"`
}
// OAuthRequestSchemaProfile ...
type OAuthRequestSchemaProfile struct {
LastName string `json:"last_name"`
Image string `json:"image"`
ID string `json:"id"`
Email string `json:"email"`
FullName string `json:"full_name"`
FirstName string `json:"first_name"`
}
// AuthSuccessUser ...
type AuthSuccessUser struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Debug AuthSuccessUserDebug `json:"debug"`
Active bool `json:"active"`
Emails AuthSuccessUserEmails `json:"emails"`
}
// AuthSuccessUserDebug ...
type AuthSuccessUserDebug struct {
Platform string `json:"platform"`
}
// AuthSuccessUserEmails ...
type AuthSuccessUserEmails struct {
Email string `json:"email"`
Verified bool `json:"verified"`
Primary bool `json:"primary"`
Active bool `json:"active"`
}
// CreateUserRequestSchema ...
type CreateUserRequestSchema struct {
PhoneNumber string `json:"phone_number"`
Email string `json:"email"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Gender string `json:"gender"`
Username string `json:"username"`
Meta map[string]interface{} `json:"meta"`
}
// CreateUserResponseSchema ...
type CreateUserResponseSchema struct {
User UserSchema `json:"user"`
}
// CreateUserSessionRequestSchema ...
type CreateUserSessionRequestSchema struct {
Domain string `json:"domain"`
MaxAge float64 `json:"max_age"`
UserID string `json:"user_id"`
}
// CreateUserSessionResponseSchema ...
type CreateUserSessionResponseSchema struct {
Domain string `json:"domain"`
MaxAge float64 `json:"max_age"`
Secure bool `json:"secure"`
HttpOnly bool `json:"http_only"`
Cookie map[string]interface{} `json:"cookie"`
}
// PlatformSchema ...
type PlatformSchema struct {
Display string `json:"display"`
LookAndFeel LookAndFeel `json:"look_and_feel"`
UpdatedAt string `json:"updated_at"`
Active bool `json:"active"`
ForgotPassword bool `json:"forgot_password"`
Login Login `json:"login"`
SkipCaptcha bool `json:"skip_captcha"`
Name string `json:"name"`
Meta MetaSchema `json:"meta"`
ID string `json:"_id"`
Social Social `json:"social"`
RequiredFields RequiredFields `json:"required_fields"`
RegisterRequiredFields RegisterRequiredFields `json:"register_required_fields"`
SkipLogin bool `json:"skip_login"`
FlashCard FlashCard `json:"flash_card"`
Subtext string `json:"subtext"`
SocialTokens SocialTokens `json:"social_tokens"`
CreatedAt string `json:"created_at"`
Register bool `json:"register"`
MobileImage string `json:"mobile_image"`
DesktopImage string `json:"desktop_image"`
}
// LookAndFeel ...
type LookAndFeel struct {
CardPosition string `json:"card_position"`
BackgroundColor string `json:"background_color"`
}
// Login ...
type Login struct {
Password bool `json:"password"`
Otp bool `json:"otp"`
}
// MetaSchema ...
type MetaSchema struct {
FyndDefault bool `json:"fynd_default"`
}
// Social ...
type Social struct {
AccountKit bool `json:"account_kit"`
Facebook bool `json:"facebook"`
Google bool `json:"google"`
}
// RequiredFields ...
type RequiredFields struct {
Email PlatformEmail `json:"email"`
Mobile PlatformMobile `json:"mobile"`
}
// PlatformEmail ...
type PlatformEmail struct {
IsRequired bool `json:"is_required"`
Level string `json:"level"`
}
// PlatformMobile ...
type PlatformMobile struct {
IsRequired bool `json:"is_required"`
Level string `json:"level"`
}
// RegisterRequiredFields ...
type RegisterRequiredFields struct {
Email RegisterRequiredFieldsEmail `json:"email"`
Mobile RegisterRequiredFieldsMobile `json:"mobile"`
}
// RegisterRequiredFieldsEmail ...
type RegisterRequiredFieldsEmail struct {
IsRequired bool `json:"is_required"`
Level string `json:"level"`
}
// RegisterRequiredFieldsMobile ...
type RegisterRequiredFieldsMobile struct {
IsRequired bool `json:"is_required"`
Level string `json:"level"`
}
// FlashCard ...
type FlashCard struct {
Text string `json:"text"`
TextColor string `json:"text_color"`
BackgroundColor string `json:"background_color"`
}
// SocialTokens ...
type SocialTokens struct {
Facebook Facebook `json:"facebook"`
AccountKit Accountkit `json:"account_kit"`
Google Google `json:"google"`
}
// Facebook ...
type Facebook struct {
AppID string `json:"app_id"`
}
// Accountkit ...
type Accountkit struct {
AppID string `json:"app_id"`
}
// Google ...
type Google struct {
AppID string `json:"app_id"`
}
// UpdateUserRequestSchema ...
type UpdateUserRequestSchema struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Gender string `json:"gender"`
Meta map[string]interface{} `json:"meta"`
}
// UserSchema ...
type UserSchema struct {
FirstName string `json:"first_name"`
Meta map[string]interface{} `json:"meta"`
LastName string `json:"last_name"`
PhoneNumbers []PhoneNumber `json:"phone_numbers"`
Emails []Email `json:"emails"`
Gender string `json:"gender"`
Dob string `json:"dob"`
Active bool `json:"active"`
ProfilePicURL string `json:"profile_pic_url"`
Username string `json:"username"`
AccountType string `json:"account_type"`
UID string `json:"uid"`
Debug Debug `json:"debug"`
HasOldPasswordHash bool `json:"has_old_password_hash"`
ID string `json:"_id"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
// ApplicationLegal ...
type ApplicationLegal struct {
Application string `json:"application"`
Tnc string `json:"tnc"`
Policy string `json:"policy"`
Shipping string `json:"shipping"`
Faq []ApplicationLegalFAQ `json:"faq"`
ID string `json:"_id"`
UpdatedAt string `json:"updated_at"`
CreatedAt string `json:"created_at"`
}
// ApplicationLegalFAQ ...
type ApplicationLegalFAQ struct {
Question string `json:"question"`
Answer string `json:"answer"`
}
// SeoComponent ...
type SeoComponent struct {
Seo SeoSchema `json:"seo"`
}
// SeoSchema ...
type SeoSchema struct {
App string `json:"app"`
ID string `json:"_id"`
RobotsTxt string `json:"robots_txt"`
SitemapEnabled bool `json:"sitemap_enabled"`
CustomMetaTags []map[string]interface{} `json:"custom_meta_tags"`
Details Detail `json:"details"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
// CustomMetaTag ...
type CustomMetaTag struct {
Name string `json:"name"`
Content string `json:"content"`
ID string `json:"_id"`
}
// Detail ...
type Detail struct {
Title string `json:"title"`
Description string `json:"description"`
}
// AnnouncementPageSchema ...
type AnnouncementPageSchema struct {
PageSlug string `json:"page_slug"`
Type string `json:"type"`
}
// EditorMeta ...
type EditorMeta struct {
ForegroundColor string `json:"foreground_color"`
BackgroundColor string `json:"background_color"`
ContentType string `json:"content_type"`
Content string `json:"content"`
}
// AnnouncementAuthorSchema ...
type AnnouncementAuthorSchema struct {
CreatedBy string `json:"created_by"`
ModifiedBy string `json:"modified_by"`
}
// AdminAnnouncementSchema ...
type AdminAnnouncementSchema struct {
ID string `json:"_id"`
Platforms []string `json:"platforms"`
Title string `json:"title"`
Announcement string `json:"announcement"`
Pages []AnnouncementPageSchema `json:"pages"`
EditorMeta EditorMeta `json:"editor_meta"`
Author AnnouncementAuthorSchema `json:"author"`
CreatedAt string `json:"created_at"`
App string `json:"app"`
ModifiedAt string `json:"modified_at"`
Schedule ScheduleSchema `json:"_schedule"`
}
// ScheduleSchema ...
type ScheduleSchema struct {
Cron string `json:"cron"`
Start string `json:"start"`
End string `json:"end"`
Duration float64 `json:"duration"`
NextSchedule []map[string]interface{} `json:"next_schedule"`
}
// NextSchedule ...
type NextSchedule struct {
Start string `json:"start"`
End string `json:"end"`
}
// AnnouncementSchema ...
type AnnouncementSchema struct {
Announcement string `json:"announcement"`
Schedule ScheduleStartSchema `json:"schedule"`
}
// ScheduleStartSchema ...
type ScheduleStartSchema struct {
Start string `json:"start"`
End string `json:"end"`
}
// BlogGetResponse ...
type BlogGetResponse struct {
Items []BlogSchema `json:"items"`
Page Page `json:"page"`
}
// ResourceContent ...
type ResourceContent struct {
Type string `json:"type"`
Value string `json:"value"`
}
// Asset ...
type Asset struct {
AspectRatio string `json:"aspect_ratio"`
ID string `json:"id"`
SecureURL string `json:"secure_url"`
}
// Author ...
type Author struct {
Designation string `json:"designation"`
ID string `json:"id"`
Name string `json:"name"`
}
// BlogSchema ...
type BlogSchema struct {
ID string `json:"_id"`
CustomJson map[string]interface{} `json:"_custom_json"`
Application string `json:"application"`
Archived bool `json:"archived"`
Author Author `json:"author"`
Content []ResourceContent `json:"content"`
FeatureImage Asset `json:"feature_image"`
Published bool `json:"published"`
ReadingTime string `json:"reading_time"`
Slug string `json:"slug"`
Tags []string `json:"tags"`
Seo SEO `json:"seo"`
Schedule CronSchedule `json:"_schedule"`
Title string `json:"title"`
DateMeta DateMeta `json:"date_meta"`
}
// SEO ...
type SEO struct {
Description string `json:"description"`
Image SEOImage `json:"image"`
Title string `json:"title"`
}
// SEOImage ...
type SEOImage struct {
URL string `json:"url"`
}
// DateMeta ...
type DateMeta struct {
CreatedOn string `json:"created_on"`
ModifiedOn string `json:"modified_on"`
}
// BlogRequest ...
type BlogRequest struct {
Application string `json:"application"`
CustomJson map[string]interface{} `json:"_custom_json"`
Author Author `json:"author"`
Content []ResourceContent `json:"content"`
FeatureImage Asset `json:"feature_image"`
Published bool `json:"published"`
ReadingTime string `json:"reading_time"`
Slug string `json:"slug"`
Tags []string `json:"tags"`
Title string `json:"title"`
Seo SEO `json:"seo"`
Schedule CronSchedule `json:"_schedule"`
}
// GetAnnouncementListSchema ...
type GetAnnouncementListSchema struct {
Items []AdminAnnouncementSchema `json:"items"`
Page Page `json:"page"`
}
// CreateAnnouncementSchema ...
type CreateAnnouncementSchema struct {
Message string `json:"message"`
Data AdminAnnouncementSchema `json:"data"`
}
// Navigation ...
type Navigation struct {
Name string `json:"name"`
Slug string `json:"slug"`
Orientation string `json:"orientation"`
CreatedBy CreatedBySchema `json:"created_by"`
DateMeta DateMeta `json:"date_meta"`
ID string `json:"_id"`
Position string `json:"position"`
Application string `json:"application"`
Platform string `json:"platform"`
Navigation NavigationReference `json:"navigation"`
}
// LocaleLanguage ...
type LocaleLanguage struct {
Hi Language `json:"hi"`
Ar Language `json:"ar"`
EnUs Language `json:"en_us"`
}
// Language ...
type Language struct {
Display string `json:"display"`
}
// Action ...
type Action struct {
Page ActionPage `json:"page"`
Popup ActionPage `json:"popup"`
Type string `json:"type"`
}
// ActionPage ...
type ActionPage struct {
Params map[string][]string `json:"params"`
Query map[string][]string `json:"query"`
URL string `json:"url"`
Type string `json:"type"`
}
// NavigationReference ...
type NavigationReference struct {
Acl []string `json:"acl"`
Tags []string `json:"tags"`
LocaleLanguage LocaleLanguage `json:"_locale_language"`
Image string `json:"image"`
Type string `json:"type"`
Action Action `json:"action"`
Active bool `json:"active"`
Display string `json:"display"`
SortOrder float64 `json:"sort_order"`
SubNavigation []NavigationReference `json:"sub_navigation"`
}
// LandingPage ...
type LandingPage struct {
Data LandingPageSchema `json:"data"`
Success bool `json:"success"`
}
// ConfigurationSchema ...
type ConfigurationSchema struct {
SleepTime float64 `json:"sleep_time"`
StartOnLaunch bool `json:"start_on_launch"`
Duration float64 `json:"duration"`
SlideDirection string `json:"slide_direction"`
}
// SlideshowMedia ...
type SlideshowMedia struct {
Type string `json:"type"`
URL string `json:"url"`
BgColor string `json:"bg_color"`
Duration float64 `json:"duration"`
AutoDecideDuration bool `json:"auto_decide_duration"`
Action Action `json:"action"`
}
// Slideshow ...
type Slideshow struct {
Data SlideshowSchema `json:"data"`
Success bool `json:"success"`
}
// AnnouncementsResponseSchema ...
type AnnouncementsResponseSchema struct {
Announcements map[string][]AnnouncementSchema `json:"announcements"`
RefreshRate float64 `json:"refresh_rate"`
RefreshPages []string `json:"refresh_pages"`
}
// FaqResponseSchema ...
type FaqResponseSchema struct {
Faqs []FaqSchema `json:"faqs"`
}
// UpdateHandpickedSchema ...
type UpdateHandpickedSchema struct {
Tag HandpickedTagSchema `json:"tag"`
}
// HandpickedTagSchema ...
type HandpickedTagSchema struct {
Position string `json:"position"`
Attributes map[string]interface{} `json:"attributes"`
Name string `json:"name"`
URL string `json:"url"`
Type string `json:"type"`
SubType string `json:"sub_type"`
Content string `json:"content"`
}
// RemoveHandpickedSchema ...
type RemoveHandpickedSchema struct {
Tags []string `json:"tags"`
}
// CreateTagSchema ...
type CreateTagSchema struct {
Name string `json:"name"`
SubType string `json:"sub_type"`
ID string `json:"_id"`
Type string `json:"type"`
URL string `json:"url"`
Position string `json:"position"`
Attributes map[string]interface{} `json:"attributes"`
Content string `json:"content"`
}
// CreateTagRequestSchema ...
type CreateTagRequestSchema struct {
Tags []CreateTagSchema `json:"tags"`
}
// APIError ...
type APIError struct {
Message string `json:"message"`
Status float64 `json:"status"`
Code string `json:"code"`
Exception string `json:"exception"`
Info string `json:"info"`
RequestID string `json:"request_id"`
StackTrace string `json:"stack_trace"`
Meta map[string]interface{} `json:"meta"`
}
// CategorySchema ...
type CategorySchema struct {
Index float64 `json:"index"`
Title string `json:"title"`
Description string `json:"description"`
Children []string `json:"children"`
ID string `json:"_id"`
Slug string `json:"slug"`
Application string `json:"application"`
IconURL string `json:"icon_url"`
CustomJson map[string]interface{} `json:"_custom_json"`
}
// ChildrenSchema ...
type ChildrenSchema struct {
Question string `json:"question"`
Answer string `json:"answer"`
Slug string `json:"slug"`
Application string `json:"application"`
ID string `json:"_id"`
}
// CategoryRequestSchema ...
type CategoryRequestSchema struct {
Slug string `json:"slug"`
Title string `json:"title"`
}
// FAQCategorySchema ...
type FAQCategorySchema struct {
Index float64 `json:"index"`
Title string `json:"title"`
Description string `json:"description"`
Children []ChildrenSchema `json:"children"`
ID string `json:"_id"`
Slug string `json:"slug"`
Application string `json:"application"`
IconURL string `json:"icon_url"`
CustomJson map[string]interface{} `json:"_custom_json"`
}
// FaqSchema ...
type FaqSchema struct {
Slug string `json:"slug"`
Application string `json:"application"`
ID string `json:"_id"`
Question string `json:"question"`
Answer string `json:"answer"`
}
// FAQ ...
type FAQ struct {
Slug string `json:"slug"`
Question string `json:"question"`
Answer string `json:"answer"`
}
// CreateFaqResponseSchema ...
type CreateFaqResponseSchema struct {
Faq FaqSchema `json:"faq"`
}
// CreateFaqSchema ...
type CreateFaqSchema struct {
Faq FAQ `json:"faq"`
}
// GetFaqSchema ...
type GetFaqSchema struct {
Faqs []map[string]interface{} `json:"faqs"`
}
// UpdateFaqCategoryRequestSchema ...
type UpdateFaqCategoryRequestSchema struct {
Category CategorySchema `json:"category"`
}
// CreateFaqCategoryRequestSchema ...
type CreateFaqCategoryRequestSchema struct {
Category CategoryRequestSchema `json:"category"`
}
// CreateFaqCategorySchema ...
type CreateFaqCategorySchema struct {
Category CategorySchema `json:"category"`
}
// GetFaqCategoriesSchema ...
type GetFaqCategoriesSchema struct {
Categories []CategorySchema `json:"categories"`
}
// GetFaqCategoryBySlugSchema ...
type GetFaqCategoryBySlugSchema struct {
Category FAQCategorySchema `json:"category"`
}
// LandingPageGetResponse ...
type LandingPageGetResponse struct {
Items []LandingPageSchema `json:"items"`
Page Page `json:"page"`
}
// LandingPageSchema ...
type LandingPageSchema struct {
Slug string `json:"slug"`
Action Action `json:"action"`
Platform []string `json:"platform"`
CreatedBy CreatedBySchema `json:"created_by"`
DateMeta DateMeta `json:"date_meta"`
ID string `json:"_id"`
Application string `json:"application"`
Archived bool `json:"archived"`
CustomJson map[string]interface{} `json:"_custom_json"`
}
// DefaultNavigationResponse ...
type DefaultNavigationResponse struct {
Items []NavigationSchema `json:"items"`
}
// NavigationGetResponse ...
type NavigationGetResponse struct {
Items []NavigationSchema `json:"items"`
Page Page `json:"page"`
}
// Orientation ...
type Orientation struct {
Portrait []string `json:"portrait"`
Landscape []string `json:"landscape"`
}
// NavigationSchema ...
type NavigationSchema struct {
ID string `json:"_id"`
Application string `json:"application"`
Archived bool `json:"archived"`
Name string `json:"name"`
Slug string `json:"slug"`
Platform []string `json:"platform"`
CreatedBy CreatedBySchema `json:"created_by"`
DateMeta DateMeta `json:"date_meta"`
Orientation Orientation `json:"orientation"`
Version float64 `json:"version"`
Navigation []NavigationReference `json:"navigation"`
}
// NavigationRequest ...
type NavigationRequest struct {
Name string `json:"name"`
Slug string `json:"slug"`
Platform []string `json:"platform"`
Orientation Orientation `json:"orientation"`
Navigation []NavigationReference `json:"navigation"`
}
// CustomPageSchema ...
type CustomPageSchema struct {
ID string `json:"_id"`
Platform string `json:"platform"`
Title string `json:"title"`
Slug string `json:"slug"`
Type string `json:"type"`
Orientation string `json:"orientation"`
Application string `json:"application"`
Description string `json:"description"`
Published bool `json:"published"`
Tags []string `json:"tags"`
Content []map[string]interface{} `json:"content"`
CreatedBy CreatedBySchema `json:"created_by"`
DateMeta DateMeta `json:"date_meta"`
Schedule ScheduleSchema `json:"_schedule"`
}
// ContentSchema ...
type ContentSchema struct {
Type string `json:"type"`
Value map[string]interface{} `json:"value"`
}
// CustomPage ...
type CustomPage struct {
Data CustomPageSchema `json:"data"`
}
// FeatureImage ...
type FeatureImage struct {
SecureURL string `json:"secure_url"`
}
// PageGetResponse ...
type PageGetResponse struct {
Items []PageSchema `json:"items"`
Page Page `json:"page"`
}
// PageSpec ...
type PageSpec struct {
Specifications []map[string]interface{} `json:"specifications"`
}
// PageSpecParam ...
type PageSpecParam struct {
Key string `json:"key"`
Required bool `json:"required"`
}
// PageSpecItem ...
type PageSpecItem struct {
PageType string `json:"page_type"`
DisplayName string `json:"display_name"`
Params []PageSpecParam `json:"params"`
Query []PageSpecParam `json:"query"`
}
// PageSchema ...
type PageSchema struct {
ID string `json:"_id"`
Application string `json:"application"`
ComponentIds []string `json:"component_ids"`
Content []map[string]interface{} `json:"content"`
CreatedBy CreatedBySchema `json:"created_by"`
DateMeta DateMeta `json:"date_meta"`
Description string `json:"description"`
FeatureImage Asset `json:"feature_image"`
PageMeta []PageMeta `json:"page_meta"`
Schedule ScheduleSchema `json:"_schedule"`
CustomJson map[string]interface{} `json:"_custom_json"`
Orientation string `json:"orientation"`
Platform string `json:"platform"`
Published bool `json:"published"`
Slug string `json:"slug"`
Tags []string `json:"tags"`
Title string `json:"title"`
Type string `json:"type"`
Seo SEO `json:"seo"`
Visibility map[string]interface{} `json:"visibility"`
Archived bool `json:"archived"`
}
// CreatedBySchema ...
type CreatedBySchema struct {
ID string `json:"id"`
}
// PageContent ...
type PageContent struct {
Type string `json:"type"`
Value map[string]interface{} `json:"value"`
}
// PageMeta ...
type PageMeta struct {
Key string `json:"key"`
Value map[string]interface{} `json:"value"`
}
// PageRequest ...
type PageRequest struct {
Schedule CronSchedule `json:"_schedule"`
Application string `json:"application"`
Author Author `json:"author"`
CustomJson map[string]interface{} `json:"_custom_json"`
Orientation string `json:"orientation"`
Content []map[string]interface{} `json:"content"`
FeatureImage Asset `json:"feature_image"`
Published bool `json:"published"`
ReadingTime string `json:"reading_time"`
Slug string `json:"slug"`
Tags []string `json:"tags"`
Seo SEO `json:"seo"`
Title string `json:"title"`
}
// CronSchedule ...
type CronSchedule struct {
Cron string `json:"cron"`
Start string `json:"start"`
End string `json:"end"`
Duration float64 `json:"duration"`
}
// PagePublishRequest ...
type PagePublishRequest struct {
Publish bool `json:"publish"`
}
// PageMetaSchema ...
type PageMetaSchema struct {
SystemPages []NavigationSchema `json:"system_pages"`
CustomPages []PageSchema `json:"custom_pages"`
ApplicationID string `json:"application_id"`
}
// SlideshowGetResponse ...
type SlideshowGetResponse struct {
Items []SlideshowSchema `json:"items"`
Page Page `json:"page"`
}
// SlideshowSchema ...
type SlideshowSchema struct {
ID string `json:"_id"`
Slug string `json:"slug"`
DateMeta DateMeta `json:"date_meta"`
Application string `json:"application"`
Platform string `json:"platform"`
Configuration ConfigurationSchema `json:"configuration"`
Media []SlideshowMedia `json:"media"`
Active bool `json:"active"`
Archived bool `json:"archived"`
CustomJson map[string]interface{} `json:"_custom_json"`
}
// SlideshowRequest ...
type SlideshowRequest struct {
Slug string `json:"slug"`
Platform string `json:"platform"`
Configuration ConfigurationSchema `json:"configuration"`
Media SlideshowMedia `json:"media"`
Active bool `json:"active"`
}
// Support ...
type Support struct {
Created bool `json:"created"`
ID string `json:"_id"`
ConfigType string `json:"config_type"`
Application string `json:"application"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
Contact ContactSchema `json:"contact"`
}
// PhoneProperties ...
type PhoneProperties struct {
Key string `json:"key"`
Code string `json:"code"`
Number string `json:"number"`
}
// PhoneSchema ...
type PhoneSchema struct {
Active bool `json:"active"`
Phone []PhoneProperties `json:"phone"`
}
// EmailProperties ...
type EmailProperties struct {
Key string `json:"key"`
Value string `json:"value"`
}
// EmailSchema ...
type EmailSchema struct {
Active bool `json:"active"`
Email []EmailProperties `json:"email"`
}
// ContactSchema ...
type ContactSchema struct {
Phone PhoneSchema `json:"phone"`
Email EmailSchema `json:"email"`
}
// TagsSchema ...
type TagsSchema struct {
Application string `json:"application"`
ID string `json:"_id"`
Tags []TagSchema `json:"tags"`
}
// TagSchema ...
type TagSchema struct {
Name string `json:"name"`
URL string `json:"url"`
Type string `json:"type"`
SubType string `json:"sub_type"`
ID string `json:"_id"`
Position string `json:"position"`
Attributes map[string]interface{} `json:"attributes"`
Content string `json:"content"`
}
// CommunicationConsentReq ...
type CommunicationConsentReq struct {
Response string `json:"response"`
Action string `json:"action"`
Channel string `json:"channel"`
}
// CommunicationConsentRes ...
type CommunicationConsentRes struct {
AppID string `json:"app_id"`
UserID string `json:"user_id"`
Channels CommunicationConsentChannels `json:"channels"`
}
// CommunicationConsentChannelsEmail ...
type CommunicationConsentChannelsEmail struct {
Response string `json:"response"`
DisplayName string `json:"display_name"`
}
// CommunicationConsentChannelsSms ...
type CommunicationConsentChannelsSms struct {
Response string `json:"response"`
DisplayName string `json:"display_name"`
}
// CommunicationConsentChannelsWhatsapp ...
type CommunicationConsentChannelsWhatsapp struct {
Response string `json:"response"`
DisplayName string `json:"display_name"`
CountryCode string `json:"country_code"`
PhoneNumber string `json:"phone_number"`
}
// CommunicationConsentChannels ...
type CommunicationConsentChannels struct {
Email CommunicationConsentChannelsEmail `json:"email"`
Sms CommunicationConsentChannelsSms `json:"sms"`
Whatsapp CommunicationConsentChannelsWhatsapp `json:"whatsapp"`
}
// CommunicationConsent ...
type CommunicationConsent struct {
AppID string `json:"app_id"`
UserID string `json:"user_id"`
Channels CommunicationConsentChannels `json:"channels"`
}
// PushtokenReq ...
type PushtokenReq struct {
Action string `json:"action"`
BundleIdentifier string `json:"bundle_identifier"`
PushToken string `json:"push_token"`
UniqueDeviceID string `json:"unique_device_id"`
Type string `json:"type"`
}
// PushtokenRes ...
type PushtokenRes struct {
ID string `json:"_id"`
BundleIdentifier string `json:"bundle_identifier"`
PushToken string `json:"push_token"`
UniqueDeviceID string `json:"unique_device_id"`
Type string `json:"type"`
Platform string `json:"platform"`
ApplicationID string `json:"application_id"`
UserID string `json:"user_id"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
ExpiredAt string `json:"expired_at"`
}
// QRCodeResp ...
type QRCodeResp struct {
Link string `json:"link"`
Svg string `json:"svg"`
}
// RedirectDevice ...
type RedirectDevice struct {
Link string `json:"link"`
Type string `json:"type"`
}
// WebRedirect ...
type WebRedirect struct {
Link string `json:"link"`
Type string `json:"type"`
}
// Redirects ...
type Redirects struct {
Ios RedirectDevice `json:"ios"`
Android RedirectDevice `json:"android"`
Web WebRedirect `json:"web"`
ForceWeb bool `json:"force_web"`
}
// CampaignShortLink ...
type CampaignShortLink struct {
Source string `json:"source"`
Medium string `json:"medium"`
}
// Attribution ...
type Attribution struct {
CampaignCookieExpiry string `json:"campaign_cookie_expiry"`
}
// SocialMediaTags ...
type SocialMediaTags struct {
Title string `json:"title"`
Description string `json:"description"`
Image string `json:"image"`
}
// ShortLinkReq ...
type ShortLinkReq struct {
Title string `json:"title"`
URL string `json:"url"`
Hash string `json:"hash"`
Active bool `json:"active"`
ExpireAt string `json:"expire_at"`
EnableTracking bool `json:"enable_tracking"`
Personalized bool `json:"personalized"`
Campaign CampaignShortLink `json:"campaign"`
Redirects Redirects `json:"redirects"`
Attribution Attribution `json:"attribution"`
SocialMediaTags SocialMediaTags `json:"social_media_tags"`
Count float64 `json:"count"`
}
// UrlInfo ...
type UrlInfo struct {
Original string `json:"original"`
Short string `json:"short"`
Hash string `json:"hash"`
}
// ShortLinkRes ...
type ShortLinkRes struct {
Title string `json:"title"`
URL UrlInfo `json:"url"`
CreatedBy string `json:"created_by"`
AppRedirect bool `json:"app_redirect"`
Fallback string `json:"fallback"`
Active bool `json:"active"`
ID string `json:"_id"`
EnableTracking bool `json:"enable_tracking"`
ExpireAt string `json:"expire_at"`
Application string `json:"application"`
UserID string `json:"user_id"`
CreatedAt string `json:"created_at"`
Meta map[string]interface{} `json:"meta"`
UpdatedAt string `json:"updated_at"`
Personalized bool `json:"personalized"`
Campaign CampaignShortLink `json:"campaign"`
Redirects Redirects `json:"redirects"`
Attribution Attribution `json:"attribution"`
SocialMediaTags SocialMediaTags `json:"social_media_tags"`
Count float64 `json:"count"`
}
// ShortLinkList ...
type ShortLinkList struct {
Items []ShortLinkRes `json:"items"`
Page Page `json:"page"`
}
// ErrorRes ...
type ErrorRes struct {
Message string `json:"message"`
}
// FailedResponse ...
type FailedResponse struct {
Message string `json:"message"`
}
// CDN ...
type CDN struct {
URL string `json:"url"`
}
// Upload ...
type Upload struct {
Expiry float64 `json:"expiry"`
URL string `json:"url"`
}
// StartResponse ...
type StartResponse struct {
FileName string `json:"file_name"`
FilePath string `json:"file_path"`
ContentType string `json:"content_type"`
Method string `json:"method"`
Namespace string `json:"namespace"`
Operation string `json:"operation"`
Size float64 `json:"size"`
Upload Upload `json:"upload"`
Cdn CDN `json:"cdn"`
Tags []string `json:"tags"`
}
// StartRequest ...
type StartRequest struct {
FileName string `json:"file_name"`
ContentType string `json:"content_type"`
Size float64 `json:"size"`
Tags []string `json:"tags"`
Params map[string]interface{} `json:"params"`
}
// CompleteResponse ...
type CompleteResponse struct {
ID string `json:"_id"`
FileName string `json:"file_name"`
FilePath string `json:"file_path"`
ContentType string `json:"content_type"`
Method string `json:"method"`
Namespace string `json:"namespace"`
Operation string `json:"operation"`
Size float64 `json:"size"`
Upload Upload `json:"upload"`
Cdn CDN `json:"cdn"`
Success string `json:"success"`
Tags []string `json:"tags"`
CreatedOn string `json:"created_on"`
ModifiedOn string `json:"modified_on"`
}
// Opts ...
type Opts struct {
Attempts float64 `json:"attempts"`
Timestamp float64 `json:"timestamp"`
Delay float64 `json:"delay"`
}
// CopyFileTask ...
type CopyFileTask struct {
ID string `json:"id"`
Name string `json:"name"`
Data BulkRequest `json:"data"`
Opts Opts `json:"opts"`
Progress float64 `json:"progress"`
Delay float64 `json:"delay"`
Timestamp float64 `json:"timestamp"`
AttemptsMade float64 `json:"attempts_made"`
Stacktrace []string `json:"stacktrace"`
FinishedOn float64 `json:"finished_on"`
ProcessedOn float64 `json:"processed_on"`
}
// BulkResponse ...
type BulkResponse struct {
TrackingURL string `json:"tracking_url"`
Task CopyFileTask `json:"task"`
}
// ReqConfiguration ...
type ReqConfiguration struct {
Concurrency float64 `json:"concurrency"`
}
// Destination ...
type Destination struct {
Namespace string `json:"namespace"`
Rewrite string `json:"rewrite"`
Basepath string `json:"basepath"`
}
// BulkRequest ...
type BulkRequest struct {
Urls []string `json:"urls"`
Destination Destination `json:"destination"`
Configuration ReqConfiguration `json:"configuration"`
}
// Urls ...
type Urls struct {
URL string `json:"url"`
SignedURL string `json:"signed_url"`
Expiry float64 `json:"expiry"`
}
// SignUrlResponse ...
type SignUrlResponse struct {
Urls []Urls `json:"urls"`
}
// SignUrlRequest ...
type SignUrlRequest struct {
Expiry float64 `json:"expiry"`
Urls []string `json:"urls"`
}
// DbRecord ...
type DbRecord struct {
Success bool `json:"success"`
Tags []string `json:"tags"`
ID string `json:"_id"`
FileName string `json:"file_name"`
Operation string `json:"operation"`
Namespace string `json:"namespace"`
ContentType string `json:"content_type"`
FilePath string `json:"file_path"`
Upload Upload `json:"upload"`
Cdn CDN `json:"cdn"`
CreatedOn string `json:"created_on"`
ModifiedOn string `json:"modified_on"`
}
// BrowseResponse ...
type BrowseResponse struct {
Items []DbRecord `json:"items"`
Page Page `json:"page"`
}
// ApplicationAboutResponse ...
type ApplicationAboutResponse struct {
ApplicationInfo ApplicationInfo `json:"application_info"`
CompanyInfo CompanyInfo `json:"company_info"`
OwnerInfo OwnerInfo `json:"owner_info"`
}
// ApplicationInfo ...
type ApplicationInfo struct {
ID string `json:"_id"`
Domain Domain `json:"domain"`
Website ApplicationWebsite `json:"website"`
Cors ApplicationCors `json:"cors"`
Description string `json:"description"`
Name string `json:"name"`
Meta ApplicationMeta `json:"meta"`
Token string `json:"token"`
Secret string `json:"secret"`
CreatedAt string `json:"created_at"`
Banner SecureUrl `json:"banner"`
Logo SecureUrl `json:"logo"`
IsActive bool `json:"is_active"`
}
// CompanyInfo ...
type CompanyInfo struct {
ID string `json:"_id"`
UID float64 `json:"uid"`
CreatedOn string `json:"created_on"`
IsActive bool `json:"is_active"`
Name string `json:"name"`
Addresses []CompanyAboutAddress `json:"addresses"`
NotificationEmails []string `json:"notification_emails"`
}
// OwnerInfo ...
type OwnerInfo struct {
ID string `json:"_id"`
Emails []UserEmail `json:"emails"`
PhoneNumbers []UserPhoneNumber `json:"phone_numbers"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
ProfilePic string `json:"profile_pic"`
}
// AppVersionRequest ...
type AppVersionRequest struct {
Application ApplicationVersionRequest `json:"application"`
Device Device `json:"device"`
Locale string `json:"locale"`
Timezone string `json:"timezone"`
}
// ApplicationVersionRequest ...
type ApplicationVersionRequest struct {
ID string `json:"id"`
Name string `json:"name"`
Namespace string `json:"namespace"`
Token string `json:"token"`
Version string `json:"version"`
}
// Device ...
type Device struct {
Build float64 `json:"build"`
Model string `json:"model"`
Os OS `json:"os"`
}
// OS ...
type OS struct {
Name string `json:"name"`
Version string `json:"version"`
}
// SupportedLanguage ...
type SupportedLanguage struct {
Name string `json:"name"`
Code string `json:"code"`
}
// LanguageResponse ...
type LanguageResponse struct {
Items []SupportedLanguage `json:"items"`
}
// AppStaffResponse ...
type AppStaffResponse struct {
StaffUsers []AppStaff `json:"staff_users"`
}
// UpdateDialog ...
type UpdateDialog struct {
Type string `json:"type"`
Interval float64 `json:"interval"`
}
// OrderingStoreSelectRequest ...
type OrderingStoreSelectRequest struct {
OrderingStore OrderingStoreSelect `json:"ordering_store"`
}
// OrderingStoreSelect ...
type OrderingStoreSelect struct {
UID float64 `json:"uid"`
}
// AppStaff ...
type AppStaff struct {
ID string `json:"_id"`
OrderIncent bool `json:"order_incent"`
Stores []float64 `json:"stores"`
Application string `json:"application"`
Title string `json:"title"`
User string `json:"user"`
EmployeeCode string `json:"employee_code"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
ProfilePicURL string `json:"profile_pic_url"`
}
// AppTokenResponse ...
type AppTokenResponse struct {
Tokens Tokens `json:"tokens"`
ID string `json:"_id"`
Application string `json:"application"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
V float64 `json:"__v"`
}
// Tokens ...
type Tokens struct {
Firebase Firebase `json:"firebase"`
Moengage Moengage `json:"moengage"`
Segment Segment `json:"segment"`
Gtm Gtm `json:"gtm"`
Freshchat Freshchat `json:"freshchat"`
Safetynet Safetynet `json:"safetynet"`
FyndRewards FyndRewards `json:"fynd_rewards"`
GoogleMap GoogleMap `json:"google_map"`
}
// Firebase ...
type Firebase struct {
Credentials Credentials `json:"credentials"`
Enabled bool `json:"enabled"`
}
// Credentials ...
type Credentials struct {
Ios Ios `json:"ios"`
Android Android `json:"android"`
ProjectID string `json:"project_id"`
GcmSenderID string `json:"gcm_sender_id"`
ApplicationID string `json:"application_id"`
APIKey string `json:"api_key"`
}
// Ios ...
type Ios struct {
ApplicationID string `json:"application_id"`
APIKey string `json:"api_key"`
}
// Android ...
type Android struct {
ApplicationID string `json:"application_id"`
APIKey string `json:"api_key"`
}
// Moengage ...
type Moengage struct {
Credentials MoengageCredentials `json:"credentials"`
Enabled bool `json:"enabled"`
}
// MoengageCredentials ...
type MoengageCredentials struct {
AppID string `json:"app_id"`
}
// Segment ...
type Segment struct {
Credentials SegmentCredentials `json:"credentials"`
Enabled bool `json:"enabled"`
}
// SegmentCredentials ...
type SegmentCredentials struct {
WriteKey string `json:"write_key"`
}
// Gtm ...
type Gtm struct {
Credentials GtmCredentials `json:"credentials"`
Enabled bool `json:"enabled"`
}
// GtmCredentials ...
type GtmCredentials struct {
APIKey string `json:"api_key"`
}
// Freshchat ...
type Freshchat struct {
Credentials FreshchatCredentials `json:"credentials"`
Enabled bool `json:"enabled"`
}
// FreshchatCredentials ...
type FreshchatCredentials struct {
AppID string `json:"app_id"`
AppKey string `json:"app_key"`
WebToken string `json:"web_token"`
}
// Safetynet ...
type Safetynet struct {
Credentials SafetynetCredentials `json:"credentials"`
Enabled bool `json:"enabled"`
}
// SafetynetCredentials ...
type SafetynetCredentials struct {
APIKey string `json:"api_key"`
}
// FyndRewards ...
type FyndRewards struct {
Credentials FyndRewardsCredentials `json:"credentials"`
}
// FyndRewardsCredentials ...
type FyndRewardsCredentials struct {
PublicKey string `json:"public_key"`
}
// GoogleMap ...
type GoogleMap struct {
Credentials GoogleMapCredentials `json:"credentials"`
}
// GoogleMapCredentials ...
type GoogleMapCredentials struct {
APIKey string `json:"api_key"`
}
// RewardPointsConfig ...
type RewardPointsConfig struct {
Credit Credit `json:"credit"`
Debit Debit `json:"debit"`
}
// Credit ...
type Credit struct {
Enabled bool `json:"enabled"`
}
// Debit ...
type Debit struct {
Enabled bool `json:"enabled"`
AutoApply bool `json:"auto_apply"`
StrategyChannel string `json:"strategy_channel"`
}
// ProductDetailFeature ...
type ProductDetailFeature struct {
Similar []string `json:"similar"`
SellerSelection bool `json:"seller_selection"`
UpdateProductMeta bool `json:"update_product_meta"`
RequestProduct bool `json:"request_product"`
}
// LaunchPage ...
type LaunchPage struct {
PageType string `json:"page_type"`
Params map[string]interface{} `json:"params"`
Query map[string]interface{} `json:"query"`
}
// LandingPageFeature ...
type LandingPageFeature struct {
LaunchPage LaunchPage `json:"launch_page"`
ContinueAsGuest bool `json:"continue_as_guest"`
LoginBtnText string `json:"login_btn_text"`
ShowDomainTextbox bool `json:"show_domain_textbox"`
ShowRegisterBtn bool `json:"show_register_btn"`
}
// RegistrationPageFeature ...
type RegistrationPageFeature struct {
AskStoreAddress bool `json:"ask_store_address"`
}
// AppFeature ...
type AppFeature struct {
ProductDetail ProductDetailFeature `json:"product_detail"`
LandingPage LandingPageFeature `json:"landing_page"`
RegistrationPage RegistrationPageFeature `json:"registration_page"`
HomePage HomePageFeature `json:"home_page"`
Common CommonFeature `json:"common"`
Cart CartFeature `json:"cart"`
Qr QrFeature `json:"qr"`
Pcr PcrFeature `json:"pcr"`
Order OrderFeature `json:"order"`
ID string `json:"_id"`
App string `json:"app"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
V float64 `json:"__v"`
}
// HomePageFeature ...
type HomePageFeature struct {
OrderProcessing bool `json:"order_processing"`
}
// CommonFeature ...
type CommonFeature struct {
CommunicationOptinDialog CommunicationOptinDialogFeature `json:"communication_optin_dialog"`
DeploymentStoreSelection DeploymentStoreSelectionFeature `json:"deployment_store_selection"`
ListingPrice ListingPriceFeature `json:"listing_price"`
ListingPage ListingPageFeature `json:"listing_page"`
Currency CurrencyFeature `json:"currency"`
RevenueEngine RevenueEngineFeature `json:"revenue_engine"`
Feedback FeedbackFeature `json:"feedback"`
CompareProducts CompareProductsFeature `json:"compare_products"`
RewardPoints RewardPointsConfig `json:"reward_points"`
}
// CommunicationOptinDialogFeature ...
type CommunicationOptinDialogFeature struct {
Visibility bool `json:"visibility"`
}
// DeploymentStoreSelectionFeature ...
type DeploymentStoreSelectionFeature struct {
Enabled bool `json:"enabled"`
Type string `json:"type"`
}
// ListingPriceFeature ...
type ListingPriceFeature struct {
Value string `json:"value"`
Sort string `json:"sort"`
}
// ListingPageFeature ...
type ListingPageFeature struct {
SortOn string `json:"sort_on"`
}
// CurrencyFeature ...
type CurrencyFeature struct {
Value []string `json:"value"`
Type string `json:"type"`
DefaultCurrency string `json:"default_currency"`
}
// RevenueEngineFeature ...
type RevenueEngineFeature struct {
Enabled bool `json:"enabled"`
}
// FeedbackFeature ...
type FeedbackFeature struct {
Enabled bool `json:"enabled"`
}
// CompareProductsFeature ...
type CompareProductsFeature struct {
Enabled bool `json:"enabled"`
}
// CartFeature ...
type CartFeature struct {
GstInput bool `json:"gst_input"`
StaffSelection bool `json:"staff_selection"`
PlacingForCustomer bool `json:"placing_for_customer"`
GoogleMap bool `json:"google_map"`
}
// QrFeature ...
type QrFeature struct {
Application bool `json:"application"`
Products bool `json:"products"`
Collections bool `json:"collections"`
}
// PcrFeature ...
type PcrFeature struct {
StaffSelection bool `json:"staff_selection"`
}
// OrderFeature ...
type OrderFeature struct {
BuyAgain bool `json:"buy_again"`
}
// AppFeatureRequest ...
type AppFeatureRequest struct {
Feature AppFeature `json:"feature"`
}
// AppFeatureResponse ...
type AppFeatureResponse struct {
Feature AppFeature `json:"feature"`
}
// Currency ...
type Currency struct {
ID string `json:"_id"`
IsActive bool `json:"is_active"`
Name string `json:"name"`
Code string `json:"code"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
DecimalDigits float64 `json:"decimal_digits"`
Symbol string `json:"symbol"`
}
// Domain ...
type Domain struct {
Verified bool `json:"verified"`
IsPrimary bool `json:"is_primary"`
IsDefault bool `json:"is_default"`
IsShortlink bool `json:"is_shortlink"`
ID string `json:"_id"`
Name string `json:"name"`
}
// ApplicationWebsite ...
type ApplicationWebsite struct {
Enabled bool `json:"enabled"`
Basepath string `json:"basepath"`
}
// ApplicationCors ...
type ApplicationCors struct {
Domains []string `json:"domains"`
}
// ApplicationAuth ...
type ApplicationAuth struct {
Enabled bool `json:"enabled"`
}
// ApplicationRedirections ...
type ApplicationRedirections struct {
From string `json:"from"`
RedirectTo string `json:"redirect_to"`
Type string `json:"type"`
}
// ApplicationMeta ...
type ApplicationMeta struct {
Name string `json:"name"`
Value string `json:"value"`
}
// SecureUrl ...
type SecureUrl struct {
SecureURL string `json:"secure_url"`
}
// Application ...
type Application struct {
Website ApplicationWebsite `json:"website"`
Cors ApplicationCors `json:"cors"`
Auth ApplicationAuth `json:"auth"`
Description string `json:"description"`
ChannelType string `json:"channel_type"`
CacheTtl float64 `json:"cache_ttl"`
IsInternal bool `json:"is_internal"`
IsActive bool `json:"is_active"`
ID string `json:"_id"`
Name string `json:"name"`
Owner string `json:"owner"`
CompanyID float64 `json:"company_id"`
Token string `json:"token"`
Redirections []ApplicationRedirections `json:"redirections"`
Meta []ApplicationMeta `json:"meta"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
V float64 `json:"__v"`
Banner SecureUrl `json:"banner"`
Logo SecureUrl `json:"logo"`
Favicon SecureUrl `json:"favicon"`
Domains []Domain `json:"domains"`
AppType string `json:"app_type"`
MobileLogo SecureUrl `json:"mobile_logo"`
Domain Domain `json:"domain"`
}
// NotFound ...
type NotFound struct {
Message string `json:"message"`
}
// UnhandledError ...
type UnhandledError struct {
Message string `json:"message"`
}
// InvalidPayloadRequest ...
type InvalidPayloadRequest struct {
Message string `json:"message"`
}
// SuccessMessageResponse ...
type SuccessMessageResponse struct {
Message string `json:"message"`
}
// InventoryBrandRule ...
type InventoryBrandRule struct {
Criteria string `json:"criteria"`
Brands []float64 `json:"brands"`
}
// StoreCriteriaRule ...
type StoreCriteriaRule struct {
Companies []float64 `json:"companies"`
Brands []float64 `json:"brands"`
}
// InventoryStoreRule ...
type InventoryStoreRule struct {
Criteria string `json:"criteria"`
Rules []StoreCriteriaRule `json:"rules"`
Stores []float64 `json:"stores"`
}
// InventoryPaymentConfig ...
type InventoryPaymentConfig struct {
ModeOfPayment string `json:"mode_of_payment"`
Source string `json:"source"`
}
// StorePriorityRule ...
type StorePriorityRule struct {
Enabled bool `json:"enabled"`
StoretypeOrder []string `json:"storetype_order"`
}
// ArticleAssignmentRule ...
type ArticleAssignmentRule struct {
StorePriority StorePriorityRule `json:"store_priority"`
}
// InventoryArticleAssignment ...
type InventoryArticleAssignment struct {
PostOrderReassignment bool `json:"post_order_reassignment"`
Rules ArticleAssignmentRule `json:"rules"`
}
// CompanyAboutAddress ...
type CompanyAboutAddress struct {
Pincode float64 `json:"pincode"`
Address1 string `json:"address1"`
Address2 string `json:"address2"`
City string `json:"city"`
State string `json:"state"`
Country string `json:"country"`
AddressType string `json:"address_type"`
}
// UserEmail ...
type UserEmail struct {
Active bool `json:"active"`
Primary bool `json:"primary"`
Verified bool `json:"verified"`
Email string `json:"email"`
}
// UserPhoneNumber ...
type UserPhoneNumber struct {
Active bool `json:"active"`
Primary bool `json:"primary"`
Verified bool `json:"verified"`
CountryCode float64 `json:"country_code"`
Phone string `json:"phone"`
}
// ApplicationInformation ...
type ApplicationInformation struct {
Address InformationAddress `json:"address"`
Support InformationSupport `json:"support"`
SocialLinks SocialLinks `json:"social_links"`
Links Links `json:"links"`
CopyrightText string `json:"copyright_text"`
ID string `json:"_id"`
BusinessHighlights BusinessHighlights `json:"business_highlights"`
Application string `json:"application"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
V float64 `json:"__v"`
}
// InformationAddress ...
type InformationAddress struct {
Loc string `json:"loc"`
AddressLine []string `json:"address_line"`
Phone InformationPhone `json:"phone"`
City string `json:"city"`
Country string `json:"country"`
Pincode float64 `json:"pincode"`
}
// InformationPhone ...
type InformationPhone struct {
Code string `json:"code"`
Number string `json:"number"`
}
// InformationSupport ...
type InformationSupport struct {
Phone []string `json:"phone"`
Email []string `json:"email"`
Timing string `json:"timing"`
}
// SocialLinks ...
type SocialLinks struct {
Facebook FacebookLink `json:"facebook"`
Instagram InstagramLink `json:"instagram"`
Twitter TwitterLink `json:"twitter"`
Pinterest PinterestLink `json:"pinterest"`
GooglePlus GooglePlusLink `json:"google_plus"`
Youtube YoutubeLink `json:"youtube"`
LinkedIn LinkedInLink `json:"linked_in"`
Vimeo VimeoLink `json:"vimeo"`
BlogLink BlogLink `json:"blog_link"`
}
// FacebookLink ...
type FacebookLink struct {
Title string `json:"title"`
Icon string `json:"icon"`
Link string `json:"link"`
}
// InstagramLink ...
type InstagramLink struct {
Title string `json:"title"`
Icon string `json:"icon"`
Link string `json:"link"`
}
// TwitterLink ...
type TwitterLink struct {
Title string `json:"title"`
Icon string `json:"icon"`
Link string `json:"link"`
}
// PinterestLink ...
type PinterestLink struct {
Title string `json:"title"`
Icon string `json:"icon"`
Link string `json:"link"`
}
// GooglePlusLink ...
type GooglePlusLink struct {
Title string `json:"title"`
Icon string `json:"icon"`
Link string `json:"link"`
}
// YoutubeLink ...
type YoutubeLink struct {
Title string `json:"title"`
Icon string `json:"icon"`
Link string `json:"link"`
}
// LinkedInLink ...
type LinkedInLink struct {
Title string `json:"title"`
Icon string `json:"icon"`
Link string `json:"link"`
}
// VimeoLink ...
type VimeoLink struct {
Title string `json:"title"`
Icon string `json:"icon"`
Link string `json:"link"`
}
// BlogLink ...
type BlogLink struct {
Title string `json:"title"`
Icon string `json:"icon"`
Link string `json:"link"`
}
// Links ...
type Links struct {
Title string `json:"title"`
Link string `json:"link"`
}
// BusinessHighlights ...
type BusinessHighlights struct {
ID string `json:"_id"`
Title string `json:"title"`
Icon string `json:"icon"`
SubTitle string `json:"sub_title"`
}
// ApplicationDetail ...
type ApplicationDetail struct {
Name string `json:"name"`
Description string `json:"description"`
Logo SecureUrl `json:"logo"`
MobileLogo SecureUrl `json:"mobile_logo"`
Favicon SecureUrl `json:"favicon"`
Banner SecureUrl `json:"banner"`
Domain Domain `json:"domain"`
Domains []Domain `json:"domains"`
ID string `json:"_id"`
}
// CurrenciesResponse ...
type CurrenciesResponse struct {
Items []Currency `json:"items"`
}
// StoreLatLong ...
type StoreLatLong struct {
Type string `json:"type"`
Coordinates []float64 `json:"coordinates"`
}
// OptedStoreAddress ...
type OptedStoreAddress struct {
State string `json:"state"`
Address1 string `json:"address1"`
LatLong StoreLatLong `json:"lat_long"`
Address2 string `json:"address2"`
Pincode float64 `json:"pincode"`
Country string `json:"country"`
City string `json:"city"`
}
// OrderingStore ...
type OrderingStore struct {
Address OptedStoreAddress `json:"address"`
ID string `json:"_id"`
UID float64 `json:"uid"`
Name string `json:"name"`
DisplayName string `json:"display_name"`
StoreType string `json:"store_type"`
StoreCode string `json:"store_code"`
Pincode float64 `json:"pincode"`
Code string `json:"code"`
}
// OrderingStores ...
type OrderingStores struct {
Page Page `json:"page"`
Items []OrderingStore `json:"items"`
DeployedStores []float64 `json:"deployed_stores"`
AllStores bool `json:"all_stores"`
Enabled bool `json:"enabled"`
Type string `json:"type"`
ID string `json:"_id"`
App string `json:"app"`
V float64 `json:"__v"`
}
// AggregatorConfigDetail ...
type AggregatorConfigDetail struct {
Sdk bool `json:"sdk"`
VerifyAPI string `json:"verify_api"`
Pin string `json:"pin"`
MerchantKey string `json:"merchant_key"`
MerchantID string `json:"merchant_id"`
API string `json:"api"`
Secret string `json:"secret"`
Key string `json:"key"`
ConfigType string `json:"config_type"`
UserID string `json:"user_id"`
}
// AggregatorsConfigDetailResponse ...
type AggregatorsConfigDetailResponse struct {
Razorpay AggregatorConfigDetail `json:"razorpay"`
Juspay AggregatorConfigDetail `json:"juspay"`
Env string `json:"env"`
Rupifi AggregatorConfigDetail `json:"rupifi"`
Stripe AggregatorConfigDetail `json:"stripe"`
Mswipe AggregatorConfigDetail `json:"mswipe"`
Payumoney AggregatorConfigDetail `json:"payumoney"`
Ccavenue AggregatorConfigDetail `json:"ccavenue"`
Success bool `json:"success"`
Simpl AggregatorConfigDetail `json:"simpl"`
}
// ErrorCodeAndDescription ...
type ErrorCodeAndDescription struct {
Description string `json:"description"`
Code string `json:"code"`
}
// HttpErrorCodeAndResponse ...
type HttpErrorCodeAndResponse struct {
Error ErrorCodeAndDescription `json:"error"`
Success bool `json:"success"`
}
// AttachCardRequest ...
type AttachCardRequest struct {
Refresh bool `json:"refresh"`
Nickname string `json:"nickname"`
NameOnCard string `json:"name_on_card"`
CardID string `json:"card_id"`
}
// AttachCardsResponse ...
type AttachCardsResponse struct {
Message string `json:"message"`
Data map[string]interface{} `json:"data"`
Success bool `json:"success"`
}
// CardPaymentGateway ...
type CardPaymentGateway struct {
CustomerID string `json:"customer_id"`
API string `json:"api"`
Aggregator string `json:"aggregator"`
}
// ActiveCardPaymentGatewayResponse ...
type ActiveCardPaymentGatewayResponse struct {
Message string `json:"message"`
Cards CardPaymentGateway `json:"cards"`
Success bool `json:"success"`
}
// Card ...
type Card struct {
ExpYear float64 `json:"exp_year"`
CardType string `json:"card_type"`
Expired bool `json:"expired"`
CardBrandImage string `json:"card_brand_image"`
CardToken string `json:"card_token"`
CardFingerprint string `json:"card_fingerprint"`
CardIssuer string `json:"card_issuer"`
CardIsin string `json:"card_isin"`
CardBrand string `json:"card_brand"`
Nickname string `json:"nickname"`
CardID string `json:"card_id"`
CardName string `json:"card_name"`
ExpMonth float64 `json:"exp_month"`
CardNumber string `json:"card_number"`
AggregatorName string `json:"aggregator_name"`
CardReference string `json:"card_reference"`
}
// ListCardsResponse ...
type ListCardsResponse struct {
Message string `json:"message"`
Data []Card `json:"data"`
Success bool `json:"success"`
}
// DeletehCardRequest ...
type DeletehCardRequest struct {
CardID string `json:"card_id"`
}
// DeleteCardsResponse ...
type DeleteCardsResponse struct {
Message string `json:"message"`
Success bool `json:"success"`
}
// ValidateCustomerRequest ...
type ValidateCustomerRequest struct {
PhoneNumber string `json:"phone_number"`
TransactionAmountInPaise float64 `json:"transaction_amount_in_paise"`
MerchantParams map[string]interface{} `json:"merchant_params"`
Payload string `json:"payload"`
Aggregator string `json:"aggregator"`
}
// ValidateCustomerResponse ...
type ValidateCustomerResponse struct {
Message string `json:"message"`
Data map[string]interface{} `json:"data"`
Success bool `json:"success"`
}
// ChargeCustomerRequest ...
type ChargeCustomerRequest struct {
TransactionToken string `json:"transaction_token"`
Amount float64 `json:"amount"`
OrderID string `json:"order_id"`
Aggregator string `json:"aggregator"`
Verified bool `json:"verified"`
}
// ChargeCustomerResponse ...
type ChargeCustomerResponse struct {
CartID string `json:"cart_id"`
OrderID string `json:"order_id"`
Status string `json:"status"`
Message string `json:"message"`
DeliveryAddressID string `json:"delivery_address_id"`
Aggregator string `json:"aggregator"`
Success bool `json:"success"`
}
// PaymentInitializationRequest ...
type PaymentInitializationRequest struct {
Method string `json:"method"`
PollingURL string `json:"polling_url"`
RazorpayPaymentID string `json:"razorpay_payment_id"`
CustomerID string `json:"customer_id"`
Timeout float64 `json:"timeout"`
MerchantOrderID string `json:"merchant_order_id"`
VirtualID string `json:"virtual_id"`
AggregatorOrderID string `json:"aggregator_order_id"`
Aggregator string `json:"aggregator"`
}
// PaymentInitializationResponse ...
type PaymentInitializationResponse struct {
Method string `json:"method"`
Currency string `json:"currency"`
BqrImage string `json:"bqr_image"`
PollingURL string `json:"polling_url"`
RazorpayPaymentID string `json:"razorpay_payment_id"`
CustomerID string `json:"customer_id"`
Timeout float64 `json:"timeout"`
MerchantOrderID string `json:"merchant_order_id"`
VirtualID string `json:"virtual_id"`
Amount float64 `json:"amount"`
Status string `json:"status"`
Vpa string `json:"vpa"`
AggregatorOrderID string `json:"aggregator_order_id"`
Aggregator string `json:"aggregator"`
Success bool `json:"success"`
}
// PaymentStatusUpdateRequest ...
type PaymentStatusUpdateRequest struct {
Email string `json:"email"`
Method string `json:"method"`
Currency string `json:"currency"`
Contact string `json:"contact"`
CustomerID string `json:"customer_id"`
MerchantOrderID string `json:"merchant_order_id"`
Amount float64 `json:"amount"`
OrderID string `json:"order_id"`
Status string `json:"status"`
Vpa string `json:"vpa"`
Aggregator string `json:"aggregator"`
}
// PaymentStatusUpdateResponse ...
type PaymentStatusUpdateResponse struct {
AggregatorName string `json:"aggregator_name"`
Retry bool `json:"retry"`
Status string `json:"status"`
}
// PaymentModeLogo ...
type PaymentModeLogo struct {
Small string `json:"small"`
Large string `json:"large"`
}
// PaymentModeList ...
type PaymentModeList struct {
Timeout float64 `json:"timeout"`
RetryCount float64 `json:"retry_count"`
CardID string `json:"card_id"`
CardName string `json:"card_name"`
ExpMonth float64 `json:"exp_month"`
Code string `json:"code"`
DisplayName string `json:"display_name"`
Name string `json:"name"`
Expired bool `json:"expired"`
CardToken string `json:"card_token"`
CardFingerprint string `json:"card_fingerprint"`
FyndVpa string `json:"fynd_vpa"`
IntentAppErrorList []string `json:"intent_app_error_list"`
AggregatorName string `json:"aggregator_name"`
CardType string `json:"card_type"`
MerchantCode string `json:"merchant_code"`
IntentFlow string `json:"intent_flow"`
CardIsin string `json:"card_isin"`
CardBrand string `json:"card_brand"`
CardNumber string `json:"card_number"`
DisplayPriority float64 `json:"display_priority"`
ExpYear float64 `json:"exp_year"`
CardBrandImage string `json:"card_brand_image"`
CardIssuer string `json:"card_issuer"`
Nickname string `json:"nickname"`
LogoURL PaymentModeLogo `json:"logo_url"`
CardReference string `json:"card_reference"`
}
// RootPaymentMode ...
type RootPaymentMode struct {
Name string `json:"name"`
List []PaymentModeList `json:"list"`
AnonymousEnable bool `json:"anonymous_enable"`
DisplayName string `json:"display_name"`
AggregatorName string `json:"aggregator_name"`
DisplayPriority float64 `json:"display_priority"`
AddCardEnabled bool `json:"add_card_enabled"`
}
// AggregatorRoute ...
type AggregatorRoute struct {
APILink string `json:"api_link"`
PaymentFlow string `json:"payment_flow"`
Data map[string]interface{} `json:"data"`
}
// PaymentFlow ...
type PaymentFlow struct {
Juspay AggregatorRoute `json:"juspay"`
Razorpay AggregatorRoute `json:"razorpay"`
BqrRazorpay AggregatorRoute `json:"bqr_razorpay"`
Fynd AggregatorRoute `json:"fynd"`
UpiRazorpay AggregatorRoute `json:"upi_razorpay"`
Rupifi AggregatorRoute `json:"rupifi"`
Payubiz AggregatorRoute `json:"payubiz"`
Msipe AggregatorRoute `json:"msipe"`
Stripe AggregatorRoute `json:"stripe"`
Ccavenue AggregatorRoute `json:"ccavenue"`
Simpl AggregatorRoute `json:"simpl"`
}
// PaymentOptionAndFlow ...
type PaymentOptionAndFlow struct {
PaymentOption []RootPaymentMode `json:"payment_option"`
PaymentFlows PaymentFlow `json:"payment_flows"`
}
// PaymentModeRouteResponse ...
type PaymentModeRouteResponse struct {
Success bool `json:"success"`
PaymentOptions PaymentOptionAndFlow `json:"payment_options"`
}
// RupifiBannerData ...
type RupifiBannerData struct {
KycURL string `json:"kyc_url"`
Status string `json:"status"`
}
// RupifiBannerResponse ...
type RupifiBannerResponse struct {
Data RupifiBannerData `json:"data"`
Success bool `json:"success"`
}
// TransferItemsDetails ...
type TransferItemsDetails struct {
Name string `json:"name"`
LogoSmall string `json:"logo_small"`
ID string `json:"id"`
DisplayName bool `json:"display_name"`
LogoLarge string `json:"logo_large"`
}
// TransferModeDetails ...
type TransferModeDetails struct {
Items []TransferItemsDetails `json:"items"`
DisplayName string `json:"display_name"`
}
// TransferModeResponse ...
type TransferModeResponse struct {
Data []TransferModeDetails `json:"data"`
}
// UpdateRefundTransferModeRequest ...
type UpdateRefundTransferModeRequest struct {
Enable bool `json:"enable"`
TransferMode string `json:"transfer_mode"`
}
// UpdateRefundTransferModeResponse ...
type UpdateRefundTransferModeResponse struct {
Success bool `json:"success"`
}
// OrderBeneficiaryDetails ...
type OrderBeneficiaryDetails struct {
Email string `json:"email"`
DelightsUserName string `json:"delights_user_name"`
BeneficiaryID string `json:"beneficiary_id"`
Comment bool `json:"comment"`
Title string `json:"title"`
DisplayName string `json:"display_name"`
Subtitle string `json:"subtitle"`
BranchName bool `json:"branch_name"`
Address string `json:"address"`
ID float64 `json:"id"`
TransferMode string `json:"transfer_mode"`
BankName string `json:"bank_name"`
CreatedOn string `json:"created_on"`
ModifiedOn string `json:"modified_on"`
IsActive bool `json:"is_active"`
IfscCode string `json:"ifsc_code"`
AccountHolder string `json:"account_holder"`
Mobile bool `json:"mobile"`
AccountNo string `json:"account_no"`
}
// OrderBeneficiaryResponse ...
type OrderBeneficiaryResponse struct {
Beneficiaries []OrderBeneficiaryDetails `json:"beneficiaries"`
ShowBeneficiaryDetails bool `json:"show_beneficiary_details"`
}
// NotFoundResourceError ...
type NotFoundResourceError struct {
Description string `json:"description"`
Success bool `json:"success"`
Code string `json:"code"`
}
// IfscCodeResponse ...
type IfscCodeResponse struct {
BankName string `json:"bank_name"`
BranchName string `json:"branch_name"`
Success bool `json:"success"`
}
// ErrorCodeDescription ...
type ErrorCodeDescription struct {
Description string `json:"description"`
Success bool `json:"success"`
Code string `json:"code"`
}
// AddBeneficiaryViaOtpVerificationRequest ...
type AddBeneficiaryViaOtpVerificationRequest struct {
RequestID string `json:"request_id"`
Otp string `json:"otp"`
HashKey string `json:"hash_key"`
}
// AddBeneficiaryViaOtpVerificationResponse ...
type AddBeneficiaryViaOtpVerificationResponse struct {
RequestID string `json:"request_id"`
Otp string `json:"otp"`
HashKey string `json:"hash_key"`
}
// WrongOtpError ...
type WrongOtpError struct {
Success string `json:"success"`
Description string `json:"description"`
}
// BeneficiaryModeDetails ...
type BeneficiaryModeDetails struct {
BankName string `json:"bank_name"`
Email string `json:"email"`
Comment string `json:"comment"`
IfscCode string `json:"ifsc_code"`
BranchName string `json:"branch_name"`
AccountNo string `json:"account_no"`
Address string `json:"address"`
Wallet string `json:"wallet"`
AccountHolder string `json:"account_holder"`
Mobile string `json:"mobile"`
Vpa string `json:"vpa"`
}
// AddBeneficiaryDetailsRequest ...
type AddBeneficiaryDetailsRequest struct {
RequestID string `json:"request_id"`
Delights bool `json:"delights"`
Otp string `json:"otp"`
Details BeneficiaryModeDetails `json:"details"`
ShipmentID string `json:"shipment_id"`
OrderID string `json:"order_id"`
TransferMode string `json:"transfer_mode"`
}
// RefundAccountResponse ...
type RefundAccountResponse struct {
Message string `json:"message"`
Data map[string]interface{} `json:"data"`
Success bool `json:"success"`
}
// WalletOtpRequest ...
type WalletOtpRequest struct {
Mobile string `json:"mobile"`
CountryCode string `json:"country_code"`
}
// WalletOtpResponse ...
type WalletOtpResponse struct {
RequestID string `json:"request_id"`
IsVerifiedFlag string `json:"is_verified_flag"`
Success bool `json:"success"`
}
// SetDefaultBeneficiaryRequest ...
type SetDefaultBeneficiaryRequest struct {
OrderID string `json:"order_id"`
BeneficiaryID string `json:"beneficiary_id"`
}
// SetDefaultBeneficiaryResponse ...
type SetDefaultBeneficiaryResponse struct {
IsBeneficiarySet bool `json:"is_beneficiary_set"`
Success bool `json:"success"`
}
// OrderById ...
type OrderById struct {
Order OrderSchema `json:"order"`
}
// OrderList ...
type OrderList struct {
Items []OrderSchema `json:"items"`
Page OrderPage `json:"page"`
Filters OrderFilters `json:"filters"`
}
// OrderPage ...
type OrderPage struct {
ItemTotal float64 `json:"item_total"`
Type string `json:"type"`
Size float64 `json:"size"`
Current float64 `json:"current"`
HasNext bool `json:"has_next"`
}
// OrderFilters ...
type OrderFilters struct {
Statuses []OrderStatuses `json:"statuses"`
}
// OrderStatuses ...
type OrderStatuses struct {
Display string `json:"display"`
Value float64 `json:"value"`
IsSelected bool `json:"is_selected"`
}
// ShipmentById ...
type ShipmentById struct {
Shipment Shipments `json:"shipment"`
}
// ShipmentReasons ...
type ShipmentReasons struct {
Reasons []Reasons `json:"reasons"`
}
// ShipmentStatusUpdateBody ...
type ShipmentStatusUpdateBody struct {
Statuses []StatusesBody `json:"statuses"`
ForceTransition bool `json:"force_transition"`
}
// StatusesBody ...
type StatusesBody struct {
Status string `json:"status"`
Shipments map[string]interface{} `json:"shipments"`
}
// ShipmentStatusUpdate ...
type ShipmentStatusUpdate struct {
Message []map[string]interface{} `json:"message"`
Status bool `json:"status"`
}
// ShipmentTrack ...
type ShipmentTrack struct {
Results []Track `json:"results"`
}
// OrderSchema ...
type OrderSchema struct {
OrderID string `json:"order_id"`
BreakupValues []BreakupValues `json:"breakup_values"`
OrderCreatedTime string `json:"order_created_time"`
Shipments []Shipments `json:"shipments"`
TotalShipmentsInOrder float64 `json:"total_shipments_in_order"`
UserInfo UserInfo `json:"user_info"`
BagsForReorder []BagsForReorder `json:"bags_for_reorder"`
}
// BagsForReorder ...
type BagsForReorder struct {
ItemID float64 `json:"item_id"`
ItemSize string `json:"item_size"`
StoreID float64 `json:"store_id"`
SellerID float64 `json:"seller_id"`
Quantity float64 `json:"quantity"`
ArticleAssignment BagsForReorderArticleAssignment `json:"article_assignment"`
}
// BagsForReorderArticleAssignment ...
type BagsForReorderArticleAssignment struct {
Level string `json:"level"`
Strategy string `json:"strategy"`
}
// PosOrderById ...
type PosOrderById struct {
Order OrderSchema `json:"order"`
}
// Bags ...
type Bags struct {
Item Item `json:"item"`
Prices Prices `json:"prices"`
CurrentStatus CurrentStatus `json:"current_status"`
ID float64 `json:"id"`
FinancialBreakup []FinancialBreakup `json:"financial_breakup"`
}
// Item ...
type Item struct {
Brand ItemBrand `json:"brand"`
Name string `json:"name"`
Size string `json:"size"`
SlugKey string `json:"slug_key"`
Image []string `json:"image"`
Code string `json:"code"`
ID float64 `json:"id"`
}
// Prices ...
type Prices struct {
AmountPaidRoundoff float64 `json:"amount_paid_roundoff"`
FyndCredits float64 `json:"fynd_credits"`
CodCharges float64 `json:"cod_charges"`
Cashback float64 `json:"cashback"`
AddedToFyndCash bool `json:"added_to_fynd_cash"`
PriceMarked float64 `json:"price_marked"`
TransferPrice float64 `json:"transfer_price"`
CouponValue float64 `json:"coupon_value"`
PriceEffective float64 `json:"price_effective"`
RefundCredit float64 `json:"refund_credit"`
AmountPaid float64 `json:"amount_paid"`
RefundAmount float64 `json:"refund_amount"`
CashbackApplied float64 `json:"cashback_applied"`
GstTaxPercentage float64 `json:"gst_tax_percentage"`
ValueOfGood float64 `json:"value_of_good"`
BrandCalculatedAmount float64 `json:"brand_calculated_amount"`
PromotionEffectiveDiscount float64 `json:"promotion_effective_discount"`
Discount float64 `json:"discount"`
CouponEffectiveDiscount float64 `json:"coupon_effective_discount"`
DeliveryCharge float64 `json:"delivery_charge"`
}
// CurrentStatus ...
type CurrentStatus struct {
UpdatedAt string `json:"updated_at"`
Status string `json:"status"`
Name string `json:"name"`
JourneyType string `json:"journey_type"`
}
// FinancialBreakup ...
type FinancialBreakup struct {
BrandCalculatedAmount float64 `json:"brand_calculated_amount"`
CouponValue float64 `json:"coupon_value"`
AmountPaidRoundoff float64 `json:"amount_paid_roundoff"`
GstFee string `json:"gst_fee"`
RefundCredit float64 `json:"refund_credit"`
Cashback float64 `json:"cashback"`
RefundAmount float64 `json:"refund_amount"`
ValueOfGood float64 `json:"value_of_good"`
PromotionEffectiveDiscount float64 `json:"promotion_effective_discount"`
Size string `json:"size"`
TotalUnits float64 `json:"total_units"`
Discount float64 `json:"discount"`
AmountPaid float64 `json:"amount_paid"`
FyndCredits float64 `json:"fynd_credits"`
AddedToFyndCash bool `json:"added_to_fynd_cash"`
DeliveryCharge float64 `json:"delivery_charge"`
HsnCode string `json:"hsn_code"`
CouponEffectiveDiscount float64 `json:"coupon_effective_discount"`
TransferPrice float64 `json:"transfer_price"`
Identifiers Identifiers `json:"identifiers"`
GstTag string `json:"gst_tag"`
PriceMarked float64 `json:"price_marked"`
PriceEffective float64 `json:"price_effective"`
CodCharges float64 `json:"cod_charges"`
ItemName string `json:"item_name"`
CashbackApplied float64 `json:"cashback_applied"`
GstTaxPercentage float64 `json:"gst_tax_percentage"`
}
// Identifiers ...
type Identifiers struct {
Ean string `json:"ean"`
SkuCode string `json:"sku_code"`
}
// ItemBrand ...
type ItemBrand struct {
Name string `json:"name"`
Logo string `json:"logo"`
}
// BreakupValues ...
type BreakupValues struct {
Display string `json:"display"`
Value float64 `json:"value"`
Name string `json:"name"`
}
// DeliveryAddress ...
type DeliveryAddress struct {
Pincode string `json:"pincode"`
Landmark string `json:"landmark"`
ContactPerson string `json:"contact_person"`
Phone string `json:"phone"`
State string `json:"state"`
Version string `json:"version"`
Address1 string `json:"address1"`
CreatedAt string `json:"created_at"`
AddressType string `json:"address_type"`
AddressCategory string `json:"address_category"`
Area string `json:"area"`
City string `json:"city"`
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
Email string `json:"email"`
Country string `json:"country"`
Address2 string `json:"address2"`
UpdatedAt string `json:"updated_at"`
Name string `json:"name"`
Address string `json:"address"`
}
// FulfillingStore ...
type FulfillingStore struct {
Code string `json:"code"`
ID float64 `json:"id"`
Name string `json:"name"`
CompanyID float64 `json:"company_id"`
}
// Invoice ...
type Invoice struct {
UpdatedDate string `json:"updated_date"`
InvoiceURL string `json:"invoice_url"`
LabelURL string `json:"label_url"`
}
// Promise ...
type Promise struct {
Timestamp Timestamp `json:"timestamp"`
}
// Timestamp ...
type Timestamp struct {
Min string `json:"min"`
Max string `json:"max"`
}
// Reasons ...
type Reasons struct {
ReasonText string `json:"reason_text"`
ShowTextArea bool `json:"show_text_area"`
FeedbackType string `json:"feedback_type"`
Flow string `json:"flow"`
ReasonID float64 `json:"reason_id"`
Priority float64 `json:"priority"`
}
// ShipmentStatus ...
type ShipmentStatus struct {
Title string `json:"title"`
HexCode string `json:"hex_code"`
}
// ShipmentUserInfo ...
type ShipmentUserInfo struct {
Gender string `json:"gender"`
Mobile string `json:"mobile"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
}
// Shipments ...
type Shipments struct {
OrderID string `json:"order_id"`
BreakupValues []BreakupValues `json:"breakup_values"`
TrackURL string `json:"track_url"`
TrakingNo string `json:"traking_no"`
TrackingDetails []TrackingDetails `json:"tracking_details"`
BeneficiaryDetails bool `json:"beneficiary_details"`
CanReturn bool `json:"can_return"`
Prices Prices `json:"prices"`
NeedHelpURL string `json:"need_help_url"`
ShipmentID string `json:"shipment_id"`
TotalBags float64 `json:"total_bags"`
DeliveryAddress DeliveryAddress `json:"delivery_address"`
Invoice Invoice `json:"invoice"`
Comment string `json:"comment"`
OrderType string `json:"order_type"`
Promise Promise `json:"promise"`
FulfillingStore FulfillingStore `json:"fulfilling_store"`
Bags []Bags `json:"bags"`
CanCancel bool `json:"can_cancel"`
Payment ShipmentPayment `json:"payment"`
ShipmentCreatedAt string `json:"shipment_created_at"`
ShipmentStatus ShipmentStatus `json:"shipment_status"`
UserInfo ShipmentUserInfo `json:"user_info"`
SizeInfo map[string]interface{} `json:"size_info"`
TotalDetails ShipmentTotalDetails `json:"total_details"`
}
// ShipmentTotalDetails ...
type ShipmentTotalDetails struct {
TotalPrice float64 `json:"total_price"`
Sizes float64 `json:"sizes"`
Pieces float64 `json:"pieces"`
}
// ShipmentPayment ...
type ShipmentPayment struct {
Logo string `json:"logo"`
Mode string `json:"mode"`
Status string `json:"status"`
}
// Track ...
type Track struct {
Awb string `json:"awb"`
UpdatedAt string `json:"updated_at"`
LastLocationRecievedAt string `json:"last_location_recieved_at"`
Reason string `json:"reason"`
ShipmentType string `json:"shipment_type"`
Status string `json:"status"`
UpdatedTime string `json:"updated_time"`
AccountName string `json:"account_name"`
}
// TrackingDetails ...
type TrackingDetails struct {
IsCurrent bool `json:"is_current"`
Status string `json:"status"`
Time string `json:"time"`
IsPassed bool `json:"is_passed"`
}
// UserInfo ...
type UserInfo struct {
Gender string `json:"gender"`
Mobile string `json:"mobile"`
Name string `json:"name"`
Email string `json:"email"`
}
// ApefaceApiError ...
type ApefaceApiError struct {
Message string `json:"message"`
}
// ActionPageParams ...
type ActionPageParams struct {
Slug []string `json:"slug"`
}
// CatalogueOrderRequest ...
type CatalogueOrderRequest struct {
Articles []RewardsArticle `json:"articles"`
}
// CatalogueOrderResponse ...
type CatalogueOrderResponse struct {
Articles []RewardsArticle `json:"articles"`
}
// DiscountProperties ...
type DiscountProperties struct {
Absolute float64 `json:"absolute"`
Currency string `json:"currency"`
DisplayAbsolute string `json:"display_absolute"`
DisplayPercent string `json:"display_percent"`
Percent float64 `json:"percent"`
}
// Error ...
type Error struct {
Code float64 `json:"code"`
Exception string `json:"exception"`
Info string `json:"info"`
Message string `json:"message"`
}
// Offer ...
type Offer struct {
Schedule Schedule `json:"_schedule"`
Active bool `json:"active"`
ApplicationID string `json:"application_id"`
BannerImage Asset `json:"banner_image"`
CreatedAt string `json:"created_at"`
Name string `json:"name"`
Rule map[string]interface{} `json:"rule"`
Share ShareMessages `json:"share"`
SubText string `json:"sub_text"`
Text string `json:"text"`
Type string `json:"type"`
UpdatedAt string `json:"updated_at"`
UpdatedBy string `json:"updated_by"`
URL string `json:"url"`
}
// OrderDiscountRequest ...
type OrderDiscountRequest struct {
Currency string `json:"currency"`
OrderAmount float64 `json:"order_amount"`
}
// OrderDiscountResponse ...
type OrderDiscountResponse struct {
AppliedRuleBucket OrderDiscountRuleBucket `json:"applied_rule_bucket"`
BaseDiscount DiscountProperties `json:"base_discount"`
Discount DiscountProperties `json:"discount"`
OrderAmount float64 `json:"order_amount"`
Points float64 `json:"points"`
}
// OrderDiscountRuleBucket ...
type OrderDiscountRuleBucket struct {
High float64 `json:"high"`
Low float64 `json:"low"`
Max float64 `json:"max"`
Value float64 `json:"value"`
ValueType string `json:"value_type"`
}
// PointsHistory ...
type PointsHistory struct {
ID string `json:"_id"`
ApplicationID string `json:"application_id"`
Claimed bool `json:"claimed"`
CreatedAt string `json:"created_at"`
ExpiresOn string `json:"expires_on"`
Meta map[string]interface{} `json:"meta"`
Points float64 `json:"points"`
RemainingPoints float64 `json:"remaining_points"`
Text1 string `json:"text_1"`
Text2 string `json:"text_2"`
Text3 string `json:"text_3"`
TxnName string `json:"txn_name"`
UpdatedAt string `json:"updated_at"`
UserID string `json:"user_id"`
}
// PointsHistoryResponse ...
type PointsHistoryResponse struct {
Items []PointsHistory `json:"items"`
Page Page `json:"page"`
}
// PointsResponse ...
type PointsResponse struct {
Points float64 `json:"points"`
}
// RedeemReferralCodeRequest ...
type RedeemReferralCodeRequest struct {
DeviceID string `json:"device_id"`
ReferralCode string `json:"referral_code"`
}
// RedeemReferralCodeResponse ...
type RedeemReferralCodeResponse struct {
Message string `json:"message"`
Points float64 `json:"points"`
Redeemed bool `json:"redeemed"`
ReferrerID string `json:"referrer_id"`
ReferrerInfo string `json:"referrer_info"`
}
// ReferralDetailsResponse ...
type ReferralDetailsResponse struct {
Referral Offer `json:"referral"`
ReferrerInfo string `json:"referrer_info"`
Share ShareMessages `json:"share"`
User ReferralDetailsUser `json:"user"`
}
// ReferralDetailsUser ...
type ReferralDetailsUser struct {
Blocked bool `json:"blocked"`
Points float64 `json:"points"`
Redeemed bool `json:"redeemed"`
ReferralCode string `json:"referral_code"`
}
// RewardsArticle ...
type RewardsArticle struct {
ID string `json:"id"`
Points float64 `json:"points"`
Price float64 `json:"price"`
}
// Schedule ...
type Schedule struct {
Cron string `json:"cron"`
Duration float64 `json:"duration"`
End string `json:"end"`
Start string `json:"start"`
}
// ShareMessages ...
type ShareMessages struct {
Email string `json:"email"`
Facebook string `json:"facebook"`
Fallback string `json:"fallback"`
Message string `json:"message"`
Messenger string `json:"messenger"`
Sms string `json:"sms"`
Text string `json:"text"`
Twitter string `json:"twitter"`
Whatsapp string `json:"whatsapp"`
}
// AbuseReport ...
type AbuseReport struct {
Abused bool `json:"abused"`
DateMeta DateMeta `json:"date_meta"`
Description string `json:"description"`
Entity Entity `json:"entity"`
ID string `json:"id"`
Name string `json:"name"`
State FeedbackState `json:"state"`
Tags []TagMeta `json:"tags"`
}
// Access ...
type Access struct {
Answer bool `json:"answer"`
AskQuestion bool `json:"ask_question"`
Comment bool `json:"comment"`
Rnr bool `json:"rnr"`
}
// AddMediaListRequest ...
type AddMediaListRequest struct {
EntityID string `json:"entity_id"`
EntityType string `json:"entity_type"`
MediaList []AddMediaRequest `json:"media_list"`
RefID string `json:"ref_id"`
RefType string `json:"ref_type"`
}
// AddMediaRequest ...
type AddMediaRequest struct {
CloudID string `json:"cloud_id"`
CloudName string `json:"cloud_name"`
CloudProvider string `json:"cloud_provider"`
EntityID string `json:"entity_id"`
EntityType string `json:"entity_type"`
MediaURL string `json:"media_url"`
RefID string `json:"ref_id"`
RefType string `json:"ref_type"`
Tags []string `json:"tags"`
ThumbnailURL string `json:"thumbnail_url"`
Type string `json:"type"`
}
// ApplicationSchema ...
type ApplicationSchema struct {
ID string `json:"id"`
}
// Attribute ...
type Attribute struct {
DateMeta DateMeta `json:"date_meta"`
Description string `json:"description"`
ID string `json:"id"`
Name string `json:"name"`
Slug string `json:"slug"`
Tags []TagMeta `json:"tags"`
}
// AttributeObject ...
type AttributeObject struct {
Description string `json:"description"`
Name string `json:"name"`
Slug string `json:"slug"`
Title string `json:"title"`
Type string `json:"type"`
Value float64 `json:"value"`
}
// AttributeResponse ...
type AttributeResponse struct {
Items []Attribute `json:"items"`
Page Page `json:"page"`
}
// AutoDetectors ...
type AutoDetectors struct {
TextDetector []TextDetector `json:"text_detector"`
}
// CheckEligibilityResponse ...
type CheckEligibilityResponse struct {
Access Access `json:"access"`
}
// Cloud ...
type Cloud struct {
ID string `json:"id"`
Name string `json:"name"`
Provider string `json:"provider"`
}
// Comment ...
type Comment struct {
Comment []string `json:"comment"`
DateMeta DateMeta `json:"date_meta"`
Entity Entity `json:"entity"`
ID string `json:"id"`
Name string `json:"name"`
State FeedbackState `json:"state"`
Tags []TagMeta `json:"tags"`
VoteCount VoteCount `json:"vote_count"`
}
// CommentGetResponse ...
type CommentGetResponse struct {
Items []Comment `json:"items"`
Page Page `json:"page"`
}
// CommentRequest ...
type CommentRequest struct {
Comment []string `json:"comment"`
EntityID string `json:"entity_id"`
EntityType string `json:"entity_type"`
}
// CreateQNARequest ...
type CreateQNARequest struct {
Choices []string `json:"choices"`
EntityID string `json:"entity_id"`
EntityType string `json:"entity_type"`
MaxLen float64 `json:"max_len"`
SortPriority float64 `json:"sort_priority"`
Tags []string `json:"tags"`
Text string `json:"text"`
Type string `json:"type"`
}
// CreatedBy ...
type CreatedBy struct {
ID string `json:"id"`
Name string `json:"name"`
Tags []TagMeta `json:"tags"`
}
// CursorGetResponse ...
type CursorGetResponse struct {
Items []map[string]interface{} `json:"items"`
Page Page `json:"page"`
}
// CustomerReview ...
type CustomerReview struct {
AutoDetectors AutoDetectors `json:"auto_detectors"`
CreatedOn string `json:"created_on"`
DeviceMeta DeviceMeta `json:"device_meta"`
Entity ProductEntity `json:"entity"`
ID string `json:"id"`
LocationMeta LocationMeta `json:"location_meta"`
ModifiedOn string `json:"modified_on"`
Name string `json:"name"`
Rating ReviewRating `json:"rating"`
Review Review `json:"review"`
Slug string `json:"slug"`
State State `json:"state"`
Tags []TagMeta `json:"tags"`
Template Template `json:"template"`
VoteCount VoteCount `json:"vote_count"`
}
// DeviceMeta ...
type DeviceMeta struct {
AppVersion string `json:"app_version"`
Platform string `json:"platform"`
}
// Entity ...
type Entity struct {
ID string `json:"id"`
Type string `json:"type"`
}
// EntityMeta ...
type EntityMeta struct {
OrderID string `json:"order_id"`
Type string `json:"type"`
}
// FeedbackError ...
type FeedbackError struct {
Code string `json:"code"`
Exception string `json:"exception"`
Info string `json:"info"`
Message string `json:"message"`
Meta map[string]interface{} `json:"meta"`
RequestID string `json:"request_id"`
StackTrace string `json:"stack_trace"`
Status float64 `json:"status"`
}
// FeedbackMedia ...
type FeedbackMedia struct {
Application ApplicationSchema `json:"application"`
Cloud Cloud `json:"cloud"`
CreatedBy CreatedBy `json:"created_by"`
DateMeta DateMeta `json:"date_meta"`
Description string `json:"description"`
Entity Entity `json:"entity"`
ID string `json:"id"`
Name string `json:"name"`
Reference Entity `json:"reference"`
State MediaState `json:"state"`
Tags []TagMeta `json:"tags"`
Type string `json:"type"`
URL Url `json:"url"`
}
// FeedbackState ...
type FeedbackState struct {
Active bool `json:"active"`
Archive bool `json:"archive"`
Media string `json:"media"`
Qna bool `json:"qna"`
Rating bool `json:"rating"`
Review bool `json:"review"`
}
// GeoLoc ...
type GeoLoc struct {
Latitude string `json:"latitude"`
Longitude string `json:"longitude"`
}
// InsertResponse ...
type InsertResponse struct {
Ids string `json:"ids"`
}
// Location ...
type Location struct {
CountryCode string `json:"country_code"`
FlagURL string `json:"flag_url"`
GeoLoc GeoLoc `json:"geo_loc"`
Name string `json:"name"`
Pincode string `json:"pincode"`
}
// LocationMeta ...
type LocationMeta struct {
Demand Location `json:"demand"`
Supply Location `json:"supply"`
}
// MediaGetResponse ...
type MediaGetResponse struct {
Items []FeedbackMedia `json:"items"`
Page Page `json:"page"`
}
// MediaMeta ...
type MediaMeta struct {
Cloud Cloud `json:"cloud"`
Comment []string `json:"comment"`
Description string `json:"description"`
ID string `json:"id"`
Type string `json:"type"`
URL Url `json:"url"`
}
// MediaState ...
type MediaState struct {
Approve bool `json:"approve"`
Archive bool `json:"archive"`
}
// NumberGetResponse ...
type NumberGetResponse struct {
Items []map[string]interface{} `json:"items"`
Page PageNumber `json:"page"`
}
// PageNumber ...
type PageNumber struct {
Current float64 `json:"current"`
HasNext bool `json:"has_next"`
ItemTotal float64 `json:"item_total"`
Size float64 `json:"size"`
Type string `json:"type"`
}
// ProductEntity ...
type ProductEntity struct {
ID string `json:"id"`
Meta EntityMeta `json:"meta"`
Type string `json:"type"`
}
// QNA ...
type QNA struct {
Comments []Comment `json:"comments"`
DateMeta DateMeta `json:"date_meta"`
Entity Entity `json:"entity"`
ID string `json:"id"`
Name string `json:"name"`
Question Question `json:"question"`
State QNAState `json:"state"`
Tag []string `json:"tag"`
Tags []TagMeta `json:"tags"`
}
// QNAGetResponse ...
type QNAGetResponse struct {
Items []QNA `json:"items"`
Page Page `json:"page"`
}
// QNAState ...
type QNAState struct {
Active bool `json:"active"`
Approve bool `json:"approve"`
Modify bool `json:"modify"`
Priority float64 `json:"priority"`
Reply bool `json:"reply"`
Vote bool `json:"vote"`
}
// Question ...
type Question struct {
Choices []string `json:"choices"`
MaxLen float64 `json:"max_len"`
Text string `json:"text"`
Type string `json:"type"`
}
// Rating ...
type Rating struct {
Attributes []Attribute `json:"attributes"`
AttributesSlugs []string `json:"attributes_slugs"`
UI UI `json:"ui"`
}
// RatingGetResponse ...
type RatingGetResponse struct {
Items []Rating `json:"items"`
Page Page `json:"page"`
}
// RatingMetric ...
type RatingMetric struct {
Avg float64 `json:"avg"`
Count float64 `json:"count"`
Name string `json:"name"`
Slug string `json:"slug"`
Type string `json:"type"`
}
// ReportAbuseGetResponse ...
type ReportAbuseGetResponse struct {
Items []AbuseReport `json:"items"`
Page Page `json:"page"`
}
// ReportAbuseRequest ...
type ReportAbuseRequest struct {
Description string `json:"description"`
EntityID string `json:"entity_id"`
EntityType string `json:"entity_type"`
}
// Review ...
type Review struct {
AnswerIds []string `json:"answer_ids"`
Comments []string `json:"comments"`
Description string `json:"description"`
MediaMeta []MediaMeta `json:"media_meta"`
Title string `json:"title"`
}
// ReviewFacet ...
type ReviewFacet struct {
Display string `json:"display"`
Name string `json:"name"`
Selected bool `json:"selected"`
Slug string `json:"slug"`
Type string `json:"type"`
}
// ReviewGetResponse ...
type ReviewGetResponse struct {
Facets []ReviewFacet `json:"facets"`
Items []CustomerReview `json:"items"`
Page Page `json:"page"`
Sort []SortMethod `json:"sort"`
}
// ReviewMediaMeta ...
type ReviewMediaMeta struct {
MaxCount float64 `json:"max_count"`
Size float64 `json:"size"`
Type string `json:"type"`
}
// ReviewMetric ...
type ReviewMetric struct {
AttributeMetric []RatingMetric `json:"attribute_metric"`
CreatedOn string `json:"created_on"`
Entity Entity `json:"entity"`
ID string `json:"id"`
ModifiedOn string `json:"modified_on"`
RatingAvg float64 `json:"rating_avg"`
RatingCount float64 `json:"rating_count"`
RatingMetric []RatingMetric `json:"rating_metric"`
ReviewCount float64 `json:"review_count"`
}
// ReviewMetricGetResponse ...
type ReviewMetricGetResponse struct {
Items []ReviewMetric `json:"items"`
Page Page `json:"page"`
}
// ReviewRating ...
type ReviewRating struct {
Attributes []AttributeObject `json:"attributes"`
Value float64 `json:"value"`
}
// SaveAttributeRequest ...
type SaveAttributeRequest struct {
Description string `json:"description"`
Name string `json:"name"`
Slug string `json:"slug"`
}
// SortMethod ...
type SortMethod struct {
Name string `json:"name"`
Selected bool `json:"selected"`
Type string `json:"type"`
}
// State ...
type State struct {
Active bool `json:"active"`
Approve bool `json:"approve"`
AutoDecided bool `json:"auto_decided"`
Status float64 `json:"status"`
}
// TagMeta ...
type TagMeta struct {
Media []MediaMeta `json:"media"`
Name string `json:"name"`
Type string `json:"type"`
}
// Template ...
type Template struct {
DateMeta DateMeta `json:"date_meta"`
Entity Entity `json:"entity"`
ID string `json:"id"`
Name string `json:"name"`
Rating Rating `json:"rating"`
Review TemplateReview `json:"review"`
State FeedbackState `json:"state"`
}
// TemplateGetResponse ...
type TemplateGetResponse struct {
Items []Template `json:"items"`
Page Page `json:"page"`
}
// TemplateReview ...
type TemplateReview struct {
Description string `json:"description"`
Header string `json:"header"`
ImageMeta ReviewMediaMeta `json:"image_meta"`
Title string `json:"title"`
VideoMeta ReviewMediaMeta `json:"video_meta"`
VoteAllowed bool `json:"vote_allowed"`
}
// TextDetector ...
type TextDetector struct {
Confidence float64 `json:"confidence"`
Text string `json:"text"`
TextClass string `json:"text_class"`
TextType string `json:"text_type"`
}
// UI ...
type UI struct {
FeedbackQuestion []string `json:"feedback_question"`
Icon UIIcon `json:"icon"`
Text []string `json:"text"`
Type string `json:"type"`
}
// UIIcon ...
type UIIcon struct {
Active string `json:"active"`
Inactive string `json:"inactive"`
Selected []string `json:"selected"`
}
// UpdateAbuseStatusRequest ...
type UpdateAbuseStatusRequest struct {
Abusive bool `json:"abusive"`
Active bool `json:"active"`
Approve bool `json:"approve"`
Description string `json:"description"`
EntityID string `json:"entity_id"`
EntityType string `json:"entity_type"`
ID string `json:"id"`
}
// UpdateAttributeRequest ...
type UpdateAttributeRequest struct {
Description string `json:"description"`
Name string `json:"name"`
Slug string `json:"slug"`
}
// UpdateCommentRequest ...
type UpdateCommentRequest struct {
Active bool `json:"active"`
Approve bool `json:"approve"`
Comment []string `json:"comment"`
ID string `json:"id"`
}
// UpdateMediaListRequest ...
type UpdateMediaListRequest struct {
Approve bool `json:"approve"`
Archive bool `json:"archive"`
EntityType string `json:"entity_type"`
Ids []string `json:"ids"`
}
// UpdateQNARequest ...
type UpdateQNARequest struct {
Active bool `json:"active"`
Approve bool `json:"approve"`
Choices []string `json:"choices"`
ID string `json:"id"`
Tags []string `json:"tags"`
}
// UpdateResponse ...
type UpdateResponse struct {
ID string `json:"id"`
}
// UpdateReviewRequest ...
type UpdateReviewRequest struct {
Active bool `json:"active"`
Application string `json:"application"`
Approve bool `json:"approve"`
Archive bool `json:"archive"`
AttributesRating []AttributeObject `json:"attributes_rating"`
Description string `json:"description"`
DeviceMeta DeviceMeta `json:"device_meta"`
EntityID string `json:"entity_id"`
EntityType string `json:"entity_type"`
MediaResource []MediaMeta `json:"media_resource"`
Rating float64 `json:"rating"`
ReviewID string `json:"review_id"`
TemplateID string `json:"template_id"`
Title string `json:"title"`
}
// UpdateVoteRequest ...
type UpdateVoteRequest struct {
Action string `json:"action"`
Active bool `json:"active"`
ID string `json:"id"`
RefID string `json:"ref_id"`
RefType string `json:"ref_type"`
}
// Url ...
type Url struct {
Main string `json:"main"`
Thumbnail string `json:"thumbnail"`
}
// Vote ...
type Vote struct {
Action string `json:"action"`
DateMeta DateMeta `json:"date_meta"`
Entity Entity `json:"entity"`
ID string `json:"id"`
Name string `json:"name"`
Reference Entity `json:"reference"`
State FeedbackState `json:"state"`
Tags []TagMeta `json:"tags"`
}
// VoteCount ...
type VoteCount struct {
Downvote float64 `json:"downvote"`
Upvote float64 `json:"upvote"`
}
// VoteRequest ...
type VoteRequest struct {
Action string `json:"action"`
EntityID string `json:"entity_id"`
EntityType string `json:"entity_type"`
RefID string `json:"ref_id"`
RefType string `json:"ref_type"`
}
// VoteResponse ...
type VoteResponse struct {
Items []Vote `json:"items"`
Page Page `json:"page"`
}
// UpdateCartShipmentItem ...
type UpdateCartShipmentItem struct {
ArticleUID string `json:"article_uid"`
ShipmentType string `json:"shipment_type"`
Quantity float64 `json:"quantity"`
}
// UpdateCartShipmentRequest ...
type UpdateCartShipmentRequest struct {
Shipments []UpdateCartShipmentItem `json:"shipments"`
}
// Files ...
type Files struct {
Key string `json:"key"`
Values []string `json:"values"`
}
// CartPosCheckoutDetailRequest ...
type CartPosCheckoutDetailRequest struct {
Staff StaffCheckout `json:"staff"`
PickAtStoreUID float64 `json:"pick_at_store_uid"`
MerchantCode string `json:"merchant_code"`
PaymentParams map[string]interface{} `json:"payment_params"`
OrderingStore float64 `json:"ordering_store"`
PaymentAutoConfirm bool `json:"payment_auto_confirm"`
CallbackURL string `json:"callback_url"`
BillingAddress map[string]interface{} `json:"billing_address"`
FyndstoreEmpID string `json:"fyndstore_emp_id"`
PaymentIdentifier string `json:"payment_identifier"`
PaymentMode string `json:"payment_mode"`
DeliveryAddress map[string]interface{} `json:"delivery_address"`
Files []Files `json:"files"`
Aggregator string `json:"aggregator"`
OrderType string `json:"order_type"`
ExtraMeta map[string]interface{} `json:"extra_meta"`
BillingAddressID string `json:"billing_address_id"`
AddressID string `json:"address_id"`
Meta map[string]interface{} `json:"meta"`
Pos bool `json:"pos"`
}
// CartDeliveryModesResponse ...
type CartDeliveryModesResponse struct {
PickupStores []float64 `json:"pickup_stores"`
AvailableModes []string `json:"available_modes"`
}
// PickupStoreDetail ...
type PickupStoreDetail struct {
Address string `json:"address"`
Country string `json:"country"`
City string `json:"city"`
AreaCode string `json:"area_code"`
UID float64 `json:"uid"`
StoreCode string `json:"store_code"`
Name string `json:"name"`
ID float64 `json:"id"`
AddressType string `json:"address_type"`
Pincode float64 `json:"pincode"`
Landmark string `json:"landmark"`
Area string `json:"area"`
AreaCodeSlug string `json:"area_code_slug"`
State string `json:"state"`
Phone string `json:"phone"`
Email string `json:"email"`
}
// StoreDetailsResponse ...
type StoreDetailsResponse struct {
Items []PickupStoreDetail `json:"items"`
}
// GetPincodeCityResponse ...
type GetPincodeCityResponse struct {
RequestUUID string `json:"request_uuid"`
StormbreakerUUID string `json:"stormbreaker_uuid"`
Success bool `json:"success"`
Data []LogisticPincodeData `json:"data"`
}
// LogisticPincodeData ...
type LogisticPincodeData struct {
Meta LogisticMeta `json:"meta"`
Parents []LogisticParents `json:"parents"`
SubType string `json:"sub_type"`
Name string `json:"name"`
Error LogisticError `json:"error"`
UID string `json:"uid"`
DisplayName string `json:"display_name"`
}
// LogisticMeta ...
type LogisticMeta struct {
Zone string `json:"zone"`
Deliverables []interface{} `json:"deliverables"`
}
// LogisticParents ...
type LogisticParents struct {
SubType string `json:"sub_type"`
Name string `json:"name"`
DisplayName string `json:"display_name"`
UID string `json:"uid"`
}
// LogisticError ...
type LogisticError struct {
Type string `json:"type"`
Value string `json:"value"`
Message string `json:"message"`
}
// GetTatProductReqBody ...
type GetTatProductReqBody struct {
LocationDetails []LocationDetailsReq `json:"location_details"`
ToPincode string `json:"to_pincode"`
Action string `json:"action"`
}
// LocationDetailsReq ...
type LocationDetailsReq struct {
FromPincode string `json:"from_pincode"`
Articles []TatReqProductArticles `json:"articles"`
FulfillmentID float64 `json:"fulfillment_id"`
}
// TatReqProductArticles ...
type TatReqProductArticles struct {
Category LogisticRequestCategory `json:"category"`
}
// LogisticRequestCategory ...
type LogisticRequestCategory struct {
ID float64 `json:"id"`
Level string `json:"level"`
}
// GetTatProductResponse ...
type GetTatProductResponse struct {
LocationDetails []LocationDetails `json:"location_details"`
RequestUUID string `json:"request_uuid"`
Error map[string]interface{} `json:"error"`
ToCity string `json:"to_city"`
Source string `json:"source"`
ToPincode string `json:"to_pincode"`
Action string `json:"action"`
StormbreakerUUID string `json:"stormbreaker_uuid"`
Success bool `json:"success"`
Identifier string `json:"identifier"`
Journey string `json:"journey"`
}
// LocationDetails ...
type LocationDetails struct {
FromPincode string `json:"from_pincode"`
Articles []TatProductArticles `json:"articles"`
FulfillmentID float64 `json:"fulfillment_id"`
}
// TatProductArticles ...
type TatProductArticles struct {
Error map[string]interface{} `json:"error"`
Category LogisticResponseCategory `json:"category"`
Promise LogisticPromise `json:"promise"`
}
// LogisticResponseCategory ...
type LogisticResponseCategory struct {
ID float64 `json:"id"`
Level string `json:"level"`
}
// LogisticPromise ...
type LogisticPromise struct {
Timestamp LogisticTimestamp `json:"timestamp"`
Formatted Formatted `json:"formatted"`
}
// LogisticTimestamp ...
type LogisticTimestamp struct {
Min float64 `json:"min"`
Max float64 `json:"max"`
}
// Formatted ...
type Formatted struct {
Min string `json:"min"`
Max string `json:"max"`
}
| 26.499823 | 105 | 0.524224 |
16ce64004cfc78fb03c10224f25ac1dfe6554282 | 11,481 | ts | TypeScript | packages/loader/src/HDRLoader.ts | sthagen/oasis-engine-engine | 4d2db00c87c3bf0f4c5fa6c4ae632fa11c69ec61 | [
"MIT"
] | null | null | null | packages/loader/src/HDRLoader.ts | sthagen/oasis-engine-engine | 4d2db00c87c3bf0f4c5fa6c4ae632fa11c69ec61 | [
"MIT"
] | null | null | null | packages/loader/src/HDRLoader.ts | sthagen/oasis-engine-engine | 4d2db00c87c3bf0f4c5fa6c4ae632fa11c69ec61 | [
"MIT"
] | null | null | null | import {
AssetPromise,
AssetType,
Loader,
LoadItem,
resourceLoader,
ResourceManager,
TextureCube,
TextureCubeFace
} from "@oasis-engine/core";
import { Color, Vector3 } from "@oasis-engine/math";
const PI = Math.PI;
interface IHDRHeader {
/**
* The width of the texture in pixels.
*/
width: number;
/**
* The height of the texture in pixels.
*/
height: number;
/**
* The index of the beginning of the data in the binary file.
*/
dataPosition: number;
}
@resourceLoader(AssetType.HDR, ["hdr"])
class HDRLoader extends Loader<TextureCube> {
private static _rightBottomBack = new Vector3(1.0, -1.0, -1.0);
private static _rightBottomFront = new Vector3(1.0, -1.0, 1.0);
private static _rightUpBack = new Vector3(1.0, 1.0, -1.0);
private static _rightUpFront = new Vector3(1.0, 1.0, 1.0);
private static _leftBottomBack = new Vector3(-1.0, -1.0, -1.0);
private static _leftBottomFront = new Vector3(-1.0, -1.0, 1.0);
private static _leftUpBack = new Vector3(-1.0, 1.0, -1.0);
private static _leftUpFront = new Vector3(-1.0, 1.0, 1.0);
private static _faceRight = [
HDRLoader._rightBottomBack,
HDRLoader._rightBottomFront,
HDRLoader._rightUpBack,
HDRLoader._rightUpFront
];
private static _faceLeft = [
HDRLoader._leftBottomFront,
HDRLoader._leftBottomBack,
HDRLoader._leftUpFront,
HDRLoader._leftUpBack
];
private static _faceUp = [
HDRLoader._leftBottomFront,
HDRLoader._rightBottomFront,
HDRLoader._leftBottomBack,
HDRLoader._rightBottomBack
];
private static _faceBottom = [
HDRLoader._leftUpBack,
HDRLoader._rightUpBack,
HDRLoader._leftUpFront,
HDRLoader._rightUpFront
];
private static _faceFront = [
HDRLoader._leftBottomBack,
HDRLoader._rightBottomBack,
HDRLoader._leftUpBack,
HDRLoader._rightUpBack
];
private static _faceBack = [
HDRLoader._rightBottomFront,
HDRLoader._leftBottomFront,
HDRLoader._rightUpFront,
HDRLoader._leftUpFront
];
private static _tempVector3 = new Vector3();
private static _temp2Vector3 = new Vector3();
private static _temp3Vector3 = new Vector3();
private static _temp4Vector3 = new Vector3();
private static _temp5Vector3 = new Vector3();
private static _convertToCubemap(
pixels: Uint8Array,
inputWidth: number,
inputHeight: number,
size: number
): Uint8ClampedArray[] {
if (!pixels) {
throw "ConvertPanoramaToCubemap: input cannot be null";
}
if (pixels.length != inputWidth * inputHeight * 4) {
throw "ConvertPanoramaToCubemap: input size is wrong";
}
const textureRight = this._createCubemapData(size, this._faceRight, pixels, inputWidth, inputHeight);
const textureLeft = this._createCubemapData(size, this._faceLeft, pixels, inputWidth, inputHeight);
const textureUp = this._createCubemapData(size, this._faceUp, pixels, inputWidth, inputHeight);
const textureDown = this._createCubemapData(size, this._faceBottom, pixels, inputWidth, inputHeight);
const textureFront = this._createCubemapData(size, this._faceFront, pixels, inputWidth, inputHeight);
const textureBack = this._createCubemapData(size, this._faceBack, pixels, inputWidth, inputHeight);
return [textureRight, textureLeft, textureUp, textureDown, textureFront, textureBack];
}
private static _createCubemapData(
texSize: number,
faceData: Vector3[],
pixels: Uint8Array,
inputWidth: number,
inputHeight: number
): Uint8ClampedArray {
const textureArray = new Uint8ClampedArray(texSize * texSize * 4);
const rotDX1 = this._tempVector3
.setValue(0, 0, 0)
.add(faceData[1])
.subtract(faceData[0])
.scale(1 / texSize);
const rotDX2 = this._temp2Vector3
.setValue(0, 0, 0)
.add(faceData[3])
.subtract(faceData[2])
.scale(1 / texSize);
const dy = 1 / texSize;
let fy = 0;
for (let y = 0; y < texSize; y++) {
let xv1 = this._temp3Vector3.setValue(0, 0, 0).add(faceData[0]);
let xv2 = this._temp4Vector3.setValue(0, 0, 0).add(faceData[2]);
for (let x = 0; x < texSize; x++) {
const v = this._temp5Vector3.setValue(0, 0, 0).add(xv2).subtract(xv1).scale(fy).add(xv1);
v.normalize();
const color = this._calcProjectionSpherical(v, pixels, inputWidth, inputHeight);
this._RGBEToLinear(color);
this._linearToRGBM(color, 5);
// 4 channels per pixels
const index = y * texSize * 4 + x * 4;
textureArray[index] = color.r;
textureArray[index + 1] = color.g;
textureArray[index + 2] = color.b;
textureArray[index + 3] = color.a;
xv1.add(rotDX1);
xv2.add(rotDX2);
}
fy += dy;
}
return textureArray;
}
private static _calcProjectionSpherical(
vDir: Vector3,
pixels: Uint8Array,
inputWidth: number,
inputHeight: number
): Color {
let theta = Math.atan2(vDir.z, -vDir.x);
let phi = Math.acos(vDir.y);
while (theta < -PI) {
theta += 2 * PI;
}
while (theta > PI) {
theta -= 2 * PI;
}
let dx = theta / PI;
let dy = phi / PI;
// recenter.
dx = dx * 0.5 + 0.5;
let px = Math.round(dx * inputWidth);
if (px < 0) {
px = 0;
} else if (px >= inputWidth) {
px = inputWidth - 1;
}
let py = Math.round(dy * inputHeight);
if (py < 0) {
py = 0;
} else if (py >= inputHeight) {
py = inputHeight - 1;
}
const inputY = inputHeight - py - 1;
const index = inputY * inputWidth * 4 + px * 4;
const r = pixels[index];
const g = pixels[index + 1];
const b = pixels[index + 2];
const a = pixels[index + 3];
return new Color(r, g, b, a);
}
private static _readStringLine(uint8array: Uint8Array, startIndex: number): string {
let line = "";
let character = "";
for (let i = startIndex; i < uint8array.length - startIndex; i++) {
character = String.fromCharCode(uint8array[i]);
if (character == "\n") {
break;
}
line += character;
}
return line;
}
private static _parseHeader(uint8array: Uint8Array): IHDRHeader {
let height: number = 0;
let width: number = 0;
let line = this._readStringLine(uint8array, 0);
if (line[0] != "#" || line[1] != "?") {
throw "Bad HDR Format.";
}
let endOfHeader = false;
let findFormat = false;
let lineIndex: number = 0;
do {
lineIndex += line.length + 1;
line = this._readStringLine(uint8array, lineIndex);
if (line == "FORMAT=32-bit_rle_rgbe") {
findFormat = true;
} else if (line.length == 0) {
endOfHeader = true;
}
} while (!endOfHeader);
if (!findFormat) {
throw "HDR Bad header format, unsupported FORMAT";
}
lineIndex += line.length + 1;
line = this._readStringLine(uint8array, lineIndex);
const sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
const match = sizeRegexp.exec(line);
// TODO. Support +Y and -X if needed.
if (!match || match.length < 3) {
throw "HDR Bad header format, no size";
}
width = parseInt(match[2]);
height = parseInt(match[1]);
if (width < 8 || width > 0x7fff) {
throw "HDR Bad header format, unsupported size";
}
lineIndex += line.length + 1;
return {
height: height,
width: width,
dataPosition: lineIndex
};
}
private static _readPixels(buffer: Uint8Array, width: number, height: number): Uint8Array {
const scanLineWidth = width;
const byteLength = buffer.byteLength;
const dataRGBA = new Uint8Array(4 * width * height);
let offset = 0,
pos = 0;
const ptrEnd = 4 * scanLineWidth;
const rgbeStart = new Uint8Array(4);
const scanLineBuffer = new Uint8Array(ptrEnd);
let numScanLines = height; // read in each successive scanLine
while (numScanLines > 0 && pos < byteLength) {
rgbeStart[0] = buffer[pos++];
rgbeStart[1] = buffer[pos++];
rgbeStart[2] = buffer[pos++];
rgbeStart[3] = buffer[pos++];
if (2 != rgbeStart[0] || 2 != rgbeStart[1] || ((rgbeStart[2] << 8) | rgbeStart[3]) != scanLineWidth) {
throw "HDR Bad header format, wrong scan line width";
}
// read each of the four channels for the scanline into the buffer
// first red, then green, then blue, then exponent
let ptr = 0,
count;
while (ptr < ptrEnd && pos < byteLength) {
count = buffer[pos++];
const isEncodedRun = count > 128;
if (isEncodedRun) count -= 128;
if (0 === count || ptr + count > ptrEnd) {
throw "HDR Bad Format, bad scanline data (run)";
}
if (isEncodedRun) {
// a (encoded) run of the same value
const byteValue = buffer[pos++];
for (let i = 0; i < count; i++) {
scanLineBuffer[ptr++] = byteValue;
} //ptr += count;
} else {
// a literal-run
scanLineBuffer.set(buffer.subarray(pos, pos + count), ptr);
ptr += count;
pos += count;
}
} // now convert data from buffer into rgba
// first red, then green, then blue, then exponent (alpha)
const l = scanLineWidth; //scanLine_buffer.byteLength;
for (let i = 0; i < l; i++) {
let off = 0;
dataRGBA[offset] = scanLineBuffer[i + off];
off += scanLineWidth;
dataRGBA[offset + 1] = scanLineBuffer[i + off];
off += scanLineWidth;
dataRGBA[offset + 2] = scanLineBuffer[i + off];
off += scanLineWidth;
dataRGBA[offset + 3] = scanLineBuffer[i + off];
offset += 4;
}
numScanLines--;
}
return dataRGBA;
}
private static _RGBEToLinear(color: Color): void {
const scaleFactor = Math.pow(2, color.a - 128) / 255;
color.r *= scaleFactor;
color.g *= scaleFactor;
color.b *= scaleFactor;
color.a = 1;
}
private static _linearToRGBM(color: Color, maxRange: number): void {
const maxRGB = Math.max(color.r, Math.max(color.g, color.b));
let M = Math.min(maxRGB / maxRange, 1);
M = Math.ceil(M * 255);
const scaleFactor = 65025 / (M * maxRange); // 255 * (255 / (M * maxRange) )
color.r *= scaleFactor;
color.g *= scaleFactor;
color.b *= scaleFactor;
color.a *= M;
}
load(item: LoadItem, resourceManager: ResourceManager): AssetPromise<TextureCube> {
return new AssetPromise((resolve, reject) => {
const engine = resourceManager.engine;
resourceManager
.load<ArrayBuffer>({
url: item.url,
type: AssetType.Buffer
})
.then((buffer) => {
const uint8Array = new Uint8Array(buffer);
const { width, height, dataPosition } = HDRLoader._parseHeader(uint8Array);
const pixels = HDRLoader._readPixels(uint8Array.subarray(dataPosition), width, height);
const cubeSize = height >> 1;
const cubeMapData = HDRLoader._convertToCubemap(pixels, width, height, cubeSize);
const texture = new TextureCube(engine, cubeSize);
for (let faceIndex = 0; faceIndex < 6; faceIndex++) {
texture.setPixelBuffer(TextureCubeFace.PositiveX + faceIndex, cubeMapData[faceIndex], 0);
}
texture.generateMipmaps();
resolve(texture);
})
.catch(reject);
});
}
}
| 28.630923 | 108 | 0.615365 |
57631a4cf0d5b22306ac35daecda6aabb22a9e54 | 384 | swift | Swift | GetYourGuide/Constants/URLConstants.swift | leonardo-ferreira07/GetYourGuide-HomeTest | 4ae2d57cf6bc9d9c70c146b0075fd4b08ae2a9c3 | [
"MIT"
] | 1 | 2019-08-31T15:24:11.000Z | 2019-08-31T15:24:11.000Z | GetYourGuide/Constants/URLConstants.swift | leonardo-ferreira07/GetYourGuide-HomeTest | 4ae2d57cf6bc9d9c70c146b0075fd4b08ae2a9c3 | [
"MIT"
] | null | null | null | GetYourGuide/Constants/URLConstants.swift | leonardo-ferreira07/GetYourGuide-HomeTest | 4ae2d57cf6bc9d9c70c146b0075fd4b08ae2a9c3 | [
"MIT"
] | null | null | null | //
// URLConstants.swift
// GetYourGuide
//
// Created by Leonardo Vinicius Kaminski Ferreira on 30/07/19.
// Copyright © 2019 Leonardo Ferreira. All rights reserved.
//
import Foundation
struct URLConstants {
static let reviewsURL: String = "https://www.getyourguide.com/berlin-l17/tempelhof-2-hour-airport-history-tour-berlin-airlift-more-t23776/reviews.json"
}
| 24 | 155 | 0.731771 |
12f91527f702a276dadf40ff0f2c27e4e2ce75c6 | 2,805 | html | HTML | public/index.html | ernestognw/avatheeers-link | 9ce60e31fbea66d36ccf0ee62a86adbfb88f081f | [
"MIT"
] | 1 | 2020-10-06T19:52:57.000Z | 2020-10-06T19:52:57.000Z | public/index.html | ernestognw/avatheeers | 9d1e01da99c601b8acbe7cd6f3490517441cdf97 | [
"MIT"
] | null | null | null | public/index.html | ernestognw/avatheeers | 9d1e01da99c601b8acbe7cd6f3490517441cdf97 | [
"MIT"
] | 2 | 2021-03-12T00:33:36.000Z | 2022-01-07T07:47:00.000Z | <!DOCTYPE html>
<html class="uk-background-muted" lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- UIkit CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/uikit@3.5.7/dist/css/uikit.min.css" />
<!-- UIkit JS -->
<script src="https://cdn.jsdelivr.net/npm/uikit@3.5.7/dist/js/uikit.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/uikit@3.5.7/dist/js/uikit-icons.min.js"></script>
<style>
.inventory-list {
display: grid;
grid-gap: 30px;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
}
.hidden {
display: none !important;
}
.uk-notification-message {
background: #222;
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
}
.fade {
opacity: 0.7;
}
</style>
<title>Avatheeer</title>
</head>
<body>
<!-- Loading -->
<div id="loading-container">
<div uk-spinner="ratio: 3" class="uk-position-center"></div>
</div>
<!-- Welcome -->
<div id="welcome-container" class="uk-position-center hidden">
<h1 class="uk-heading-medium uk-text-center">Welcome!</h1>
<h3 id="start-message" class="uk-text-center">Please connect your metamask
account to begin.</h3>
<img src="./images/metamask.svg" class="uk-align-center" />
<button id="connect-button" class="uk-button uk-button-primary uk-align-center">Connect</button>
</div>
<!-- Main -->
<div id="main-container" class="uk-container uk-container-small uk-padding-large hidden">
<!-- Header -->
<h1 class="uk-heading-small uk-text-center uk-text-bold ">avatheeer</h1>
<!-- Navigation -->
<ul class="uk-flex-center" uk-tab="animation: uk-animation-fade">
<li class="uk-active"><a href="#">Create new</a></li>
<li><a id="inventory-tab" href="#">Inventory</a></li>
</ul>
<ul class="uk-switcher uk-margin">
<!-- Create section -->
<li class="uk-active">
<h2 class="uk-text-center">Create new Avatheeer</h2>
<img class="uk-align-center" id="avatheeer-container" height="350" width="350" src="./images/placeholder.png" />
<form class="uk-margin uk-text-center" uk-margin>
<input class="uk-input uk-form-width-medium" type="text" id="create-input" maxlength="20"
placeholder="Enter name...">
<button class="uk-button uk-button-primary" id="create-button">Create</button>
</form>
</li>
<!-- Inventory section -->
<li>
<h2 class="uk-text-center">Your inventory</h2>
<!-- Pizza containers will be appended to this div -->
<div id="inventory-container" class="inventory-list">
</div>
</li>
</ul>
</div>
<script src="main.js"></script>
</body>
</html> | 31.166667 | 120 | 0.606061 |
bb545e0903f40221df410d291573691481fa8d64 | 363 | swift | Swift | CodeViewer/ViewController.swift | madcato/app-clip-sample-code | c835c4521b9aa04dea26163e4ca1a6d8b05afd8f | [
"MIT"
] | 2 | 2021-01-19T22:34:05.000Z | 2021-07-16T01:21:44.000Z | CodeViewer/ViewController.swift | madcato/app-clip-sample-code | c835c4521b9aa04dea26163e4ca1a6d8b05afd8f | [
"MIT"
] | null | null | null | CodeViewer/ViewController.swift | madcato/app-clip-sample-code | c835c4521b9aa04dea26163e4ca1a6d8b05afd8f | [
"MIT"
] | null | null | null | //
// ViewController.swift
// CodeViewer
//
// Created by Daniel Vela on 11/09/2020.
// Copyright © 2020 veladan. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var codeLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
| 15.782609 | 54 | 0.688705 |
fb9d31a89811c6ff8eddf1590dea16694c2f88cd | 770 | h | C | core/src/UMBarcodeScanViewControllerPvt.h | mcyril/barcodes | 523570475149fcc9f2153ed5b11812de2a622224 | [
"MIT"
] | 2 | 2015-07-06T18:21:51.000Z | 2018-10-31T17:10:44.000Z | core/src/UMBarcodeScanViewControllerPvt.h | mcyril/barcodes | 523570475149fcc9f2153ed5b11812de2a622224 | [
"MIT"
] | 1 | 2017-11-21T04:43:44.000Z | 2017-11-21T05:07:44.000Z | core/src/UMBarcodeScanViewControllerPvt.h | mcyril/barcodes | 523570475149fcc9f2153ed5b11812de2a622224 | [
"MIT"
] | null | null | null | //
// UMBarcodeScanViewControllerPvt.h
//
// Copyright (c) 2015 Ravel Developers Group. All rights reserved.
// Created by Cyril Murzin
//
#import "UMBarcodeScanViewController.h"
@interface UMBarcodeScanViewController ()
@property (nonatomic, retain) UMBarcodeScanContext* context;
@property (nonatomic, assign) BOOL shouldStoreStatusBarStyle;
@property (nonatomic, assign) BOOL statusBarWasOriginallyHidden;
@property (nonatomic, assign) UIStatusBarStyle originalStatusBarStyle;
- (BOOL)_isBeingPresentedModally;
- (UIInterfaceOrientationMask)_supportedOverlayOrientationsMask;
+ (UIViewController*)_viewControllerWithContext:(UMBarcodeScanContext*)aContext;
+ (UMBarcodeScanViewController*)_barcodeScanViewControllerForResponder:(UIResponder*)responder;
@end
| 32.083333 | 95 | 0.824675 |
0ef61a4fdf345536da5015a32ac1f24f6476b991 | 888 | h | C | Game/Source/SceneWin.h | AMADE128/PlatformerGame | f81b25505781ef82171984e95f2a8b675767a715 | [
"MIT"
] | null | null | null | Game/Source/SceneWin.h | AMADE128/PlatformerGame | f81b25505781ef82171984e95f2a8b675767a715 | [
"MIT"
] | null | null | null | Game/Source/SceneWin.h | AMADE128/PlatformerGame | f81b25505781ef82171984e95f2a8b675767a715 | [
"MIT"
] | null | null | null | #ifndef __SCENEWIN_H__
#define __SCENEWIN_H__
#include "Module.h"
#include "GuiButton.h"
struct SDL_Texture;
class SceneWin : public Module
{
public:
SceneWin();
// Destructor
virtual ~SceneWin();
// Called before render is available
bool Awake();
// Called before the first frame
bool Start();
// Called before all Updates
bool PreUpdate();
// Called each loop iteration
bool Update(float dt);
// Called before all Updates
bool PostUpdate();
// Called before quitting
bool CleanUp();
bool OnGuiMouseClickEvent(GuiControl* control);
SDL_Texture* winTex;
SDL_Texture* appleTex;
char scoreText[30] = { "\0" };
char highscoreText[30] = { "\0" };
char secondsText[10] = { "\0" };
char minutesText[10] = { "\0" };
char msText[10] = { "\0" };
char applesText[10] = { "\0" };
private:
GuiButton* btnBack;
unsigned int winMusic;
};
#endif // __SCENE_H__ | 16.444444 | 48 | 0.679054 |
c0857b8abd473909a5ff5a991960f52ebb549fd6 | 1,690 | html | HTML | app/views/sprint2/name.html | ballzy/jsa-complaints | 058dd0916945b487233e304e61ce9f8cf3ec3c20 | [
"MIT"
] | null | null | null | app/views/sprint2/name.html | ballzy/jsa-complaints | 058dd0916945b487233e304e61ce9f8cf3ec3c20 | [
"MIT"
] | null | null | null | app/views/sprint2/name.html | ballzy/jsa-complaints | 058dd0916945b487233e304e61ce9f8cf3ec3c20 | [
"MIT"
] | null | null | null | {{<layout}}
{{$pageTitle}}
Jobseeker's Allowance (JSA)
{{/pageTitle}}
{{$content}}
<main id="content" role="main">
{{>includes/alpha-banner}}
<br>
<span class="section-progress">Section 3 of 3</span>
<div>
<h2 class="heading-large">Jobseeker's Allowance complaints</h2>
</div>
<fieldset class="inline">
<legend>
<span class="form-label-bold">
Do you want a response when your complaint's been dealt with?
</span>
</legend>
<div class="form-group form-group-compound">
<label class="block-label" data-target="example-ni-no" for="radio-indent-1">
<input id="radio-indent-1" type="radio" name="radio-indent-group" value="Yes">
Yes
</label>
<label class="block-label" for="radio-indent-2">
<input id="radio-indent-2" type="radio" name="radio-indent-group" value="No">
No
</label>
</div>
<div class="panel-indent js-hidden" id="example-ni-no">
<div class="form-group">
<label class="form-label" for="name">Name</label>
<input class="form-control" id="name" type="text">
</div>
<div class="form-group">
<label class="form-label" for="ni-number">National Insurance Number</label>
<input class="form-control" id="ni-number" type="text">
</div>
<div class="form-group">
<label class="form-label" for="phone-number">Phone number</label>
<input class="form-control" id="phone-number" type="text">
</div>
</div>
</fieldset>
<!-- Primary buttons, secondary links -->
<div>
<a href="/sprint2/sent" class="button" role="button">Send complaint</a>
</div>
</main>
{{/content}}
{{/layout}}
| 23.150685 | 86 | 0.604142 |
603f6ddddbe9d3f86766259d08823bbb6cc9ea50 | 581 | html | HTML | Desafios/d008/areas/amarelo.html | CaioAnd/curso-html | faf73e9a9b0802d5374b7ebb9bf78139005542bd | [
"MIT"
] | null | null | null | Desafios/d008/areas/amarelo.html | CaioAnd/curso-html | faf73e9a9b0802d5374b7ebb9bf78139005542bd | [
"MIT"
] | null | null | null | Desafios/d008/areas/amarelo.html | CaioAnd/curso-html | faf73e9a9b0802d5374b7ebb9bf78139005542bd | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Navegação</title>
<link rel="shortcut icon" href="../arquivos/favicon.ico" type="image/x-icon">
</head>
<body bgcolor="#FFFFE3">
<h1 style="color:#C3884B">Página Amarela</h1>
<p style="color:#D4AA76">
Você está na área amarela. Você acessou clicando no segundo link da página principal.
</p>
<ul>
<li><a href="../index.html">Voltar para a página cinza</a>
</ul>
</body>
</html> | 26.409091 | 93 | 0.623064 |
e78168a4b732d3656cc91901a1d87f1dda6057fd | 45,644 | js | JavaScript | dist/rtmp_hls.js | securogroup/clappr-rtmp-hls | eb6c7990906d37303ffdd8e0ac7c3721412cd54a | [
"BSD-3-Clause"
] | 8 | 2015-06-09T20:28:46.000Z | 2017-04-22T15:34:16.000Z | dist/rtmp_hls.js | securogroup/clappr-rtmp-hls | eb6c7990906d37303ffdd8e0ac7c3721412cd54a | [
"BSD-3-Clause"
] | null | null | null | dist/rtmp_hls.js | securogroup/clappr-rtmp-hls | eb6c7990906d37303ffdd8e0ac7c3721412cd54a | [
"BSD-3-Clause"
] | null | null | null | (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
"use strict";
var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc && desc.writable) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
var Playback = require("playback");
var JST = require("./jst");
var Events = require("events");
var Mediator = require("mediator");
var assign = require("lodash.assign");
var PlayerInfo = require("player_info");
var RtmpHls = (function (_Playback) {
function RtmpHls(options) {
var _this2 = this;
_classCallCheck(this, RtmpHls);
_get(Object.getPrototypeOf(RtmpHls.prototype), "constructor", this).call(this, options);
var _this = this;
this.options = options;
this.playbacks = {};
this.initCount = 0;
this.hlsPlayback = {};
this.rtmpPlayback = {};
PlayerInfo.playbackPlugins.forEach(function (playback) {
//console.log(playback.prototype.name);
if (playback.prototype.name == "hls") {
_this.hlsPlayback = playback;
} else if (playback.prototype.name == "rtmp") {
_this.rtmpPlayback = playback;
} else {}
});
this.currentState = "STOPPED";
this.currentPlayer = "RTMP";
this.settings = { "default": ["seekbar"] };
this.settings.left = ["playpause"];
this.settings.right = ["fullscreen"];
this.settings.seekEnabled = false;
var rtmpOptions = assign(options, { src: options.rtmpSource });
this.RTMP = new this.rtmpPlayback(rtmpOptions);
var hlsOptions = assign(options, { src: options.hlsSource, capLevelToStage: true });
this.HLS = new this.hlsPlayback(hlsOptions);
this.RTMP.once(Events.PLAYBACK_READY, function () {
return _this2.bootstrap();
});
this.HLS.once(Events.PLAYBACK_READY, function () {
return _this2.bootstrap();
});
}
_inherits(RtmpHls, _Playback);
_createClass(RtmpHls, {
name: {
get: function () {
return "rtmp_hls";
}
},
tagName: {
get: function () {
return "div";
}
},
attributes: {
get: function () {
return {
"data-rtmp-hls": ""
};
}
},
switchPlayer: {
value: function switchPlayer(newPlayer) {
this.currentPlayer = newPlayer;
if (newPlayer == "HLS") {
$("[data-rtmp]").css("visibility", "hidden");
$("[data-hls]").css("visibility", "visible");
} else if (newPlayer == "RTMP") {
$("[data-rtmp]").css("visibility", "visible");
$("[data-hls]").css("visibility", "hidden");
} else {
throw new Error("Unknown player type to switch to");
}
}
},
addFulltimeListeners: {
value: function addFulltimeListeners() {
var _this = this;
//Every x seconds the HLS player when paused will refresh the m3u8 and latest TS and update duration. How convenient
this.HLS.on(Events.PLAYBACK_TIMEUPDATE, function (hlsPos, hlsDur) {
if (!_this.isPlaying()) return;
_this.duration = hlsDur;
var pos = _this.currentPlayer == "HLS" ? hlsPos : hlsDur; //Only use the HLS position if we're using the HLS player
_this.trigger(Events.PLAYBACK_TIMEUPDATE, pos, _this.duration, _this.name);
});
}
},
addRtmpListeners: {
value: function addRtmpListeners() {
var _this = this;
//Bubble RTMP live events back up
this.RTMP.on(Events.PLAYBACK_BUFFERFULL, function () {
return _this.setPlaybackState("PLAYBACK_BUFFERFULL");
});
this.RTMP.on(Events.PLAYBACK_BUFFERING, function () {
return _this.setPlaybackState("PLAYBACK_BUFFERING");
});
this.RTMP.on(Events.PLAYBACK_PLAY, function () {
return _this.setPlaybackState("PLAYING");
});
}
},
removeRtmpListeners: {
value: function removeRtmpListeners() {
this.RTMP.off(Events.PLAYBACK_BUFFERFULL);
this.RTMP.off(Events.PLAYBACK_BUFFERING);
this.RTMP.off(Events.PLAYBACK_PLAY);
}
},
addHlsListeners: {
value: function addHlsListeners() {
var _this = this;
//Bubble RTMP live events back up
this.HLS.on(Events.PLAYBACK_BUFFERFULL, function () {
return _this.setPlaybackState("PLAYING");
});
}
},
removeHlsListeners: {
value: function removeHlsListeners() {
this.HLS.off(Events.PLAYBACK_BUFFERFULL);
}
},
bootstrap: {
value: function bootstrap() {
if (++this.initCount != 2) {
return;
}this.el.width = "100%";
this.el.height = "100%";
this.addFulltimeListeners();
this.currentState = "IDLE";
this.settings.seekEnabled = true;
this.trigger(Events.PLAYBACK_SETTINGSUPDATE, this.name);
this.trigger(Events.PLAYBACK_PLAYBACKSTATE);
this.trigger(Events.PLAYBACK_READY, this.name);
}
},
play: {
value: function play() {
var _this = this;
if (this.currentState == "IDLE") {
this.addRtmpListeners();
this.HLS.once(Events.PLAYBACK_BUFFERFULL, function () {
return _this.HLS.pause();
});
this.HLS.play();
this.RTMP.play();
}
}
},
isPlaying: {
value: function isPlaying() {
return this.currentState == "PLAYING";
}
},
getPlaybackType: {
value: function getPlaybackType() {
return "live";
}
},
getDuration: {
value: function getDuration() {
return this.duration;
}
},
setPlaybackState: {
value: function setPlaybackState(state) {
if (["PLAYING_BUFFERING", "PAUSED_BUFFERING"].indexOf(state) >= 0) {
this.trigger(Events.PLAYBACK_BUFFERING, this.name);
this.updateCurrentState(state);
} else if (["PLAYING", "PAUSED"].indexOf(state) >= 0) {
if (["PLAYING_BUFFERING", "PAUSED_BUFFERING", "IDLE"].indexOf(this.currentState) >= 0) {
this.trigger(Events.PLAYBACK_BUFFERFULL, this.name);
}
this.updateCurrentState(state);
} else if (state === "IDLE") {
this.updateCurrentState(state);
this.trigger(Events.PLAYBACK_TIMEUPDATE, 0, this.el.getDuration(), this.name);
this.trigger(Events.PLAYBACK_ENDED, this.name);
}
}
},
updateCurrentState: {
value: function updateCurrentState(state) {
this.currentState = state;
this.trigger(Events.PLAYBACK_PLAYBACKSTATE);
if (state === "PLAYING") {
this.trigger(Events.PLAYBACK_PLAY, this.name);
} else if (state === "PAUSED") {
this.trigger(Events.PLAYBACK_PAUSE, this.name);
}
}
},
updateDvr: {
value: function updateDvr(dvrInUse) {
this.trigger(Events.PLAYBACK_DVR, dvrInUse);
this.trigger(Events.PLAYBACK_STATS_ADD, { dvr: dvrInUse });
}
},
pause: {
value: function pause() {
this.HLS.seek(-1);
this.switchPlayer("HLS");
this.RTMP.pause();
this.updateDvr(true);
}
},
seek: {
value: function seek(time) {
//Time is a percentage of the duration. If the user gets within 97 percent (time==97 then go to RTMP)
//Seek to RTMP, go back to live
if (time >= 97 || time < 0) {
this.switchPlayer("RTMP");
this.removeHlsListeners();
this.HLS.seek(-1);
this.HLS.pause();
this.addRtmpListeners();
this.RTMP.play();
this.updateDvr(false);
} else {
//Seek to HLS position
if (this.currentPlayer != "HLS") {
this.switchPlayer("HLS");
this.RTMP.stop();
this.removeRtmpListeners();
this.addHlsListeners();
this.HLS.play();
this.updateDvr(true);
}
this.HLS.seek(time);
if (!this.HLS.isPlaying()) this.HLS.play();
}
}
},
stop: {
value: function stop() {
this.currentState == "STOPPED";
this.RTMP.stop();
}
},
render: {
value: function render() {
this.el.id = "rtmp-hls";
console.log("rendering", this.name);
this.$el.html("");
var style = $("<style>").html(JST.CSS[this.name]);
this.$el.append(style);
this.$el.append(this.RTMP.render().el);
this.$el.append(this.HLS.render().el);
//this.settings = {'left': ["playstop"], 'default': ['seekbar'], 'right': ['fullscreen']}
//this.settings.seekEnabled = false
//this.trigger(Events.PLAYBACK_SETTINGSUPDATE, this.name)
return this;
}
}
});
return RtmpHls;
})(Playback);
RtmpHls.canPlay = function (source) {
console.log(source);
//should return true for the supported media source
return source.indexOf("rtmp+hls://") > -1;
};
module.exports = window.RtmpHls = RtmpHls;
//console.log('ignoring '+playback.prototype.name)
//this.bootstrap()
//this.RTMP.on(Events.PLAYBACK_BUFFERING, () => this.setPlaybackState('PLAYBACK_BUFFERING'))
},{"./jst":2,"events":"events","lodash.assign":3,"mediator":"mediator","playback":"playback","player_info":"player_info"}],2:[function(require,module,exports){
//This file is generated by bin/hook.js
"use strict";
var template = require("template");
module.exports = {
CSS: {
rtmp_hls: "#rtmp-hls {\twidth: 100%;\theight: 100%;}[data-hls] {\tvisibility: hidden;}" }
};
},{"template":"template"}],3:[function(require,module,exports){
/**
* lodash 3.2.0 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
var baseAssign = require('lodash._baseassign'),
createAssigner = require('lodash._createassigner'),
keys = require('lodash.keys');
/**
* A specialized version of `_.assign` for customizing assigned values without
* support for argument juggling, multiple sources, and `this` binding `customizer`
* functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {Function} customizer The function to customize assigned values.
* @returns {Object} Returns `object`.
*/
function assignWith(object, source, customizer) {
var index = -1,
props = keys(source),
length = props.length;
while (++index < length) {
var key = props[index],
value = object[key],
result = customizer(value, source[key], key, object, source);
if ((result === result ? (result !== value) : (value === value)) ||
(value === undefined && !(key in object))) {
object[key] = result;
}
}
return object;
}
/**
* Assigns own enumerable properties of source object(s) to the destination
* object. Subsequent sources overwrite property assignments of previous sources.
* If `customizer` is provided it is invoked to produce the assigned values.
* The `customizer` is bound to `thisArg` and invoked with five arguments:
* (objectValue, sourceValue, key, object, source).
*
* **Note:** This method mutates `object` and is based on
* [`Object.assign`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign).
*
* @static
* @memberOf _
* @alias extend
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @param {Function} [customizer] The function to customize assigned values.
* @param {*} [thisArg] The `this` binding of `customizer`.
* @returns {Object} Returns `object`.
* @example
*
* _.assign({ 'user': 'barney' }, { 'age': 40 }, { 'user': 'fred' });
* // => { 'user': 'fred', 'age': 40 }
*
* // using a customizer callback
* var defaults = _.partialRight(_.assign, function(value, other) {
* return _.isUndefined(value) ? other : value;
* });
*
* defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
* // => { 'user': 'barney', 'age': 36 }
*/
var assign = createAssigner(function(object, source, customizer) {
return customizer
? assignWith(object, source, customizer)
: baseAssign(object, source);
});
module.exports = assign;
},{"lodash._baseassign":4,"lodash._createassigner":6,"lodash.keys":10}],4:[function(require,module,exports){
/**
* lodash 3.2.0 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
var baseCopy = require('lodash._basecopy'),
keys = require('lodash.keys');
/**
* The base implementation of `_.assign` without support for argument juggling,
* multiple sources, and `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssign(object, source) {
return source == null
? object
: baseCopy(source, keys(source), object);
}
module.exports = baseAssign;
},{"lodash._basecopy":5,"lodash.keys":10}],5:[function(require,module,exports){
/**
* lodash 3.0.1 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/**
* Copies properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Array} props The property names to copy.
* @param {Object} [object={}] The object to copy properties to.
* @returns {Object} Returns `object`.
*/
function baseCopy(source, props, object) {
object || (object = {});
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
object[key] = source[key];
}
return object;
}
module.exports = baseCopy;
},{}],6:[function(require,module,exports){
/**
* lodash 3.1.1 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
var bindCallback = require('lodash._bindcallback'),
isIterateeCall = require('lodash._isiterateecall'),
restParam = require('lodash.restparam');
/**
* Creates a function that assigns properties of source object(s) to a given
* destination object.
*
* **Note:** This function is used to create `_.assign`, `_.defaults`, and `_.merge`.
*
* @private
* @param {Function} assigner The function to assign values.
* @returns {Function} Returns the new assigner function.
*/
function createAssigner(assigner) {
return restParam(function(object, sources) {
var index = -1,
length = object == null ? 0 : sources.length,
customizer = length > 2 ? sources[length - 2] : undefined,
guard = length > 2 ? sources[2] : undefined,
thisArg = length > 1 ? sources[length - 1] : undefined;
if (typeof customizer == 'function') {
customizer = bindCallback(customizer, thisArg, 5);
length -= 2;
} else {
customizer = typeof thisArg == 'function' ? thisArg : undefined;
length -= (customizer ? 1 : 0);
}
if (guard && isIterateeCall(sources[0], sources[1], guard)) {
customizer = length < 3 ? undefined : customizer;
length = 1;
}
while (++index < length) {
var source = sources[index];
if (source) {
assigner(object, source, customizer);
}
}
return object;
});
}
module.exports = createAssigner;
},{"lodash._bindcallback":7,"lodash._isiterateecall":8,"lodash.restparam":9}],7:[function(require,module,exports){
/**
* lodash 3.0.1 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/**
* A specialized version of `baseCallback` which only supports `this` binding
* and specifying the number of arguments to provide to `func`.
*
* @private
* @param {Function} func The function to bind.
* @param {*} thisArg The `this` binding of `func`.
* @param {number} [argCount] The number of arguments to provide to `func`.
* @returns {Function} Returns the callback.
*/
function bindCallback(func, thisArg, argCount) {
if (typeof func != 'function') {
return identity;
}
if (thisArg === undefined) {
return func;
}
switch (argCount) {
case 1: return function(value) {
return func.call(thisArg, value);
};
case 3: return function(value, index, collection) {
return func.call(thisArg, value, index, collection);
};
case 4: return function(accumulator, value, index, collection) {
return func.call(thisArg, accumulator, value, index, collection);
};
case 5: return function(value, other, key, object, source) {
return func.call(thisArg, value, other, key, object, source);
};
}
return function() {
return func.apply(thisArg, arguments);
};
}
/**
* This method returns the first argument provided to it.
*
* @static
* @memberOf _
* @category Utility
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'user': 'fred' };
*
* _.identity(object) === object;
* // => true
*/
function identity(value) {
return value;
}
module.exports = bindCallback;
},{}],8:[function(require,module,exports){
/**
* lodash 3.0.9 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/** Used to detect unsigned integer values. */
var reIsUint = /^\d+$/;
/**
* Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer)
* of an array-like value.
*/
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
/**
* Gets the "length" property value of `object`.
*
* **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
* that affects Safari on at least iOS 8.1-8.3 ARM64.
*
* @private
* @param {Object} object The object to query.
* @returns {*} Returns the "length" value.
*/
var getLength = baseProperty('length');
/**
* Checks if `value` is array-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
*/
function isArrayLike(value) {
return value != null && isLength(getLength(value));
}
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
length = length == null ? MAX_SAFE_INTEGER : length;
return value > -1 && value % 1 == 0 && value < length;
}
/**
* Checks if the provided arguments are from an iteratee call.
*
* @private
* @param {*} value The potential iteratee value argument.
* @param {*} index The potential iteratee index or key argument.
* @param {*} object The potential iteratee object argument.
* @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`.
*/
function isIterateeCall(value, index, object) {
if (!isObject(object)) {
return false;
}
var type = typeof index;
if (type == 'number'
? (isArrayLike(object) && isIndex(index, object.length))
: (type == 'string' && index in object)) {
var other = object[index];
return value === value ? (value === other) : (other !== other);
}
return false;
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength).
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
*/
function isLength(value) {
return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
module.exports = isIterateeCall;
},{}],9:[function(require,module,exports){
/**
* lodash 3.6.1 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/* Native method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Creates a function that invokes `func` with the `this` binding of the
* created function and arguments from `start` and beyond provided as an array.
*
* **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters).
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
* @example
*
* var say = _.restParam(function(what, names) {
* return what + ' ' + _.initial(names).join(', ') +
* (_.size(names) > 1 ? ', & ' : '') + _.last(names);
* });
*
* say('hello', 'fred', 'barney', 'pebbles');
* // => 'hello fred, barney, & pebbles'
*/
function restParam(func, start) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0);
return function() {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
rest = Array(length);
while (++index < length) {
rest[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, rest);
case 1: return func.call(this, args[0], rest);
case 2: return func.call(this, args[0], args[1], rest);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = rest;
return func.apply(this, otherArgs);
};
}
module.exports = restParam;
},{}],10:[function(require,module,exports){
/**
* lodash 3.1.1 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
var getNative = require('lodash._getnative'),
isArguments = require('lodash.isarguments'),
isArray = require('lodash.isarray');
/** Used to detect unsigned integer values. */
var reIsUint = /^\d+$/;
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/* Native method references for those with the same name as other `lodash` methods. */
var nativeKeys = getNative(Object, 'keys');
/**
* Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer)
* of an array-like value.
*/
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
/**
* Gets the "length" property value of `object`.
*
* **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
* that affects Safari on at least iOS 8.1-8.3 ARM64.
*
* @private
* @param {Object} object The object to query.
* @returns {*} Returns the "length" value.
*/
var getLength = baseProperty('length');
/**
* Checks if `value` is array-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
*/
function isArrayLike(value) {
return value != null && isLength(getLength(value));
}
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
length = length == null ? MAX_SAFE_INTEGER : length;
return value > -1 && value % 1 == 0 && value < length;
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength).
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
*/
function isLength(value) {
return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* A fallback implementation of `Object.keys` which creates an array of the
* own enumerable property names of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function shimKeys(object) {
var props = keysIn(object),
propsLength = props.length,
length = propsLength && object.length;
var allowIndexes = !!length && isLength(length) &&
(isArray(object) || isArguments(object));
var index = -1,
result = [];
while (++index < propsLength) {
var key = props[index];
if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) {
result.push(key);
}
}
return result;
}
/**
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.keys)
* for more details.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
var keys = !nativeKeys ? shimKeys : function(object) {
var Ctor = object == null ? null : object.constructor;
if ((typeof Ctor == 'function' && Ctor.prototype === object) ||
(typeof object != 'function' && isArrayLike(object))) {
return shimKeys(object);
}
return isObject(object) ? nativeKeys(object) : [];
};
/**
* Creates an array of the own and inherited enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keysIn(new Foo);
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
*/
function keysIn(object) {
if (object == null) {
return [];
}
if (!isObject(object)) {
object = Object(object);
}
var length = object.length;
length = (length && isLength(length) &&
(isArray(object) || isArguments(object)) && length) || 0;
var Ctor = object.constructor,
index = -1,
isProto = typeof Ctor == 'function' && Ctor.prototype === object,
result = Array(length),
skipIndexes = length > 0;
while (++index < length) {
result[index] = (index + '');
}
for (var key in object) {
if (!(skipIndexes && isIndex(key, length)) &&
!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
result.push(key);
}
}
return result;
}
module.exports = keys;
},{"lodash._getnative":11,"lodash.isarguments":12,"lodash.isarray":13}],11:[function(require,module,exports){
/**
* lodash 3.9.0 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/** `Object#toString` result references. */
var funcTag = '[object Function]';
/**
* Used to match `RegExp` [special characters](http://www.regular-expressions.info/characters.html#special).
* In addition to special characters the forward slash is escaped to allow for
* easier `eval` use and `Function` compilation.
*/
var reRegExpChars = /[.*+?^${}()|[\]\/\\]/g,
reHasRegExpChars = RegExp(reRegExpChars.source);
/** Used to detect host constructors (Safari > 5). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/**
* Converts `value` to a string if it's not one. An empty string is returned
* for `null` or `undefined` values.
*
* @private
* @param {*} value The value to process.
* @returns {string} Returns the string.
*/
function baseToString(value) {
if (typeof value == 'string') {
return value;
}
return value == null ? '' : (value + '');
}
/**
* Checks if `value` is object-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var fnToString = Function.prototype.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
escapeRegExp(fnToString.call(hasOwnProperty))
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = object == null ? undefined : object[key];
return isNative(value) ? value : undefined;
}
/**
* Checks if `value` is a native function.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function, else `false`.
* @example
*
* _.isNative(Array.prototype.push);
* // => true
*
* _.isNative(_);
* // => false
*/
function isNative(value) {
if (value == null) {
return false;
}
if (objToString.call(value) == funcTag) {
return reIsNative.test(fnToString.call(value));
}
return isObjectLike(value) && reIsHostCtor.test(value);
}
/**
* Escapes the `RegExp` special characters "\", "/", "^", "$", ".", "|", "?",
* "*", "+", "(", ")", "[", "]", "{" and "}" in `string`.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to escape.
* @returns {string} Returns the escaped string.
* @example
*
* _.escapeRegExp('[lodash](https://lodash.com/)');
* // => '\[lodash\]\(https:\/\/lodash\.com\/\)'
*/
function escapeRegExp(string) {
string = baseToString(string);
return (string && reHasRegExpChars.test(string))
? string.replace(reRegExpChars, '\\$&')
: string;
}
module.exports = getNative;
},{}],12:[function(require,module,exports){
/**
* lodash 3.0.3 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/** `Object#toString` result references. */
var argsTag = '[object Arguments]';
/**
* Checks if `value` is object-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/** Used for native method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/**
* Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer)
* of an array-like value.
*/
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
/**
* Gets the "length" property value of `object`.
*
* **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
* that affects Safari on at least iOS 8.1-8.3 ARM64.
*
* @private
* @param {Object} object The object to query.
* @returns {*} Returns the "length" value.
*/
var getLength = baseProperty('length');
/**
* Checks if `value` is array-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
*/
function isArrayLike(value) {
return value != null && isLength(getLength(value));
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength).
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
*/
function isLength(value) {
return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is classified as an `arguments` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
function isArguments(value) {
return isObjectLike(value) && isArrayLike(value) && objToString.call(value) == argsTag;
}
module.exports = isArguments;
},{}],13:[function(require,module,exports){
/**
* lodash 3.0.3 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/** `Object#toString` result references. */
var arrayTag = '[object Array]',
funcTag = '[object Function]';
/**
* Used to match `RegExp` [special characters](http://www.regular-expressions.info/characters.html#special).
* In addition to special characters the forward slash is escaped to allow for
* easier `eval` use and `Function` compilation.
*/
var reRegExpChars = /[.*+?^${}()|[\]\/\\]/g,
reHasRegExpChars = RegExp(reRegExpChars.source);
/** Used to detect host constructors (Safari > 5). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/**
* Converts `value` to a string if it's not one. An empty string is returned
* for `null` or `undefined` values.
*
* @private
* @param {*} value The value to process.
* @returns {string} Returns the string.
*/
function baseToString(value) {
if (typeof value == 'string') {
return value;
}
return value == null ? '' : (value + '');
}
/**
* Checks if `value` is object-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var fnToString = Function.prototype.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
escapeRegExp(fnToString.call(hasOwnProperty))
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/* Native method references for those with the same name as other `lodash` methods. */
var nativeIsArray = getNative(Array, 'isArray');
/**
* Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer)
* of an array-like value.
*/
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = object == null ? undefined : object[key];
return isNative(value) ? value : undefined;
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength).
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
*/
function isLength(value) {
return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(function() { return arguments; }());
* // => false
*/
var isArray = nativeIsArray || function(value) {
return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag;
};
/**
* Checks if `value` is a native function.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function, else `false`.
* @example
*
* _.isNative(Array.prototype.push);
* // => true
*
* _.isNative(_);
* // => false
*/
function isNative(value) {
if (value == null) {
return false;
}
if (objToString.call(value) == funcTag) {
return reIsNative.test(fnToString.call(value));
}
return isObjectLike(value) && reIsHostCtor.test(value);
}
/**
* Escapes the `RegExp` special characters "\", "/", "^", "$", ".", "|", "?",
* "*", "+", "(", ")", "[", "]", "{" and "}" in `string`.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to escape.
* @returns {string} Returns the escaped string.
* @example
*
* _.escapeRegExp('[lodash](https://lodash.com/)');
* // => '\[lodash\]\(https:\/\/lodash\.com\/\)'
*/
function escapeRegExp(string) {
string = baseToString(string);
return (string && reHasRegExpChars.test(string))
? string.replace(reRegExpChars, '\\$&')
: string;
}
module.exports = isArray;
},{}]},{},[1]);
| 31.435262 | 480 | 0.642691 |
b8813e56c103ffd835cc06ce4c780ac085cdb642 | 3,970 | rs | Rust | tests/manifestv1.rs | sjpotter/trow | e55c7d17e4685d43b8c0c7c0a5c2737257fd98e4 | [
"Apache-2.0"
] | null | null | null | tests/manifestv1.rs | sjpotter/trow | e55c7d17e4685d43b8c0c7c0a5c2737257fd98e4 | [
"Apache-2.0"
] | null | null | null | tests/manifestv1.rs | sjpotter/trow | e55c7d17e4685d43b8c0c7c0a5c2737257fd98e4 | [
"Apache-2.0"
] | 1 | 2020-02-07T16:55:50.000Z | 2020-02-07T16:55:50.000Z |
extern crate jwt;
extern crate rustc_serialize;
extern crate crypto;
#[cfg(test)]
mod manifestv1_tests {
use crypto::sha2::Sha256;
// fn generate_manifest(digest: &str) -> Result<Value, ()> {
// use std::fs::File;
// use std::io::Read;
// let mut template = File::open(MANIFEST_TEMPLATE).unwrap();
// let mut contents = String::new();
// template.read_to_string(&mut contents).unwrap();
// let mut v: Value = serde_json::from_str(&contents).unwrap();
// v["fsLayers"][0]["blobSum"] = Value::String(digest.to_string());
// Ok(v)
// }
#[derive(Clone, Debug, Default, RustcDecodable, RustcEncodable)]
struct EmptyStruct {}
#[derive(Clone, Debug, Default, RustcDecodable, RustcEncodable)]
#[allow(non_snake_case)]
struct BlobSummary {
blobSum: String
}
#[derive(Debug, RustcDecodable, RustcEncodable)]
#[allow(non_snake_case)]
struct SigningManifest {
schemaVersion: u8,
name: String,
tag: String,
architecture: String,
fsLayers: Vec<BlobSummary>,
history: Vec<EmptyStruct>
}
impl Default for SigningManifest {
fn default() -> Self {
SigningManifest {
schemaVersion: 1,
name: "test/test".to_owned(),
tag: "latest".to_owned(),
architecture: "amd64".to_owned(),
fsLayers: Default::default(),
history: Default::default(),
}
}
}
#[derive(Debug, Default)]
struct SignatureJWK {
crv: String,
kty: String,
x: String,
y: String,
}
#[derive(Debug, Default)]
struct SignatureHeader {
alg: String,
jwk: SignatureJWK
}
#[derive(Debug, Default)]
struct Signature {
header: SignatureHeader,
payload: String,
protected: String,
signature: String,
}
#[derive(Debug, Default)]
#[allow(non_snake_case)]
struct Manifest {
schemaVersion: u8,
name: String,
tag: String,
architecture: String,
fsLayers: Vec<BlobSummary>,
history: Vec<EmptyStruct>,
signatures: Vec<Signature>,
}
#[test]
fn upload_manifest() {
// manifest with invalid layer
sign_manifest("invalid_digest");
// manifest with test/test/test_digest layer
}
fn sign_manifest(digest: &str) {
// copying from https://github.com/ContainerSolutions/manifest-sample-python/blob/master/construct-manifest.py
use jwt::{Header, Token};
// let format_length = manifest_str.len() - 1;
// let format_tail = '}';
let header: Header = Default::default();
let claims = SigningManifest {
fsLayers: vec!(BlobSummary { blobSum: digest.to_owned() }),
..Default::default()
};
let manifest = Manifest::from_signing_manifest(&claims);
let token = Token::new(header, claims);
println!("{:?}", manifest);
let signed = token.signed(b"secret_key", Sha256::new()).ok();
println!("{:?}", signed);
}
impl Manifest {
/* transformation function from SigningManifest -> Manifest
* Possibly would be worth it to think about being able to
* statically catch incorrect transformations when structs
* change shape. ie. missed values in the transformation...
*/
fn from_signing_manifest(sig: &SigningManifest) -> Self {
Manifest {
schemaVersion: sig.schemaVersion.to_owned(),
name: sig.name.to_owned(),
tag: sig.tag.to_owned(),
architecture: sig.architecture.to_owned(),
fsLayers: sig.fsLayers.clone(),
history: sig.history.clone(),
signatures: Default::default(),
}
}
}
} | 28.768116 | 118 | 0.566247 |
dc785a3a47678be88ab49538a3c0346806189c15 | 1,881 | swift | Swift | SmartToDo/Views/Cells/ToDoEditorTextBaseTableViewCell.swift | otakisan/SmartToDo | db14478db1dddb7e44d1c9eaa76e67f75836d00e | [
"MIT"
] | null | null | null | SmartToDo/Views/Cells/ToDoEditorTextBaseTableViewCell.swift | otakisan/SmartToDo | db14478db1dddb7e44d1c9eaa76e67f75836d00e | [
"MIT"
] | null | null | null | SmartToDo/Views/Cells/ToDoEditorTextBaseTableViewCell.swift | otakisan/SmartToDo | db14478db1dddb7e44d1c9eaa76e67f75836d00e | [
"MIT"
] | null | null | null | //
// ToDoEditorTextBaseTableViewCell.swift
// SmartToDo
//
// Created by takashi on 2014/11/03.
// Copyright (c) 2014年 ti. All rights reserved.
//
import UIKit
class ToDoEditorTextBaseTableViewCell: ToDoEditorBaseTableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
override func valueOfCell() -> AnyObject? {
return self.textValueOfCell()
}
func textValueOfCell() -> String {
return ""
}
override func setValueOfCell(value: AnyObject) {
if let entityData = value as? String {
self.setTextValueOfCell(entityData)
}
}
func setTextValueOfCell(textValue : String) {
}
func completeDelegate() -> ((UIView) -> Void)? {
return self.didFinishDetailView
}
func didFinishDetailView(detailView : UIView){
if let view = detailView as? UITextView{
self.didFinishTextView(view)
}
}
func didFinishTextView(textView : UITextView){
// Subclass Must Implement
}
override func createDetailView() -> UIViewController? {
let vc = self.loadDetailView()
vc?.setViewValue(self.detailViewInitValue()!)
vc?.setCompleteDeleage(self.completeDelegate())
return vc
}
func loadDetailView() -> CommonTextViewController? {
let vc = NSBundle.mainBundle().loadNibNamed("CommonTextViewController", owner: CommonTextViewController(), options: nil)[0] as? CommonTextViewController
return vc
}
func detailViewInitValue() -> AnyObject? {
return ""
}
}
| 24.75 | 160 | 0.61882 |
0b59207603dace13de5bad24d570481b2383557b | 4,282 | py | Python | frontend/main.py | loukwn/klougle | 45432841c594ced36437566f416e9c71017f83a5 | [
"MIT"
] | 2 | 2018-10-26T11:06:51.000Z | 2020-04-29T13:38:13.000Z | frontend/main.py | loukwn/klougle | 45432841c594ced36437566f416e9c71017f83a5 | [
"MIT"
] | null | null | null | frontend/main.py | loukwn/klougle | 45432841c594ced36437566f416e9c71017f83a5 | [
"MIT"
] | null | null | null | import json
import operator
import os
import webbrowser
from timeit import default_timer as timer
from kivy.app import App
from kivy.config import Config
from kivy.properties import ObjectProperty
from kivy.uix.stacklayout import StackLayout
from nltk.stem.wordnet import WordNetLemmatizer
Config.set('input', 'mouse', 'mouse,multitouch_on_demand')
INV_IDX_NAME = 'inv_index.json'
_wordnet_lemmatizer = WordNetLemmatizer()
_wordnet_lemmatizer.lemmatize('asd')
def get_data_from_json():
# loads the inverted index in memory
rel_path = "inv_index/" + INV_IDX_NAME
abs_file_path = os.path.join(os.pardir, rel_path)
with open(abs_file_path) as data_file:
return json.load(data_file)
def get_doc_details(key):
# uses the id of the document to find its location in disk and then returns its title and its link
temp = key.split('_')
partial_path = 'crawlers/crawled/' + temp[0] + '/' + temp[1] + '/' + temp[2] + '.json'
abs_file_path = os.path.join(os.pardir, partial_path)
with open(abs_file_path) as f:
j = json.load(f)
return [j['title'], j['link']]
def perform_query(query):
# we process the query (split/lemmatize/turn to lowercase)
terms = [_wordnet_lemmatizer.lemmatize(x.strip().lower()) for x in query.split()]
data = get_data_from_json()
# the dictionary that will hold the document results
docs_returned = {}
# we search for every term in the query the corresponing lemma in the inverted index
for lemma in data:
if lemma in terms:
# if we find the the term in the inverted index
for i in data[lemma]:
# we add its weight to the docs_returned structure
if i['id'] not in docs_returned:
docs_returned[i['id']] = i['w']
else:
docs_returned[i['id']] += i['w']
# we sort the docs based on their values (descending)
sorted_x = sorted(docs_returned.items(), key=operator.itemgetter(1), reverse=True)
to_return = []
count = 1
for key, value in sorted_x:
# and for every doc we extract the title and link so that we can show them
[title, link] = get_doc_details(key)
title = str(count) + ') ' + title
to_return.append([title, link, value])
count += 1
return to_return
# -------------------------- UI -------------------------- #
def open_url(text):
# click an item to open the link to the browser
webbrowser.open(text.split('\n')[0], new=2)
# top layout of UI
class SearchUI(StackLayout):
statusLabel = ObjectProperty()
resultList = ObjectProperty()
searchInput = ObjectProperty()
def add_result_to_list_view(self, title, link, weight):
resized_link = link
if len(resized_link) >= 102:
resized_link = resized_link[0:102] + '...'
content = link + '\n[size=16][b]' + title + '[/b][/size]\n-- [size=15][color=#757575][i]Weight: ' + str(
weight) + '[/i][/color]\n[color=#3F51B5]' + resized_link + '[/size][/color]'
self.resultList.adapter.data.extend([content])
self.resultList._trigger_reset_populate()
def go_pressed(self):
query = self.searchInput.text.strip()
if len(query) > 0:
self.clear_list()
self.statusLabel.text = "Searching.."
start = timer() #
results = perform_query(query) # query to inverted index happens (and is timed) here
end = timer() #
if len(results) > 0:
for doc in results:
self.add_result_to_list_view(doc[0], doc[1], doc[2])
self.statusLabel.text = "Results: " + str(
len(self.resultList.adapter.data)) + " (Time elapsed: " + "{:10.4f}s) ".format(end - start)
else:
self.statusLabel.text = "No results.."
else:
self.clear_list()
self.statusLabel.text = 'Type some search terms and hit "Go"'
def clear_list(self):
del self.resultList.adapter.data[:]
# kivy app
class SearchApp(App):
def build(self):
return SearchUI()
# starting point
if __name__ == '__main__':
SearchApp().run()
| 34.532258 | 115 | 0.609295 |
ce019e337681e6eb8ee9a6d79a45b64a4c27127c | 301 | h | C | Mail/DMLayeredClipView.h | DotMail/DotMail | d620baeaae767a6d99005f818a809ee29245e904 | [
"MIT"
] | 329 | 2015-01-21T13:41:49.000Z | 2021-05-17T06:36:06.000Z | Mail/DMLayeredClipView.h | DotMail/DotMail | d620baeaae767a6d99005f818a809ee29245e904 | [
"MIT"
] | 5 | 2015-02-22T03:12:34.000Z | 2015-03-03T17:22:00.000Z | Mail/DMLayeredClipView.h | DotMail/DotMail | d620baeaae767a6d99005f818a809ee29245e904 | [
"MIT"
] | 37 | 2015-02-12T19:49:03.000Z | 2017-11-21T01:06:20.000Z | //
// DMLayeredClipView.h
// DotMail
//
// Created by Robert Widmann on 8/8/13.
// Copyright (c) 2013 CodaFi Inc. All rights reserved.
//
#import <Cocoa/Cocoa.h>
@interface DMLayeredClipView : NSClipView
@end
@interface DMPullToRefreshClipView : DMLayeredClipView
- (BOOL)isRefreshing;
@end
| 15.05 | 55 | 0.72093 |
d7c84fd144603b53a65a2101628454e1a3a16354 | 1,871 | kt | Kotlin | app/src/main/java/com/example/github/videoapp/home/HomeActivity.kt | vsay01/VideoApp | 3211026e8914207317a48309f9d991cd141efcdc | [
"Apache-2.0"
] | 8 | 2017-10-27T19:56:45.000Z | 2018-12-21T06:53:37.000Z | app/src/main/java/com/example/github/videoapp/home/HomeActivity.kt | vsay01/VideoApp | 3211026e8914207317a48309f9d991cd141efcdc | [
"Apache-2.0"
] | 2 | 2018-12-21T07:35:54.000Z | 2018-12-21T08:22:35.000Z | app/src/main/java/com/example/github/videoapp/home/HomeActivity.kt | vsay01/VideoApp | 3211026e8914207317a48309f9d991cd141efcdc | [
"Apache-2.0"
] | 10 | 2017-11-06T04:21:01.000Z | 2019-08-12T16:34:08.000Z | package com.example.github.videoapp.home
import android.net.Uri
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.example.github.videoapp.R
import com.example.github.videoapp.util.ActivityUtils
import javax.inject.Inject
class HomeActivity : AppCompatActivity(), HomeFragment.OnFragmentInteractionListener {
@Inject
lateinit var homePresenter: HomePresenter
lateinit var homeFragment: HomeFragment
override fun onFragmentInteraction(uri: Uri) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
homeFragment = supportFragmentManager.findFragmentById(R.id.frame_layout_content)
as HomeFragment? ?: HomeFragment.newInstance().also {
ActivityUtils.addFragmentToActivity(
supportFragmentManager, it, R.id.frame_layout_content)
}
homeFragment = HomeFragment.newInstance()
val transaction = supportFragmentManager.beginTransaction()
transaction.add(R.id.frame_layout_content, homeFragment)
transaction.commit()
/*
* thanks to the lazy statement, we can specify the value of the graph in the definition of the property,
* thus get read-only access to that property. The code defined by the property won’t be executed until component.inject (this) is done,
* so that by that time this already exists and can be created securely way.*/
val component: HomeComponent by lazy {
DaggerHomeComponent
.builder()
.homeModule(HomeModule(homeFragment))
.build()
}
component.inject(this)
}
}
| 38.183673 | 143 | 0.69535 |
b4fc3fcbe814bd549cfa230df81903695a5cc90d | 211 | asm | Assembly | libsrc/_DEVELOPMENT/stdio/c/sdcc_iy/fflush_unlocked_fastcall.asm | meesokim/z88dk | 5763c7778f19a71d936b3200374059d267066bb2 | [
"ClArtistic"
] | null | null | null | libsrc/_DEVELOPMENT/stdio/c/sdcc_iy/fflush_unlocked_fastcall.asm | meesokim/z88dk | 5763c7778f19a71d936b3200374059d267066bb2 | [
"ClArtistic"
] | null | null | null | libsrc/_DEVELOPMENT/stdio/c/sdcc_iy/fflush_unlocked_fastcall.asm | meesokim/z88dk | 5763c7778f19a71d936b3200374059d267066bb2 | [
"ClArtistic"
] | null | null | null |
; int fflush_unlocked_fastcall(FILE *stream)
SECTION code_stdio
PUBLIC _fflush_unlocked_fastcall
EXTERN asm_fflush_unlocked
_fflush_unlocked_fastcall:
push hl
pop ix
jp asm_fflush_unlocked
| 13.1875 | 44 | 0.791469 |
80971396f922a00794bbb6367cd14dbea033c481 | 117 | sql | SQL | src/main/resources/liquibase/harness/change/expectedSql/mysql/renameView.sql | AlexanderSashchenko/liquibase-test-harness | c626754b75e6470aa03bf6fb88073ff073039862 | [
"Apache-2.0"
] | 1 | 2021-02-25T04:30:04.000Z | 2021-02-25T04:30:04.000Z | src/main/resources/liquibase/harness/change/expectedSql/mysql/renameView.sql | AlexanderSashchenko/liquibase-test-harness | c626754b75e6470aa03bf6fb88073ff073039862 | [
"Apache-2.0"
] | 1 | 2021-06-21T08:40:11.000Z | 2021-06-21T13:32:01.000Z | src/main/resources/liquibase/harness/change/expectedSql/mysql/renameView.sql | Sfurti-yb/liquibase-test-harness | 86b413938f13d9d899fc010ca42f26041b6fccb8 | [
"Apache-2.0"
] | 1 | 2021-03-08T20:36:14.000Z | 2021-03-08T20:36:14.000Z | CREATE VIEW test_view AS select id, first_name, last_name, email from authors
RENAME TABLE test_view TO test_view_new | 58.5 | 77 | 0.846154 |
1d4041ea5398289265afbced17e3dfb91d37d31e | 4,261 | lua | Lua | packages/lorem.lua | Nathan22Miles/sile-0.9.1 | 418a89011659a6b5a4978559fc2654a5126c6482 | [
"MIT"
] | null | null | null | packages/lorem.lua | Nathan22Miles/sile-0.9.1 | 418a89011659a6b5a4978559fc2654a5126c6482 | [
"MIT"
] | null | null | null | packages/lorem.lua | Nathan22Miles/sile-0.9.1 | 418a89011659a6b5a4978559fc2654a5126c6482 | [
"MIT"
] | null | null | null | local lorem = [[lorem ipsum dolor sit amet consetetur sadipscing elitr sed diam nonumy
eirmod tempor invidunt ut labore et dolore magna aliquyam erat sed diam
voluptua at vero eos et accusam et justo duo dolores et ea rebum stet clita
kasd gubergren no sea takimata sanctus est lorem ipsum dolor sit amet lorem
ipsum dolor sit amet consetetur sadipscing elitr sed diam nonumy eirmod
tempor invidunt ut labore et dolore magna aliquyam erat sed diam voluptua at
vero eos et accusam et justo duo dolores et ea rebum stet clita kasd
gubergren no sea takimata sanctus est lorem ipsum dolor sit amet lorem ipsum
dolor sit amet consetetur sadipscing elitr sed diam nonumy eirmod tempor
invidunt ut labore et dolore magna aliquyam erat sed diam voluptua at vero
eos et accusam et justo duo dolores et ea rebum stet clita kasd gubergren no
sea takimata sanctus est lorem ipsum dolor sit amet
duis autem vel eum iriure dolor in hendrerit in vulputate velit esse
molestie consequat vel illum dolore eu feugiat nulla facilisis at vero eros
et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril
delenit augue duis dolore te feugait nulla facilisi lorem ipsum dolor sit
amet consectetuer adipiscing elit sed diam nonummy nibh euismod tincidunt ut
laoreet dolore magna aliquam erat volutpat
ut wisi enim ad minim veniam quis nostrud exerci tation ullamcorper suscipit
lobortis nisl ut aliquip ex ea commodo consequat duis autem vel eum iriure
dolor in hendrerit in vulputate velit esse molestie consequat vel illum
dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio
dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te
feugait nulla facilisi
nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet
doming id quod mazim placerat facer possim assum lorem ipsum dolor sit amet
consectetuer adipiscing elit sed diam nonummy nibh euismod tincidunt ut
laoreet dolore magna aliquam erat volutpat ut wisi enim ad minim veniam quis
nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea
commodo consequat
duis autem vel eum iriure dolor in hendrerit in vulputate velit esse
molestie consequat vel illum dolore eu feugiat nulla facilisis
at vero eos et accusam et justo duo dolores et ea rebum stet clita kasd
gubergren no sea takimata sanctus est lorem ipsum dolor sit amet lorem ipsum
dolor sit amet consetetur sadipscing elitr sed diam nonumy eirmod tempor
invidunt ut labore et dolore magna aliquyam erat sed diam voluptua at vero
eos et accusam et justo duo dolores et ea rebum stet clita kasd gubergren no
sea takimata sanctus est lorem ipsum dolor sit amet lorem ipsum dolor sit
amet consetetur sadipscing elitr at accusam aliquyam diam diam dolore
dolores duo eirmod eos erat et nonumy sed tempor et et invidunt justo labore
stet clita ea et gubergren kasd magna no rebum sanctus sea sed takimata ut
vero voluptua est lorem ipsum dolor sit amet lorem ipsum dolor sit amet
consetetur sadipscing elitr sed diam nonumy eirmod tempor invidunt ut labore
et dolore magna aliquyam erat
consetetur sadipscing elitr sed diam nonumy eirmod tempor invidunt ut labore
et dolore magna aliquyam erat sed diam voluptua at vero eos et accusam et
justo duo dolores et ea rebum stet clita kasd gubergren no sea takimata
sanctus est lorem ipsum dolor sit amet lorem ipsum dolor sit amet consetetur
sadipscing elitr sed diam nonumy eirmod tempor invidunt ut labore et dolore
magna aliquyam erat sed diam voluptua at vero eos et accusam et justo duo
dolores et ea rebum stet clita kasd gubergren no sea takimata sanctus est
lorem ipsum dolor sit amet lorem ipsum dolor sit amet consetetur sadipscing
elitr sed diam nonumy eirmod tempor invidunt ut labore et dolore magna
aliquyam erat sed diam voluptua at vero eos et accusam et justo duo dolores
et ea rebum stet clita kasd gubergren no sea takimata sanctus est lorem
ipsum dolor sit amet]]
SILE.registerCommand("lorem", function(options, content)
local words = tonumber(options.words) or 50
local s = ""
local t
while words > 1 do
if not t then t = lorem end
s = s .. string.match(t, "%w+%s+")
t = string.gsub(t, "%w+%s+", "", 1)
words = words - 1
end
SILE.typesetter:typeset(s)
SILE.typesetter:leaveHmode()
end) | 56.065789 | 86 | 0.812485 |
844721b98bccf160fef178306fe7cd440b7ef78d | 426 | html | HTML | static_doc/html/build_tarball_py.html | wake-forest-ctsi/mist-toolkit | 857e91976fa3b75ef2cad08612fa79cf2f743615 | [
"BSD-3-Clause"
] | 2 | 2015-10-28T17:58:31.000Z | 2021-10-12T10:34:39.000Z | scrubber/MIST_2_0_4/static_doc/html/build_tarball_py.html | manaswini18/DmD | dd1e865ddb7b43c8478b2b5733385143b1980951 | [
"Apache-2.0"
] | null | null | null | scrubber/MIST_2_0_4/static_doc/html/build_tarball_py.html | manaswini18/DmD | dd1e865ddb7b43c8478b2b5733385143b1980951 | [
"Apache-2.0"
] | 9 | 2016-12-17T22:50:37.000Z | 2020-09-26T01:08:06.000Z | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<!-- Copyright (C) 2007 - 2009 The MITRE Corporation. See the toplevel
file LICENSE for license terms. -->
<meta content="text/html; charset=ISO-8859-1"
http-equiv="Content-Type">
<title>build_tarball.py Utility</title>
<link href="../css/doc.css" rel="stylesheet" type="text/css">
</head>
<body>
<p>Under construction.
</p>
</body>
</html>
| 26.625 | 70 | 0.683099 |
ad49344d5176c839ac16bb670a7153036161965d | 4,925 | sql | SQL | sql/ash_graph_waits.sql | fatdba/oracle-script-lib | efa9f5623bc3f27cea37a815f5bc3766d21b1b19 | [
"MIT"
] | null | null | null | sql/ash_graph_waits.sql | fatdba/oracle-script-lib | efa9f5623bc3f27cea37a815f5bc3766d21b1b19 | [
"MIT"
] | null | null | null | sql/ash_graph_waits.sql | fatdba/oracle-script-lib | efa9f5623bc3f27cea37a815f5bc3766d21b1b19 | [
"MIT"
] | 2 | 2022-01-16T20:34:08.000Z | 2022-02-10T16:45:46.000Z |
-- ashmasters - https://github.com/khailey/ashmasters
-- Kyle Hailey
/*
ASH graph from v$active_session_history no filter by DBID nor time
don't use dba_hist_active_sess_history ,
Output looks like
TO_CHAR( AAS PCT1 FIRST PCT2 SECOND GRAPH
-------- --- ---- --------------- ---- --------------- -------------------------------------------
15 15:00 7 46 db file sequent 19 CPU +++++++ooooooooooooo4ooooooooooo------
15 16:00 6 53 db file sequent 31 CPU +++++++++ooooooooooo4oooooooo---
15 17:00 7 48 db file sequent 41 CPU +++++++++++++++ooooo4oooooooooooooooo-
15 18:00 5 55 CPU 37 db file sequent ++++++++++++++oooooo4oooooo-
15 19:00 1 64 CPU 21 db file sequent ++o 4
15 20:00 1 63 CPU 19 read by other s ++++o- 4
15 21:00 2 31 db file sequent 24 CPU ++ooo---- 4
15 22:00 3 35 CPU 24 db file scatter +++++ooooooo--- 4
15 23:00 6 29 log file sync 25 db file sequent ++++ooooooooo-------4-------------
16 00:00 7 52 db file sequent 27 CPU ++++++++++oooooooooo4ooooooooooooooo--
16 01:00 4 57 CPU 36 db file sequent +++++++++++oooooooo 4
16 02:00 6 38 db file sequent 21 CPU ++++++oooooooooooo--4---------
16 03:00 3 69 db file sequent 20 CPU +++ooooooooooo 4
16 04:00 0 45 db file sequent 28 CPU o 4
16 05:00 1 58 db file sequent 24 CPU +ooo 4
16 06:00 1 41 db file sequent 39 CPU +oo 4
The "graph" on the right shows the load over time each line is an hour by default.
The "+" represent CPU, "o" represent I/O and "-" represent a wait.
The columns "FIRST" and "SECOND" represent the top two things happening on the database.
hello from RMOUG
*/
ef v_secs=3600 -- bucket size
Def v_secs=60 -- bucket size
Def v_bars=5 -- size of one AAS in characters
Def v_graph=80
col aveact format 999.99
col graph format a30
col fpct format 9.99
col spct format 9.99
col tpct format 9.99
col aas1 format 9.99
col aas2 format 9.99
col first format a15
col second format a15
select
to_char(to_date(
trunc((id*&v_secs)/ (24*60*60)) || ' ' || -- Julian days
mod((id*&v_secs), 24*60*60) -- seconds in the day
, 'J SSSSS' ), 'MON DD YYYY HH24:MI:SS') start_time,
round(fpct * ((cpu+waits)/&v_secs),2) aas1,
decode(fpct,null,null,first) first,
round(spct * ((cpu+waits)/&v_secs),2) aas2,
decode(spct,null,null,second) second,
substr(
substr(
rpad('+',round(( cpu/&v_secs)*&v_bars),'+’) ||
rpad('-',round((waits/&v_secs)*&v_bars),'-') ||
rpad(' ',p.value * &v_bars,' ')
,0,(p.value * &v_bars)) ||
p.value ||
substr(
rpad('+',round(( cpu/&v_secs)*&v_bars),'+’) ||
rpad('-',round((waits/&v_secs)*&v_bars),'-') ||
rpad(' ',p.value * &v_bars,' '),
(p.value * &v_bars))
,0,&v_graph)
graph
from (
select id
, round(max(decode(top.seq,1,pct,null)),2) fpct
, substr(max(decode(top.seq,1,decode(top.event,'ON CPU','CPU',event),null)),0,15) first
, round(max(decode(top.seq,2,pct,null)),2) spct
, substr(max(decode(top.seq,2,decode(top.event,'ON CPU','CPU',event),null)),0,15) second
, round(max(decode(top.seq,3,pct,null)),2) tpct
, substr(max(decode(top.seq,3,decode(top.event,'ON CPU','CPU',event),null)),0,10) third
, sum(waits) waits
, sum(cpu) cpu
from (
select
id
, event
, row_number() over ( partition by id order by event_count desc ) seq -- 1 for top wait, 2 for 2nd, etc
, ratio_to_report( event_count ) over ( partition by id ) pct -- % of event_count to total for id
, sum(decode(event,'ON CPU',event_count,0)) cpu
, sum(decode(event,'ON CPU',0,event_count)) waits
from (
select
trunc((to_char(sample_time,'J')*(24*60*60)+to_char(sample_time,'SSSSS'))/&v_secs) id
, decode(session_state,'ON CPU','ON CPU',ash.event) event
, count(*) event_count
from
v$active_session_history ash
group by
trunc((to_char(sample_time,'J')*(24*60*60)+to_char(sample_time,'SSSSS'))/&v_secs)
, decode(session_state,'ON CPU','ON CPU',ash.event)
) chunks
group by id, event, event_count
) top
group by id
) aveact,
v$parameter p
where p.name='cpu_count'
order by id
/
| 42.456897 | 111 | 0.519188 |
1e00fe4779d8567ea4a3dd1dd3e8f11ab2c82391 | 1,175 | css | CSS | view/adminhtml/web/styles.css | Overdose-Digital/adyen-magento2 | 2cc992bfcc3316fdf57bc8263360a858bdf5a884 | [
"MIT"
] | 134 | 2016-02-09T19:21:49.000Z | 2022-03-31T02:12:07.000Z | view/adminhtml/web/styles.css | Overdose-Digital/adyen-magento2 | 2cc992bfcc3316fdf57bc8263360a858bdf5a884 | [
"MIT"
] | 1,039 | 2016-02-09T14:57:59.000Z | 2022-03-31T15:43:48.000Z | view/adminhtml/web/styles.css | Overdose-Digital/adyen-magento2 | 2cc992bfcc3316fdf57bc8263360a858bdf5a884 | [
"MIT"
] | 181 | 2016-02-09T14:25:52.000Z | 2022-03-23T20:26:24.000Z | /**
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
*
* Adyen Payment module (https://www.adyen.com/)
*
* Copyright (c) 2015 Adyen BV (https://www.adyen.com/)
* See LICENSE.txt for license details.
*
* Author: Adyen <magento@adyen.com>
*/
.adyen-method-adyen-cc > .entry-edit-head > .config-heading .heading strong { padding-left:90px;background:url(images/adyen-logo.png) no-repeat 0 0; background-size: 83px 24px;line-height: 23px;}
ul.adyen-list { margin:0 20px 10px;} | 48.958333 | 196 | 0.257021 |
c439b6e9ea878485f2a654842a670cdab6215ab9 | 1,041 | h | C | chapter_1/lesson_03/DispatchEvent.h | sergey-shambir/cg_course_examples | 921b6218d71731bcb79ddddcc92c9d04a72c62ab | [
"MIT"
] | 5 | 2017-05-13T20:47:13.000Z | 2020-04-18T18:18:03.000Z | chapter_1/lesson_03/DispatchEvent.h | sergey-shambir/cg_course_examples | 921b6218d71731bcb79ddddcc92c9d04a72c62ab | [
"MIT"
] | null | null | null | chapter_1/lesson_03/DispatchEvent.h | sergey-shambir/cg_course_examples | 921b6218d71731bcb79ddddcc92c9d04a72c62ab | [
"MIT"
] | 8 | 2016-10-24T16:24:21.000Z | 2021-03-15T11:23:57.000Z | #pragma once
#include "AbstractWindow.h"
class IInputEventAcceptor;
namespace sdl
{
// Совершает диспетчеризацию событий SDL по категориям.
void DispatchEvent(const SDL_Event & event, IInputEventAcceptor & acceptor);
}
// Принимает события SDL, разделённые по категориям.
// Деление условное и может быть изменено.
class IInputEventAcceptor
{
public:
virtual ~IInputEventAcceptor() = default;
virtual void OnMouseUp(const SDL_MouseButtonEvent &) {}
virtual void OnMouseDown(const SDL_MouseButtonEvent &) {}
virtual void OnMouseMotion(const SDL_MouseMotionEvent &) {}
virtual void OnMouseWheel(const SDL_MouseWheelEvent &) {}
virtual void OnKeyDown(const SDL_KeyboardEvent &) {}
virtual void OnKeyUp(const SDL_KeyboardEvent &) {}
};
// Окно, совершающее диспетчеризацию событий SDL
class CAbstractInputControlWindow
: public CAbstractWindow
, public IInputEventAcceptor
{
protected:
void OnWindowEvent(const SDL_Event &event) final
{
sdl::DispatchEvent(event, *this);
}
};
| 27.394737 | 76 | 0.747358 |
2c227d04f505b8bf0d108f23e99fb1be599a6e08 | 504 | asm | Assembly | programs/oeis/313/A313793.asm | jmorken/loda | 99c09d2641e858b074f6344a352d13bc55601571 | [
"Apache-2.0"
] | 1 | 2021-03-15T11:38:20.000Z | 2021-03-15T11:38:20.000Z | programs/oeis/313/A313793.asm | jmorken/loda | 99c09d2641e858b074f6344a352d13bc55601571 | [
"Apache-2.0"
] | null | null | null | programs/oeis/313/A313793.asm | jmorken/loda | 99c09d2641e858b074f6344a352d13bc55601571 | [
"Apache-2.0"
] | null | null | null | ; A313793: Coordination sequence Gal.4.134.1 where G.u.t.v denotes the coordination sequence for a vertex of type v in tiling number t in the Galebach list of u-uniform tilings.
; 1,5,10,15,21,27,32,37,42,47,52,57,63,69,74,79,84,89,94,99,105,111,116,121,126,131,136,141,147,153,158,163,168,173,178,183,189,195,200,205,210,215,220,225,231,237,242,247,252,257
mov $1,$0
add $1,5
mov $2,$0
lpb $0
sub $0,1
trn $3,$1
trn $1,8
sub $2,$3
add $2,6
mov $3,2
lpe
trn $1,2
add $2,6
add $1,$2
sub $1,8
| 26.526316 | 179 | 0.674603 |
61e36ab845ad8ef1e09b1abf8ac5233bc8fdf7a4 | 1,781 | css | CSS | style.css | Joao-Inacio/my-portfolio | 670bfa90ee427cac53e7806850648ef5f340593c | [
"MIT"
] | null | null | null | style.css | Joao-Inacio/my-portfolio | 670bfa90ee427cac53e7806850648ef5f340593c | [
"MIT"
] | 1 | 2022-03-19T18:13:22.000Z | 2022-03-19T18:13:22.000Z | style.css | Joao-Inacio/my-portfolio | 670bfa90ee427cac53e7806850648ef5f340593c | [
"MIT"
] | null | null | null | html, body {
font-family: Merriweather sans-serif ;
overflow-x: hidden;
}
@media (max-width: 575.98px) {
html, body{
text-align: center;
}
img.myfoto{
margin-left: 25px;
}
div.contfoto{
margin-right:50px ;
}
nav div.container{
margin-right:25px;
margin-left: 25px;
}
footer div.contato a{
margin-left: 0;
}
}
div.contfoto img{
margin-left: 55px;
width: 90px;
}
nav.nav-transparente{
padding: 15px 0px;
background: rgba(0, 0, 0, 0.5);
}
.navbar-light .navbar-nav .nav-link{
color: white;
}
.navbar-light .navbar-nav .nav-link:hover{
color: #9bf0e1;
}
.navbar-light .navbar-toggler{
color: rgba(245, 208, 208, 0.699);
border-color: rgba(223, 196, 196, 0.904);
background-color: #ffffff65;
}
.caixar{
border-bottom: 1px solid #e5e5e5;
padding: 60px 0;
}
.intro{
text-align: center;
height:450px;
background-image: url(img/progra.jpg);
background-repeat: no-repeat;
background-position: center;
}
.intro, .tit, .sub{
background-color: black;
color: green;
}
.info, .tit, .sub{
display: block;
margin: 0 auto;
}
.titu{
color: white;
}
.myfoto{
width: 400px;
height: 400px;
}
.roxo{
background-color:#777BB3;
}
.pyazul{
background-color: #3776AB;
}
.pyama{
background-color: #FFD343;
}
.w{
width: 5%;
}
.R{
background-color: #3864BA;
}
footer{
padding-top: 45px;
padding-bottom: 50px;
}
footer a.rodalink {
color: grey;
font-size: 30px;
}
footer div.contato{
margin-bottom: 10px;
text-align: center;
}
footer div.direitos{
margin-left: 0%;
text-align: center;
}
a.rodalink:hover{
color:blue
}
footer a:hover{
color: grey;
} | 15.901786 | 45 | 0.597979 |
0eed61bad26a9e2991ae7220efe7a9b06a5a3337 | 707 | tsx | TypeScript | src/components/Parcels/ParcelDetails/DetailsTrackingTable/Signature/Signature.tsx | Haverim-Larefua/haverim-larefua-portal | 8bfd3db0e2f0b499370a39728d359f9ef29edea0 | [
"MIT"
] | null | null | null | src/components/Parcels/ParcelDetails/DetailsTrackingTable/Signature/Signature.tsx | Haverim-Larefua/haverim-larefua-portal | 8bfd3db0e2f0b499370a39728d359f9ef29edea0 | [
"MIT"
] | 3 | 2020-07-23T07:56:24.000Z | 2022-02-27T20:11:53.000Z | src/components/Parcels/ParcelDetails/DetailsTrackingTable/Signature/Signature.tsx | Haverim-Larefua/haverim-larefua-portal | 8bfd3db0e2f0b499370a39728d359f9ef29edea0 | [
"MIT"
] | null | null | null | import React, { useState } from 'react';
import { ReactComponent as SignatureIcon } from '../../../../../assets/icons/signature.svg';
import './Signature.scss';
export interface SignatureProps {
signature: string;
}
const Signature:React.FC<SignatureProps> = ({signature}: SignatureProps) => {
const [sign, setSign] = useState(signature);
return (
<div className="ffh-signature">
<SignatureIcon />
{sign &&
<div className="ffh-signature__pane">
<img className="ffh-signature__image" src={`data:image/png;base64,${sign}`} alt="חתימה" />
</div>
}
</div>
);
}
export default Signature;
| 28.28 | 110 | 0.584158 |
b2f71e9c0092918763ba4db64292488e285e5cbe | 14,866 | py | Python | python/dolfinx_contact/unbiased/nitsche_unbiased.py | jorgensd/asimov-contact | 08704ade6343c346bc54dfd38186983cc7ab4485 | [
"MIT"
] | null | null | null | python/dolfinx_contact/unbiased/nitsche_unbiased.py | jorgensd/asimov-contact | 08704ade6343c346bc54dfd38186983cc7ab4485 | [
"MIT"
] | null | null | null | python/dolfinx_contact/unbiased/nitsche_unbiased.py | jorgensd/asimov-contact | 08704ade6343c346bc54dfd38186983cc7ab4485 | [
"MIT"
] | null | null | null | # Copyright (C) 2021 Sarah Roggendorf
#
# SPDX-License-Identifier: MIT
from typing import Callable, Tuple, Union
import dolfinx.common as _common
import dolfinx.fem as _fem
import dolfinx.log as _log
import dolfinx.mesh as _mesh
import dolfinx_cuas
import numpy as np
import ufl
from dolfinx.cpp.graph import AdjacencyList_int32
from dolfinx.cpp.mesh import MeshTags_int32
from petsc4py import PETSc as _PETSc
import dolfinx_contact
import dolfinx_contact.cpp
from dolfinx_contact.helpers import (epsilon, lame_parameters,
rigid_motions_nullspace, sigma_func)
kt = dolfinx_contact.cpp.Kernel
__all__ = ["nitsche_unbiased"]
def nitsche_unbiased(mesh: _mesh.Mesh, mesh_tags: list[MeshTags_int32],
domain_marker: MeshTags_int32,
surfaces: AdjacencyList_int32,
dirichlet: list[Tuple[int, Callable[[np.ndarray], np.ndarray]]],
neumann: list[Tuple[int, Callable[[np.ndarray], np.ndarray]]],
contact_pairs: list[Tuple[int, int]],
body_forces: list[Tuple[int, Callable[[np.ndarray], np.ndarray]]],
physical_parameters: dict[str, Union[bool, np.float64, int]],
nitsche_parameters: dict[str, np.float64],
quadrature_degree: int = 5, form_compiler_params: dict = None, jit_params: dict = None,
petsc_options: dict = None, newton_options: dict = None, initial_guess=None,
outfile: str = None, order: int = 1) -> Tuple[_fem.Function, int, int, float]:
"""
Use custom kernel to compute the contact problem with two elastic bodies coming into contact.
Parameters
==========
mesh
The input mesh
mesh_tags
A list of meshtags. The first element must contain the mesh_tags for all puppet surfaces,
Dirichlet-surfaces and Neumann-surfaces
All further elements may contain candidate_surfaces
domain_marker
marker for subdomains where a body force is applied
surfaces
Adjacency list. Links of i are meshtag values for contact surfaces in ith mesh_tag in mesh_tags
dirichlet
List of Dirichlet boundary conditions as pairs of (meshtag value, function), where function
is a function to be interpolated into the dolfinx function space
neumann
Same as dirichlet for Neumann boundary conditions
contact_pairs:
list of pairs (i, j) marking the ith surface as a puppet surface and the jth surface
as the corresponding candidate surface
physical_parameters
Optional dictionary with information about the linear elasticity problem.
Valid (key, value) tuples are: ('E': float), ('nu', float), ('strain', bool)
nitsche_parameters
Optional dictionary with information about the Nitsche configuration.
Valid (keu, value) tuples are: ('gamma', float), ('theta', float) where theta can be -1, 0 or 1 for
skew-symmetric, penalty like or symmetric enforcement of Nitsche conditions
displacement
The displacement enforced on Dirichlet boundary
quadrature_degree
The quadrature degree to use for the custom contact kernels
form_compiler_params
Parameters used in FFCX compilation of this form. Run `ffcx --help` at
the commandline to see all available options. Takes priority over all
other parameter values, except for `scalar_type` which is determined by
DOLFINX.
jit_params
Parameters used in CFFI JIT compilation of C code generated by FFCX.
See https://github.com/FEniCS/dolfinx/blob/main/python/dolfinx/jit.py
for all available parameters. Takes priority over all other parameter values.
petsc_options
Parameters that is passed to the linear algebra backend
PETSc. For available choices for the 'petsc_options' kwarg,
see the `PETSc-documentation
<https://petsc4py.readthedocs.io/en/stable/manual/ksp/>`
newton_options
Dictionary with Newton-solver options. Valid (key, item) tuples are:
("atol", float), ("rtol", float), ("convergence_criterion", "str"),
("max_it", int), ("error_on_nonconvergence", bool), ("relaxation_parameter", float)
initial_guess
A functon containing an intial guess to use for the Newton-solver
outfile
File to append solver summary
order
The order of mesh and function space
"""
form_compiler_params = {} if form_compiler_params is None else form_compiler_params
jit_params = {} if jit_params is None else jit_params
petsc_options = {} if petsc_options is None else petsc_options
newton_options = {} if newton_options is None else newton_options
strain = physical_parameters.get("strain")
if strain is None:
raise RuntimeError("Need to supply if problem is plane strain (True) or plane stress (False)")
else:
plane_strain = bool(strain)
_E = physical_parameters.get("E")
if _E is not None:
E = np.float64(_E)
else:
raise RuntimeError("Need to supply Youngs modulus")
if physical_parameters.get("nu") is None:
raise RuntimeError("Need to supply Poisson's ratio")
else:
nu = physical_parameters.get("nu")
# Compute lame parameters
mu_func, lambda_func = lame_parameters(plane_strain)
mu = mu_func(E, nu)
lmbda = lambda_func(E, nu)
sigma = sigma_func(mu, lmbda)
# Nitche parameters and variables
theta = nitsche_parameters.get("theta")
if theta is None:
raise RuntimeError("Need to supply theta for Nitsche imposition of boundary conditions")
_gamma = nitsche_parameters.get("gamma")
if _gamma is None:
raise RuntimeError("Need to supply Coercivity/Stabilization parameter for Nitsche condition")
else:
gamma: np.float64 = _gamma * E
lifting = nitsche_parameters.get("lift_bc", False)
# Functions space and FEM functions
V = _fem.VectorFunctionSpace(mesh, ("CG", order))
u = _fem.Function(V)
v = ufl.TestFunction(V)
du = ufl.TrialFunction(V)
h = ufl.CellDiameter(mesh)
n = ufl.FacetNormal(mesh)
# Integration measure and ufl part of linear/bilinear form
# metadata = {"quadrature_degree": quadrature_degree}
dx = ufl.Measure("dx", domain=mesh, subdomain_data=domain_marker)
ds = ufl.Measure("ds", domain=mesh, # metadata=metadata,
subdomain_data=mesh_tags[0])
J = ufl.inner(sigma(du), epsilon(v)) * dx
F = ufl.inner(sigma(u), epsilon(v)) * dx
for contact_pair in contact_pairs:
surface_value = int(surfaces.links(0)[contact_pair[0]])
J += - 0.5 * theta * h / gamma * ufl.inner(sigma(du) * n, sigma(v) * n) * \
ds(surface_value)
F += - 0.5 * theta * h / gamma * ufl.inner(sigma(u) * n, sigma(v) * n) * \
ds(surface_value)
# Dirichle boundary conditions
bcs = []
if lifting:
tdim = mesh.topology.dim
for bc in dirichlet:
facets = mesh_tags[0].find(bc[0])
cells = _mesh.compute_incident_entities(mesh, facets, tdim - 1, tdim)
u_bc = _fem.Function(V)
u_bc.interpolate(bc[1], cells)
u_bc.x.scatter_forward()
bcs.append(_fem.dirichletbc(u_bc, _fem.locate_dofs_topological(V, tdim - 1, facets)))
else:
for bc in dirichlet:
f = _fem.Function(V)
f.interpolate(bc[1])
F += - ufl.inner(sigma(u) * n, v) * ds(bc[0])\
- theta * ufl.inner(sigma(v) * n, u - f) * \
ds(bc[0]) + gamma / h * ufl.inner(u - f, v) * ds(bc[0])
J += - ufl.inner(sigma(du) * n, v) * ds(bc[0])\
- theta * ufl.inner(sigma(v) * n, du) * \
ds(bc[0]) + gamma / h * ufl.inner(du, v) * ds(bc[0])
# Neumann boundary conditions
for bc in neumann:
g = _fem.Function(V)
g.interpolate(bc[1])
F -= ufl.inner(g, v) * ds(bc[0])
# body forces
for bf in body_forces:
f = _fem.Function(V)
f.interpolate(bf[1])
F -= ufl.inner(f, v) * dx(bf[0])
# Custom assembly
# create contact class
with _common.Timer("~Contact: Init"):
contact = dolfinx_contact.cpp.Contact(mesh_tags, surfaces, contact_pairs,
V._cpp_object, quadrature_degree=quadrature_degree)
with _common.Timer("~Contact: Distance maps"):
for i in range(len(contact_pairs)):
contact.create_distance_map(i)
# pack constants
consts = np.array([gamma, theta])
# Pack material parameters mu and lambda on each contact surface
with _common.Timer("~Contact: Interpolate coeffs (mu, lmbda)"):
V2 = _fem.FunctionSpace(mesh, ("DG", 0))
lmbda2 = _fem.Function(V2)
lmbda2.interpolate(lambda x: np.full((1, x.shape[1]), lmbda))
mu2 = _fem.Function(V2)
mu2.interpolate(lambda x: np.full((1, x.shape[1]), mu))
entities = []
with _common.Timer("~Contact: Compute active entities"):
for pair in contact_pairs:
entities.append(contact.active_entities(pair[0]))
material = []
with _common.Timer("~Contact: Pack coeffs (mu, lmbda"):
for i in range(len(contact_pairs)):
material.append(dolfinx_cuas.pack_coefficients([mu2, lmbda2], entities[i]))
# Pack celldiameter on each surface
h_packed = []
with _common.Timer("~Contact: Compute and pack celldiameter"):
surface_cells = np.unique(np.hstack([entities[i][:, 0] for i in range(len(contact_pairs))]))
h_int = _fem.Function(V2)
expr = _fem.Expression(h, V2.element.interpolation_points)
h_int.interpolate(expr, surface_cells)
for i in range(len(contact_pairs)):
h_packed.append(dolfinx_cuas.pack_coefficients([h_int], entities[i]))
# Pack gap, normals and test functions on each surface
gaps = []
normals = []
test_fns = []
with _common.Timer("~Contact: Pack gap, normals, testfunction"):
for i in range(len(contact_pairs)):
gaps.append(contact.pack_gap(i))
normals.append(contact.pack_ny(i, gaps[i]))
test_fns.append(contact.pack_test_functions(i, gaps[i]))
# Concatenate all coeffs
coeffs_const = []
for i in range(len(contact_pairs)):
coeffs_const.append(np.hstack([material[i], h_packed[i], gaps[i], normals[i], test_fns[i]]))
# Generate Jacobian data structures
J_custom = _fem.form(J, form_compiler_params=form_compiler_params, jit_params=jit_params)
with _common.Timer("~Contact: Generate Jacobian kernel"):
kernel_jac = contact.generate_kernel(kt.Jac)
with _common.Timer("~Contact: Create matrix"):
J = contact.create_matrix(J_custom)
# Generate residual data structures
F_custom = _fem.form(F, form_compiler_params=form_compiler_params, jit_params=jit_params)
with _common.Timer("~Contact: Generate residual kernel"):
kernel_rhs = contact.generate_kernel(kt.Rhs)
with _common.Timer("~Contact: Create vector"):
b = _fem.petsc.create_vector(F_custom)
@_common.timed("~Contact: Update coefficients")
def compute_coefficients(x, coeffs):
u.vector[:] = x.array
u_candidate = []
with _common.Timer("~~Contact: Pack u contact"):
for i in range(len(contact_pairs)):
u_candidate.append(contact.pack_u_contact(i, u._cpp_object, gaps[i]))
u_puppet = []
with _common.Timer("~~Contact: Pack u"):
for i in range(len(contact_pairs)):
u_puppet.append(dolfinx_cuas.pack_coefficients([u], entities[i]))
for i in range(len(contact_pairs)):
c_0 = np.hstack([coeffs_const[i], u_puppet[i], u_candidate[i]])
coeffs[i][:, :] = c_0[:, :]
@_common.timed("~Contact: Assemble residual")
def compute_residual(x, b, coeffs):
b.zeroEntries()
with _common.Timer("~~Contact: Contact contributions (in assemble vector)"):
for i in range(len(contact_pairs)):
contact.assemble_vector(b, i, kernel_rhs, coeffs[i], consts)
with _common.Timer("~~Contact: Standard contributions (in assemble vector)"):
_fem.petsc.assemble_vector(b, F_custom)
# Apply boundary condition
if lifting:
_fem.petsc.apply_lifting(b, [J_custom], bcs=[bcs], x0=[x], scale=-1.0)
b.ghostUpdate(addv=_PETSc.InsertMode.ADD, mode=_PETSc.ScatterMode.REVERSE)
_fem.petsc.set_bc(b, bcs, x, -1.0)
@_common.timed("~Contact: Assemble matrix")
def compute_jacobian_matrix(x, A, coeffs):
A.zeroEntries()
with _common.Timer("~~Contact: Contact contributions (in assemble matrix)"):
for i in range(len(contact_pairs)):
contact.assemble_matrix(A, [], i, kernel_jac, coeffs[i], consts)
with _common.Timer("~~Contact: Standard contributions (in assemble matrix)"):
_fem.petsc.assemble_matrix(A, J_custom, bcs=bcs)
A.assemble()
# coefficient arrays
num_coeffs = contact.coefficients_size()
coeffs = np.array([np.zeros((len(entities[i]), num_coeffs)) for i in range(len(contact_pairs))])
newton_solver = dolfinx_contact.NewtonSolver(mesh.comm, J, b, coeffs)
# Set matrix-vector computations
newton_solver.set_residual(compute_residual)
newton_solver.set_jacobian(compute_jacobian_matrix)
newton_solver.set_coefficients(compute_coefficients)
# Set rigid motion nullspace
null_space = rigid_motions_nullspace(V)
newton_solver.A.setNearNullSpace(null_space)
# Set Newton solver options
newton_solver.set_newton_options(newton_options)
# Set initial guess
if initial_guess is None:
u.x.array[:] = 0
else:
u.x.array[:] = initial_guess.x.array[:]
# Set Krylov solver options
newton_solver.set_krylov_options(petsc_options)
dofs_global = V.dofmap.index_map_bs * V.dofmap.index_map.size_global
_log.set_log_level(_log.LogLevel.OFF)
# Solve non-linear problem
timing_str = f"~Contact: {id(dofs_global)} Solve Nitsche"
with _common.Timer(timing_str):
n, converged = newton_solver.solve(u)
if outfile is not None:
viewer = _PETSc.Viewer().createASCII(outfile, "a")
newton_solver.krylov_solver.view(viewer)
newton_time = _common.timing(timing_str)
if not converged:
raise RuntimeError("Newton solver did not converge")
u.x.scatter_forward()
print(f"{dofs_global}\n Number of Newton iterations: {n:d}\n",
f"Number of Krylov iterations {newton_solver.krylov_iterations}\n", flush=True)
return u, n, newton_solver.krylov_iterations, newton_time[1]
| 42.965318 | 108 | 0.654245 |
e40ff8d34d18738a41beeb1725ab82a0a65ad52b | 109 | sql | SQL | src/test/resources/sql/_unknown/0c420bf0.sql | Shuttl-Tech/antlr_psql | fcf83192300abe723f3fd3709aff5b0c8118ad12 | [
"MIT"
] | 66 | 2018-06-15T11:34:03.000Z | 2022-03-16T09:24:49.000Z | src/test/resources/sql/_unknown/0c420bf0.sql | Shuttl-Tech/antlr_psql | fcf83192300abe723f3fd3709aff5b0c8118ad12 | [
"MIT"
] | 13 | 2019-03-19T11:56:28.000Z | 2020-08-05T04:20:50.000Z | src/test/resources/sql/_unknown/0c420bf0.sql | Shuttl-Tech/antlr_psql | fcf83192300abe723f3fd3709aff5b0c8118ad12 | [
"MIT"
] | 28 | 2019-01-05T19:59:02.000Z | 2022-03-24T11:55:50.000Z | -- file:triggers.sql ln:1511 expect:false
AAA 42
BBB 42
CCC 42
\.
drop trigger child1_insert_trig on child1
| 13.625 | 41 | 0.770642 |
933a64dc667d2ccd6f890df289346d2f72656f91 | 4,080 | rs | Rust | karamellib/src/vm/executer.rs | erhanbaris/karamel | 11bb8ce079092729f66a152fc8971b4a323dd115 | [
"BSD-3-Clause"
] | 17 | 2021-03-19T22:04:41.000Z | 2022-02-06T19:21:36.000Z | karamellib/src/vm/executer.rs | erhanbaris/TPD | 11bb8ce079092729f66a152fc8971b4a323dd115 | [
"BSD-3-Clause"
] | 22 | 2021-03-22T11:46:12.000Z | 2022-02-13T13:54:26.000Z | karamellib/src/vm/executer.rs | turkce-yazilim-konati/karamel | 0e629afd454bc85c7b59e85258511c47ceaac39d | [
"BSD-3-Clause"
] | 2 | 2022-01-27T18:54:33.000Z | 2022-03-07T16:26:13.000Z | use std::borrow::Borrow;
use std::cell::RefCell;
use crate::compiler::context::{ExecutionPathInfo, KaramelCompilerContext};
use crate::file::read_module_or_script;
use crate::{types::Token, vm::interpreter::run_vm};
use crate::parser::*;
use crate::compiler::*;
use crate::syntax::SyntaxParser;
use crate::logger::{CONSOLE_LOGGER};
use crate::error::generate_error_message;
use log;
use crate::types::VmObject;
pub enum ExecutionSource {
Code(String),
File(String)
}
pub struct ExecutionParameters {
pub source: ExecutionSource,
pub return_opcode: bool,
pub return_output: bool
}
#[derive(Default)]
pub struct ExecutionStatus {
pub compiled: bool,
pub executed: bool,
pub memory_output: Option<Vec<VmObject>>,
pub stdout: Option<RefCell<String>>,
pub stderr: Option<RefCell<String>>,
pub opcodes: Option<Vec<Token>>
}
pub fn get_execution_path<T: Borrow<ExecutionSource>>(source: T) -> ExecutionPathInfo {
ExecutionPathInfo {
path: match source.borrow() {
ExecutionSource::Code(_) => match std::env::current_exe() {
Ok(path) => match path.parent() {
Some(parent_path) => parent_path.to_str().unwrap().to_string(),
_ => String::from(".")
},
_ => String::from(".")
},
ExecutionSource::File(file_name) => file_name.to_string()
},
script: None
}
}
pub fn code_executer(parameters: ExecutionParameters) -> ExecutionStatus {
let mut status = ExecutionStatus::default();
match log::set_logger(&CONSOLE_LOGGER) {
Ok(_) => {
if cfg!(debug_assertions) {
log::set_max_level(log::LevelFilter::Debug)
} else {
log::set_max_level(log::LevelFilter::Info)
}
},
_ => ()
};
let mut context: KaramelCompilerContext = KaramelCompilerContext::new();
context.execution_path = get_execution_path(¶meters.source);
log::debug!("Execution path: {}", context.execution_path.path);
let data = match parameters.source {
ExecutionSource::Code(code) => code,
ExecutionSource::File(filename) => {
match read_module_or_script(filename, &context) {
Ok(content) => content,
Err(error) => {
log::error!("Program hata ile sonlandırıldı: {}", error);
status.executed = false;
return status
}
}
}
};
let mut parser = Parser::new(&data);
match parser.parse() {
Err(error) => {
log::error!("{}", generate_error_message(&data, &error));
return status;
},
_ => ()
};
let syntax = SyntaxParser::new(parser.tokens().to_vec());
let ast = match syntax.parse() {
Ok(ast) => ast,
Err(error) => {
log::error!("{}", generate_error_message(&data, &error));
return status;
}
};
let opcode_compiler = InterpreterCompiler {};
if parameters.return_output {
context.stdout = Some(RefCell::new(String::new()));
context.stderr = Some(RefCell::new(String::new()));
}
let execution_status = match opcode_compiler.compile(ast.clone(), &mut context) {
Ok(_) => unsafe { run_vm(&mut context) },
Err(message) => {
log::error!("Program hata ile sonlandırıldı: {}", message);
return status;
}
};
match execution_status {
Ok(memory) => {
status.compiled = true;
status.executed = true;
status.memory_output = Some(memory)
},
Err(error) => {
log::error!("Program hata ile sonlandırıldı: {}", error);
return status;
}
};
log::info!("Program başarıyla çalıştırıldı");
if parameters.return_opcode {
status.opcodes = Some(parser.tokens());
}
status.stdout = context.stdout;
status.stderr = context.stderr;
status
}
| 29.352518 | 87 | 0.574755 |
44dedb28f71196236178b30a7f1dc6c58b5be064 | 1,060 | kt | Kotlin | library/src/main/java/com/wultra/android/powerauth/networking/error/ApiHttpException.kt | wultra/networking-android | 9cad951f2d03085064575ae418bb5eaad821a218 | [
"Apache-2.0"
] | 1 | 2021-09-27T14:45:02.000Z | 2021-09-27T14:45:02.000Z | library/src/main/java/com/wultra/android/powerauth/networking/error/ApiHttpException.kt | wultra/networking-android | 9cad951f2d03085064575ae418bb5eaad821a218 | [
"Apache-2.0"
] | 10 | 2021-09-24T11:07:48.000Z | 2022-03-08T09:57:13.000Z | library/src/main/java/com/wultra/android/powerauth/networking/error/ApiHttpException.kt | wultra/networking-android | 9cad951f2d03085064575ae418bb5eaad821a218 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2020, Wultra s.r.o. (www.wultra.com).
*
* All rights reserved. This source code can be used only for purposes specified
* by the given license contract signed by the rightful deputy of Wultra s.r.o.
* This source code can be used only by the owner of the license.
*
* Any disputes arising in respect of this agreement (license) shall be brought
* before the Municipal Court of Prague.
*/
package com.wultra.android.powerauth.networking.error
import okhttp3.Response
/**
* Exception for describing HTTP exceptions.
*/
class ApiHttpException(response: Response,
val errorResponse: ErrorResponse? = null,
cause: Throwable? = null):
RuntimeException(getErrorMessage(response), cause) {
companion object {
private fun getErrorMessage(response: Response): String {
return "HTTP " + response.code() + " " + response.message()
}
}
/** Response code */
val code: Int = response.code()
override val message: String = response.message()
} | 32.121212 | 80 | 0.670755 |
5c768fd1fb74f5d6f3507bebbfe31a8de453f400 | 718 | h | C | PrivateFrameworks/ContactsUICore/CNUIUserActionContext-Protocol.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 17 | 2018-11-13T04:02:58.000Z | 2022-01-20T09:27:13.000Z | PrivateFrameworks/ContactsUICore/CNUIUserActionContext-Protocol.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 3 | 2018-04-06T02:02:27.000Z | 2018-10-02T01:12:10.000Z | PrivateFrameworks/ContactsUICore/CNUIUserActionContext-Protocol.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 1 | 2018-09-28T13:54:23.000Z | 2018-09-28T13:54:23.000Z | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "NSObject.h"
@class BSServiceConnectionEndpoint;
@protocol CNUIUserActionContext <NSObject>
@property(copy, nonatomic) BSServiceConnectionEndpoint *connectionEndpoint;
@property(readonly, nonatomic) id <CNUIUserActionCurator> actionCurator;
@property(readonly, nonatomic) id <CNUIUserActionRecorder> actionRecorder;
@property(readonly, nonatomic) id <CNUIUserActionDialRequestOpener> dialRequestOpener;
@property(readonly, nonatomic) id <CNUIUserActionUserActivityOpener> userActivityOpener;
@property(readonly, nonatomic) id <CNUIUserActionURLOpener> urlOpener;
@end
| 35.9 | 88 | 0.79805 |
5406c29865f2eb6bf234c1291ed7db9a0afa61ca | 245 | go | Go | logger.go | Bose/go-work | 0a9c8610aa1934383f66de1a7110e35862b21a5b | [
"BSD-3-Clause"
] | 2 | 2021-04-04T18:39:08.000Z | 2022-02-26T15:25:55.000Z | logger.go | Bose/go-work | 0a9c8610aa1934383f66de1a7110e35862b21a5b | [
"BSD-3-Clause"
] | 3 | 2020-01-24T20:06:07.000Z | 2020-08-20T22:03:27.000Z | logger.go | Bose/go-work | 0a9c8610aa1934383f66de1a7110e35862b21a5b | [
"BSD-3-Clause"
] | 2 | 2020-02-07T13:09:21.000Z | 2021-11-20T02:38:29.000Z | package work
// Logger is used by worker to write logs
type Logger interface {
Debugf(string, ...interface{})
Infof(string, ...interface{})
Errorf(string, ...interface{})
Debug(...interface{})
Info(...interface{})
Error(...interface{})
}
| 20.416667 | 41 | 0.669388 |
eaf0e0037869b9433c0285dff68844c87626b018 | 1,380 | swift | Swift | SecureSwiftLang.playground/Contents.swift | TotemTraining/PracticaliOSAppSecurity | 582355ca262e1b75fc4db0e2edc2d36ae18cc465 | [
"MIT"
] | 1 | 2015-05-10T13:49:43.000Z | 2015-05-10T13:49:43.000Z | SecureSwiftLang.playground/Contents.swift | TotemTraining/PracticaliOSAppSecurity | 582355ca262e1b75fc4db0e2edc2d36ae18cc465 | [
"MIT"
] | null | null | null | SecureSwiftLang.playground/Contents.swift | TotemTraining/PracticaliOSAppSecurity | 582355ca262e1b75fc4db0e2edc2d36ae18cc465 | [
"MIT"
] | null | null | null | import UIKit
//: ## Type Safety and Mutability
//: Explicit and Inferred with constants and variables
let firstName: String = "Jim"
let lastName = "Bob"
//firstName = "We Like Beer!"
//firstName: Int = 12345
let fullName = firstName + " " + lastName
var fact = "I Like Beer"
fact = "I Like Beer and Pizza"
fact += " and Swift"
//: ## String Safety
//printf("Nice try %x", firstName)
class Dog: NSObject {
var name: String
var breed: String
init(name: String, breed: String){
self.name = name
self.breed = breed
}
}
let myDog = Dog(name: "Spot", breed: "Snoopy-kind")
println("My dog's name is \(myDog.name)")
// Still beware of Cocoa's NSString and the old school format-specifiers - %x, %p, etc.
//let someString = NSString(format:"Hello Mem Addrs! %p", firstName)
//: ## Definitive Init
let favoriteBeer: String
let age = 37
// Not init'd yet
//println(favoriteBeer)
if age < 28 {
favoriteBeer = "Miller Lite"
}else{
favoriteBeer = "Anchor Steam"
}
println(favoriteBeer)
//: ## Integer Overflow
//// Highest positive Int
Int.max
//
//// Set a variable at it
var a = 9223372036854775807
//
//// Overflow trapped and reported out (crash, good thing)
//a += 1
//
//// Forced overflow behavior
a = a &+ 1
//: ## Array Bounds Checking
let fruit = ["Apple", "Banana", "Orange"]
//
fruit[1]
// Crash, good thing
//fruit[3]
| 18.90411 | 87 | 0.649275 |
7485a6ed63abc27b6343d026ef56c01ed03a867f | 2,418 | h | C | PROX/FOUNDATION/GEOMETRY/GEOMETRY/include/geometry.h | diku-dk/PROX | c6be72cc253ff75589a1cac28e4e91e788376900 | [
"MIT"
] | null | null | null | PROX/FOUNDATION/GEOMETRY/GEOMETRY/include/geometry.h | diku-dk/PROX | c6be72cc253ff75589a1cac28e4e91e788376900 | [
"MIT"
] | null | null | null | PROX/FOUNDATION/GEOMETRY/GEOMETRY/include/geometry.h | diku-dk/PROX | c6be72cc253ff75589a1cac28e4e91e788376900 | [
"MIT"
] | null | null | null | #ifndef GEOMETRY_H
#define GEOMETRY_H
#include <geometry_convert.h>
#include <geometry_inside.h>
#include <geometry_is_valid.h>
#include <geometry_make_intersection.h>
#include <geometry_make_union.h>
#include <geometry_transform.h>
#include <barycentric/geometry_barycentric.h>
#include <barycentric/geometry_barycentric_inside.h>
#include <barycentric/geometry_barycentric_derivatives.h>
#include <types/geometry_direction_table.h>
#include <types/geometry_interval.h>
#include <types/geometry_dop.h>
#include <types/geometry_line.h>
#include <types/geometry_plane.h>
#include <types/geometry_ray.h>
#include <types/geometry_aabb.h>
#include <types/geometry_capsule.h>
#include <types/geometry_cylinder.h>
#include <types/geometry_box.h>
#include <types/geometry_obb.h>
#include <types/geometry_sphere.h>
#include <types/geometry_tetrahedron.h>
#include <types/geometry_triangle.h>
#include <types/geometry_gauss_map_of_convex_polyhedra.h>
#include <types/geometry_point.h>
#include <overlap/geometry_overlap_dop_dop.h>
#include <overlap/geometry_overlap_interval_interval.h>
#include <overlap/geometry_overlap_obb_obb.h>
#include <overlap/geometry_overlap_tetrahedron_tetrahedron.h>
#include <overlap/geometry_overlap_triangle_triangle.h>
#include <overlap/geometry_overlap_obb_capsule.h>
#include <raycast/geometry_raycast_aabb.h>
#include <raycast/geometry_raycast_plane.h>
#include <raycast/geometry_raycast_dop.h>
#include <raycast/geometry_raycast_triangle.h>
#include <raycast/geometry_raycast_tetrahedron.h>
#include <raycast/geometry_raycast_sphere.h>
#include <raycast/geometry_raycast_obb.h>
#include <closest_points/geometry_closest_point_on_line.h>
#include <closest_points/geometry_closest_point_on_plane.h>
#include <closest_points/geometry_closest_points_line_line.h>
#include <closest_points/geometry_closest_points_tetrahedron_tetrahedron.h>
#include <contacts/geometry_contacts_callback.h>
#include <contacts/geometry_contacts_obb_cylinder.h>
#include <contacts/geometry_contacts_obb_obb.h>
#include <contacts/geometry_contacts_obb_sphere.h>
#include <contacts/geometry_contacts_sphere_sphere.h>
#include <contacts/geometry_contacts_sphere_tetrahedron.h>
#include <contacts/geometry_contacts_tetrahedron_tetrahedron.h>
#include <contacts/geometry_contacts_tetrahedron_tetrahedron_growth.h>
#include <contacts/geometry_contacts_tetrahedron_tetrahedron_closest_points.h>
//GEOMETRY_H
#endif
| 37.78125 | 78 | 0.846981 |
9c14af3a3b177b621bfc460a06d280710a4117aa | 307 | swift | Swift | VIPER/VIPER best practices/VIPER best practices/Sources/Modules/Todos/Implementations/Default/TodosDefaultRouter.swift | offsetkeyz/tutorials | 0c9574aed0a1ae11fd8445fd0f5d56110c142418 | [
"WTFPL"
] | 122 | 2019-09-05T14:27:42.000Z | 2022-03-29T19:49:05.000Z | VIPER/VIPER best practices/VIPER best practices/Sources/Modules/Todos/Implementations/Default/TodosDefaultRouter.swift | offsetkeyz/tutorials | 0c9574aed0a1ae11fd8445fd0f5d56110c142418 | [
"WTFPL"
] | 1 | 2019-09-30T11:21:58.000Z | 2019-09-30T11:21:58.000Z | VIPER/VIPER best practices/VIPER best practices/Sources/Modules/Todos/Implementations/Default/TodosDefaultRouter.swift | offsetkeyz/tutorials | 0c9574aed0a1ae11fd8445fd0f5d56110c142418 | [
"WTFPL"
] | 32 | 2019-11-14T11:50:08.000Z | 2022-03-02T16:09:19.000Z | //
// TodosDefaultRouter.swift
// VIPER best practices
//
// Created by Tibor Bödecs on 2019. 03. 05..
//
import Foundation
import UIKit
class TodosDefaultRouter {
weak var presenter: TodosPresenter?
weak var viewController: UIViewController?
}
extension TodosDefaultRouter: TodosRouter {
}
| 15.35 | 46 | 0.736156 |
2e70514d591305a1a9728e7eeb86f38cc144a1f1 | 624 | kt | Kotlin | src/app/src/main/java/jp/kaleidot725/sample/room/dao/RepoDao.kt | kaleidot725-android/room | c2ad5c579bc67fa27f8d28ce4515d39837c22d6a | [
"MIT"
] | null | null | null | src/app/src/main/java/jp/kaleidot725/sample/room/dao/RepoDao.kt | kaleidot725-android/room | c2ad5c579bc67fa27f8d28ce4515d39837c22d6a | [
"MIT"
] | null | null | null | src/app/src/main/java/jp/kaleidot725/sample/room/dao/RepoDao.kt | kaleidot725-android/room | c2ad5c579bc67fa27f8d28ce4515d39837c22d6a | [
"MIT"
] | null | null | null | package jp.kaleidot725.sample.room.dao
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import jp.kaleidot725.sample.room.data.Repo
import jp.kaleidot725.sample.room.data.User
@Dao
interface RepoDao {
@Insert
fun insert(repo : Repo)
@Update
fun update(repo : Repo)
@Delete
fun delete(repo : Repo)
@Query("delete from repos")
fun deleteAll()
@Query("select * from repos")
fun getAll(): List<Repo>
@Query("select * from repos where userId = :userId")
fun getRepo(userId: Int): Repo
}
| 20.129032 | 56 | 0.705128 |
0e1c41c0953b1a8f46874a91008a9a9c3a00cea7 | 70 | sql | SQL | db/config/init.sql | mauitz/dockerTest | cedb474b36ada83287332fc7d0b39a9aae2c610c | [
"MIT"
] | null | null | null | db/config/init.sql | mauitz/dockerTest | cedb474b36ada83287332fc7d0b39a9aae2c610c | [
"MIT"
] | null | null | null | db/config/init.sql | mauitz/dockerTest | cedb474b36ada83287332fc7d0b39a9aae2c610c | [
"MIT"
] | null | null | null | GRANT ALL ON *.* TO 'root'@'%' IDENTIFIED BY 'root' WITH GRANT OPTION; | 70 | 70 | 0.671429 |
2b6afee745537e03f74ba2e568d22b688a359ce3 | 426 | sql | SQL | samples/SqlServerDemo/SqlServerDemo.Database/Migrations/20220323-165532-03-create-ntangle-customerbatchtracking-table.sql | Avanade/NTangle | fc35e5120246cc1830916ee384eaeaca8ee5865a | [
"MIT"
] | 1 | 2022-02-16T23:16:13.000Z | 2022-02-16T23:16:13.000Z | samples/SqlServerDemo/SqlServerDemo.Database/Migrations/20220323-165532-03-create-ntangle-customerbatchtracking-table.sql | Avanade/NTangle | fc35e5120246cc1830916ee384eaeaca8ee5865a | [
"MIT"
] | 4 | 2022-02-14T17:20:52.000Z | 2022-03-29T15:39:49.000Z | samples/SqlServerDemo/SqlServerDemo.Database/Migrations/20220323-165532-03-create-ntangle-customerbatchtracking-table.sql | Avanade/NTangle | fc35e5120246cc1830916ee384eaeaca8ee5865a | [
"MIT"
] | null | null | null | CREATE TABLE [NTangle].[CustomerBatchTracking] (
[BatchTrackingId] BIGINT IDENTITY (1, 1) NOT NULL PRIMARY KEY CLUSTERED ([BatchTrackingId] ASC),
[CreatedDate] DATETIME2 NOT NULL,
[IsComplete] BIT NOT NULL,
[CompletedDate] DATETIME2 NULL,
[CorrelationId] NVARCHAR(127) NULL,
[HasDataLoss] BIT NOT NULL,
[CustomerMinLsn] BINARY(10) NULL, -- Primary table: '[Legacy].[Cust]'
[CustomerMaxLsn] BINARY(10) NULL,
); | 42.6 | 98 | 0.7277 |
dc15343009622065d3859e28d2ac6876741022f0 | 3,243 | py | Python | microservice_demo/app.py | weiss-d/microservice-demo | 0a3bb713585e5dc4b1dc17ce04a4c74568656452 | [
"MIT"
] | null | null | null | microservice_demo/app.py | weiss-d/microservice-demo | 0a3bb713585e5dc4b1dc17ce04a4c74568656452 | [
"MIT"
] | null | null | null | microservice_demo/app.py | weiss-d/microservice-demo | 0a3bb713585e5dc4b1dc17ce04a4c74568656452 | [
"MIT"
] | null | null | null | """
Simple demo of microservice in Flask.
Personal project for learning Flask and Docker.
The app returns a list of files and folders and some of their properties
from given subdirectory of a directory specified in 'cofig.py'.
$ pip install -r requirements.txt
$ python -m microservice_demo.app
"""
import logging
import os
import re
from string import Template
from flask import Flask, jsonify
from flask.wrappers import Response
import waitress
from microservice_demo import dir_data
# Initializing Flask app and logging
app = Flask(__name__)
app.config.from_pyfile("config.py", silent=True)
logging.basicConfig(
level=logging.INFO,
format="[%(asctime)s] %(message)s",
datefmt="%d-%m-%y %H:%M:%S",
)
if not app.config["ROOT_DIR_PATH"].exists():
logging.warning("WARNING: Root directory specified in 'config.py' doesn't exist.")
# Templates are used instead of string interpolation for security reasons.
LOGGING_INFO_FOLDER_PROCESSING = Template(
"Done processing request for folder '$folder'."
)
LOGGING_INFO_FOLDER_ERROR = Template("ERROR in processing '$folder': $error.")
@app.after_request
def add_hostname_header(response: Response) -> Response:
"""Adding Docker container info to a response header for debugging possibilities.
Parameters
----------
response : Response
Initial Flask response.
Returns
-------
Response
Flask response with added Docker container info.
"""
env_host = str(os.environ.get("HOSTNAME"))
hostname = re.findall(r"[a-z]{3}-\d$", env_host)
if hostname:
response.headers["SP-LOCATION"] = hostname
return response
# Routes
@app.route("/")
@app.route("/api/")
def root_url() -> str:
"""Root API route. No functions.
Returns
-------
str
Error and message about API usage.
"""
return "Folder data microservice.\nWrong request. Use /api/meta/<folder> to get folder list."
@app.route("/api/meta/")
def api_meta_url() -> Response:
"""Base API route. Returns data of the configured root folder.
Returns
-------
Response
List of file/forder data of the rood directory specified in 'config.py' in JSON format.
"""
logging.info(
LOGGING_INFO_FOLDER_PROCESSING.substitute(folder=app.config["ROOT_DIR_PATH"])
)
return jsonify({"data": dir_data.get_dir_data(app.config["ROOT_DIR_PATH"])})
@app.route("/api/meta/<path:folder>")
def api_meta_folder_url(folder: str) -> Response:
"""Main API route for retrieving data for subfolders.
Parameters
----------
folder : str
Any level subfolder of a root forlder.
Returns
-------
Response
List of file/folder data of given subfolder in JSON format.
"""
abs_folder = app.config["ROOT_DIR_PATH"] / folder
try:
response = {"data": dir_data.get_dir_data(abs_folder)}
logging.info(LOGGING_INFO_FOLDER_PROCESSING.substitute(folder=abs_folder))
except Exception as e:
e = str(e)
response = {"error": e}
logging.info(LOGGING_INFO_FOLDER_ERROR.substitute(folder=abs_folder, error=e))
return jsonify(response)
if __name__ == "__main__":
waitress.serve(app, listen="*:5000")
| 25.139535 | 97 | 0.681159 |
202648bc7e4727351b7afc9706266c75596b2c89 | 948 | css | CSS | REACTJS/ReactJs-With-Redux-JavaScriptLibrary-master/React-CRUD-master/src/App.css | DevelopByTarun/TODAY-HELP | 8f5d900ef8ecae4cdea1bb2edd9ef3fbc10df496 | [
"MIT"
] | null | null | null | REACTJS/ReactJs-With-Redux-JavaScriptLibrary-master/React-CRUD-master/src/App.css | DevelopByTarun/TODAY-HELP | 8f5d900ef8ecae4cdea1bb2edd9ef3fbc10df496 | [
"MIT"
] | 4 | 2019-12-20T06:14:41.000Z | 2022-03-02T08:05:02.000Z | REACTJS/ReactJs-With-Redux-JavaScriptLibrary-master/React-CRUD-master/src/App.css | DevelopByTarun/TODAY-HELP | 8f5d900ef8ecae4cdea1bb2edd9ef3fbc10df496 | [
"MIT"
] | null | null | null | .App {
text-align: center;
}
.App-logo {
animation: App-logo-spin infinite 20s linear;
height: 80px;
}
label{
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
text-shadow: 5px;
font-size: 20px;
}
#del,#mark{
height: 50px;
width: 50px;
}
#s1,#s2,#s3{
display: inline;
}
#inputState, #inputState2{
height: 35px;
width: 85px;
}
#inputState3{
height: 35px;
width: 85px;
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
font-size: 12px;
}
.icon{
width: 72px;
height: 72px;
cursor: pointer;
}
.red{
background-color: red;
font-style: italic;
}
img{
height: 100px;
widows: 100px;
}
.App-header {
background-color: #222;
height: 150px;
padding: 20px;
color: white;
}
.App-title {
font-size: 1.5em;
}
.App-intro {
font-size: large;
}
@keyframes App-logo-spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
} | 15.047619 | 80 | 0.635021 |
26252b5b1911ac5e92ce19d245d81b890061b24e | 1,549 | java | Java | src/main/java/me/interview/entity/OptionGroup.java | StarOceanReimi/InsticatorInterview | 1ca351583013021304bf3900de043fc0af68aece | [
"MIT"
] | null | null | null | src/main/java/me/interview/entity/OptionGroup.java | StarOceanReimi/InsticatorInterview | 1ca351583013021304bf3900de043fc0af68aece | [
"MIT"
] | null | null | null | src/main/java/me/interview/entity/OptionGroup.java | StarOceanReimi/InsticatorInterview | 1ca351583013021304bf3900de043fc0af68aece | [
"MIT"
] | null | null | null | package me.interview.entity;
import static javax.persistence.CascadeType.ALL;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.Size;
import org.hibernate.annotations.BatchSize;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.IndexedEmbedded;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonManagedReference;
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
@Entity
public class OptionGroup implements IDAware<Long> {
private static final long serialVersionUID = -7448814545577623152L;
@Min(1)
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@Field
private String name;
@IndexedEmbedded
@Size(min=1)
@JsonManagedReference
@OneToMany(mappedBy="owner", cascade={ ALL }, fetch=FetchType.EAGER)
@BatchSize(size=10)
private Set<OptionValue> options;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<@Valid OptionValue> getOptions() {
return options;
}
public void setOptions(Set<OptionValue> options) {
this.options = options;
}
}
| 22.449275 | 69 | 0.781795 |
56a53741f1c2d3adee0c789079d8040b9f01a38d | 81 | ts | TypeScript | frontend/src/types/dto/data/JoinRoomData.ts | valentin30/skribbl-clone | e234fdcde5bad8c221d937c2b2ad0a75a9c2af62 | [
"MIT"
] | null | null | null | frontend/src/types/dto/data/JoinRoomData.ts | valentin30/skribbl-clone | e234fdcde5bad8c221d937c2b2ad0a75a9c2af62 | [
"MIT"
] | 1 | 2021-03-24T20:54:57.000Z | 2021-03-24T21:00:20.000Z | frontend/src/types/dto/data/JoinRoomData.ts | valentin30/skribbl-clone | e234fdcde5bad8c221d937c2b2ad0a75a9c2af62 | [
"MIT"
] | null | null | null | export interface JoinRoomData {
secondsPerRound: number
rounds: number
}
| 16.2 | 31 | 0.740741 |
5828276f9e8cc9f30be0439119e70d7c8b4830c0 | 647 | c | C | src/Context.c | bitwig/libusb4java | 66afb8eb5e15224ecde6bd36a8103338166ba7b7 | [
"MIT"
] | 45 | 2015-08-21T16:29:41.000Z | 2022-02-05T16:13:10.000Z | src/Context.c | bitwig/libusb4java | 66afb8eb5e15224ecde6bd36a8103338166ba7b7 | [
"MIT"
] | 12 | 2016-03-03T04:33:46.000Z | 2021-12-01T08:59:06.000Z | src/Context.c | bitwig/libusb4java | 66afb8eb5e15224ecde6bd36a8103338166ba7b7 | [
"MIT"
] | 40 | 2015-02-19T10:31:08.000Z | 2022-01-26T21:12:10.000Z | /*
* Copyright (C) 2013 Klaus Reimer (k@ailis.de)
* See LICENSE.md file for copying conditions
*/
#include "Context.h"
void setContext(JNIEnv* env, const libusb_context* context, jobject object)
{
SET_POINTER(env, context, object, "contextPointer");
}
jobject wrapContext(JNIEnv* env, const libusb_context* context)
{
return wrapPointer(env, context, CLASS_PATH("Context"), "contextPointer");
}
libusb_context* unwrapContext(JNIEnv* env, jobject context)
{
return (libusb_context *) unwrapPointer(env, context, "contextPointer");
}
void resetContext(JNIEnv* env, jobject obj)
{
RESET_POINTER(env, obj, "contextPointer");
}
| 23.962963 | 78 | 0.731066 |
8a148b494b9a57884163996e6ef8990359f71979 | 2,548 | rs | Rust | secure/storage/src/error.rs | mohanz/libra | d4600a24262f6f6af9af2bef880cc471354abd4c | [
"Apache-2.0"
] | null | null | null | secure/storage/src/error.rs | mohanz/libra | d4600a24262f6f6af9af2bef880cc471354abd4c | [
"Apache-2.0"
] | 85 | 2020-05-14T04:11:32.000Z | 2021-07-23T06:27:27.000Z | secure/storage/src/error.rs | mohanz/libra | d4600a24262f6f6af9af2bef880cc471354abd4c | [
"Apache-2.0"
] | null | null | null | // Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
use serde::{Deserialize, Serialize};
use std::io;
use thiserror::Error;
#[derive(Debug, Deserialize, Error, PartialEq, Serialize)]
pub enum Error {
#[error("Entropy error: {0}")]
EntropyError(String),
#[error("Internal error: {0}")]
InternalError(String),
#[error("Key already exists: {0}")]
KeyAlreadyExists(String),
#[error("Key not set: {0}")]
KeyNotSet(String),
#[error("Permission denied")]
PermissionDenied,
#[error("Serialization error: {0}")]
SerializationError(String),
#[error("Unexpected value type")]
UnexpectedValueType,
#[error("Key version not found: {0}")]
KeyVersionNotFound(String),
}
impl From<base64::DecodeError> for Error {
fn from(error: base64::DecodeError) -> Self {
Self::SerializationError(format!("{}", error))
}
}
impl From<chrono::format::ParseError> for Error {
fn from(error: chrono::format::ParseError) -> Self {
Self::SerializationError(format!("{}", error))
}
}
impl From<io::Error> for Error {
fn from(error: io::Error) -> Self {
Self::InternalError(format!("{}", error))
}
}
impl From<lcs::Error> for Error {
fn from(error: lcs::Error) -> Self {
Self::SerializationError(format!("{}", error))
}
}
impl From<serde_json::Error> for Error {
fn from(error: serde_json::Error) -> Self {
Self::SerializationError(format!("{}", error))
}
}
impl From<toml::de::Error> for Error {
fn from(error: toml::de::Error) -> Self {
Self::SerializationError(format!("{}", error))
}
}
impl From<toml::ser::Error> for Error {
fn from(error: toml::ser::Error) -> Self {
Self::SerializationError(format!("{}", error))
}
}
impl From<libra_vault_client::Error> for Error {
fn from(error: libra_vault_client::Error) -> Self {
match error {
libra_vault_client::Error::NotFound(_, key) => Self::KeyNotSet(key),
libra_vault_client::Error::HttpError(403, _) => Self::PermissionDenied,
_ => Self::InternalError(format!("{}", error)),
}
}
}
impl From<libra_github_client::Error> for Error {
fn from(error: libra_github_client::Error) -> Self {
match error {
libra_github_client::Error::NotFound(key) => Self::KeyNotSet(key),
libra_github_client::Error::HttpError(403, _) => Self::PermissionDenied,
_ => Self::InternalError(format!("{}", error)),
}
}
}
| 28.629213 | 84 | 0.617347 |
2a2726c67dacde583f366c6d31879b902f94fccf | 2,384 | kt | Kotlin | Core/src/commonMain/kotlin/io/nacular/doodle/layout/HorizontalFlowLayout.kt | hiperbou/doodle | 3baaf792bc13ef9f15aee4a772dcde211fff628b | [
"MIT"
] | null | null | null | Core/src/commonMain/kotlin/io/nacular/doodle/layout/HorizontalFlowLayout.kt | hiperbou/doodle | 3baaf792bc13ef9f15aee4a772dcde211fff628b | [
"MIT"
] | null | null | null | Core/src/commonMain/kotlin/io/nacular/doodle/layout/HorizontalFlowLayout.kt | hiperbou/doodle | 3baaf792bc13ef9f15aee4a772dcde211fff628b | [
"MIT"
] | null | null | null | package io.nacular.doodle.layout
import io.nacular.doodle.core.Layout
import io.nacular.doodle.core.Positionable
import io.nacular.doodle.core.PositionableContainer
import io.nacular.doodle.geometry.Point
import io.nacular.doodle.utils.HorizontalAlignment
import io.nacular.doodle.utils.HorizontalAlignment.Center
import io.nacular.doodle.utils.HorizontalAlignment.Left
import io.nacular.doodle.utils.HorizontalAlignment.Right
import kotlin.math.max
/**
* Created by Nicholas Eddy on 3/17/19.
*/
class HorizontalFlowLayout(private val justification : HorizontalAlignment = Left,
private val verticalSpacing : Double = 1.0,
private val horizontalSpacing: Double = 1.0): Layout {
override fun layout(container: PositionableContainer) {
var y = container.insets.top
var height = 0.0
val itemList = mutableListOf<Positionable>()
var lineWidth = 0.0
val maxLineWidth = container.width - container.insets.left - container.insets.right
container.children.filter { it.visible }.forEach { child ->
child.idealSize?.let { child.size = it }
val temp = lineWidth + child.width + if (itemList.isNotEmpty()) horizontalSpacing else 0.0
if (temp > maxLineWidth) {
layoutLine(itemList, container, lineWidth, y)
itemList.clear()
lineWidth = child.width
if (height > 0) {
y += height + verticalSpacing
}
height = child.height
} else {
lineWidth = temp
}
itemList.add(child)
height = max(height, child.height)
}
if (itemList.isNotEmpty()) {
layoutLine(itemList, container, lineWidth, y)
}
}
private fun layoutLine(itemList: List<Positionable>, parent: PositionableContainer, lineWidth: Double, y: Double) {
var startX = when (justification) {
Right -> parent.width - lineWidth - parent.insets.right
Center -> (parent.width - lineWidth) / 2
Left -> parent.insets.left
}
itemList.forEach {
it.position = Point(startX, y)
startX += it.width + horizontalSpacing
}
}
}
| 32.657534 | 119 | 0.598993 |
dd6c51238d47f2b946e00ab70481bf75e6904670 | 25,002 | go | Go | pkg/synchronization/state.pb.go | BearerPipelineTest/mutagen | 4f8d81212f7d2621b8b03c23a6c2f8408756c184 | [
"MIT"
] | null | null | null | pkg/synchronization/state.pb.go | BearerPipelineTest/mutagen | 4f8d81212f7d2621b8b03c23a6c2f8408756c184 | [
"MIT"
] | null | null | null | pkg/synchronization/state.pb.go | BearerPipelineTest/mutagen | 4f8d81212f7d2621b8b03c23a6c2f8408756c184 | [
"MIT"
] | null | null | null | // Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.28.0
// protoc v3.19.4
// source: synchronization/state.proto
package synchronization
import (
core "github.com/mutagen-io/mutagen/pkg/synchronization/core"
rsync "github.com/mutagen-io/mutagen/pkg/synchronization/rsync"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
// Status encodes the status of a synchronization session.
type Status int32
const (
// Status_Disconnected indicates that the session is unpaused but not
// currently connected or connecting to either endpoint.
Status_Disconnected Status = 0
// Status_HaltedOnRootEmptied indicates that the session is halted due to
// the root emptying safety check.
Status_HaltedOnRootEmptied Status = 1
// Status_HaltedOnRootDeletion indicates that the session is halted due to
// the root deletion safety check.
Status_HaltedOnRootDeletion Status = 2
// Status_HaltedOnRootTypeChange indicates that the session is halted due to
// the root type change safety check.
Status_HaltedOnRootTypeChange Status = 3
// Status_ConnectingAlpha indicates that the session is attempting to
// connect to the alpha endpoint.
Status_ConnectingAlpha Status = 4
// Status_ConnectingBeta indicates that the session is attempting to connect
// to the beta endpoint.
Status_ConnectingBeta Status = 5
// Status_Watching indicates that the session is watching for filesystem
// changes.
Status_Watching Status = 6
// Status_Scanning indicates that the session is scanning the filesystem on
// each endpoint.
Status_Scanning Status = 7
// Status_WaitingForRescan indicates that the session is waiting to retry
// scanning after an error during the previous scanning operation.
Status_WaitingForRescan Status = 8
// Status_Reconciling indicates that the session is performing
// reconciliation.
Status_Reconciling Status = 9
// Status_StagingAlpha indicates that the session is staging files on alpha.
Status_StagingAlpha Status = 10
// Status_StagingBeta indicates that the session is staging files on beta.
Status_StagingBeta Status = 11
// Status_Transitioning indicates that the session is performing transition
// operations on each endpoint.
Status_Transitioning Status = 12
// Status_Saving indicates that the session is recording synchronization
// history to disk.
Status_Saving Status = 13
)
// Enum value maps for Status.
var (
Status_name = map[int32]string{
0: "Disconnected",
1: "HaltedOnRootEmptied",
2: "HaltedOnRootDeletion",
3: "HaltedOnRootTypeChange",
4: "ConnectingAlpha",
5: "ConnectingBeta",
6: "Watching",
7: "Scanning",
8: "WaitingForRescan",
9: "Reconciling",
10: "StagingAlpha",
11: "StagingBeta",
12: "Transitioning",
13: "Saving",
}
Status_value = map[string]int32{
"Disconnected": 0,
"HaltedOnRootEmptied": 1,
"HaltedOnRootDeletion": 2,
"HaltedOnRootTypeChange": 3,
"ConnectingAlpha": 4,
"ConnectingBeta": 5,
"Watching": 6,
"Scanning": 7,
"WaitingForRescan": 8,
"Reconciling": 9,
"StagingAlpha": 10,
"StagingBeta": 11,
"Transitioning": 12,
"Saving": 13,
}
)
func (x Status) Enum() *Status {
p := new(Status)
*p = x
return p
}
func (x Status) String() string {
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
}
func (Status) Descriptor() protoreflect.EnumDescriptor {
return file_synchronization_state_proto_enumTypes[0].Descriptor()
}
func (Status) Type() protoreflect.EnumType {
return &file_synchronization_state_proto_enumTypes[0]
}
func (x Status) Number() protoreflect.EnumNumber {
return protoreflect.EnumNumber(x)
}
// Deprecated: Use Status.Descriptor instead.
func (Status) EnumDescriptor() ([]byte, []int) {
return file_synchronization_state_proto_rawDescGZIP(), []int{0}
}
// State encodes the current state of a synchronization session. It is mutable
// within the context of the daemon, so it should be accessed and modified in a
// synchronized fashion. Outside of the daemon (e.g. when returned via the API),
// it should be considered immutable.
type State struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// Session is the session metadata. If the session is paused, then the
// remainder of the fields in this structure should be ignored.
Session *Session `protobuf:"bytes,1,opt,name=session,proto3" json:"session,omitempty"`
// Status is the session status.
Status Status `protobuf:"varint,2,opt,name=status,proto3,enum=synchronization.Status" json:"status,omitempty"`
// AlphaConnected indicates whether or not the session controller is
// currently connected to the alpha endpoint.
AlphaConnected bool `protobuf:"varint,3,opt,name=alphaConnected,proto3" json:"alphaConnected,omitempty"`
// BetaConnected indicates whether or not the session controller is
// currently connected to the beta endpoint.
BetaConnected bool `protobuf:"varint,4,opt,name=betaConnected,proto3" json:"betaConnected,omitempty"`
// LastError is the last error to occur during synchronization. It is
// cleared after a successful synchronization cycle.
LastError string `protobuf:"bytes,5,opt,name=lastError,proto3" json:"lastError,omitempty"`
// SuccessfulSynchronizationCycles is the number of successful
// synchronization cycles to occur since successfully connecting to the
// endpoints.
SuccessfulSynchronizationCycles uint64 `protobuf:"varint,6,opt,name=successfulSynchronizationCycles,proto3" json:"successfulSynchronizationCycles,omitempty"`
// StagingStatus is the rsync-based staging status. It is only set if the
// session status is Status_StagingAlpha or Status_StagingBeta.
StagingStatus *rsync.ReceiverStatus `protobuf:"bytes,7,opt,name=stagingStatus,proto3" json:"stagingStatus,omitempty"`
// AlphaScanProblems is the list of non-terminal problems encountered during
// scanning on alpha. This list may be a truncated version of the full list
// if too many problems are encountered to report via the RPC API.
AlphaScanProblems []*core.Problem `protobuf:"bytes,8,rep,name=alphaScanProblems,proto3" json:"alphaScanProblems,omitempty"`
// ExcludedAlphaScanProblems is the number of problems that have been
// excluded from AlphaScanProblems due to truncation. This value can only be
// non-zero if alphaScanProblems is non-empty.
ExcludedAlphaScanProblems uint64 `protobuf:"varint,9,opt,name=excludedAlphaScanProblems,proto3" json:"excludedAlphaScanProblems,omitempty"`
// BetaScanProblems is the list of non-terminal problems encountered during
// scanning on beta. This list may be a truncated version of the full list
// if too many problems are encountered to report via the RPC API.
BetaScanProblems []*core.Problem `protobuf:"bytes,10,rep,name=betaScanProblems,proto3" json:"betaScanProblems,omitempty"`
// ExcludedBetaScanProblems is the number of problems that have been
// excluded from BetaScanProblems due to truncation. This value can only be
// non-zero if betaScanProblems is non-empty.
ExcludedBetaScanProblems uint64 `protobuf:"varint,11,opt,name=excludedBetaScanProblems,proto3" json:"excludedBetaScanProblems,omitempty"`
// Conflicts are the conflicts that identified during reconciliation. This
// list may be a truncated version of the full list if too many conflicts
// are encountered to report via the RPC API.
Conflicts []*core.Conflict `protobuf:"bytes,12,rep,name=conflicts,proto3" json:"conflicts,omitempty"`
// ExcludedConflicts is the number of conflicts that have been excluded from
// Conflicts due to truncation. This value can only be non-zero if conflicts
// is non-empty.
ExcludedConflicts uint64 `protobuf:"varint,13,opt,name=excludedConflicts,proto3" json:"excludedConflicts,omitempty"`
// AlphaTransitionProblems is the list of non-terminal problems encountered
// during transition operations on alpha. This list may be a truncated
// version of the full list if too many problems are encountered to report
// via the RPC API.
AlphaTransitionProblems []*core.Problem `protobuf:"bytes,14,rep,name=alphaTransitionProblems,proto3" json:"alphaTransitionProblems,omitempty"`
// ExcludedAlphaTransitionProblems is the number of problems that have been
// excluded from AlphaTransitionProblems due to truncation. This value can
// only be non-zero if alphaTransitionProblems is non-empty.
ExcludedAlphaTransitionProblems uint64 `protobuf:"varint,15,opt,name=excludedAlphaTransitionProblems,proto3" json:"excludedAlphaTransitionProblems,omitempty"`
// BetaTransitionProblems is the list of non-terminal problems encountered
// during transition operations on beta. This list may be a truncated
// version of the full list if too many problems are encountered to report
// via the RPC API.
BetaTransitionProblems []*core.Problem `protobuf:"bytes,16,rep,name=betaTransitionProblems,proto3" json:"betaTransitionProblems,omitempty"`
// ExcludedBetaTransitionProblems is the number of problems that have been
// excluded from BetaTransitionProblems due to truncation. This value can
// only be non-zero if betaTransitionProblems is non-empty.
ExcludedBetaTransitionProblems uint64 `protobuf:"varint,17,opt,name=excludedBetaTransitionProblems,proto3" json:"excludedBetaTransitionProblems,omitempty"`
}
func (x *State) Reset() {
*x = State{}
if protoimpl.UnsafeEnabled {
mi := &file_synchronization_state_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *State) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*State) ProtoMessage() {}
func (x *State) ProtoReflect() protoreflect.Message {
mi := &file_synchronization_state_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use State.ProtoReflect.Descriptor instead.
func (*State) Descriptor() ([]byte, []int) {
return file_synchronization_state_proto_rawDescGZIP(), []int{0}
}
func (x *State) GetSession() *Session {
if x != nil {
return x.Session
}
return nil
}
func (x *State) GetStatus() Status {
if x != nil {
return x.Status
}
return Status_Disconnected
}
func (x *State) GetAlphaConnected() bool {
if x != nil {
return x.AlphaConnected
}
return false
}
func (x *State) GetBetaConnected() bool {
if x != nil {
return x.BetaConnected
}
return false
}
func (x *State) GetLastError() string {
if x != nil {
return x.LastError
}
return ""
}
func (x *State) GetSuccessfulSynchronizationCycles() uint64 {
if x != nil {
return x.SuccessfulSynchronizationCycles
}
return 0
}
func (x *State) GetStagingStatus() *rsync.ReceiverStatus {
if x != nil {
return x.StagingStatus
}
return nil
}
func (x *State) GetAlphaScanProblems() []*core.Problem {
if x != nil {
return x.AlphaScanProblems
}
return nil
}
func (x *State) GetExcludedAlphaScanProblems() uint64 {
if x != nil {
return x.ExcludedAlphaScanProblems
}
return 0
}
func (x *State) GetBetaScanProblems() []*core.Problem {
if x != nil {
return x.BetaScanProblems
}
return nil
}
func (x *State) GetExcludedBetaScanProblems() uint64 {
if x != nil {
return x.ExcludedBetaScanProblems
}
return 0
}
func (x *State) GetConflicts() []*core.Conflict {
if x != nil {
return x.Conflicts
}
return nil
}
func (x *State) GetExcludedConflicts() uint64 {
if x != nil {
return x.ExcludedConflicts
}
return 0
}
func (x *State) GetAlphaTransitionProblems() []*core.Problem {
if x != nil {
return x.AlphaTransitionProblems
}
return nil
}
func (x *State) GetExcludedAlphaTransitionProblems() uint64 {
if x != nil {
return x.ExcludedAlphaTransitionProblems
}
return 0
}
func (x *State) GetBetaTransitionProblems() []*core.Problem {
if x != nil {
return x.BetaTransitionProblems
}
return nil
}
func (x *State) GetExcludedBetaTransitionProblems() uint64 {
if x != nil {
return x.ExcludedBetaTransitionProblems
}
return 0
}
var File_synchronization_state_proto protoreflect.FileDescriptor
var file_synchronization_state_proto_rawDesc = []byte{
0x0a, 0x1b, 0x73, 0x79, 0x6e, 0x63, 0x68, 0x72, 0x6f, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f,
0x6e, 0x2f, 0x73, 0x74, 0x61, 0x74, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0f, 0x73,
0x79, 0x6e, 0x63, 0x68, 0x72, 0x6f, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x1a, 0x23,
0x73, 0x79, 0x6e, 0x63, 0x68, 0x72, 0x6f, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f,
0x72, 0x73, 0x79, 0x6e, 0x63, 0x2f, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x2e, 0x70, 0x72,
0x6f, 0x74, 0x6f, 0x1a, 0x1d, 0x73, 0x79, 0x6e, 0x63, 0x68, 0x72, 0x6f, 0x6e, 0x69, 0x7a, 0x61,
0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f,
0x74, 0x6f, 0x1a, 0x23, 0x73, 0x79, 0x6e, 0x63, 0x68, 0x72, 0x6f, 0x6e, 0x69, 0x7a, 0x61, 0x74,
0x69, 0x6f, 0x6e, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x6c, 0x69, 0x63,
0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x22, 0x73, 0x79, 0x6e, 0x63, 0x68, 0x72, 0x6f,
0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x70, 0x72,
0x6f, 0x62, 0x6c, 0x65, 0x6d, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xcf, 0x07, 0x0a, 0x05,
0x53, 0x74, 0x61, 0x74, 0x65, 0x12, 0x32, 0x0a, 0x07, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e,
0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x18, 0x2e, 0x73, 0x79, 0x6e, 0x63, 0x68, 0x72, 0x6f,
0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e,
0x52, 0x07, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x2f, 0x0a, 0x06, 0x73, 0x74, 0x61,
0x74, 0x75, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x17, 0x2e, 0x73, 0x79, 0x6e, 0x63,
0x68, 0x72, 0x6f, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x53, 0x74, 0x61, 0x74,
0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x26, 0x0a, 0x0e, 0x61, 0x6c,
0x70, 0x68, 0x61, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, 0x18, 0x03, 0x20, 0x01,
0x28, 0x08, 0x52, 0x0e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74,
0x65, 0x64, 0x12, 0x24, 0x0a, 0x0d, 0x62, 0x65, 0x74, 0x61, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63,
0x74, 0x65, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0d, 0x62, 0x65, 0x74, 0x61, 0x43,
0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, 0x12, 0x1c, 0x0a, 0x09, 0x6c, 0x61, 0x73, 0x74,
0x45, 0x72, 0x72, 0x6f, 0x72, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x6c, 0x61, 0x73,
0x74, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x12, 0x48, 0x0a, 0x1f, 0x73, 0x75, 0x63, 0x63, 0x65, 0x73,
0x73, 0x66, 0x75, 0x6c, 0x53, 0x79, 0x6e, 0x63, 0x68, 0x72, 0x6f, 0x6e, 0x69, 0x7a, 0x61, 0x74,
0x69, 0x6f, 0x6e, 0x43, 0x79, 0x63, 0x6c, 0x65, 0x73, 0x18, 0x06, 0x20, 0x01, 0x28, 0x04, 0x52,
0x1f, 0x73, 0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x66, 0x75, 0x6c, 0x53, 0x79, 0x6e, 0x63, 0x68,
0x72, 0x6f, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x43, 0x79, 0x63, 0x6c, 0x65, 0x73,
0x12, 0x3b, 0x0a, 0x0d, 0x73, 0x74, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x53, 0x74, 0x61, 0x74, 0x75,
0x73, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x72, 0x73, 0x79, 0x6e, 0x63, 0x2e,
0x52, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x72, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x0d,
0x73, 0x74, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x3b, 0x0a,
0x11, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x53, 0x63, 0x61, 0x6e, 0x50, 0x72, 0x6f, 0x62, 0x6c, 0x65,
0x6d, 0x73, 0x18, 0x08, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0d, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e,
0x50, 0x72, 0x6f, 0x62, 0x6c, 0x65, 0x6d, 0x52, 0x11, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x53, 0x63,
0x61, 0x6e, 0x50, 0x72, 0x6f, 0x62, 0x6c, 0x65, 0x6d, 0x73, 0x12, 0x3c, 0x0a, 0x19, 0x65, 0x78,
0x63, 0x6c, 0x75, 0x64, 0x65, 0x64, 0x41, 0x6c, 0x70, 0x68, 0x61, 0x53, 0x63, 0x61, 0x6e, 0x50,
0x72, 0x6f, 0x62, 0x6c, 0x65, 0x6d, 0x73, 0x18, 0x09, 0x20, 0x01, 0x28, 0x04, 0x52, 0x19, 0x65,
0x78, 0x63, 0x6c, 0x75, 0x64, 0x65, 0x64, 0x41, 0x6c, 0x70, 0x68, 0x61, 0x53, 0x63, 0x61, 0x6e,
0x50, 0x72, 0x6f, 0x62, 0x6c, 0x65, 0x6d, 0x73, 0x12, 0x39, 0x0a, 0x10, 0x62, 0x65, 0x74, 0x61,
0x53, 0x63, 0x61, 0x6e, 0x50, 0x72, 0x6f, 0x62, 0x6c, 0x65, 0x6d, 0x73, 0x18, 0x0a, 0x20, 0x03,
0x28, 0x0b, 0x32, 0x0d, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x50, 0x72, 0x6f, 0x62, 0x6c, 0x65,
0x6d, 0x52, 0x10, 0x62, 0x65, 0x74, 0x61, 0x53, 0x63, 0x61, 0x6e, 0x50, 0x72, 0x6f, 0x62, 0x6c,
0x65, 0x6d, 0x73, 0x12, 0x3a, 0x0a, 0x18, 0x65, 0x78, 0x63, 0x6c, 0x75, 0x64, 0x65, 0x64, 0x42,
0x65, 0x74, 0x61, 0x53, 0x63, 0x61, 0x6e, 0x50, 0x72, 0x6f, 0x62, 0x6c, 0x65, 0x6d, 0x73, 0x18,
0x0b, 0x20, 0x01, 0x28, 0x04, 0x52, 0x18, 0x65, 0x78, 0x63, 0x6c, 0x75, 0x64, 0x65, 0x64, 0x42,
0x65, 0x74, 0x61, 0x53, 0x63, 0x61, 0x6e, 0x50, 0x72, 0x6f, 0x62, 0x6c, 0x65, 0x6d, 0x73, 0x12,
0x2c, 0x0a, 0x09, 0x63, 0x6f, 0x6e, 0x66, 0x6c, 0x69, 0x63, 0x74, 0x73, 0x18, 0x0c, 0x20, 0x03,
0x28, 0x0b, 0x32, 0x0e, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x43, 0x6f, 0x6e, 0x66, 0x6c, 0x69,
0x63, 0x74, 0x52, 0x09, 0x63, 0x6f, 0x6e, 0x66, 0x6c, 0x69, 0x63, 0x74, 0x73, 0x12, 0x2c, 0x0a,
0x11, 0x65, 0x78, 0x63, 0x6c, 0x75, 0x64, 0x65, 0x64, 0x43, 0x6f, 0x6e, 0x66, 0x6c, 0x69, 0x63,
0x74, 0x73, 0x18, 0x0d, 0x20, 0x01, 0x28, 0x04, 0x52, 0x11, 0x65, 0x78, 0x63, 0x6c, 0x75, 0x64,
0x65, 0x64, 0x43, 0x6f, 0x6e, 0x66, 0x6c, 0x69, 0x63, 0x74, 0x73, 0x12, 0x47, 0x0a, 0x17, 0x61,
0x6c, 0x70, 0x68, 0x61, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x50, 0x72,
0x6f, 0x62, 0x6c, 0x65, 0x6d, 0x73, 0x18, 0x0e, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0d, 0x2e, 0x63,
0x6f, 0x72, 0x65, 0x2e, 0x50, 0x72, 0x6f, 0x62, 0x6c, 0x65, 0x6d, 0x52, 0x17, 0x61, 0x6c, 0x70,
0x68, 0x61, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x50, 0x72, 0x6f, 0x62,
0x6c, 0x65, 0x6d, 0x73, 0x12, 0x48, 0x0a, 0x1f, 0x65, 0x78, 0x63, 0x6c, 0x75, 0x64, 0x65, 0x64,
0x41, 0x6c, 0x70, 0x68, 0x61, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x50,
0x72, 0x6f, 0x62, 0x6c, 0x65, 0x6d, 0x73, 0x18, 0x0f, 0x20, 0x01, 0x28, 0x04, 0x52, 0x1f, 0x65,
0x78, 0x63, 0x6c, 0x75, 0x64, 0x65, 0x64, 0x41, 0x6c, 0x70, 0x68, 0x61, 0x54, 0x72, 0x61, 0x6e,
0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x50, 0x72, 0x6f, 0x62, 0x6c, 0x65, 0x6d, 0x73, 0x12, 0x45,
0x0a, 0x16, 0x62, 0x65, 0x74, 0x61, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e,
0x50, 0x72, 0x6f, 0x62, 0x6c, 0x65, 0x6d, 0x73, 0x18, 0x10, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0d,
0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x50, 0x72, 0x6f, 0x62, 0x6c, 0x65, 0x6d, 0x52, 0x16, 0x62,
0x65, 0x74, 0x61, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x50, 0x72, 0x6f,
0x62, 0x6c, 0x65, 0x6d, 0x73, 0x12, 0x46, 0x0a, 0x1e, 0x65, 0x78, 0x63, 0x6c, 0x75, 0x64, 0x65,
0x64, 0x42, 0x65, 0x74, 0x61, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x50,
0x72, 0x6f, 0x62, 0x6c, 0x65, 0x6d, 0x73, 0x18, 0x11, 0x20, 0x01, 0x28, 0x04, 0x52, 0x1e, 0x65,
0x78, 0x63, 0x6c, 0x75, 0x64, 0x65, 0x64, 0x42, 0x65, 0x74, 0x61, 0x54, 0x72, 0x61, 0x6e, 0x73,
0x69, 0x74, 0x69, 0x6f, 0x6e, 0x50, 0x72, 0x6f, 0x62, 0x6c, 0x65, 0x6d, 0x73, 0x2a, 0x97, 0x02,
0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x44, 0x69, 0x73, 0x63,
0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, 0x10, 0x00, 0x12, 0x17, 0x0a, 0x13, 0x48, 0x61,
0x6c, 0x74, 0x65, 0x64, 0x4f, 0x6e, 0x52, 0x6f, 0x6f, 0x74, 0x45, 0x6d, 0x70, 0x74, 0x69, 0x65,
0x64, 0x10, 0x01, 0x12, 0x18, 0x0a, 0x14, 0x48, 0x61, 0x6c, 0x74, 0x65, 0x64, 0x4f, 0x6e, 0x52,
0x6f, 0x6f, 0x74, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x69, 0x6f, 0x6e, 0x10, 0x02, 0x12, 0x1a, 0x0a,
0x16, 0x48, 0x61, 0x6c, 0x74, 0x65, 0x64, 0x4f, 0x6e, 0x52, 0x6f, 0x6f, 0x74, 0x54, 0x79, 0x70,
0x65, 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x10, 0x03, 0x12, 0x13, 0x0a, 0x0f, 0x43, 0x6f, 0x6e,
0x6e, 0x65, 0x63, 0x74, 0x69, 0x6e, 0x67, 0x41, 0x6c, 0x70, 0x68, 0x61, 0x10, 0x04, 0x12, 0x12,
0x0a, 0x0e, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6e, 0x67, 0x42, 0x65, 0x74, 0x61,
0x10, 0x05, 0x12, 0x0c, 0x0a, 0x08, 0x57, 0x61, 0x74, 0x63, 0x68, 0x69, 0x6e, 0x67, 0x10, 0x06,
0x12, 0x0c, 0x0a, 0x08, 0x53, 0x63, 0x61, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x10, 0x07, 0x12, 0x14,
0x0a, 0x10, 0x57, 0x61, 0x69, 0x74, 0x69, 0x6e, 0x67, 0x46, 0x6f, 0x72, 0x52, 0x65, 0x73, 0x63,
0x61, 0x6e, 0x10, 0x08, 0x12, 0x0f, 0x0a, 0x0b, 0x52, 0x65, 0x63, 0x6f, 0x6e, 0x63, 0x69, 0x6c,
0x69, 0x6e, 0x67, 0x10, 0x09, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x74, 0x61, 0x67, 0x69, 0x6e, 0x67,
0x41, 0x6c, 0x70, 0x68, 0x61, 0x10, 0x0a, 0x12, 0x0f, 0x0a, 0x0b, 0x53, 0x74, 0x61, 0x67, 0x69,
0x6e, 0x67, 0x42, 0x65, 0x74, 0x61, 0x10, 0x0b, 0x12, 0x11, 0x0a, 0x0d, 0x54, 0x72, 0x61, 0x6e,
0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x69, 0x6e, 0x67, 0x10, 0x0c, 0x12, 0x0a, 0x0a, 0x06, 0x53,
0x61, 0x76, 0x69, 0x6e, 0x67, 0x10, 0x0d, 0x42, 0x33, 0x5a, 0x31, 0x67, 0x69, 0x74, 0x68, 0x75,
0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x6d, 0x75, 0x74, 0x61, 0x67, 0x65, 0x6e, 0x2d, 0x69, 0x6f,
0x2f, 0x6d, 0x75, 0x74, 0x61, 0x67, 0x65, 0x6e, 0x2f, 0x70, 0x6b, 0x67, 0x2f, 0x73, 0x79, 0x6e,
0x63, 0x68, 0x72, 0x6f, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x62, 0x06, 0x70, 0x72,
0x6f, 0x74, 0x6f, 0x33,
}
var (
file_synchronization_state_proto_rawDescOnce sync.Once
file_synchronization_state_proto_rawDescData = file_synchronization_state_proto_rawDesc
)
func file_synchronization_state_proto_rawDescGZIP() []byte {
file_synchronization_state_proto_rawDescOnce.Do(func() {
file_synchronization_state_proto_rawDescData = protoimpl.X.CompressGZIP(file_synchronization_state_proto_rawDescData)
})
return file_synchronization_state_proto_rawDescData
}
var file_synchronization_state_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
var file_synchronization_state_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_synchronization_state_proto_goTypes = []interface{}{
(Status)(0), // 0: synchronization.Status
(*State)(nil), // 1: synchronization.State
(*Session)(nil), // 2: synchronization.Session
(*rsync.ReceiverStatus)(nil), // 3: rsync.ReceiverStatus
(*core.Problem)(nil), // 4: core.Problem
(*core.Conflict)(nil), // 5: core.Conflict
}
var file_synchronization_state_proto_depIdxs = []int32{
2, // 0: synchronization.State.session:type_name -> synchronization.Session
0, // 1: synchronization.State.status:type_name -> synchronization.Status
3, // 2: synchronization.State.stagingStatus:type_name -> rsync.ReceiverStatus
4, // 3: synchronization.State.alphaScanProblems:type_name -> core.Problem
4, // 4: synchronization.State.betaScanProblems:type_name -> core.Problem
5, // 5: synchronization.State.conflicts:type_name -> core.Conflict
4, // 6: synchronization.State.alphaTransitionProblems:type_name -> core.Problem
4, // 7: synchronization.State.betaTransitionProblems:type_name -> core.Problem
8, // [8:8] is the sub-list for method output_type
8, // [8:8] is the sub-list for method input_type
8, // [8:8] is the sub-list for extension type_name
8, // [8:8] is the sub-list for extension extendee
0, // [0:8] is the sub-list for field type_name
}
func init() { file_synchronization_state_proto_init() }
func file_synchronization_state_proto_init() {
if File_synchronization_state_proto != nil {
return
}
file_synchronization_session_proto_init()
if !protoimpl.UnsafeEnabled {
file_synchronization_state_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*State); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_synchronization_state_proto_rawDesc,
NumEnums: 1,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_synchronization_state_proto_goTypes,
DependencyIndexes: file_synchronization_state_proto_depIdxs,
EnumInfos: file_synchronization_state_proto_enumTypes,
MessageInfos: file_synchronization_state_proto_msgTypes,
}.Build()
File_synchronization_state_proto = out.File
file_synchronization_state_proto_rawDesc = nil
file_synchronization_state_proto_goTypes = nil
file_synchronization_state_proto_depIdxs = nil
}
| 46.558659 | 159 | 0.721142 |
876af10dbd387c5ea49bcf8b70f923c640d34ab0 | 9,765 | html | HTML | libs/examples/src/table/table-observable-example/table-observable-example.html | matyjerez/barista | 497b134e426d3b62cf5598394a534c99b0fd9981 | [
"Apache-2.0"
] | 124 | 2019-11-27T07:40:21.000Z | 2022-03-11T19:57:50.000Z | libs/examples/src/table/table-observable-example/table-observable-example.html | matyjerez/barista | 497b134e426d3b62cf5598394a534c99b0fd9981 | [
"Apache-2.0"
] | 2,152 | 2019-11-25T17:29:41.000Z | 2022-03-31T12:10:50.000Z | libs/examples/src/table/table-observable-example/table-observable-example.html | matyjerez/barista | 497b134e426d3b62cf5598394a534c99b0fd9981 | [
"Apache-2.0"
] | 90 | 2019-11-25T17:29:05.000Z | 2022-02-11T18:48:16.000Z | <button
*ngIf="!isSubscribed; else cancel"
class="dt-example-button"
dt-button
(click)="startSubscription()"
>
Start subscription
</button>
<button
class="dt-example-button"
dt-button
variant="secondary"
(click)="clearRows()"
>
Clear
</button>
<dt-table [dataSource]="dataSource">
<ng-container dtColumnDef="host" dtColumnAlign="text">
<dt-header-cell *dtHeaderCellDef>Host</dt-header-cell>
<dt-cell *dtCellDef="let row">{{ row.host }}</dt-cell>
</ng-container>
<ng-container dtColumnDef="cpu" dtColumnAlign="text">
<dt-header-cell *dtHeaderCellDef>CPU</dt-header-cell>
<dt-cell *dtCellDef="let row">{{ row.cpu }}</dt-cell>
</ng-container>
<ng-container dtColumnDef="memory" dtColumnAlign="number">
<dt-header-cell *dtHeaderCellDef>Memory</dt-header-cell>
<dt-cell *dtCellDef="let row">{{ row.memory }}</dt-cell>
</ng-container>
<ng-container dtColumnDef="traffic" dtColumnAlign="control">
<dt-header-cell *dtHeaderCellDef>Network traffic</dt-header-cell>
<dt-cell *dtCellDef="let row">{{ row.traffic }}</dt-cell>
</ng-container>
<dt-header-row
*dtHeaderRowDef="['host', 'cpu', 'memory', 'traffic']"
></dt-header-row>
<dt-row
*dtRowDef="let row; columns: ['host', 'cpu', 'memory', 'traffic']"
></dt-row>
<dt-empty-state role="row">
<dt-empty-state-item role="cell">
<dt-empty-state-item-img>
<img
alt="glass"
src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFoAAABaCAYAAAA4qEECAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gQaCCky3/6ewQAAFo1JREFUeNrtXVtvY9d1/s6d5/B+EyWRFDWSRho547EDx4mTQZMmaDMFXKMGUsNtUyAtUKQokKc+9I/0IWj8kL64BdIUtgMM0hStkzix46RO7LEnc7FulERdeBfJQx6eex8Gew+PSEqkxLGdQAswxiIons3vrL3Wt7619hHjuq6LC3vkxl5AcAH0BdAXNr7xj/oCzWYTmqah1WrBsixYlgVZlqEoCmzbBsMwaDQaME0TADA7O4twOAxBEMAwzLmubds2bNuGKIofO9DMpJJht9sFz/PgeZ7+LAgC7t+/D13X4fP5EAqFYBgGarXa8C3Gskin05iamvK8XqvVYJomZFlGKBQaeV2macK2bViWBdd1oSgKOI7zvKfVakGSpEd6Q/qAdl3X40mu60LTNPh8PrBsf6QxDAOdTgc8z6PRaCAUCoFlWTiOg3K5DJ7noSgK4vE4arUaKpUKVFUduqD5+XnE4/Gh14lEIieCqqoqotGo57VisYh6vQ7DMMAwDFZXV+l30XUdfr8fLMtCVVU4jgNFUajDMAwDy7Jg2zYEQRiIwdhA1+t1FItFLC8vQ9d17O3todVqwXEciKKI2dlZDwidTgeVSgXVahWhUAjJZBLtdhuSJKHT6cC2bciyjGQy6bl59+7dQ7vd7l8Mw2BlZQV+v3/sL+I4DnZ3dzE3NweGYajD5PN5VKtVzzWIAxFTFAWCIKDdbsOyLPo+juMgyzJM00S32wXHcUilUkilUmMD7gG61WpBEAQUi0W0221omkbfKAgCAIDjOJimCVEUEQ6H6e85joNcLodOpwNFUXB4eAhd16FpGoLBIJaWlsCyLFzXxZ07d9DtdvtCxuzsLFKp1Jk8xjAMHB0dYWpqCrZt4/bt2wgGg2i1WnBdF7ZtTywMKIqCbDaLQCBwtmToui729vbQ6XRgGAZ93efzwTAMOI5Dk5amadA0DYqiwDRNRKNRNJtN1Go1RKNRSJKExcVFbG5uotlswjRNSJJEk9NxoBVF8Wz5YdZqtVCpVGCaJgKBAGKxGERRhCAIkGUZ5XIZlUoFsiyj3W6D4zjouj4RgEkM73Q6aLfbZwPacRysr69Tr/X5fNB1HZIk9YHSa51OBwBQKpUAgG616elpHB4e4ujoCPF4HN1uF5IkoVAooNlsUi+Ox+OYmZkBz/OwLItec5AdHh5if38fPM+DYRhomoZutwtFUVCr1Tw7sHf7T4QHsyzC4TAymQz29/eRTCbHp3eu66Lb7SKVSiGRSFBqVSwWcXBwMNIHRaNRChjHcdA0DYFAAIFAAPF4nN59kmQCgQCWl5dpzHQcB4VCAY7jYGFhoY/adbtdlEolMAyD2dlZ7OzsQBRFsCyLYrFIY+vxHTro9XEtEolgbm6Ohs92u42DgwOk0+nxYrRpmuA4ri/Au66L27dve8LIIEsmk5ibm6M/V6tV5PN5LCwsIBwOez63Wq1ib28Pq6urdOGn2dHREba3t+G6LtLpNJrNJo6OjmjSe9QWj8cxPz/vuelra2vIZDIjhTtaGQ6iLY7jQNO0kZIIx3GeL7y3twcAaDQayOfzfYu+evXqSCA7jkP/JfFR13XMz88jmUxOLCyMUnQVCgWUy2U4jgOfz4fV1dWxYj9/UkxSVXUkoAnDyGQyNFER75VluY+bj0KNSDU5NTWFWCwGSZJQKpUQjUahaRp0XUcwGESz2TxxjYTHk6LFMIyRdgHLsggEAjBNE5qmoVgsAgAsy8LU1BR4nsf09PRktI56vT7yB7VaLbRarb6Yrmka9vf3x/IgArKmaXAcB47jQFVVyLKMRqOBg4MD6LqOer0OWZaHx0WGgSRJaDabNKGT4oTceFEUIYoi/H4/AoEAJEkCwzDw+/0wDAOapkGWZfp6vV4fC5dTPdpxHHAcR2M34aKu64LjOFoxEbMsC9vb2/RnWZbBcRwkSUIsFhtbo/D5fDg4OICiKLQwIizCsiwa7izLQjgchqZpMAwDHMchEAjQtZH8QnQPXdehKApYlgXP89B1HYIgoNVq0TDo9/uhqipEUaSJneM4upZAIADDMMYq2YdqHYVCgW6Xk7YXwzBwHIduR4ZhIMsyAoEAstks9vf3YRiGJ5mMYq7rotPpoFgsQtM0mKYJlmXpfwRIomGIokjf07uek/IK+Z1hzITjuL7vxrIsrly5AoZhUK1WMTs7e3aPbrVap4Lcm6yIxxNaSECybRuzs7P0fWOVrAxDwwOhg7que26s67qIRCKUS1erVdi2jampKfh8Puzu7kIQhIGsSRAEyrsFQeijgscdiNz8mZkZ+Hw+uK5LK+MzA10oFMYChHBjwzCQzWYRi8U8xcK4uoBlWXS7Es8i2z0ajdLiyLIsxONxGqZIDO/1yF6Z1DAMCILQd+NJ8iYhkThR7/tCoRCVeXvFpmazOZKayA/yUlLtjbrFSWxcXl5GMBg8N51qt9vI5/OwLAuhUAiXLl2iX7JarSKdTtOY3e12Ua1WaTVLkl4sFsP09DQODg6oZ0qSRG/eIK37JPZCiq7Dw0OoqopAIACe57G/vz8S0H2udlZd4PLlyxMBmayB7IJ0Og2e5+E4Dvx+P8LhMBRFAcMwyGazKBQKqNfrqFQqKBQKNOZ2Oh0Eg0FPUUMEMRLaxrGtrS0wDINMJoNGo0HZlCiKI9HFgXr05uYmjo6ORl5ELBbDpUuXJlYgmKaJUqkEWZYpaK7rIpFIUIGeNBZarRZ0XYfruiiXyzQZGoZBWQJhGARkURTBMAxM0xwrf4RCISwuLoJlWTSbTbAsC7/fP1IniB8Uc4ku0W63Ydv20MUwDIO5uTkkEomJVmKu61K+SnYYCQ1kbQQs0gjodDoolUowTZPmB+K1ZP2EmpqmSbtBp8kLxyvESqWCqakpuntHbbfxw2gbWRDLshAEAbZtU8EpEAhA0zTU6/WJg0xK+OM81XVdVCoVlMtl5HI5HBwcgOM4BINByhgYhqGhglDPXibRy50dx6E9y95GwKDGwPGW2tTU1Nj9TP6ksrVarVJvyGQyHmnQ5/ONHedGMVVVoapqn45MEpppmlTOFUWRSq7BYJAWJaTQymQy2NraouU3oYy9LIj8P/nXcRywLDt0JxOGNZHKkCy6VCrRu+/z+fouOE6tP2qDN5/P00JhkMmyjGAwCEVR4PP5IAhCX/VqGAa9SVevXkWz2YSqqpQhtdtt+vmEadi2DUmS4DgODT2D1hCPx1Gv10dW7U71aJ7nEQ6HUSqVIAgCjUlEICL9NRIrJ2GlUsnTDCYJS5ZlxONxxGKxE1U/UrkJguDpO4bDYYTDYUrtKpWKRy7o9e5EIkHXQbyXZVlIkoS5uTn4fL4zFWD8aZoDKQzItlxfX8fq6ir8fj/1+mg0SrfrWc1xHDSbTRpTHceBJElYWFjwtIzaNQPljRYqeRWtUhdqzYDZtWEbDjieAe/j4I9KCE5JiM8FkFwMIJTy9XmlIAg0BBEwFxYWKBcn2gfLsshkMjRcktdIiDq31kGALhQKqFarEEURtm3Tyq83mzcaDQiCQKu3s9qtW7eoYJTL5WiJa+k2tn5Vxfava6jttsf+3FBKxtyno1j8fAJS4OGOWFtbozF+bm6O5iDTNHH37l0qrAWDQWQyGerhruvSjvtEgO4tIHRdp9pBMBjEzMzMROOzbdu4e/cu/H4/stnsgx6i4eDejw+x9rMSTO38XWxOYHHpcwl86qszkPw8bZ8ZhoGlpaU+Lr+xsQFN0yCKIqLRqEdAKhaLSCQSI3v1WJNKlmXh8PAQpml6ChSSqc9jveMCALB3u4F3X9lB58jApE1UeFx7No2FZxJU/x6ka1cqFTov4vf7ceXKlT6pYtRdPPZIGJn8SafTYBgGu7u7VKwJBAKQZflEMf7UWG25eO8HBay/WTrxfYGED/GcgkDCBynAgxNY2KYDXbWgVrqo7XTQKndP/IzM4xE8/WIOgswP1Vz8fj/29/chy3If0zg+BjdRoMkCNE3D0dERLUVJ4pRlmSaVsUvvro03v7uB0nprCLgSFp5JYu7JKJTo6aJ7p25g5706Nt8uQ60M1nDC0zK++M0lyGFx4C7TdR2BQGAgs2q32yiXyyNp7ecactza2kKtVvNUkpIkUWoYj8dH7kKYXRs/+faHqBf6iyAlIuLas2lkn4yCYcenkq7jYve9Ot6/uTcwFClREV/51gqUiOjJGZ1OB6qqIhKJ0F1q2zby+TzS6TR8Ph9M0xyp0XxmoF3Xxf379+kMHc/zVEAnMVuSpL4kMyxcvPHS2kBPXngmgSf/LAtePP8ot2U4uPWDXWz8ojKAmfjwlW+tQFQehgHS/+Q4DlNTU1Rw63a7nkHJ483nsZuzJ1m1WqWCjKIoVC7sdrv033a7PZLs+t4PCn0gsxyDz/7FPD7zQm4iIAMAL7J46s9z+OxfXgLLeYFpFrv41b/ngR63m56eRrVapR67vb2NTqdDZwpbrRbtko+tR49qR0dHnvZVp9Ohontvx2JzcxP5fH6oSrZ3+6gv8bEcgy/8zSLmn47jUdj8Z2K4/rdLfWDv32lg7eclT6WZSqVwcHAAy7IgSRIMw6DtMzLKqygKisUims0mGo3GwAbCmSf+GYbxqF/D+DeRMMmMx+LiIp2tswwH776y2/d7T784j9nHwniUNrMawtMvzuOX/7blef2DH+4h/XiExutEIoFqtQpN05BKpRCPx2HbtkcvMQwDoVAIe3t7aDQatPM/OztLw8qZPZoMxkiSNHDWeZBpmoZ79+7Rn+/9+LAvOS1dTyL3VAwfheWeimHpuvdkgaU7+O2P9j0OtbKygmazSRkWoXqkQhZFEbIsY2lpiVaXBwcHHjHrzB49MzODSqUCy7LoJCjpbpxkROyxdBtrP/OGDH9MwhPPZU699jvvvIO9vT1UKhUaM1mWhc/no3Nyjz/+OBRFOfWznngujYN7DbSrD3NJ/p0aHvujGfjjEgU7nU6j3W6j2+3SiVmiafdS2UgkAsMwkMlkoKoqrSbPFTpmZmaws7MDlmVpMjwJaLJgANj6VbWvrH7iuQw44fRN9vrrrw8UpYiWvb29jbfffhvPPvvsqayHE1g8+VwGb/7rhocObvyijGt/mhnoJERYchyHJkoSIkKhEPx+f9/Q6LnSOem4EHCHTaX2LpTw0e1f1/qEn8zjkYmFBV3X8dprr514MIlY+moE4WlvNZt/p4aTiC/RrG3bRqVSwa1btygdJOMQvd3xcx1/YxgGV65cwe7uLj0AROYoBrEMIsC0a0afCrd0PQmMWIukUinkcjmkUimEw2GIooh2u407d+7ggw8+8BQdt27dwpe//OVTvgiweD2J3/znzsPyumWimleRuBQ4keKSGRjbtmnDpFqt9p1zOfc5Q1EUsbi4iPX1dTQaDbqlBs0uE28ub3g5M8MC2SdG9+ZvfOMbA3dXLpdDu93G5uamB4xRLHstindf2YXrPFxzca01FOhyuUwH54ltbm4iEonQiaqJ8OjjRkpvQRCopny8e0FEmUree/wtMqN4dOLz2PHjcaMOu0sBHpFZb/Ksbvcf06vX69ja2uoDmYTOcrlMqe9EePQgVY/neXS7Xdp9JjEskUggm83SrdQqeVW1WM4/kTVomob79+97FbpMZuTfj+cU1AsPQ1qr6K1q9/b2cHh4OJI8Ua/XPc3siXp074V6e26xWMwTr9SqN34Hk75zX98wDLz66qseTh8Oh3Ht2rWRP+P4OjoN3RNKxpmLPl5b8JMEujcBko4z4bfHlbpe8wXPFzZUVcX3v/99mu1Jxn/hhRdGDh0PwodwTPV7UMAIMke7TKPa8ZNsEwOaSKUkbpFhlunp6b4va5tOH5c9T8j63ve+h0rloSI3OzuL559/fqxzgER0Om62+QDocTvfx3PFxIA+flbcdV164LKP5vEMLMMdCvw49v7773tAnp+fx9e+9rUzdeQHrYPlH7AH0hUn9YDf74dlWQN5uiiKfecQJwY0icueD+f5gYczeR8Hy3j4pYz22c8C9lI5ALhx48aZxx70Y+tgGYCXOLpzcrkcRFGkhYhpmtB13ROPOY7DwsJC3xomGqN7hwaj0Siy2ezgCjEqods0H2b3SvfM1+31tGAwONYUfl+sP7YOKShQKXXQ4U1BEBCJRDzNj5WVlYFtvIkBzfM8ZFlGp9OBKIrIZrNDE1FwSvJw1LPMahB75plnaOI5S5+y146v4/jgzbAcwXEcnUUZtAbDMCb7BJpwOAxVVekJgKF8dS6A/P89rNjqux2YXRuCb/wtf+XKFXqAdNSDOwMB023Udr39ymj2dH6fyWTo0exh1ul0Jgs0acSSEDLMw5KLXjbg2C72bh9h/jPjdVRs28bLL79Mi4hUKoWvf/3rZ5r43P+gAcfy5pjU5dOPTBweHiIUCg28puu6qNVqDyTkSQLt9/shSRKdqx5moZQPoZRXLdt4qzL29XZ2djyVWrFYHDi8OIpt/MKrjQs+DomF0z16enp64INcjo6OUKlUEAgEHghMmLBNT09DUZRTz3XMfTrapyuU1tWx88Ior51m5Q0Vlbw3PmefjILjR5hAOiYe1et17O7uQpIkJJNJyromDnQwGMT8/Dyq1eqJj3BY/Hyir1B57zWvejZKfFxdXaU/r6ysjDV4+KD6c/Hea7t9sunSF5Jn3tXZbLZvWov5OB+Z+ZtXdrH+c++Wvfons3jsj8cboCQnD0ZpXR23u/9ziA9+uOd5bWY1jD/4u6WJfteP9QGDn/rqjGdgBQB++98HKK21xvocRVHOBHJpXcXtH3kfCMCwDK49m574d2U+7ofAbr5dwTv/sd2XiP7wH5YRzSiP7Lr1Qgc/+faHfQJXO7mNllKALMu4cePG2KHoE+nRwIORr+O9QjKHV95QH8k1y+vqQJCrobsos+vodruo1+u4efPm70foIPb0i7m+5qjZtfHTf/kQ939S9IxpnU+PAe69foiffmcwyC3ZG0Z6h2R+50MHMa1h4H//+T469f6mbjyn4NPPzyE2d/ZOTHVbxbuvFlDb6S/3B4EMACEzgxf++nnEc8rvD9DAg3nmN76zhmZpsMiUWg5h6QtJzKyGqXx5YuVoOji428T6W6WhCXYYyIqeRLJxFaIk4IvfXD432Mwn7YnoRsfCL1/ewsG95tD3CD4OiXk/YnN+BJI+SH7vxH+r3EVtp41KXoWlD9/6p4HMuCy93nnBZj6Jj553XWDtjRJu/9eeR7eeGNViGajxPMrs+qkg997c84D9iXxQN8MAy1+awo1/egy5p2JgJrjK6ZUQvvqPq2gphZFBJsn5je98iOp25/fHo49bq9zFxltl5H9dO1M3hpdYZK9FsXQ9SaXPl156ydPVPgnkSXg287v0Vytcx0V5Q0VxvYlqvo1mqYtuy+yjf6KfRzjlQzSjIHU5hKmlILhjjdft7W3cvHnzwaM9uzOI1C+fCvJ5wGZ+1/88iG05MDUbtumA5VmIMjdWV91xHNR3u3hjALeeJNjMxd9hITy780jBvvirFT1F0Re/uTxWO22cBHkB9EcE9gXQHxHYF0BPGOxhoxMXQE8Y7De/uzkwoV4APWGwtYaBrV9WL4D+KMAubzYvgP4owLZN9wLojwLsSFq5APpRg80JLBY/n7gAehJgf+nvLw88DsLyDD73V5fgj0kXWsekTG9bWPtZCeXNFlzbRTTrx9L15NCDTxdAf0R2ETougL4A+sIugP7k2v8Do6Jp3UCqD5oAAAAASUVORK5CYII="
/>
</dt-empty-state-item-img>
<dt-empty-state-item-title aria-level="1">
No data that matches your query
</dt-empty-state-item-title>
To add data to the query, click the start subscription button.
</dt-empty-state-item>
</dt-empty-state>
</dt-table>
<ng-template #cancel>
<button class="example-button" dt-button (click)="cancelSubscription()">
Cancel subscription
</button>
</ng-template>
| 145.746269 | 7,890 | 0.906196 |
7af2ee2300500ba921090fc798d531bce5beb5cc | 407 | rb | Ruby | db/migrate/20150221093349_create_targets.rb | atbaker/mayone-2.0 | 6d7953eb0c4cd5e4d47d5278cf2b10105ae81417 | [
"Apache-2.0"
] | null | null | null | db/migrate/20150221093349_create_targets.rb | atbaker/mayone-2.0 | 6d7953eb0c4cd5e4d47d5278cf2b10105ae81417 | [
"Apache-2.0"
] | null | null | null | db/migrate/20150221093349_create_targets.rb | atbaker/mayone-2.0 | 6d7953eb0c4cd5e4d47d5278cf2b10105ae81417 | [
"Apache-2.0"
] | null | null | null | class CreateTargets < ActiveRecord::Migration
def change
create_table :targets do |t|
t.belongs_to :campaign, index: true
t.belongs_to :legislator, index: true
t.integer :priority
t.timestamps null: false
end
add_foreign_key :targets, :campaigns
add_foreign_key :targets, :legislators
add_index :targets, [:legislator_id, :campaign_id], unique: true
end
end
| 27.133333 | 68 | 0.70516 |
836de4554c10c5be8a2b02efddfe2828c9bddc05 | 225 | sql | SQL | Admin_Console/DDL_users.sql | DataChant/amazon-quicksight-sdk-proserve | 98c8ceb1b603f7c5dd88357c49e8f71372cd3a1a | [
"MIT-0"
] | 42 | 2020-09-08T03:50:08.000Z | 2022-03-25T08:21:20.000Z | Admin_Console/DDL_users.sql | DataChant/amazon-quicksight-sdk-proserve | 98c8ceb1b603f7c5dd88357c49e8f71372cd3a1a | [
"MIT-0"
] | 3 | 2021-01-13T15:50:11.000Z | 2022-03-21T22:25:37.000Z | Admin_Console/DDL_users.sql | DataChant/amazon-quicksight-sdk-proserve | 98c8ceb1b603f7c5dd88357c49e8f71372cd3a1a | [
"MIT-0"
] | 31 | 2020-06-22T18:26:59.000Z | 2022-03-24T20:20:05.000Z | CREATE OR REPLACE VIEW users AS
(select Namespace,
Group,
User,
(case
when Group in ('quicksight-fed-bi-developer', 'quicksight-fed-bi-admin')
then 'Author'
else 'Reader'
end)
as author_status
from "group_membership" ) | 20.454545 | 73 | 0.742222 |
089e823e432425f7f220f1b4ed5c182dc240732d | 526 | go | Go | commands/list.go | JadeRedworth/cli | db53c6ab28d94d82b9fe57da8f0a8d2cfcc9c62d | [
"Apache-2.0"
] | null | null | null | commands/list.go | JadeRedworth/cli | db53c6ab28d94d82b9fe57da8f0a8d2cfcc9c62d | [
"Apache-2.0"
] | null | null | null | commands/list.go | JadeRedworth/cli | db53c6ab28d94d82b9fe57da8f0a8d2cfcc9c62d | [
"Apache-2.0"
] | null | null | null | package commands
import (
"github.com/urfave/cli"
)
// ListCommand returns list cli.command
func ListCommand() cli.Command {
return cli.Command{
Name: "list",
Aliases: []string{"ls"},
Usage: "\tReturn a list of created objects",
Category: "MANAGEMENT COMMANDS",
Hidden: false,
ArgsUsage: "<subcommand>",
Description: "This command returns a list of created objects ('app', 'call', 'context', 'function' or 'trigger') or configurations.",
Subcommands: GetCommands(ListCmds),
}
}
| 26.3 | 135 | 0.6673 |
f38cbdc86a77c3334d8d29f7ef2ff67ce1a46d9b | 2,357 | swift | Swift | SoraPassport/Modules/Wallet/CoreData/DepositOperationData+TransferInfo.swift | metrocoindev/Sora-iOS | ded201e998285f8124f6f82fa34d8937847e5da5 | [
"Apache-2.0"
] | null | null | null | SoraPassport/Modules/Wallet/CoreData/DepositOperationData+TransferInfo.swift | metrocoindev/Sora-iOS | ded201e998285f8124f6f82fa34d8937847e5da5 | [
"Apache-2.0"
] | null | null | null | SoraPassport/Modules/Wallet/CoreData/DepositOperationData+TransferInfo.swift | metrocoindev/Sora-iOS | ded201e998285f8124f6f82fa34d8937847e5da5 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache 2.0
*/
import Foundation
import CommonWallet
enum DepositOperationDataError: Error {
case invalidAmount
}
extension DepositOperationData {
static func createForEthereumFromInfo(_ info: TransferInfo,
transactionId: String,
receiverName: String? = nil) throws
-> DepositOperationData {
guard
let amount = info.context?[WalletOperationContextKey.ERC20Withdraw.balance],
let depositAmount = AmountDecimal(string: amount) else {
throw DepositOperationDataError.invalidAmount
}
let timestamp = Int64(Date().timeIntervalSince1970)
let transferAmount: AmountDecimal?
if info.source != info.destination {
let soranetAmount: Decimal
if let amount = info.context?[WalletOperationContextKey.SoranetTransfer.balance] {
soranetAmount = Decimal(string: amount) ?? Decimal(0)
} else {
soranetAmount = Decimal(0)
}
let totalFee = info.fees.reduce(Decimal(0.0)) { (result, fee) in
if fee.feeDescription.assetId == info.asset {
return result + fee.value.decimalValue
} else {
return result
}
}
transferAmount = AmountDecimal(value: soranetAmount + depositAmount.decimalValue - totalFee)
} else {
transferAmount = nil
}
return DepositOperationData(depositTransactionId: transactionId,
transferTransactionId: nil,
timestamp: timestamp,
status: .depositPending,
assetId: info.asset,
sender: info.source,
receiver: info.destination,
receiverName: receiverName,
depositAmount: depositAmount,
transferAmount: transferAmount,
fees: info.fees,
note: info.details)
}
}
| 37.412698 | 104 | 0.51888 |
8130ea1ab8158bf77740addcd9150db31b73fa5f | 691 | swift | Swift | 15-mvc-exercise/mvc-ifyme-capn/Controller/Controller.swift | BBarisKilic/Swift-5-Course | 524fc7843f9e3e3f26825c2c549ca233fd728d11 | [
"MIT"
] | 2 | 2021-06-11T08:44:59.000Z | 2021-09-27T21:00:25.000Z | 15-mvc-exercise/mvc-ifyme-capn/Controller/Controller.swift | BBarisKilic/Swift-5-Course | 524fc7843f9e3e3f26825c2c549ca233fd728d11 | [
"MIT"
] | null | null | null | 15-mvc-exercise/mvc-ifyme-capn/Controller/Controller.swift | BBarisKilic/Swift-5-Course | 524fc7843f9e3e3f26825c2c549ca233fd728d11 | [
"MIT"
] | null | null | null | //
// Controller.swift
// mvc-ifyme-capn
//
// Created by Caleb Stultz on 9/20/17.
// Copyright © 2017 Caleb Stultz. All rights reserved.
//
import UIKit
class Controller: UIViewController {
@IBOutlet weak var iphoneNameLabel: UILabel!
@IBOutlet weak var iphoneColorLabel: UILabel!
@IBOutlet weak var iphonePriceLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let appleProduct = AppleProduct(name: "iPhone X", color: "Space Gray", price: 999.99)
iphoneNameLabel.text = appleProduct.name
iphoneColorLabel.text = "in \(appleProduct.color)"
iphonePriceLabel.text = "$\(appleProduct.price)"
}
}
| 25.592593 | 93 | 0.668596 |
40c674234b211bf9712357f3965b06eff613baf5 | 1,430 | py | Python | web2py/applications/smc/modules/ednet/appsettings.py | aduckworth1969/smc | b1771d9ed68f0e35f46271aab5b1e1fab363e3d9 | [
"MIT"
] | 1 | 2018-04-19T05:09:06.000Z | 2018-04-19T05:09:06.000Z | web2py/applications/smc/modules/ednet/appsettings.py | aduckworth1969/smc | b1771d9ed68f0e35f46271aab5b1e1fab363e3d9 | [
"MIT"
] | 14 | 2018-03-04T22:56:41.000Z | 2020-12-10T19:49:43.000Z | web2py/applications/smc/modules/ednet/appsettings.py | aduckworth1969/smc | b1771d9ed68f0e35f46271aab5b1e1fab363e3d9 | [
"MIT"
] | 2 | 2020-09-18T15:12:26.000Z | 2020-11-10T22:09:59.000Z | # -*- coding: utf-8 -*-
from gluon import *
from gluon import current
import json
# Settings Class
class AppSettings:
def __init__(self):
pass
@staticmethod
def SetValue(key, value):
db = current.db # Grab current db object
items = {key: value}
db(db.my_app_settings).update(**items)
db.commit()
@staticmethod
def GetValue(key, default):
db = current.db # Grab the current db object
ret = ""
settings = dict()
if len(settings) < 1:
# Need to load the settings
rows = db(db.my_app_settings).select(limitby=(0, 1))
for row in rows:
for col in db.my_app_settings.fields:
settings[col] = row[col]
if key in settings:
if settings[key] is not None and len(str(settings[key])) > 0:
ret = settings[key] # t1
else:
ret = default
else:
ret = default
# Test to see if this is a password that decoded properly - don't send back bad unicode passwords
# Protects against 500 errors when enc key is wrong
try:
json.dumps(dict(k=ret))
except UnicodeDecodeError:
# This error means error decoding the value - common w decrypting with invalid key
ret = default
return ret
# End MySettings
| 26 | 105 | 0.553846 |
25bcdde6814182e6184eb9f2f31cc34483b442f2 | 366 | kts | Kotlin | build.gradle.kts | demidko/aot-bytecode | a9d7f03c502374300fa4d67524a7f735118ec216 | [
"MIT"
] | null | null | null | build.gradle.kts | demidko/aot-bytecode | a9d7f03c502374300fa4d67524a7f735118ec216 | [
"MIT"
] | 1 | 2021-11-13T07:52:40.000Z | 2021-11-29T07:53:47.000Z | build.gradle.kts | demidko/aot-bytecode | a9d7f03c502374300fa4d67524a7f735118ec216 | [
"MIT"
] | null | null | null | repositories {
mavenCentral()
}
plugins {
`java-library`
`maven-publish`
}
dependencies {
testImplementation("org.junit.jupiter:junit-jupiter:5.8.1")
testImplementation("org.hamcrest:hamcrest:2.2")
}
tasks.test {
useJUnitPlatform()
}
publishing {
publications {
create<MavenPublication>("aot-bytecode") {
from(components["java"])
}
}
}
| 16.636364 | 61 | 0.685792 |
abbb0b99644db34a98efd53b46fccc1b90e1ee3b | 1,817 | rb | Ruby | app/controllers/application_controller.rb | drakmail/auth_example | 88738d5ac94a00c45907dcaba21b4add1b2bedef | [
"MIT"
] | null | null | null | app/controllers/application_controller.rb | drakmail/auth_example | 88738d5ac94a00c45907dcaba21b4add1b2bedef | [
"MIT"
] | 9 | 2019-11-10T12:08:39.000Z | 2022-03-30T23:13:34.000Z | app/controllers/application_controller.rb | drakmail/auth_example | 88738d5ac94a00c45907dcaba21b4add1b2bedef | [
"MIT"
] | null | null | null | # frozen_string_literal: true
class ApplicationController < ActionController::API
class AuthError < StandardError; end
before_action :authenticate, :authenticate!
attr_reader :current_user
rescue_from AuthError, with: :handle_access_denied
rescue_from ActiveRecord::RecordInvalid, with: :handle_invalid_record
rescue_from ActiveRecord::RecordNotUnique, with: :handle_not_unique_record
rescue_from ActiveRecord::RecordNotFound, with: :handle_record_not_found
rescue_from PG::ForeignKeyViolation, with: :handle_record_in_usage
protected
def handle_access_denied
render json: { success: false, errors: ["AUTH_REQUIRED"] }, status: 403
end
def handle_invalid_record(e)
errors = e.record.errors.details.reduce([]) do |acc, (field, errors)|
acc << [field.to_s.upcase, errors[0][:error].to_s.upcase].join("_")
end
render json: { success: false, errors: errors }, status: 400
end
def handle_not_unique_record
render json: { success: false, errors: ["NOT_UNIQUE"] }, status: 400
end
def handle_record_not_found
render json: { success: false, errors: ["NOT_FOUND"] }, status: 404
end
def handle_record_in_usage
render json: { success: false, errors: ["NOT_ALLOWED", "IN_USAGE"] }, status: 403
end
# Check JWT and set user if exists
def authenticate
token = request.headers["Authorization"]&.split(" ")&.last
# TODO: for production need to change to RSA or any another similar algo :-)
decoded_token = JWT.decode(token, nil, false)
@current_user = decoded_token[0]["sub"]
rescue JWT::DecodeError
Rails.logger.warn "Unable to decode JWT token"
end
# Check that request has authorized user
def authenticate!
# just check, that something exists in sub :-)
raise AuthError.new if current_user.nil?
end
end
| 31.877193 | 85 | 0.729224 |
0be895734fc4752fbd96cdd5b68c4e7546286c90 | 3,822 | js | JavaScript | src/layouts/index.js | mabhub/ortho44-2018 | 99864cc1bafb0c62cbb5581c84cabfcba15ef838 | [
"MIT"
] | null | null | null | src/layouts/index.js | mabhub/ortho44-2018 | 99864cc1bafb0c62cbb5581c84cabfcba15ef838 | [
"MIT"
] | null | null | null | src/layouts/index.js | mabhub/ortho44-2018 | 99864cc1bafb0c62cbb5581c84cabfcba15ef838 | [
"MIT"
] | null | null | null | import React from 'react';
import PropTypes from 'prop-types';
import Helmet from 'react-helmet';
import { navigateTo } from 'gatsby-link';
import { getLocationHref } from '../helpers';
import Header from '../components/Header';
import Footer from '../components/Footer';
import Icons from '../components/Icons';
import CustomModal from '../components/CustomModal';
import './main.scss';
import favicon from '../img/favicon.ico';
export default class TemplateWrapper extends React.Component {
static propTypes = {
location: PropTypes.object.isRequired,
children: PropTypes.func,
data: PropTypes.shape({
site: PropTypes.object,
}),
}
static childContextTypes = {
setPosts: PropTypes.func,
}
getChildContext = () => ({
setPosts: posts => {
this.posts = posts;
},
})
componentDidMount = () => {
// Create references to html/body elements
this.htmlElement = document.querySelector('html');
this.bodyElement = document.querySelector('body');
// Cache the window width.
this.windowWidth = window.innerWidth;
}
componentWillReceiveProps = nextProps => {
// if we're changing to a non-homepage page, put things in
// a modal (unless we're on mobile).
if (
nextProps.location.pathname !== '/' &&
this.windowWidth > 750
) {
// Freeze the background from scrolling.
this.htmlElement.style.overflow = 'hidden';
this.bodyElement.style.overflow = 'hidden';
// Always set overflow-y to scroll so the scrollbar stays visible avoiding
// weird jumping.
this.htmlElement.style.overflowY = 'scroll';
} else {
// Otherwise we're navigating back home so delete old home so the
// modal can be destroyed.
delete this.modalBackgroundChildren;
this.htmlElement.style.overflow = 'visible';
this.bodyElement.style.overflow = 'visible';
// Always set overflow-y to scroll so the scrollbar stays visible avoiding
// weird jumping.
this.htmlElement.style.overflowY = 'scroll';
}
}
render () {
const { location, data } = this.props;
let isModal = false;
if (
typeof window !== 'undefined' &&
this.props.location.pathname !== '/' &&
this.windowWidth > 750
) {
isModal = true;
}
return (
<div className="u-site">
<Helmet>
<html lang="fr" prefix="og: http://ogp.me/ns#" />
<title>{data.site.siteMetadata.title}</title>
<meta property="og:title" content={data.site.siteMetadata.title} />
<meta property="og:type" content="website" />
<meta property="og:url" content={getLocationHref()} />
<link rel="shortcut icon" type="image/png" href={favicon} />
</Helmet>
<Header />
<main role="main">
<div>
{isModal
? this.props.children({
...this.props,
location: { pathname: '/' },
})
: this.props.children()}
</div>
<div>
{isModal && (
<CustomModal
isOpen
handleClose={() => navigateTo('/')}
>
{this.props.children({ location: { pathname: location.pathname } })}
</CustomModal>
)}
</div>
</main>
<Footer />
<Icons />
</div>
);
}
}
export const query = graphql`
query siteQuery {
site {
siteMetadata {
title
}
}
allMarkdownRemark {
edges {
node {
excerpt(pruneLength: 400)
id
fields {
slug
}
frontmatter {
title
templateKey
picture
}
}
}
}
}
`;
| 26.727273 | 84 | 0.559393 |
7f05c250eb491a42bf847b1c2b9e52d9f45b49d7 | 55,823 | rs | Rust | spinoso-array/src/array/smallvec/mod.rs | b-n/artichoke | af29747df98f72dc6c53f524530ad4ab3bd81182 | [
"MIT"
] | null | null | null | spinoso-array/src/array/smallvec/mod.rs | b-n/artichoke | af29747df98f72dc6c53f524530ad4ab3bd81182 | [
"MIT"
] | 50 | 2022-01-23T10:32:11.000Z | 2022-02-28T08:45:47.000Z | spinoso-array/src/array/smallvec/mod.rs | b-n/artichoke | af29747df98f72dc6c53f524530ad4ab3bd81182 | [
"MIT"
] | null | null | null | //! Ruby `Array` based on [`SmallVec`].
use alloc::boxed::Box;
use alloc::vec::Vec;
use core::cmp;
use core::slice::{Iter, IterMut};
use smallvec::SmallVec;
use crate::array::INLINE_CAPACITY;
mod convert;
mod eq;
mod impls;
mod iter;
/// A contiguous growable array type based on
/// [`SmallVec<[T; INLINE_CAPACITY]>`](SmallVec) that implements the small vector
/// optimization.
///
/// `SmallArray` is an alternate implementation of [`Array`] that implements the
/// small vector optimization. For `SmallArray`s less than [`INLINE_CAPACITY`]
/// elements long, there is no heap allocation.
///
/// `SmallArray` provides a nearly identical API to the one in [`Array`]. There
/// are two important differences:
///
/// 1. `SmallVec<[T; INLINE_CAPACITY]>` is used in some places where
/// [`Vec<T>`](Vec) would have been used.
/// 2. Trait bounds on some methods are more restrictive and require elements to
/// be [`Copy`].
///
/// Similar to `Array`, `SmallArray` implements indexing and mutating APIs that
/// make an ideal backend for the [Ruby `Array` core class][ruby-array]. In
/// practice, this results in less generic, more single-use APIs. For example,
/// instead of [`Vec::drain`], `SmallArray` implements [`shift`], [`shift_n`],
/// [`pop`], and [`pop_n`].
///
/// Similarly, slicing APIs are more specialized, such as [`first_n`] and
/// [`last_n`]. Slicing APIs do not return [`Option`], instead preferring to
/// return an empty slice.
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let mut ary = SmallArray::new();
/// ary.push(1);
/// ary.push(2);
///
/// assert_eq!(ary.len(), 2);
/// assert_eq!(ary[0], 1);
///
/// assert_eq!(ary.pop(), Some(2));
/// assert_eq!(ary.len(), 1);
///
/// ary[0] = 7;
/// assert_eq!(ary[0], 7);
///
/// ary.extend([1, 2, 3].iter().copied());
///
/// for x in &ary {
/// println!("{}", x);
/// }
/// assert_eq!(ary, &[7, 1, 2, 3]);
/// ```
///
/// [`Array`]: crate::Array
/// [ruby-array]: https://ruby-doc.org/core-2.6.3/Array.html
/// [`shift`]: SmallArray::shift
/// [`shift_n`]: SmallArray::shift_n
/// [`drop_n`]: SmallArray::drop_n
/// [`pop`]: SmallArray::pop
/// [`pop_n`]: SmallArray::pop_n
/// [`first_n`]: SmallArray::first_n
/// [`last_n`]: SmallArray::last_n
#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(docsrs, doc(cfg(feature = "small-array")))]
pub struct SmallArray<T>(SmallVec<[T; INLINE_CAPACITY]>);
impl<T> Default for SmallArray<T> {
#[inline]
fn default() -> Self {
Self::new()
}
}
impl<T> SmallArray<T> {
/// Construct a new, empty `SmallArray<T>`.
///
/// The vector will not allocate until more than [`INLINE_CAPACITY`]
/// elements are pushed into it.
///
/// # Examples
///
/// ```
/// use spinoso_array::{INLINE_CAPACITY, SmallArray};
/// let ary: SmallArray<i32> = SmallArray::new();
/// assert!(ary.is_empty());
/// assert_eq!(ary.capacity(), INLINE_CAPACITY);
/// ```
#[inline]
#[must_use]
pub fn new() -> Self {
Self(SmallVec::new())
}
/// Construct a new, empty `SmallArray<T>` with the specified capacity.
///
/// The vector will be able to hold `max(capacity, INLINE_CAPACITY)`
/// elements without reallocating. If `capacity` is less than or equal to
/// [`INLINE_CAPACITY`], the vector will not allocate.
///
/// It is important to note that although the returned vector has the
/// _capacity_ specified, the vector will have a zero _length_.
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let mut ary: SmallArray<i32> = SmallArray::with_capacity(10);
/// assert_eq!(ary.len(), 0);
/// assert_eq!(ary.capacity(), 10);
///
/// // These are pushes all done without reallocating...
/// for i in 0..10 {
/// ary.push(i);
/// }
///
/// // ...but this may make the vector reallocate
/// ary.push(11);
/// ```
#[inline]
#[must_use]
pub fn with_capacity(capacity: usize) -> Self {
Self(SmallVec::with_capacity(capacity))
}
/// Construct a new two-element `SmallArray` from the given arguments.
///
/// The vector is constructed without a heap allocation.
///
/// # Examples
///
/// ```
/// use spinoso_array::{INLINE_CAPACITY, SmallArray};
/// let ary = SmallArray::assoc(0, 100);
/// assert_eq!(ary.capacity(), INLINE_CAPACITY);
/// assert_eq!(ary.len(), 2);
/// assert_eq!(ary[0], 0);
/// assert_eq!(ary[1], 100);
/// ```
#[inline]
#[must_use]
pub fn assoc(first: T, second: T) -> Self {
let pair: [T; 2] = [first, second];
Self::from(pair)
}
/// Returns an iterator over the slice.
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let ary = SmallArray::from(&[1, 2, 4]);
/// let mut iterator = ary.iter();
///
/// assert_eq!(iterator.next(), Some(&1));
/// assert_eq!(iterator.next(), Some(&2));
/// assert_eq!(iterator.next(), Some(&4));
/// assert_eq!(iterator.next(), None);
/// ```
#[inline]
#[must_use]
pub fn iter(&self) -> Iter<'_, T> {
self.into_iter()
}
/// Returns an iterator that allows modifying each value.
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let mut ary = SmallArray::from(&[1, 2, 4]);
/// for elem in ary.iter_mut() {
/// *elem += 2;
/// }
///
/// assert_eq!(ary, &[3, 4, 6]);
/// ```
#[inline]
#[must_use]
pub fn iter_mut(&mut self) -> IterMut<'_, T> {
self.into_iter()
}
/// Extracts a slice containing the entire vector.
///
/// Equivalent to `&ary[..]`.
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let ary = SmallArray::from(&[1, 2, 4]);
/// let four_index = ary.as_slice().binary_search(&4);
/// assert_eq!(four_index, Ok(2));
/// ```
#[inline]
#[must_use]
pub fn as_slice(&self) -> &[T] {
self.0.as_slice()
}
/// Extracts a mutable slice containing the entire vector.
///
/// Equivalent to `&mut ary[..]`.
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let mut ary = SmallArray::from(&[2, 1, 4]);
/// ary.as_mut_slice().sort();
/// assert_eq!(ary, &[1, 2, 4]);
/// ```
#[inline]
#[must_use]
pub fn as_mut_slice(&mut self) -> &mut [T] {
self.0.as_mut_slice()
}
/// Returns a raw pointer to the vector's buffer.
///
/// The caller must ensure that the vector outlives the pointer this
/// function returns, or else it will end up pointing to garbage. Modifying
/// the vector may cause its buffer to be reallocated, which would also make
/// any pointers to it invalid.
///
/// The caller must also ensure that the memory the pointer
/// (non-transitively) points to is never written to (except inside an
/// `UnsafeCell`) using this pointer or any pointer derived from it. If you
/// need to mutate the contents of the slice, use
/// [`as_mut_ptr`](Self::as_mut_ptr).
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let ary = SmallArray::from(&[1, 2, 4]);
/// let ary_ptr = ary.as_ptr();
///
/// unsafe {
/// for i in 0..ary.len() {
/// assert_eq!(*ary_ptr.add(i), 1 << i);
/// }
/// }
/// ```
#[inline]
#[must_use]
pub fn as_ptr(&self) -> *const T {
self.0.as_ptr()
}
/// Returns an unsafe mutable pointer to the vector's buffer.
///
/// The caller must ensure that the vector outlives the pointer this
/// function returns, or else it will end up pointing to garbage.
/// Modifying the vector may cause its buffer to be reallocated, which would
/// also make any pointers to it invalid.
///
/// # Examples
///
/// This method is primarily used when mutating a `Array` via a raw pointer
/// passed over FFI.
///
/// See the [`ARY_PTR`] macro in mruby.
///
/// [`ARY_PTR`]: https://github.com/artichoke/mruby/blob/d66440864d08f1c3ac5820d45f11df031b7d43c6/include/mruby/array.h#L52
#[inline]
#[must_use]
pub fn as_mut_ptr(&mut self) -> *mut T {
self.0.as_mut_ptr()
}
/// Set the vector's length without dropping or moving out elements
///
/// This method is unsafe because it changes the notion of the number of
/// "valid" elements in the vector. Use with care.
///
/// # Safety
///
/// - `new_len` must be less than or equal to capacity().
/// - The elements at `old_len..new_len` must be initialized.
///
/// # Examples
///
/// This method is primarily used when mutating a `Array` via a raw pointer
/// passed over FFI.
///
/// See the [`ARY_PTR`] macro in mruby.
///
/// [`ARY_PTR`]: https://github.com/artichoke/mruby/blob/d66440864d08f1c3ac5820d45f11df031b7d43c6/include/mruby/array.h#L52
#[inline]
pub unsafe fn set_len(&mut self, new_len: usize) {
self.0.set_len(new_len);
}
/// Consume the array and return the inner
/// [`SmallVec<[T; INLINE_CAPACITY]>`](SmallVec).
///
/// # Examples
///
/// ```
/// # use smallvec::SmallVec;
/// use spinoso_array::{INLINE_CAPACITY, SmallArray};
/// let ary = SmallArray::from(&[1, 2, 4]);
/// let vec: SmallVec<[i32; INLINE_CAPACITY]> = ary.into_inner();
/// ```
#[inline]
#[must_use]
pub fn into_inner(self) -> SmallVec<[T; INLINE_CAPACITY]> {
self.0
}
/// Consume the array and return its elements as a [`Vec<T>`].
///
/// For `SmallArray`s with `len() > INLINE_CAPACITY`, this is a cheap
/// operation that unwraps the spilled `Vec` from the `SmallVec`. For
/// shorter arrays, this method will allocate.
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let ary = SmallArray::from(&[1, 2, 4]);
/// let vec: Vec<i32> = ary.into_vec();
/// ```
///
/// [`Vec<T>`]: alloc::vec::Vec
#[inline]
#[must_use]
pub fn into_vec(self) -> Vec<T> {
self.0.into_vec()
}
/// Converts the vector into [`Box<[T]>`](Box).
///
/// This will drop any excess capacity.
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let ary = SmallArray::from(&[1, 2, 4]);
/// let slice: Box<[i32]> = ary.into_boxed_slice();
/// ```
#[inline]
#[must_use]
pub fn into_boxed_slice(self) -> Box<[T]> {
self.0.into_boxed_slice()
}
/// Returns the number of elements the vector can hold without reallocating.
///
/// The minimum capacity of a `SmallArray` is [`INLINE_CAPACITY`].
/// `SmallArray`s with capacity less than or equal to `INLINE_CAPACITY` are
/// not allocated on the heap.
///
/// # Examples
///
/// ```
/// use spinoso_array::{INLINE_CAPACITY, SmallArray};
/// let ary: SmallArray<i32> = SmallArray::with_capacity(1);
/// assert_eq!(ary.capacity(), INLINE_CAPACITY);
///
/// let ary: SmallArray<i32> = SmallArray::with_capacity(10);
/// assert_eq!(ary.capacity(), 10);
/// ```
#[inline]
#[must_use]
pub fn capacity(&self) -> usize {
self.0.capacity()
}
/// Reserves capacity for at least `additional` more elements to be inserted
/// in the given `SmallArray<T>`. The collection may reserve more space to
/// avoid frequent reallocations. After calling reserve, capacity will be
/// greater than or equal to `self.len() + additional`. Does nothing if
/// capacity is already sufficient.
///
/// # Panics
///
/// Panics if the new capacity overflows `usize`.
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let mut ary = SmallArray::from(&[1]);
/// ary.reserve(10);
/// assert!(ary.capacity() >= 11);
/// ```
#[inline]
pub fn reserve(&mut self, additional: usize) {
self.0.reserve(additional);
}
/// Shrinks the capacity of the vector as much as possible.
///
/// It will drop down as close as possible to the length but the allocator
/// may still inform the vector that there is space for a few more elements.
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let mut ary = SmallArray::with_capacity(10);
/// ary.extend([1, 2, 3].iter().copied());
/// assert_eq!(ary.capacity(), 10);
/// ary.shrink_to_fit();
/// assert!(ary.capacity() >= 3);
/// ```
#[inline]
pub fn shrink_to_fit(&mut self) {
self.0.shrink_to_fit();
}
/// Clears the vector, removing all values.
///
/// Note that this method has no effect on the allocated capacity of the
/// vector.
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let mut ary = SmallArray::from(&[1, 2, 4]);
/// let capacity = ary.capacity();
/// ary.clear();
/// assert!(ary.is_empty());
/// assert_eq!(ary.capacity(), capacity);
/// ```
#[inline]
pub fn clear(&mut self) {
self.0.clear();
}
/// Returns the number of elements in the vector, also referred to as its
/// "length".
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let ary = SmallArray::from(&[1, 2, 4]);
/// assert_eq!(ary.len(), 3);
/// ```
#[inline]
#[must_use]
pub fn len(&self) -> usize {
self.0.len()
}
/// Returns `true` if the vector contains no elements.
///
/// # Examples
///
/// ```
/// use spinoso_array::SmallArray;
/// let mut ary = SmallArray::new();
/// assert!(ary.is_empty());
/// ary.push(1);
/// assert!(!ary.is_empty());
/// ```
#[inline]
#[must_use]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Returns a reference to an element at the index.
///
/// Unlike [`Vec`], this method does not support indexing with a range. See
/// the [`slice`](Self::slice) method for retrieving a sub-slice from the
/// array.
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let ary = SmallArray::from(&[1, 2, 4]);
/// assert_eq!(ary.get(1), Some(&2));
/// assert_eq!(ary.get(3), None);
/// ```
#[inline]
#[must_use]
pub fn get(&self, index: usize) -> Option<&T> {
self.0.get(index)
}
/// Deletes the element at the specified `index`, returning that element, or
/// [`None`] if the `index` is out of range.
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let mut ary = SmallArray::from(&[1, 2, 4]);
/// assert_eq!(ary.delete_at(1), Some(2));
/// assert_eq!(ary.delete_at(10), None);
/// ```
#[inline]
#[must_use]
pub fn delete_at(&mut self, index: usize) -> Option<T> {
if index < self.0.len() {
Some(self.0.remove(index))
} else {
None
}
}
/// Returns the first element from the vector, or [`None`] if the vector is
/// empty.
///
/// To retrieve a slice of the first elements in the vector, use
/// [`first_n`](Self::first_n).
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let mut ary = SmallArray::new();
/// assert_eq!(ary.first(), None);
/// ary.push(1);
/// assert_eq!(ary.first(), Some(&1));
/// ary.push(2);
/// assert_eq!(ary.first(), Some(&1));
/// ```
#[inline]
#[must_use]
pub fn first(&self) -> Option<&T> {
self.0.first()
}
/// Returns up to `n` of the first elements from the vector, or `&[]` if the
/// vector is empty.
///
/// To retrieve only the first element in the vector, use
/// [`first`](Self::first).
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let mut ary = SmallArray::new();
/// assert_eq!(ary.first_n(0), &[]);
/// assert_eq!(ary.first_n(4), &[]);
///
/// ary.push(1);
/// ary.push(2);
/// assert_eq!(ary.first_n(0), &[]);
/// assert_eq!(ary.first_n(4), &[1, 2]);
///
/// ary.concat(&[3, 4, 5, 6, 7, 8, 9, 10]);
/// assert_eq!(ary.first_n(0), &[]);
/// assert_eq!(ary.first_n(4), &[1, 2, 3, 4]);
/// ```
#[inline]
#[must_use]
pub fn first_n(&self, n: usize) -> &[T] {
self.0.get(..n).unwrap_or_else(|| &self.0[..])
}
/// Returns the last element from the vector, or [`None`] if the vector is
/// empty.
///
/// To retrieve a slice of the last elements in the vector, use
/// [`last_n`](Self::last_n).
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let mut ary = SmallArray::new();
/// assert_eq!(ary.last(), None);
/// ary.push(1);
/// assert_eq!(ary.last(), Some(&1));
/// ary.push(2);
/// assert_eq!(ary.last(), Some(&2));
/// ```
#[inline]
#[must_use]
pub fn last(&self) -> Option<&T> {
self.0.last()
}
/// Returns up to `n` of the last elements from the vector, or `&[]` if the
/// vector is empty.
///
/// To retrieve only the last element in the vector, use
/// [`last`](Self::last).
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let mut ary = SmallArray::new();
/// assert_eq!(ary.last_n(0), &[]);
/// assert_eq!(ary.last_n(4), &[]);
///
/// ary.push(1);
/// ary.push(2);
/// assert_eq!(ary.last_n(0), &[]);
/// assert_eq!(ary.last_n(4), &[1, 2]);
///
/// ary.concat(&[3, 4, 5, 6, 7, 8, 9, 10]);
/// assert_eq!(ary.last_n(0), &[]);
/// assert_eq!(ary.last_n(4), &[7, 8, 9, 10]);
/// ```
#[inline]
#[must_use]
pub fn last_n(&self, n: usize) -> &[T] {
let begin = self.len().checked_sub(n).unwrap_or_default();
&self.0[begin..]
}
/// Returns a slice of the underlying vector that includes only the first
/// `n` elements.
///
/// If `n` is greater than or equal to the length of the vector, `&self[..]`
/// is returned.
///
/// The inverse of this operation is [`drop_n`](Self::drop_n).
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let ary = SmallArray::from(&[1, 2, 4, 7, 8, 9]);
/// assert_eq!(ary.take_n(0), &[]);
/// assert_eq!(ary.take_n(2), &[1, 2]);
/// assert_eq!(ary.take_n(10), &[1, 2, 4, 7, 8, 9]);
/// ```
#[inline]
#[must_use]
pub fn take_n(&self, n: usize) -> &[T] {
self.0.get(..n).unwrap_or_else(|| &self.0[..])
}
/// Returns a slice of the underlying vector that excludes the first `n`
/// elements.
///
/// If `n` is greater than or equal to the length of the vector, `&[]` is
/// returned.
///
/// The inverse of this operation is [`take_n`](Self::take_n).
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let ary = SmallArray::from(&[1, 2, 4, 7, 8, 9]);
/// assert_eq!(ary.drop_n(0), &[1, 2, 4, 7, 8, 9]);
/// assert_eq!(ary.drop_n(4), &[8, 9]);
/// assert_eq!(ary.drop_n(10), &[]);
/// ```
#[inline]
#[must_use]
pub fn drop_n(&self, n: usize) -> &[T] {
self.0.get(n..).unwrap_or_default()
}
/// Removes the last element from the vector and returns it, or [`None`] if
/// the vector is empty.
///
/// To pop more than one element from the end of the vector, use
/// [`pop_n`](Self::pop_n).
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let mut ary = SmallArray::from(&[1, 2, 4]);
/// assert_eq!(ary.pop(), Some(4));
/// assert_eq!(ary, &[1, 2]);
/// ```
#[inline]
#[must_use]
pub fn pop(&mut self) -> Option<T> {
self.0.pop()
}
/// Removes the last `n` elements from the vector.
///
/// To pop a single element from the end of the vector, use
/// [`pop`](Self::pop).
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let mut ary = SmallArray::from(&[1, 2, 4, 7, 8, 9]);
/// assert_eq!(ary.pop_n(0), &[]);
/// assert_eq!(ary, &[1, 2, 4, 7, 8, 9]);
///
/// assert_eq!(ary.pop_n(3), &[7, 8, 9]);
/// assert_eq!(ary, &[1, 2, 4]);
///
/// assert_eq!(ary.pop_n(100), &[1, 2, 4]);
/// assert!(ary.is_empty());
///
/// assert_eq!(ary.pop_n(1), &[]);
/// assert!(ary.is_empty());
/// ```
#[inline]
#[must_use]
pub fn pop_n(&mut self, n: usize) -> Self {
if n == 0 {
return Self::new();
}
let begin = self.len().checked_sub(n).unwrap_or_default();
self.0.drain(begin..).collect()
}
/// Appends an element to the back of the vector.
///
/// To push more than one element to the end of the vector, use
/// [`concat`](Self::concat) or `extend`.
///
/// # Panics
///
/// Panics if the number of elements in the vector overflows a `usize`.
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let mut ary = SmallArray::from(&[1, 2]);
/// ary.push(3);
/// assert_eq!(ary, &[1, 2, 3]);
/// ```
#[inline]
pub fn push(&mut self, elem: T) {
self.0.push(elem);
}
/// Reverses the order of elements of the vector, in place.
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let mut ary = SmallArray::from(&[1, 2, 4]);
/// ary.reverse();
/// assert_eq!(ary, &[4, 2, 1]);
/// ```
#[inline]
pub fn reverse(&mut self) {
self.0.reverse();
}
/// Removes the first element of the vector and returns it (shifting all
/// other elements down by one). Returns [`None`] if the vector is empty.
///
/// This operation is also known as "pop front".
///
/// To remove more than one element from the front of the vector, use
/// [`shift_n`](Self::shift_n).
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let mut ary = SmallArray::from(&[1, 2]);
/// assert_eq!(ary.shift(), Some(1));
/// assert_eq!(ary.shift(), Some(2));
/// assert_eq!(ary.shift(), None);
/// ```
#[inline]
#[must_use]
pub fn shift(&mut self) -> Option<T> {
if self.is_empty() {
None
} else {
Some(self.0.remove(0))
}
}
/// Removes the first `n` elements from the vector.
///
/// To shift a single element from the front of the vector, use
/// [`shift`](Self::shift).
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let mut ary = SmallArray::from(&[1, 2, 4, 7, 8, 9]);
/// assert_eq!(ary.shift_n(0), &[]);
/// assert_eq!(ary, &[1, 2, 4, 7, 8, 9]);
///
/// assert_eq!(ary.shift_n(3), &[1, 2, 4]);
/// assert_eq!(ary, &[7, 8, 9]);
///
/// assert_eq!(ary.shift_n(100), &[7, 8, 9]);
/// assert!(ary.is_empty());
///
/// assert_eq!(ary.shift_n(1), &[]);
/// assert!(ary.is_empty());
/// ```
#[inline]
#[must_use]
pub fn shift_n(&mut self, n: usize) -> Self {
match n {
0 => Self::new(),
n if n < self.0.len() => self.0.drain(..n).collect(),
_ => self.0.drain(..).collect(),
}
}
/// Inserts an element to the front of the vector.
///
/// To insert more than one element to the front of the vector, use
/// [`unshift_n`](Self::unshift_n).
///
/// This operation is also known as "prepend".
///
/// # Panics
///
/// Panics if the number of elements in the vector overflows a `usize`.
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let mut ary = SmallArray::from(&[1, 2]);
/// ary.unshift(3);
/// assert_eq!(ary, &[3, 1, 2]);
/// ```
#[inline]
pub fn unshift(&mut self, elem: T) {
self.0.insert(0, elem);
}
/// Return a reference to a subslice of the vector.
///
/// This function always returns a slice. If the range specified by `start`
/// and `end` overlaps the vector (even if only partially), the overlapping
/// slice is returned. If the range does not overlap the vector, an empty
/// slice is returned.
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let empty: SmallArray<i32> = SmallArray::new();
/// assert_eq!(empty.slice(0, 0), &[]);
/// assert_eq!(empty.slice(0, 4), &[]);
/// assert_eq!(empty.slice(2, 4), &[]);
///
/// let ary = SmallArray::from(&[1, 2, 3]);
/// assert_eq!(ary.slice(0, 0), &[]);
/// assert_eq!(ary.slice(0, 4), &[1, 2, 3]);
/// assert_eq!(ary.slice(2, 0), &[]);
/// assert_eq!(ary.slice(2, 4), &[3]);
/// assert_eq!(ary.slice(10, 100), &[]);
/// ```
#[inline]
#[must_use]
pub fn slice(&self, start: usize, len: usize) -> &[T] {
if self.0.is_empty() || len == 0 {
return &[];
}
if let Some(end) = start.checked_add(len) {
self.0
.get(start..end)
.or_else(|| self.0.get(start..))
.unwrap_or_default()
} else {
self.0.get(start..).unwrap_or_default()
}
}
}
impl<T> SmallArray<T>
where
T: Copy,
{
/// Construct a new `SmallArray<T>` with length `len` and all elements set
/// to `default`. The `SmallArray` will have capacity at least `len`.
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let ary: SmallArray<&str> = SmallArray::with_len_and_default(3, "spinoso");
/// assert_eq!(ary.len(), 3);
/// assert!(ary.capacity() >= 3);
/// assert_eq!(ary, &["spinoso", "spinoso", "spinoso"]);
/// ```
#[inline]
#[must_use]
pub fn with_len_and_default(len: usize, default: T) -> Self {
Self(SmallVec::from_elem(default, len))
}
/// Appends the elements of `other` to self.
///
/// Slice version of `extend`. This operation is analogous to "push n".
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let mut ary = SmallArray::from(&[1, 2, 4]);
/// ary.concat(&[7, 8, 9]);
/// assert_eq!(ary.len(), 6);
/// ```
#[inline]
pub fn concat(&mut self, other: &[T]) {
self.0.extend_from_slice(other);
}
/// Creates a new array by repeating this array `n` times.
///
/// This function will not panic. If the resulting `Array`'s capacity would
/// overflow, [`None`] is returned.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use spinoso_array::SmallArray;
/// # fn example() -> Option<()> {
/// let mut ary = SmallArray::from(&[1, 2]);
/// let repeated_ary = ary.repeat(3)?;
/// assert_eq!(repeated_ary, &[1, 2, 1, 2, 1, 2]);
/// # Some(())
/// # }
/// # example().unwrap();
/// ```
///
/// [`None`] should be returned on overflow:
///
/// ```
/// # use spinoso_array::SmallArray;
/// let mut ary = SmallArray::from(&[1, 2]);
/// let repeated_ary = ary.repeat(usize::MAX);
/// assert_eq!(repeated_ary, None);
/// ```
#[must_use]
pub fn repeat(&self, n: usize) -> Option<Self> {
let slice = self.0.as_slice();
if slice.len().checked_mul(n).is_some() {
Some(Self::from(slice.repeat(n)))
} else {
None
}
}
/// Prepends the elements of `other` to self.
///
/// To insert one element to the front of the vector, use
/// [`unshift`](Self::unshift).
///
/// This operation is also known as "prepend".
///
/// # Panics
///
/// Panics if the number of elements in the vector overflows a `usize`.
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let mut ary = SmallArray::from(&[1, 2]);
/// ary.unshift_n(&[0, 5, 9]);
/// assert_eq!(ary, &[0, 5, 9, 1, 2]);
/// ```
#[inline]
pub fn unshift_n(&mut self, other: &[T]) {
self.0.reserve(other.len());
self.0.insert_from_slice(0, other);
}
}
impl<T> SmallArray<T>
where
T: Default,
{
/// Set element at position `index` within the vector, extending the vector
/// with `T::default()` if `index` is out of bounds.
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let mut ary = SmallArray::from(&[1, 2 ,4]);
/// ary.set(1, 11);
/// assert_eq!(ary, &[1, 11, 4]);
/// ary.set(5, 263);
/// assert_eq!(ary, &[1, 11, 4, 0, 0, 263]);
///
/// let mut ary: SmallArray<i32> = SmallArray::from(&[]);
/// ary.set(5, 11);
/// assert_eq!(ary, &[0, 0, 0, 0, 0, 11]);
/// ```
#[inline]
pub fn set(&mut self, index: usize, elem: T) {
if let Some(cell) = self.0.get_mut(index) {
*cell = elem;
} else {
let buflen = self.len();
// index is *at least* `buflen`, so this calculation never underflows
// and ensures we allocate an additional slot.
let additional = (index - buflen).checked_add(1).expect("capacity overflow");
self.0.reserve(additional);
self.0.resize_with(index, T::default);
self.0.push(elem);
}
}
/// Insert element at position `start` within the vector and remove the
/// following `drain` elements. If `start` is out of bounds, the vector will
/// be extended with `T::default()`.
///
/// This method sets a slice of the `SmallArray` to a single element,
/// including the zero-length slice. It is similar in intent to calling
/// [`Vec::splice`] with a one-element iterator.
///
/// `set_with_drain` will only drain up to the end of the vector.
///
/// To set a single element without draining, use [`set`](Self::set).
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let mut ary = SmallArray::from(&[1, 2, 4]);
/// ary.set_with_drain(1, 0, 10);
/// assert_eq!(ary, &[1, 10, 2, 4]);
/// ary.set_with_drain(2, 5, 20);
/// assert_eq!(ary, &[1, 10, 20]);
/// ary.set_with_drain(5, 5, 30);
/// assert_eq!(ary, &[1, 10, 20, 0, 0, 30]);
/// ```
#[inline]
pub fn set_with_drain(&mut self, start: usize, drain: usize, elem: T) -> usize {
let buflen = self.0.len();
let drained = cmp::min(buflen.checked_sub(start).unwrap_or_default(), drain);
if let Some(cell) = self.0.get_mut(start) {
match drain {
0 => self.0.insert(start, elem),
1 => *cell = elem,
_ => {
*cell = elem;
let drain_end_idx = cmp::min(start.saturating_add(drain), buflen);
self.0.drain(start.saturating_add(1)..drain_end_idx);
}
}
} else {
// start is *at least* `buflen`, so this calculation never underflows
// and ensures we allocate an additional slot.
let additional = (start - buflen).checked_add(1).expect("capacity overflow");
self.0.reserve(additional);
self.0.resize_with(start, T::default);
self.0.push(elem);
}
drained
}
}
impl<T> SmallArray<T>
where
T: Default + Copy,
{
/// Insert the elements from a slice at a position `index` in the vector,
/// extending the vector with `T::default()` if `index` is out of bounds.
///
/// This method is similar to [`Vec::splice`] when called with a zero-length
/// range.
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let mut ary = SmallArray::from(&[1, 2, 4]);
/// ary.insert_slice(1, &[7, 8, 9]);
/// assert_eq!(ary, &[1, 7, 8, 9, 2, 4]);
/// ary.insert_slice(8, &[100, 200]);
/// assert_eq!(ary, &[1, 7, 8, 9, 2, 4, 0, 0, 100, 200]);
/// ```
#[inline]
pub fn insert_slice(&mut self, index: usize, values: &[T]) {
if let Some(overflow) = index.checked_sub(self.0.len()) {
let additional = overflow.checked_add(values.len()).expect("capacity overflow");
self.0.reserve(additional);
self.0.resize_with(index, T::default);
} else {
self.0.reserve(values.len());
}
self.0.insert_from_slice(index, values);
}
/// Insert the elements from a slice at a position `index` in the vector and
/// remove the following `drain` elements. The vector is extended with
/// `T::default()` if `index` is out of bounds.
///
/// This method is similar to [`Vec::splice`] when called with a
/// nonzero-length range.
///
/// When called with `drain == 0`, this method is equivalent to
/// [`insert_slice`](Self::insert_slice).
///
/// If `drain >= src.len()` or the tail of the vector is replaced, this
/// method is efficient. Otherwise, a temporary buffer is used to move the
/// elements.
///
/// # Examples
///
/// ```
/// # use spinoso_array::SmallArray;
/// let mut ary = SmallArray::from(&[1, 2, 4]);
/// ary.set_slice(1, 5, &[7, 8, 9]);
/// assert_eq!(ary, &[1, 7, 8, 9]);
/// ary.set_slice(6, 1, &[100, 200]);
/// assert_eq!(ary, &[1, 7, 8, 9, 0, 0, 100, 200]);
/// ary.set_slice(4, 2, &[88, 99]);
/// assert_eq!(ary, &[1, 7, 8, 9, 88, 99, 100, 200]);
/// ary.set_slice(6, 2, &[1000, 2000, 3000, 4000]);
/// assert_eq!(ary, &[1, 7, 8, 9, 88, 99, 1000, 2000, 3000, 4000]);
/// ```
#[inline]
pub fn set_slice(&mut self, index: usize, drain: usize, values: &[T]) -> usize {
if let Some(overflow) = index.checked_sub(self.0.len()) {
let additional = overflow.saturating_add(values.len());
self.0.reserve(additional);
self.0.resize_with(index, T::default);
}
// `self.len()` is at least `index` so the below sub can never overflow.
let tail = self.len() - index;
// This is a direct append to the end of the vector, either because the
// given `index` was the vector's length or because we have extended the
// vector from an out of bounds index.
if tail == 0 {
self.0.extend_from_slice(values);
return 0;
}
// If the tail of the vector is shorter than or as long as the number of
// elements to drain, we can truncate and extend the underlying vector.
// `truncate` does not affect the existing capacity of the vector.
if tail <= drain {
self.0.truncate(index);
self.0.extend_from_slice(values);
return tail;
}
// Short circuit to a direct insert if `drain == 0`.
if drain == 0 {
self.0.insert_from_slice(index, values);
return 0;
}
// At this point, `index + drain` is guaranteed to be a valid index
// within the vector. There are two cases:
//
// - If `values.len() == drain`, we can drain elements by overwriting
// them in the vector.
// - If `values.len() >= drain`, we can drain elements by overwriting
// them in the vector and inserting the remainder.
// - Otherwise, overwrite `values` into the vector and remove the
// remaining elements we must drain.
match values.len() {
0 => {
self.0.drain(index..index + drain);
}
len if len == drain => {
let slice = &mut self.0[index..index + drain];
slice.copy_from_slice(values);
}
len if len > drain => {
let slice = &mut self.0[index..index + drain];
let (overwrite, insert) = values.split_at(drain);
slice.copy_from_slice(overwrite);
self.0.insert_from_slice(index + drain, insert);
}
len => {
let slice = &mut self.0[index..index + len];
slice.copy_from_slice(values);
// Drain the remaining elements.
self.0.drain(index + len..index + drain);
}
}
drain
}
}
#[cfg(test)]
mod test {
use crate::array::smallvec::SmallArray;
// `insert_slice`
#[test]
fn non_empty_array_insert_slice_end_empty() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
ary.insert_slice(5, &[]);
assert_eq!(ary, [1, 2, 3, 4, 5]);
}
#[test]
fn non_empty_array_insert_slice_out_of_bounds_empty() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
ary.insert_slice(10, &[]);
assert_eq!(ary, [1, 2, 3, 4, 5, 0, 0, 0, 0, 0]);
}
#[test]
fn non_empty_array_insert_slice_interior_empty() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
ary.insert_slice(2, &[]);
assert_eq!(ary, [1, 2, 3, 4, 5]);
}
#[test]
fn non_empty_array_insert_slice_begin_empty() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
ary.insert_slice(0, &[]);
assert_eq!(ary, [1, 2, 3, 4, 5]);
}
#[test]
fn empty_array_insert_slice_end_empty() {
let mut ary = SmallArray::<i32>::new();
ary.insert_slice(0, &[]);
assert_eq!(ary, []);
}
#[test]
fn empty_array_insert_slice_out_of_bounds_empty() {
let mut ary = SmallArray::<i32>::new();
ary.insert_slice(10, &[]);
assert_eq!(ary, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
}
#[test]
fn empty_array_insert_slice_begin_empty() {
let mut ary = SmallArray::<i32>::new();
ary.insert_slice(0, &[]);
assert_eq!(ary, []);
}
#[test]
fn non_empty_array_insert_slice_end() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
ary.insert_slice(5, &[8, 9, 10]);
assert_eq!(ary, [1, 2, 3, 4, 5, 8, 9, 10]);
}
#[test]
fn non_empty_array_insert_slice_out_of_bounds() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
ary.insert_slice(10, &[8, 9, 10]);
assert_eq!(ary, [1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 8, 9, 10]);
}
#[test]
fn non_empty_array_insert_slice_interior() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
ary.insert_slice(2, &[8, 9, 10]);
assert_eq!(ary, [1, 2, 8, 9, 10, 3, 4, 5]);
}
#[test]
fn non_empty_array_insert_slice_begin() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
ary.insert_slice(0, &[8, 9, 10]);
assert_eq!(ary, [8, 9, 10, 1, 2, 3, 4, 5]);
}
#[test]
fn empty_array_insert_slice_end() {
let mut ary = SmallArray::<i32>::new();
ary.insert_slice(0, &[8, 9, 10]);
assert_eq!(ary, [8, 9, 10]);
}
#[test]
fn empty_array_insert_slice_out_of_bounds() {
let mut ary = SmallArray::<i32>::new();
ary.insert_slice(10, &[8, 9, 10]);
assert_eq!(ary, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 9, 10]);
}
#[test]
fn empty_array_insert_slice_begin() {
let mut ary = SmallArray::<i32>::new();
ary.insert_slice(0, &[8, 9, 10]);
assert_eq!(ary, [8, 9, 10]);
}
// `set_slice`
#[test]
fn non_empty_array_set_slice_end_empty_drain_0() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
let drained = ary.set_slice(5, 0, &[]);
assert_eq!(drained, 0);
assert_eq!(ary, [1, 2, 3, 4, 5]);
}
#[test]
fn non_empty_array_set_slice_end_empty_drain_less_than_insert_length() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
let drained = ary.set_slice(5, 0, &[]);
assert_eq!(drained, 0);
assert_eq!(ary, [1, 2, 3, 4, 5]);
}
#[test]
fn non_empty_array_set_slice_end_empty_drain_equal_to_insert_length() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
let drained = ary.set_slice(5, 0, &[]);
assert_eq!(drained, 0);
assert_eq!(ary, [1, 2, 3, 4, 5]);
}
#[test]
fn non_empty_array_set_slice_end_empty_drain_greater_than_insert_length() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
let drained = ary.set_slice(5, 5, &[]);
assert_eq!(drained, 0);
assert_eq!(ary, [1, 2, 3, 4, 5]);
}
#[test]
fn non_empty_array_set_slice_out_of_bounds_empty_drain_0() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
let drained = ary.set_slice(10, 0, &[]);
assert_eq!(drained, 0);
assert_eq!(ary, [1, 2, 3, 4, 5, 0, 0, 0, 0, 0]);
}
#[test]
fn non_empty_array_set_slice_out_of_bounds_empty_drain_less_than_insert_length() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
let drained = ary.set_slice(10, 0, &[]);
assert_eq!(drained, 0);
assert_eq!(ary, [1, 2, 3, 4, 5, 0, 0, 0, 0, 0]);
}
#[test]
fn non_empty_array_set_slice_out_of_bounds_empty_drain_equal_to_insert_length() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
let drained = ary.set_slice(10, 0, &[]);
assert_eq!(drained, 0);
assert_eq!(ary, [1, 2, 3, 4, 5, 0, 0, 0, 0, 0]);
}
#[test]
fn non_empty_array_set_slice_out_of_bounds_empty_drain_greater_than_insert_length() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
let drained = ary.set_slice(10, 0, &[]);
assert_eq!(drained, 0);
assert_eq!(ary, [1, 2, 3, 4, 5, 0, 0, 0, 0, 0]);
}
#[test]
fn non_empty_array_set_slice_interior_empty_drain_0() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
let drained = ary.set_slice(1, 0, &[]);
assert_eq!(drained, 0);
assert_eq!(ary, [1, 2, 3, 4, 5]);
}
#[test]
fn non_empty_array_set_slice_interior_empty_drain_less_than_insert_length() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
let drained = ary.set_slice(1, 0, &[]);
assert_eq!(drained, 0);
assert_eq!(ary, [1, 2, 3, 4, 5]);
}
#[test]
fn non_empty_array_set_slice_interior_empty_drain_equal_to_insert_length() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
let drained = ary.set_slice(1, 0, &[]);
assert_eq!(drained, 0);
assert_eq!(ary, [1, 2, 3, 4, 5]);
}
#[test]
fn non_empty_array_set_slice_interior_empty_drain_greater_than_insert_length() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
let drained = ary.set_slice(1, 2, &[]);
assert_eq!(drained, 2);
assert_eq!(ary, [1, 4, 5]);
}
#[test]
fn non_empty_array_set_slice_interior_empty_drain_greater_than_insert_length_to_end() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
let drained = ary.set_slice(1, 4, &[]);
assert_eq!(drained, 4);
assert_eq!(ary, [1]);
}
#[test]
fn non_empty_array_set_slice_interior_empty_drain_greater_than_insert_length_overrun_end() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
let drained = ary.set_slice(1, 10, &[]);
assert_eq!(drained, 4);
assert_eq!(ary, [1]);
}
#[test]
fn non_empty_array_set_slice_end_non_empty_drain_0() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
let drained = ary.set_slice(5, 0, &[7, 8, 9]);
assert_eq!(drained, 0);
assert_eq!(ary, [1, 2, 3, 4, 5, 7, 8, 9]);
}
#[test]
fn non_empty_array_set_slice_end_non_empty_drain_less_than_insert_length() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
let drained = ary.set_slice(5, 2, &[7, 8, 9]);
assert_eq!(drained, 0);
assert_eq!(ary, [1, 2, 3, 4, 5, 7, 8, 9]);
}
#[test]
fn non_empty_array_set_slice_end_non_empty_drain_equal_to_insert_length() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
let drained = ary.set_slice(5, 3, &[7, 8, 9]);
assert_eq!(drained, 0);
assert_eq!(ary, [1, 2, 3, 4, 5, 7, 8, 9]);
}
#[test]
fn non_empty_array_set_slice_end_non_empty_drain_greater_than_insert_length() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
let drained = ary.set_slice(5, 5, &[7, 8, 9]);
assert_eq!(drained, 0);
assert_eq!(ary, [1, 2, 3, 4, 5, 7, 8, 9]);
}
#[test]
fn non_empty_array_set_slice_out_of_bounds_non_empty_drain_0() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
let drained = ary.set_slice(10, 0, &[7, 8, 9]);
assert_eq!(drained, 0);
assert_eq!(ary, [1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 7, 8, 9]);
}
#[test]
fn non_empty_array_set_slice_out_of_bounds_non_empty_drain_less_than_insert_length() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
let drained = ary.set_slice(10, 2, &[7, 8, 9]);
assert_eq!(drained, 0);
assert_eq!(ary, [1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 7, 8, 9]);
}
#[test]
fn non_empty_array_set_slice_out_of_bounds_non_empty_drain_equal_to_insert_length() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
let drained = ary.set_slice(10, 3, &[7, 8, 9]);
assert_eq!(drained, 0);
assert_eq!(ary, [1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 7, 8, 9]);
}
#[test]
fn non_empty_array_set_slice_out_of_bounds_non_empty_drain_greater_than_insert_length() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
let drained = ary.set_slice(10, 5, &[7, 8, 9]);
assert_eq!(drained, 0);
assert_eq!(ary, [1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 7, 8, 9]);
}
#[test]
fn non_empty_array_set_slice_interior_non_empty_drain_0() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
let drained = ary.set_slice(1, 0, &[7, 8, 9]);
assert_eq!(drained, 0);
assert_eq!(ary, [1, 7, 8, 9, 2, 3, 4, 5]);
}
#[test]
fn non_empty_array_set_slice_interior_non_empty_drain_less_than_insert_length() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
let drained = ary.set_slice(1, 2, &[7, 8, 9]);
assert_eq!(drained, 2);
assert_eq!(ary, [1, 7, 8, 9, 4, 5]);
}
#[test]
fn non_empty_array_set_slice_interior_non_empty_drain_equal_to_insert_length() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
let drained = ary.set_slice(1, 3, &[7, 8, 9]);
assert_eq!(drained, 3);
assert_eq!(ary, [1, 7, 8, 9, 5]);
}
#[test]
fn non_empty_array_set_slice_interior_non_empty_drain_greater_than_insert_length() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5, 6]);
let drained = ary.set_slice(1, 4, &[7, 8, 9]);
assert_eq!(drained, 4);
assert_eq!(ary, [1, 7, 8, 9, 6]);
assert_eq!(ary.len(), 5);
}
#[test]
fn non_empty_array_set_slice_interior_non_empty_drain_equal_to_insert_length_to_tail() {
let mut ary = SmallArray::from([1, 2, 3, 4]);
let drained = ary.set_slice(1, 3, &[7, 8, 9]);
assert_eq!(drained, 3);
assert_eq!(ary, [1, 7, 8, 9]);
}
#[test]
fn non_empty_array_set_slice_interior_non_empty_drain_greater_than_insert_length_to_tail() {
let mut ary = SmallArray::from([1, 2, 3, 4]);
let drained = ary.set_slice(1, 10, &[7, 8, 9]);
assert_eq!(drained, 3);
assert_eq!(ary, [1, 7, 8, 9]);
}
#[test]
fn non_empty_array_set_slice_interior_non_empty_drain_less_than_insert_length_overrun_tail() {
let mut ary = SmallArray::from([1, 2, 3, 4]);
let drained = ary.set_slice(3, 2, &[7, 8, 9]);
assert_eq!(drained, 1);
assert_eq!(ary, [1, 2, 3, 7, 8, 9]);
}
#[test]
fn non_empty_array_set_slice_interior_non_empty_drain_equal_to_insert_length_overrun_tail() {
let mut ary = SmallArray::from([1, 2, 3, 4]);
let drained = ary.set_slice(3, 3, &[7, 8, 9]);
assert_eq!(drained, 1);
assert_eq!(ary, [1, 2, 3, 7, 8, 9]);
}
#[test]
fn non_empty_array_set_slice_interior_non_empty_drain_greater_than_insert_length_overrun_tail() {
let mut ary = SmallArray::from([1, 2, 3, 4]);
let drained = ary.set_slice(3, 10, &[7, 8, 9]);
assert_eq!(drained, 1);
assert_eq!(ary, [1, 2, 3, 7, 8, 9]);
}
#[test]
fn non_empty_array_set_slice_begin_non_empty_drain_0() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
let drained = ary.set_slice(0, 0, &[7, 8, 9]);
assert_eq!(drained, 0);
assert_eq!(ary, [7, 8, 9, 1, 2, 3, 4, 5]);
}
#[test]
fn non_empty_array_set_slice_begin_non_empty_drain_less_than_insert_length() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
let drained = ary.set_slice(0, 2, &[7, 8, 9]);
assert_eq!(drained, 2);
assert_eq!(ary, [7, 8, 9, 3, 4, 5]);
}
#[test]
fn non_empty_array_set_slice_begin_non_empty_drain_equal_to_insert_length() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5]);
let drained = ary.set_slice(0, 3, &[7, 8, 9]);
assert_eq!(drained, 3);
assert_eq!(ary, [7, 8, 9, 4, 5]);
}
#[test]
fn non_empty_array_set_slice_begin_non_empty_drain_greater_than_insert_length() {
let mut ary = SmallArray::from([1, 2, 3, 4, 5, 6]);
let drained = ary.set_slice(0, 4, &[7, 8, 9]);
assert_eq!(drained, 4);
assert_eq!(ary, [7, 8, 9, 5, 6]);
}
#[test]
fn non_empty_array_set_slice_begin_non_empty_drain_equal_to_insert_length_to_tail() {
let mut ary = SmallArray::from([1, 2, 3, 4]);
let drained = ary.set_slice(0, 4, &[7, 8, 9, 10]);
assert_eq!(drained, 4);
assert_eq!(ary, [7, 8, 9, 10]);
}
#[test]
fn non_empty_array_set_slice_begin_non_empty_drain_greater_than_insert_length_to_tail() {
let mut ary = SmallArray::from([1, 2, 3, 4]);
let drained = ary.set_slice(0, 10, &[7, 8, 9, 10]);
assert_eq!(drained, 4);
assert_eq!(ary, [7, 8, 9, 10]);
}
#[test]
fn non_empty_array_set_slice_begin_non_empty_drain_less_than_insert_length_overrun_tail() {
let mut ary = SmallArray::from([1, 2, 3, 4]);
let drained = ary.set_slice(0, 4, &[7, 8, 9, 10, 11]);
assert_eq!(drained, 4);
assert_eq!(ary, [7, 8, 9, 10, 11]);
}
#[test]
fn non_empty_array_set_slice_begin_non_empty_drain_equal_to_insert_length_overrun_tail() {
let mut ary = SmallArray::from([1, 2, 3, 4]);
let drained = ary.set_slice(0, 5, &[7, 8, 9, 10, 11]);
assert_eq!(drained, 4);
assert_eq!(ary, [7, 8, 9, 10, 11]);
}
#[test]
fn non_empty_array_set_slice_begin_non_empty_drain_greater_than_insert_length_overrun_tail() {
let mut ary = SmallArray::from([1, 2, 3, 4]);
let drained = ary.set_slice(0, 10, &[7, 8, 9, 10, 11]);
assert_eq!(drained, 4);
assert_eq!(ary, [7, 8, 9, 10, 11]);
}
#[test]
fn empty_array_set_slice_non_empty_drain_0() {
let mut ary = SmallArray::<i32>::new();
let drained = ary.set_slice(0, 0, &[7, 8, 9]);
assert_eq!(drained, 0);
assert_eq!(ary, [7, 8, 9]);
}
#[test]
fn empty_array_set_slice_non_empty_drain_less_than_insert_length() {
let mut ary = SmallArray::<i32>::new();
let drained = ary.set_slice(0, 1, &[7, 8, 9]);
assert_eq!(drained, 0);
assert_eq!(ary, [7, 8, 9]);
}
#[test]
fn empty_array_set_slice_non_empty_drain_equal_to_insert_length() {
let mut ary = SmallArray::<i32>::new();
let drained = ary.set_slice(0, 3, &[7, 8, 9]);
assert_eq!(drained, 0);
assert_eq!(ary, [7, 8, 9]);
}
#[test]
fn empty_array_set_slice_begin_non_empty_drain_greater_than_insert_length() {
let mut ary = SmallArray::<i32>::new();
let drained = ary.set_slice(0, 10, &[7, 8, 9]);
assert_eq!(drained, 0);
assert_eq!(ary, [7, 8, 9]);
}
#[test]
fn empty_array_set_slice_out_of_bounds_non_empty_drain_0() {
let mut ary = SmallArray::<i32>::new();
let drained = ary.set_slice(5, 0, &[7, 8, 9]);
assert_eq!(drained, 0);
assert_eq!(ary, [0, 0, 0, 0, 0, 7, 8, 9]);
}
#[test]
fn empty_array_set_slice_out_of_bounds_non_empty_drain_less_than_insert_length() {
let mut ary = SmallArray::<i32>::new();
let drained = ary.set_slice(5, 1, &[7, 8, 9]);
assert_eq!(drained, 0);
assert_eq!(ary, [0, 0, 0, 0, 0, 7, 8, 9]);
}
#[test]
fn empty_array_set_slice_out_of_bounds_non_empty_drain_equal_to_insert_length() {
let mut ary = SmallArray::<i32>::new();
let drained = ary.set_slice(5, 3, &[7, 8, 9]);
assert_eq!(drained, 0);
assert_eq!(ary, [0, 0, 0, 0, 0, 7, 8, 9]);
}
#[test]
fn empty_array_set_slice_out_of_bounds_non_empty_drain_greater_than_insert_length() {
let mut ary = SmallArray::<i32>::new();
let drained = ary.set_slice(5, 10, &[7, 8, 9]);
assert_eq!(drained, 0);
assert_eq!(ary, [0, 0, 0, 0, 0, 7, 8, 9]);
}
#[test]
fn empty_array_set_slice_empty_drain_0() {
let mut ary = SmallArray::<i32>::new();
let drained = ary.set_slice(0, 0, &[]);
assert_eq!(drained, 0);
assert_eq!(ary, []);
}
#[test]
fn empty_array_set_slice_empty_drain_less_than_insert_length() {
let mut ary = SmallArray::<i32>::new();
let drained = ary.set_slice(0, 0, &[]);
assert_eq!(drained, 0);
assert_eq!(ary, []);
}
#[test]
fn empty_array_set_slice_empty_drain_equal_to_insert_length() {
let mut ary = SmallArray::<i32>::new();
let drained = ary.set_slice(0, 0, &[]);
assert_eq!(drained, 0);
assert_eq!(ary, []);
}
#[test]
fn empty_array_set_slice_begin_empty_drain_greater_than_insert_length() {
let mut ary = SmallArray::<i32>::new();
let drained = ary.set_slice(0, 10, &[]);
assert_eq!(drained, 0);
assert_eq!(ary, []);
}
#[test]
fn empty_array_set_slice_out_of_bounds_empty_drain_0() {
let mut ary = SmallArray::<i32>::new();
let drained = ary.set_slice(5, 0, &[]);
assert_eq!(drained, 0);
assert_eq!(ary, [0, 0, 0, 0, 0]);
}
#[test]
fn empty_array_set_slice_out_of_bounds_empty_drain_less_than_insert_length() {
let mut ary = SmallArray::<i32>::new();
let drained = ary.set_slice(5, 1, &[]);
assert_eq!(drained, 0);
assert_eq!(ary, [0, 0, 0, 0, 0]);
}
#[test]
fn empty_array_set_slice_out_of_bounds_empty_drain_equal_to_insert_length() {
let mut ary = SmallArray::<i32>::new();
let drained = ary.set_slice(5, 3, &[]);
assert_eq!(drained, 0);
assert_eq!(ary, [0, 0, 0, 0, 0]);
}
#[test]
fn empty_array_set_slice_out_of_bounds_empty_drain_greater_than_insert_length() {
let mut ary = SmallArray::<i32>::new();
let drained = ary.set_slice(5, 10, &[]);
assert_eq!(drained, 0);
assert_eq!(ary, [0, 0, 0, 0, 0]);
}
}
| 31.699602 | 127 | 0.541676 |
0a3b02319644444183fb02e2ecb31ff78713ad6d | 1,453 | h | C | notesapi/include/ostime.h | DominoMFA/TravelerDSAPI | 6474afbae938382996c3ee4c8989110a03b82efb | [
"Apache-2.0"
] | null | null | null | notesapi/include/ostime.h | DominoMFA/TravelerDSAPI | 6474afbae938382996c3ee4c8989110a03b82efb | [
"Apache-2.0"
] | null | null | null | notesapi/include/ostime.h | DominoMFA/TravelerDSAPI | 6474afbae938382996c3ee4c8989110a03b82efb | [
"Apache-2.0"
] | null | null | null |
#if defined(OS400) && (__OS400_TGTVRM__ >= 510)
#pragma datamodel(P128)
#endif
/* ***************************************************************** */
/* */
/* Licensed Materials - Property of IBM and/or HCL */
/* */
/* Notes_V11.0.1, Domino_V11.0.1 */
/* */
/* Copyright IBM Corp. 1988, 2017 All Rights Reserved. */
/* (c) Copyright HCL Technologies Ltd. 2020. All Rights Reserved. */
/* */
/* Note to U.S. Government Users Restricted Rights: */
/* Use, duplication or disclosure restricted by GSA ADP Schedule */
/* */
/* */
/* ***************************************************************** */
#ifdef __cplusplus
extern "C" {
#endif
/* OS time/date package */
#ifndef TIMEDATE_DEFS
#define TIMEDATE_DEFS
void LNPUBLIC OSCurrentTIMEDATE (TIMEDATE far *retTimeDate);
void LNPUBLIC OSCurrentTimeZone (int far *retZone, int far *retDST);
#endif
#ifdef __cplusplus
}
#endif
#if defined(OS400) && (__OS400_TGTVRM__ >= 510)
#pragma datamodel(pop)
#endif
| 30.914894 | 71 | 0.391604 |
35d8b4e9065d66b23a861f8ab31690639859e14a | 213 | lua | Lua | output/lua/CrouchClip/FileHooks.lua | Nintendows/ns2-rebirth | a55a9d91334e1af357600805a744ac13317dc29b | [
"MIT"
] | 1 | 2021-01-01T13:10:05.000Z | 2021-01-01T13:10:05.000Z | output/lua/CrouchClip/FileHooks.lua | TheRealNin/ns2-rebirth | a55a9d91334e1af357600805a744ac13317dc29b | [
"MIT"
] | 24 | 2017-06-30T03:54:46.000Z | 2018-06-15T22:07:45.000Z | output/lua/CrouchClip/FileHooks.lua | Nintendows/ns2-rebirth | a55a9d91334e1af357600805a744ac13317dc29b | [
"MIT"
] | 3 | 2017-07-02T18:37:12.000Z | 2021-01-01T12:57:30.000Z | ModLoader.SetupFileHook( "lua/Mixins/CrouchMoveMixin.lua", "lua/CrouchClip/CrouchMoveMixin.lua", "post" )
ModLoader.SetupFileHook( "lua/Mixins/GroundMoveMixin.lua", "lua/CrouchClip/GroundMoveMixin.lua", "post" )
| 53.25 | 105 | 0.788732 |
1accac7903e9fcd89638c846392cc2be8c0c5d87 | 58 | rs | Rust | build/classes/visao/jasperreports-6.15.0/src/net/sf/jasperreports/engine/virtualization/DateSerializer.rs | EuKaique/Projeto-Diagnostico-Medico | cf7cc535ff31992b7568dba777c8faafafa6920c | [
"MIT"
] | null | null | null | build/classes/visao/jasperreports-6.15.0/src/net/sf/jasperreports/engine/virtualization/DateSerializer.rs | EuKaique/Projeto-Diagnostico-Medico | cf7cc535ff31992b7568dba777c8faafafa6920c | [
"MIT"
] | null | null | null | build/classes/visao/jasperreports-6.15.0/src/net/sf/jasperreports/engine/virtualization/DateSerializer.rs | EuKaique/Projeto-Diagnostico-Medico | cf7cc535ff31992b7568dba777c8faafafa6920c | [
"MIT"
] | null | null | null | net.sf.jasperreports.engine.virtualization.DateSerializer
| 29 | 57 | 0.896552 |
b266b9cbb6615a14616a70842191c1428de75c51 | 960 | kt | Kotlin | app/src/main/java/moe/feng/danmaqua/ui/subscription/list/VTuberSingleItemViewDelegate.kt | fython/danmaqua-android | 68694b9f1e575af8541680afe96e2a3108338828 | [
"Apache-2.0"
] | 122 | 2020-02-14T14:51:38.000Z | 2020-07-16T18:40:24.000Z | app/src/main/java/moe/feng/danmaqua/ui/subscription/list/VTuberSingleItemViewDelegate.kt | fython/danmaqua-android | 68694b9f1e575af8541680afe96e2a3108338828 | [
"Apache-2.0"
] | 2 | 2020-11-21T15:42:07.000Z | 2021-03-16T16:00:35.000Z | app/src/main/java/moe/feng/danmaqua/ui/subscription/list/VTuberSingleItemViewDelegate.kt | fython/danmaqua-android | 68694b9f1e575af8541680afe96e2a3108338828 | [
"Apache-2.0"
] | 5 | 2020-02-16T05:22:40.000Z | 2020-07-14T05:48:07.000Z | package moe.feng.danmaqua.ui.subscription.list
import moe.feng.common.eventshelper.of
import moe.feng.danmaqua.R
import moe.feng.danmaqua.databinding.ViewVtubersSingleItemBinding
import moe.feng.danmaqua.event.OnCatalogSingleItemClickListener
import moe.feng.danmaqua.model.VTuberSingleItem
import moe.feng.danmaqua.ui.common.list.*
import androidx.content.eventsHelper
class VTuberSingleItemViewDelegate :
ItemBasedSimpleViewBinder<VTuberSingleItem, VTuberSingleItemViewDelegate.ViewHolder>() {
override val viewHolderCreator: ViewHolderCreator<ViewHolder>
= dataBindingViewHolderCreatorOf(R.layout.view_vtubers_single_item)
class ViewHolder(dataBinding: ViewVtubersSingleItemBinding)
: DataBindingViewHolder<VTuberSingleItem, ViewVtubersSingleItemBinding>(dataBinding) {
override fun onItemClick() {
context.eventsHelper.of<OnCatalogSingleItemClickListener>().onCatalogSingleItem(data)
}
}
} | 36.923077 | 97 | 0.809375 |
9d2b7e746c2a54b578b8127232e0892c2892c3ab | 1,756 | html | HTML | static/tax-web.v1.0.1/tax-module/kindeditor/asp/demo.html | lss5270/vue-cli3 | 4ddc7db04a0d69af5d86cad46012d8851c79b71b | [
"MIT"
] | 1 | 2019-03-22T04:36:36.000Z | 2019-03-22T04:36:36.000Z | static/tax-web.v1.0.1/tax-module/kindeditor/asp/demo.html | lss5270/vue-cli3 | 4ddc7db04a0d69af5d86cad46012d8851c79b71b | [
"MIT"
] | 1 | 2019-04-01T12:48:42.000Z | 2019-04-03T13:43:39.000Z | static/tax-web.v1.0.1/tax-module/kindeditor/asp/demo.html | lss5270/vue-cli3 | 4ddc7db04a0d69af5d86cad46012d8851c79b71b | [
"MIT"
] | null | null | null |
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>KindEditor </title>
<link rel="stylesheet" href="../themes/default/default.css" />
<link rel="stylesheet" href="../plugins/code/prettify.css" />
<script charset="utf-8" src="../kindeditor.js"></script>
<script charset="utf-8" src="../lang/zh-CN.js"></script>
<script charset="utf-8" src="../plugins/code/prettify.js"></script>
<script charset="utf-8" src="../kindeditor-all.js"></script>
<script>
//kingeditor
var editor;
KindEditor.ready(function(K) {
editor = K.create('#content1', {
allowImageUpload:true
,resizeType : 1
,width:"100%"
,height:"500px"
,allowFileManager : true
,filePostName: 'imgFile'// name属性默认值
,items: ["source", "|", "undo", "redo", "|", "preview", "print", "template", "code", "cut", "copy", "paste", "plainpaste", "wordpaste",
"|", "justifyleft", "justifycenter", "justifyright", "justifyfull", "insertorderedlist",
"insertunorderedlist", "indent", "outdent", "subscript", "superscript", "clearhtml",
"quickformat", "selectall", "|", "fullscreen", "/", "formatblock", "fontname", "fontsize",
"|", "forecolor", "hilitecolor", "bold", "italic", "underline", "strikethrough",
"lineheight","removeformat", "|", "image", "media",
"insertfile", "table", "hr", "emoticons", "pagebreak", "anchor", "link",
"unlink"]
});
});
</script>
</head>
<body>
<form name="example" method="post" action="demo.asp">
<textarea id="content1" style="width:700px;height:200px;visibility:hidden;"> </textarea>
<br />
<input type="submit" name="button" value="提交内容" /> (提交快捷键: Ctrl + Enter)
</form>
</body>
</html>
| 38.173913 | 143 | 0.594533 |
14407da787c7d4c7876acc702d5829bf6fddaba7 | 56 | sql | SQL | src/plugins/lackman/resources/sql/insert_installed.sql | MellonQ/leechcraft | 71cbb238d2dade56b3865278a6a8e6a58c217fc5 | [
"BSL-1.0"
] | 120 | 2015-01-22T14:10:39.000Z | 2021-11-25T12:57:16.000Z | src/plugins/lackman/resources/sql/insert_installed.sql | MellonQ/leechcraft | 71cbb238d2dade56b3865278a6a8e6a58c217fc5 | [
"BSL-1.0"
] | 8 | 2015-02-07T19:38:19.000Z | 2017-11-30T20:18:28.000Z | src/plugins/lackman/resources/sql/insert_installed.sql | MellonQ/leechcraft | 71cbb238d2dade56b3865278a6a8e6a58c217fc5 | [
"BSL-1.0"
] | 33 | 2015-02-07T16:59:55.000Z | 2021-10-12T00:36:40.000Z | INSERT INTO installed (package_id) VALUES (:package_id); | 56 | 56 | 0.803571 |
c1cd9659f0e20ab73228a1956df4669194260ca5 | 8,260 | rs | Rust | examples/example-sdl2/src/lib.rs | aclysma/minimum | f7c2ba6f76976eb2bce6a950eaa54e0377809bb2 | [
"Apache-2.0",
"MIT"
] | 59 | 2019-08-23T21:32:36.000Z | 2021-11-17T11:45:47.000Z | examples/example-sdl2/src/lib.rs | aclysma/minimum | f7c2ba6f76976eb2bce6a950eaa54e0377809bb2 | [
"Apache-2.0",
"MIT"
] | 1 | 2020-06-25T05:11:45.000Z | 2020-06-25T05:11:45.000Z | examples/example-sdl2/src/lib.rs | aclysma/minimum | f7c2ba6f76976eb2bce6a950eaa54e0377809bb2 | [
"Apache-2.0",
"MIT"
] | 6 | 2020-01-10T18:22:46.000Z | 2021-04-09T04:22:33.000Z | // There is "dead" example code in this crate
#![allow(dead_code)]
#[allow(unused_imports)]
#[macro_use]
extern crate log;
use sdl2::event::Event;
use sdl2::mouse::MouseState;
use skulpin::{Sdl2Window, RendererBuilder};
use skulpin_plugin_imgui::ImguiRendererPlugin;
use atelier_assets::core::asset_uuid;
use atelier_assets::core as atelier_core;
use legion::*;
use minimum::resources::*;
mod systems;
mod registration;
use minimum::resources::editor::{
EditorMode, EditorSelectionResource, EditorInspectRegistryResource, EditorStateResource,
EditorDraw3DResource,
};
use minimum_sdl2::resources::{Sdl2WindowResource, Sdl2ImguiManagerResource};
use minimum_sdl2::imgui::Sdl2ImguiManager;
use minimum_skulpin::resources::CanvasDrawResource;
use example_shared::resources::FpsTextResource;
use minimum_nphysics2d::resources::PhysicsResource;
use atelier_assets::loader::rpc_loader::RpcLoader;
pub const GRAVITY: f32 = -9.81;
pub const GROUND_HALF_EXTENTS_WIDTH: f32 = 3.0;
pub fn run() {
// Init SDL2
let sdl_context = sdl2::init().expect("Failed to initialize sdl2");
let video_subsystem = sdl_context
.video()
.expect("Failed to create sdl video subsystem");
// Create a window
let window_size = (900, 600);
let sdl2_window = video_subsystem
.window("Minimum SDL2 Example", window_size.0, window_size.1)
.position_centered()
.allow_highdpi()
.resizable()
.build()
.expect("Failed to create window");
// Init imgui
let sdl2_imgui = minimum_sdl2::imgui::init_imgui_manager(
&sdl2_window,
minimum_sdl2::imgui::ColorFormat::Srgb,
);
// Setup skulpin imgui plugin
let mut imgui_plugin: Option<Box<dyn skulpin::RendererPlugin>> = None;
sdl2_imgui.with_context(|context| {
imgui_plugin = Some(Box::new(ImguiRendererPlugin::new(context)));
});
// Configuration for skulpin/skia canvas
let scale_to_fit = skulpin::skia_safe::matrix::ScaleToFit::Center;
let visible_range = skulpin::skia_safe::Rect {
left: 0.0,
right: window_size.0 as f32,
top: 0.0,
bottom: window_size.1 as f32,
};
// Set up the skulpin renderer
let skulpin_window = Sdl2Window::new(&sdl2_window);
let renderer = RendererBuilder::new()
.use_vulkan_debug_layer(true)
.add_plugin(imgui_plugin.unwrap())
.coordinate_system(skulpin::CoordinateSystem::VisibleRange(
visible_range,
scale_to_fit,
))
.build(&skulpin_window);
// Check if there were error setting up the renderer
if let Err(e) = renderer {
println!("Error during renderer construction: {:?}", e);
return;
}
log::info!("renderer created");
let mut renderer = renderer.unwrap();
// Create the event pump
log::info!("Starting window event loop");
let mut event_pump = sdl_context
.event_pump()
.expect("Could not create sdl event pump");
// Create a legion world
let mut world = World::default();
let mut resources = create_resources(&sdl2_window, &sdl2_imgui);
// Start the application
EditorStateResource::open_prefab(
&mut world,
&resources,
asset_uuid!("3991506e-ed7e-4bcb-8cfd-3366b31a6439"),
)
.unwrap();
let schedule_criteria = systems::ScheduleCriteria::new(false, EditorMode::Active);
let mut update_schedule = systems::create_update_schedule(&schedule_criteria);
let mut draw_schedule = systems::create_draw_schedule(&schedule_criteria);
// Run the event loop
'running: loop {
for event in event_pump.poll_iter() {
log::info!("SDL2 Event: {:?}", event);
sdl2_imgui.handle_event(&event);
if !sdl2_imgui.ignore_event(&event) {
let mut input_resource = resources.get_mut::<InputResource>().unwrap();
minimum_sdl2::input::handle_sdl2_event(&event, input_resource.input_state_mut());
//
// Halt if the user requests to close the window
//
if let Event::Quit { .. } = event {
break 'running;
}
}
}
// Update/Draw here
sdl2_imgui.begin_frame(&sdl2_window, &MouseState::new(&event_pump));
update_schedule.execute(&mut world, &mut resources);
sdl2_imgui.render(&sdl2_window);
renderer
.draw(&skulpin_window, |canvas, coordinate_system_helper| {
resources
.get_mut::<CanvasDrawResource>()
.unwrap()
.begin_draw_context(canvas, coordinate_system_helper);
draw_schedule.execute(&mut world, &mut resources);
resources
.get_mut::<CanvasDrawResource>()
.unwrap()
.end_draw_context();
})
.unwrap();
if resources
.get::<AppControlResource>()
.unwrap()
.should_terminate_process()
{
break;
}
}
// Drop world before resources as physics components may point back at resources
std::mem::drop(world);
std::mem::drop(resources);
}
fn create_resources(
sdl2_window: &sdl2::video::Window,
sdl2_imgui: &Sdl2ImguiManager,
) -> Resources {
let mut resources = Resources::default();
let rpc_loader = RpcLoader::new("127.0.0.1:9999".to_string()).unwrap();
let asset_resource = registration::create_asset_manager(rpc_loader);
let physics_resource = PhysicsResource::new(glam::Vec2::unit_y() * GRAVITY);
let camera_resource = CameraResource::new(
glam::Vec2::new(0.0, 1.0),
crate::GROUND_HALF_EXTENTS_WIDTH * 1.5,
);
let sdl2_window_resource = Sdl2WindowResource::new(sdl2_window);
let drawable = sdl2_window_resource.drawable_size();
let mut viewport = ViewportResource::empty();
let viewport_size_in_pixels = glam::Vec2::new(drawable.width as f32, drawable.height as f32);
example_shared::viewport::update_viewport(
&mut viewport,
viewport_size_in_pixels,
camera_resource.position,
camera_resource.x_half_extents,
);
resources.insert(viewport);
resources.insert(DebugDraw2DResource::new());
resources.insert(DebugDraw3DResource::new());
resources.insert(EditorDraw3DResource::new());
resources.insert(EditorSelectionResource::new(
registration::create_editor_selection_registry(),
));
resources.insert(EditorInspectRegistryResource::new(
registration::create_editor_inspector_registry(),
));
resources.insert(ComponentRegistryResource::new(
registration::create_component_registry(),
));
resources.insert(FpsTextResource::new());
resources.insert(asset_resource);
resources.insert(physics_resource);
resources.insert(camera_resource);
resources.insert(Sdl2ImguiManagerResource::new(sdl2_imgui.clone()));
resources.insert(ImguiResource::new(sdl2_imgui.imgui_manager()));
resources.insert(AppControlResource::new());
resources.insert(TimeResource::new());
resources.insert(InputResource::new());
resources.insert(CanvasDrawResource::default());
resources.insert(Sdl2WindowResource::new(&sdl2_window));
resources.insert(EditorStateResource::new());
use minimum_sdl2::input::Sdl2KeyboardKey;
use sdl2::keyboard::Keycode;
let keybinds = minimum::resources::editor::Keybinds {
selection_add: Sdl2KeyboardKey::new(Keycode::LShift).into(),
selection_subtract: Sdl2KeyboardKey::new(Keycode::LAlt).into(),
selection_toggle: Sdl2KeyboardKey::new(Keycode::LCtrl).into(),
tool_translate: Sdl2KeyboardKey::new(Keycode::Num1).into(),
tool_scale: Sdl2KeyboardKey::new(Keycode::Num2).into(),
tool_rotate: Sdl2KeyboardKey::new(Keycode::Num3).into(),
action_quit: Sdl2KeyboardKey::new(Keycode::Escape).into(),
action_toggle_editor_pause: Sdl2KeyboardKey::new(Keycode::Space).into(),
};
resources.insert(minimum::resources::editor::EditorSettingsResource::new(
keybinds,
));
resources
}
| 32.908367 | 97 | 0.657385 |
62d575ae2241da8f47da8237839493872e75e931 | 1,403 | swift | Swift | iOS/Routine/Models/Task.swift | instinctools/routine | c421772adfc0ceaa0765cd8d6b966769595d0d28 | [
"Apache-2.0"
] | 4 | 2020-06-01T07:20:46.000Z | 2022-02-03T08:42:04.000Z | iOS/Routine/Models/Task.swift | instinctools/routine | c421772adfc0ceaa0765cd8d6b966769595d0d28 | [
"Apache-2.0"
] | 19 | 2020-06-01T08:42:11.000Z | 2020-09-29T07:48:26.000Z | iOS/Routine/Models/Task.swift | instinctools/routine | c421772adfc0ceaa0765cd8d6b966769595d0d28 | [
"Apache-2.0"
] | null | null | null | //
// Task.swift
// Routine
//
// Created by Vadzim Karonchyk on 3/23/20.
// Copyright © 2020 Instinctools. All rights reserved.
//
import UIKit
extension Optional where Wrapped == Task.ResetType {
var orDefault: Task.ResetType {
return self ?? .toPeriod
}
}
struct Task: Equatable {
enum ResetType: Int16 {
case toPeriod
case toDate
}
let id: String
let title: String
let period: Period
let periodCount: Int
let startDate: Date
let resetType: ResetType
var finishDate: Date {
return Calendar.current.date(
byAdding: period.calendarComponent,
value: periodCount,
to: startDate
).orToday
}
init(id: String, title: String, period: Period, periodCount: Int, startDate: Date, resetType: ResetType) {
self.id = id
self.title = title
self.period = period
self.periodCount = periodCount
self.startDate = startDate
self.resetType = resetType
}
init(entity: TaskEntity) {
self.id = entity.id.orEmpty
self.title = entity.title.orEmpty
self.period = Period(rawValue: entity.period).orDefault
self.periodCount = Int(entity.periodCount)
self.startDate = entity.startDate.orToday
self.resetType = ResetType(rawValue: entity.resetType).orDefault
}
}
| 24.614035 | 110 | 0.6201 |
0e74a4bff588c70365fbaf7ef4ab491fb3094c47 | 775 | htm | HTML | l2j_datapack/dist/game/data/scripts/quests/Q00385_YokeOfThePast/ziggurat-05.htm | RollingSoftware/L2J_HighFive_Hardcore | a3c794c82c32b5afca49416119b4aafa8fb9b6d4 | [
"MIT"
] | null | null | null | l2j_datapack/dist/game/data/scripts/quests/Q00385_YokeOfThePast/ziggurat-05.htm | RollingSoftware/L2J_HighFive_Hardcore | a3c794c82c32b5afca49416119b4aafa8fb9b6d4 | [
"MIT"
] | 38 | 2018-02-06T17:11:29.000Z | 2018-06-05T20:47:59.000Z | l2j_datapack/dist/game/data/scripts/quests/Q00385_YokeOfThePast/ziggurat-05.htm | RollingSoftware/L2J_HighFive_Hardcore | a3c794c82c32b5afca49416119b4aafa8fb9b6d4 | [
"MIT"
] | null | null | null | <html><body>Gatekeeper Ziggurat:<br>
Good choice! Now go to the dungeon, slay <font color="LEVEL">the guardians of ancient cult</font> and bring back the <font color="LEVEL">scrolls of ancient magic</font>.<br>
When you bring me the scroll, I will remove the magic power it contains and turn the scroll into a <font color="LEVEL">Blank Scroll</font>. A Blank Scroll is the only reward I can offer you.<br>
Have you heard of <font color="LEVEL">Merchant of Mammon</font> who often appears in the castle area? He will be very interested in a Blank Scroll. You will find out more when you meet him. It won't be easy to find him though...<br>
<a action="bypass -h Quest Q00385_YokeOfThePast ziggurat-06.htm">"Tell me more about the guardians of ancient magic."</a>
</body></html> | 129.166667 | 232 | 0.752258 |
6192a43be9a85a9f487c828a5db1b5a2fd4a41ca | 502 | css | CSS | src/components/City.module.css | cristianblar/weather_app | 1a326504624118354238c45310b4ffbb3f469721 | [
"MIT"
] | null | null | null | src/components/City.module.css | cristianblar/weather_app | 1a326504624118354238c45310b4ffbb3f469721 | [
"MIT"
] | null | null | null | src/components/City.module.css | cristianblar/weather_app | 1a326504624118354238c45310b4ffbb3f469721 | [
"MIT"
] | null | null | null | .detalles {
background-color: #226666;
color: white;
height: 80vh;
padding-top: 12px;
width: 100%;
}
.detalles h4 {
font-size: 28px;
}
.detalles ul {
list-style: none;
margin: 0;
padding: 0;
}
.detalles ul li {
margin-bottom: 12px;
}
.detalles ul li h6 {
display: inline-block;
}
@media screen and (min-width: 700px) {
.detalles {
min-height: 90vh;
}
.detalles h4 {
font-size: 40px;
}
.detalles ul li span, .detalles ul li h6 {
font-size: 24px;
}
}
| 12.55 | 44 | 0.603586 |
f9f618b351b637294312737a21c7c9ff96b9f1ac | 671 | go | Go | rbac/release.go | tinybear1976/tinycms | 26ccd28516a04f31bedd918faed8c1fe13bd7a93 | [
"MIT"
] | null | null | null | rbac/release.go | tinybear1976/tinycms | 26ccd28516a04f31bedd918faed8c1fe13bd7a93 | [
"MIT"
] | null | null | null | rbac/release.go | tinybear1976/tinycms | 26ccd28516a04f31bedd918faed8c1fe13bd7a93 | [
"MIT"
] | null | null | null | package rbac
import "encoding/json"
// 按角色名称返回给前端(全量)权限,如果权限表中没有找到对应记录(异常),则返回所有模板中的数据,并全体置为拒绝状态
// 返回json字符串
func GetUiPermission_back(role_id string) (string, error) {
ptree, err := getUiPermission_back(role_id)
if err != nil {
return "", err
}
return ptree.toJson()
}
func GetUiPermission_front(role_id string) (string, error) {
ptree, err := getUiPermission_front(role_id)
if err != nil {
return "", err
}
return ptree.toFrontJson()
}
func SaveUiPermission_back(j string) error {
var items rbac_TreeNode
b := []byte(j)
err := json.Unmarshal(b, &items)
// b = nil
if err != nil {
return err
}
err = saveUiPermission_back(&items)
return err
}
| 19.735294 | 60 | 0.706408 |
03d65045ac82b643bfb52c8b24de67514a671c4b | 363 | sql | SQL | impala/taxi360/nested_table_sql.sql | hadooparchitecturebook/taxi360 | 2de4333a9dab0322b416b8d45d4ccfd9e6a40983 | [
"Apache-2.0"
] | 6 | 2017-04-03T09:06:43.000Z | 2019-06-18T20:54:17.000Z | impala/taxi360/nested_table_sql.sql | hadooparchitecturebook/taxi360 | 2de4333a9dab0322b416b8d45d4ccfd9e6a40983 | [
"Apache-2.0"
] | null | null | null | impala/taxi360/nested_table_sql.sql | hadooparchitecturebook/taxi360 | 2de4333a9dab0322b416b8d45d4ccfd9e6a40983 | [
"Apache-2.0"
] | 5 | 2016-09-13T22:14:17.000Z | 2018-02-12T07:39:47.000Z | invalidate metadata
--drop table ny_taxi_nested;
select * from ny_taxi_nested
select
p.*,
c.*
from
ny_taxi_nested p,
p.trip c
select p.vender_id, count(*) from ny_taxi_nested p, p.trip c group by p.vender_id
select
p.vender_id,
sum(total_amount),
avg(total_amount),
count(total_amount)
from
ny_taxi_nested p,
p.trip c
group by p.vender_id | 15.125 | 81 | 0.732782 |
26a11ee7a3e635907681a7b16825cb511dc42464 | 9,040 | java | Java | src/main/java/es/upm/etsisi/cf4j/util/plot/XYPlot.java | dionisioC/cf4j | 59b0b5d08488c790eddd5ec4e50fdf8d448e1557 | [
"Apache-2.0"
] | 49 | 2018-02-25T14:31:22.000Z | 2022-03-22T09:28:51.000Z | src/main/java/es/upm/etsisi/cf4j/util/plot/XYPlot.java | dionisioC/cf4j | 59b0b5d08488c790eddd5ec4e50fdf8d448e1557 | [
"Apache-2.0"
] | 16 | 2018-05-24T21:38:15.000Z | 2022-03-29T11:06:52.000Z | src/main/java/es/upm/etsisi/cf4j/util/plot/XYPlot.java | dionisioC/cf4j | 59b0b5d08488c790eddd5ec4e50fdf8d448e1557 | [
"Apache-2.0"
] | 22 | 2018-04-20T16:45:01.000Z | 2022-02-18T09:25:14.000Z | package es.upm.etsisi.cf4j.util.plot;
import de.erichseifert.gral.data.DataSeries;
import de.erichseifert.gral.data.DataTable;
import de.erichseifert.gral.graphics.Insets2D;
import de.erichseifert.gral.graphics.Label;
import de.erichseifert.gral.graphics.Location;
import de.erichseifert.gral.graphics.Orientation;
import de.erichseifert.gral.plots.AbstractPlot;
import de.erichseifert.gral.plots.axes.AxisRenderer;
import de.erichseifert.gral.plots.lines.DefaultLineRenderer2D;
import de.erichseifert.gral.plots.lines.LineRenderer;
import de.erichseifert.gral.plots.points.PointRenderer;
import org.apache.commons.lang3.tuple.MutableTriple;
import org.apache.commons.lang3.tuple.Triple;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.*;
/** Implements an XYPlot. */
public class XYPlot extends Plot {
/** Series data */
private final List<Triple<String, double[], double[]>> series;
/** Labels related witch each xy point */
private final String[] pointsLabels;
/** Series names that must show the points labels */
private final Set<String> hasLabelsVisible;
/** Label of the x axis */
private final String xLabel;
/** Label of the y axis */
private final String yLabel;
/** Indicates if the legend must be hidden */
private final boolean hideLegend;
/**
* Creates a new XYPlot
*
* @param xLabel Label of the x axis
* @param yLabel Label of the y axis
*/
public XYPlot(String[] values, String xLabel, String yLabel) {
this(values, xLabel, yLabel, false);
}
/**
* Creates a new XYPlot
*
* @param xLabel Label of the x axis
* @param yLabel Label of the y axis
* @param hideLegend Indicates if the legend must be hidden. False by default.
*/
public XYPlot(String[] values, String xLabel, String yLabel, boolean hideLegend) {
this.pointsLabels = values;
this.xLabel = xLabel;
this.yLabel = yLabel;
this.hideLegend = hideLegend;
this.series = new ArrayList<>();
this.hasLabelsVisible = new HashSet<>();
}
/**
* Adds a new empty series to the plot. Points are initialized to x=0 and y=0 all point labels.
*
* @param seriesName Series name
* @return Self XYPlot instance
*/
public XYPlot addSeries(String seriesName) {
return this.addSeries(seriesName, 0, 0);
}
/**
* Adds a new series to the plot initializing x and y to a constant one for all point labels.
*
* @param seriesName Series name
* @param x x initialization
* @param y y initialization
* @return Self XYPlot instance
*/
public XYPlot addSeries(String seriesName, double x, double y) {
double[] xs = new double[this.pointsLabels.length];
Arrays.fill(xs, x);
double[] ys = new double[this.pointsLabels.length];
Arrays.fill(ys, y);
return this.addSeries(seriesName, xs, ys);
}
/**
* Adds a new series to the plot. xs and ys positions must be correlated with point labels.
*
* @param seriesName Series name
* @param xs x values
* @param ys y values
* @return Self XYPlot instance
*/
public XYPlot addSeries(String seriesName, double[] xs, double[] ys) {
this.series.add(new MutableTriple(seriesName, xs, ys));
return this;
}
/**
* Sets a single point of a series
*
* @param seriesName Series name
* @param label Label value of the point. Must exists
* @param x x value
* @param y y value
* @return Self XYPlot instance
*/
public XYPlot setXY(String seriesName, String label, double x, double y) {
int labelIndex = 0;
while (!this.pointsLabels[labelIndex].equals(label)) {
labelIndex++;
}
int seriesIndex = 0;
while (!this.series.get(seriesIndex).getLeft().equals(seriesName)) {
seriesIndex++;
}
this.series.get(seriesIndex).getMiddle()[labelIndex] = x;
this.series.get(seriesIndex).getRight()[labelIndex] = y;
return this;
}
/**
* Set the labels visible for a series
*
* @param seriesName Series name
* @return Self XYPlot instance
*/
public XYPlot setLabelsVisible(String seriesName) {
this.hasLabelsVisible.add(seriesName);
return this;
}
/**
* Set the labels not visible for a series
*
* @param seriesName Series name
* @return Self XYPlot instance
*/
public XYPlot setLabelsNotVisible(String seriesName) {
this.hasLabelsVisible.remove(seriesName);
return this;
}
@Override
protected String[] getDataHeaders() {
String[] headers = new String[1 + 2 * this.series.size()];
headers[0] = "Value";
for (int i = 0; i < this.series.size(); i++) {
Triple<String, double[], double[]> s = this.series.get(i);
String seriesName = s.getLeft();
headers[1 + i * 2] = seriesName + "(" + this.xLabel + ")";
headers[2 + i * 2] = seriesName + " (" + this.yLabel + ")";
}
return headers;
}
@Override
protected String[][] getDataContent(String xAxisTicksFormat, String yAxisTicksFormat) {
DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.US);
DecimalFormat xdf = new DecimalFormat(xAxisTicksFormat, dfs);
DecimalFormat ydf = new DecimalFormat(yAxisTicksFormat, dfs);
String[][] content = new String[this.pointsLabels.length][1 + 2 * this.series.size()];
for (int row = 0; row < this.pointsLabels.length; row++) {
content[row][0] = this.pointsLabels[row];
for (int i = 0; i < this.series.size(); i++) {
Triple<String, double[], double[]> s = this.series.get(i);
content[row][1 + i * 2] = xdf.format(s.getMiddle()[row]);
content[row][2 + i * 2] = ydf.format(s.getRight()[row]);
}
}
return content;
}
@Override
protected AbstractPlot getGralPlot() {
// Create XY plot with data
de.erichseifert.gral.plots.XYPlot plot = new de.erichseifert.gral.plots.XYPlot();
for (int i = 0; i < this.series.size(); i++) {
String name = this.series.get(i).getLeft();
double[] xs = this.series.get(i).getMiddle();
double[] ys = this.series.get(i).getRight();
DataTable data = new DataTable(Double.class, Double.class, String.class);
for (int j = 0; j < this.pointsLabels.length; j++) {
data.add(xs[j], ys[j], this.pointsLabels[j]);
}
DataSeries series = new DataSeries(name, data);
plot.add(i, series, true);
LineRenderer lineRenderer = new DefaultLineRenderer2D();
lineRenderer.setColor(PlotSettings.getColor(i));
plot.setLineRenderers(series, lineRenderer);
PointRenderer pointRenderer = plot.getPointRenderers(series).get(0);
pointRenderer.setColor(PlotSettings.getColor(i));
pointRenderer.setValueVisible(this.hasLabelsVisible.contains(name));
pointRenderer.setValueColumn(2);
pointRenderer.setValueFont(PlotSettings.getSecondaryFont());
pointRenderer.setValueAlignmentY(1);
pointRenderer.setValueColor(PlotSettings.getColor(i));
}
// Customize plot
plot.setBackground(PlotSettings.getBackgroundColor());
plot.setInsets(
new Insets2D.Double(
(this.hideLegend) ? PlotSettings.getClearInset() : PlotSettings.getLegendInset(),
PlotSettings.getyAxisInset(),
PlotSettings.getxAxisInset(),
PlotSettings.getClearInset()));
// Customize x axis
AxisRenderer xAxisRenderer = plot.getAxisRenderer(de.erichseifert.gral.plots.XYPlot.AXIS_X);
xAxisRenderer.setLabel(new Label(xLabel));
xAxisRenderer.getLabel().setFont(PlotSettings.getPrimaryFont());
xAxisRenderer.setLabelDistance(PlotSettings.getxAxisLabelDistance());
xAxisRenderer.setTickFont(PlotSettings.getSecondaryFont());
xAxisRenderer.setTickLabelFormat(NumberFormat.getInstance(Locale.US));
xAxisRenderer.setTicksAutoSpaced(true);
// Customize y axis
AxisRenderer yAxisRenderer = plot.getAxisRenderer(de.erichseifert.gral.plots.XYPlot.AXIS_Y);
yAxisRenderer.setLabel(new Label(yLabel));
yAxisRenderer.getLabel().setFont(PlotSettings.getPrimaryFont());
yAxisRenderer.getLabel().setRotation(90);
yAxisRenderer.setLabelDistance(PlotSettings.getyAxisLabelDistance());
yAxisRenderer.setTickFont(PlotSettings.getSecondaryFont());
yAxisRenderer.setTickLabelFormat(NumberFormat.getInstance(Locale.US));
yAxisRenderer.setTicksAutoSpaced(true);
xAxisRenderer.setIntersection(-Double.MAX_VALUE);
yAxisRenderer.setIntersection(-Double.MAX_VALUE);
// Customize legend
if (!this.hideLegend) {
plot.setLegendLocation(Location.NORTH);
plot.setLegendVisible(true);
plot.setLegendDistance(PlotSettings.getLegendDistance());
plot.getLegend().setBorderStroke(null);
plot.getLegend().setOrientation(Orientation.HORIZONTAL);
plot.getLegend().setAlignmentX(0.5);
plot.getLegend().setFont(PlotSettings.getPrimaryFont());
}
// Customize navigator settings
plot.getNavigator().setZoom(0.85);
plot.getNavigator().setZoomable(false);
return plot;
}
}
| 32.170819 | 97 | 0.690044 |
0ed21cea29ed92605a58c27f21bd7998aeb24a27 | 1,018 | ts | TypeScript | src/state/project-state.ts | milesdavis71/project-manager | 0a65fade68a9e8aae043ac4d0aafc1831f571ea4 | [
"MIT"
] | null | null | null | src/state/project-state.ts | milesdavis71/project-manager | 0a65fade68a9e8aae043ac4d0aafc1831f571ea4 | [
"MIT"
] | null | null | null | src/state/project-state.ts | milesdavis71/project-manager | 0a65fade68a9e8aae043ac4d0aafc1831f571ea4 | [
"MIT"
] | null | null | null | import { Project, ProjectStatus } from '../models/project';
type Listener<T> = (items: T[]) => void;
class State<T> {
listeners: Listener<T>[] = [];
addListeners(listenerFn: Listener<T>) {
this.listeners.push(listenerFn);
}
}
class ProjectState extends State<Project> {
projects: Project[] = [];
private static instance: ProjectState;
constructor() {
super();
}
static getInstance() {
if (this.instance) {
return this.instance;
}
this.instance = new ProjectState();
return this.instance;
}
addProject(title: string, desc: string, numOfPeople: number) {
const newProject = new Project(
Math.random().toString(),
title,
desc,
numOfPeople,
ProjectStatus.Active
);
this.projects.push(newProject);
console.log(newProject);
this.updateListeners();
}
private updateListeners() {
this.listeners.map(listenerFn => listenerFn(this.projects.slice()));
}
}
export const projectState = ProjectState.getInstance();
| 22.130435 | 72 | 0.651277 |
6e42dcb7a3e296d610e9c57d50c08e09a6fdafd8 | 4,874 | html | HTML | public/views/index.html | MelodicCrypter/Express-Workbox-Webpack-Babel-Scaffold | b0e21aa2d4eb91e0c6f2f24a4a57fb3885de85d3 | [
"MIT"
] | 1 | 2019-08-06T13:53:25.000Z | 2019-08-06T13:53:25.000Z | public/views/index.html | MelodicCrypter/Express-Workbox-Webpack-Babel-Scaffold | b0e21aa2d4eb91e0c6f2f24a4a57fb3885de85d3 | [
"MIT"
] | 3 | 2020-09-06T21:40:24.000Z | 2022-02-12T19:28:17.000Z | public/views/index.html | MelodicCrypter/Express-Workbox-Webpack-Babel-Scaffold | b0e21aa2d4eb91e0c6f2f24a4a57fb3885de85d3 | [
"MIT"
] | 1 | 2021-07-22T09:49:04.000Z | 2021-07-22T09:49:04.000Z | ${header}
<!-- Main Header -->
<body>
<nav class="light-blue lighten-1" role="navigation">
<div class="nav-wrapper container"><a id="logo-container" href="#" class="brand-logo"><iconify-icon data-icon="emojione:new-button"></iconify-icon></a>
<ul class="right hide-on-med-and-down">
<li><a href="#"><iconify-icon data-icon="dashicons:menu-alt3"></iconify-icon></a></li>
</ul>
<ul id="nav-mobile" class="sidenav">
<li><a href="#">Navbar Link</a></li>
</ul>
<a href="#" data-target="nav-mobile" class="sidenav-trigger"><iconify-icon data-icon="ic:baseline-menu"></iconify-icon></a>
</div>
</nav>
<div class="section no-pad-bot" id="index-banner">
<div class="container">
<br><br>
<h1 class="header center light-green-text">Modern PWA Scaffold</h1>
<div class="row center">
<h5 class="header col s12 light">Express, Workbox, Webpack, and Babel combined</h5>
</div>
<div class="row center">
<a href="https://github.com/MelodicCrypter/Express-Workbox-Webpack-Babel-Scaffold" id="download-button" class="btn-large waves-effect waves-light light-green" target="_blank"><iconify-icon data-icon="el:github"></iconify-icon> Fork/Clone </a>
</div>
<br><br>
</div>
</div>
<div class="container">
<section class="section">
<div class="row">
<div class="col s12 m4">
<div class="icon-block">
<h2 class="center light-blue-text"><iconify-icon data-icon="logos:nodejs-icon"></iconify-icon></h2>
<h5 class="center">Backend Node Express</h5>
<p class="light">Node Express (with Routing) already setup so you can use backend activities for your new PWA app. Alongside it, <strong>ES6Renderer</strong> was used for the template view engine, and <strong>Browser-Refresh</strong> for auto-reload while developing. You can change it though anytime you want to.</p>
</div>
</div>
<div class="col s12 m4">
<div class="icon-block">
<h2 class="center light-blue-text"><iconify-icon data-icon="logos:webpack"></iconify-icon> <iconify-icon data-icon="logos:babel"></iconify-icon></h2>
<h5 class="center">Webpack & Babel</h5>
<p class="light">Babel and Webpack can be tedious and very daunting to setup sometimes, so these two powerful tools were already setup for you. Both backend and frontend configurations were clearly configured in one file. </p>
</div>
</div>
<div class="col s12 m4">
<div class="icon-block">
<h2 class="center light-blue-text"><iconify-icon data-icon="logos:google-icon"></iconify-icon></h2>
<h5 class="center">Google Workbox</h5>
<p class="light">Progressive Web Apps (PWA) is the future for web applications. However, to setup your own service worker over and over again can be time-wasting. That is why Google developed Workbox. A library with set of best practices for creating PWAs.</p>
</div>
</div>
</div>
</section>
<br><br>
</div>
<div class="container">
<section class="section">
<div class="row">
<div class="col s12 center-align">
<p>Also, <strong>ESLint</strong>, <strong>Prettier</strong>, <strong>Materialize</strong>, and <strong>Iconify</strong> were already included. You can always change these later if you want to.</p>
<br><br>
<a href="/test" class="btn btn-small light-blue">go to => Test Page</a>
</div>
</div>
</section>
<br><br>
</div>
<div style="position: absolute;bottom: 0px;margin-bottom: -40px;left: 0;right: 0;" id="updateContainer" class="container center-align">
<div class="row">
<div class="col s12">
<a style="display: none;" id="updateButton" class="waves-effect waves-light btn"><iconify-icon data-icon="ic:round-update"></iconify-icon> Update</a>
</div>
</div>
</div>
<footer class="page-footer light-green">
<div class="footer-copyright">
<div class="container">
<iconify-icon data-icon="ant-design:heart-fill"></iconify-icon> <a class="white-text text-lighten-3" href="https://github.com/MelodicCrypter" target="_blank">MelodicCrypter</a>
</div>
</div>
</footer>
<!-- Main Footer -->
${footer}
| 48.74 | 341 | 0.561346 |
0bbbc45ba4c350c8c90d7bb728eaa10783237f8b | 2,211 | py | Python | app/daemon.py | mika-koivusaari/mqtt_db_gateway | c2e6a0f97d340f5a9d8a2f530f3ae0145064fd2b | [
"MIT"
] | 1 | 2017-12-02T17:38:23.000Z | 2017-12-02T17:38:23.000Z | app/daemon.py | mika-koivusaari/mqtt_db_gateway | c2e6a0f97d340f5a9d8a2f530f3ae0145064fd2b | [
"MIT"
] | null | null | null | app/daemon.py | mika-koivusaari/mqtt_db_gateway | c2e6a0f97d340f5a9d8a2f530f3ae0145064fd2b | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
from pep3143daemon import DaemonContext, PidFile
import signal
import os
import sys
import time
class Daemon:
def stop(self, pidfile):
try:
pid = open(pidfile).readline()
except IOError:
print("Daemon already gone, or pidfile was deleted manually")
sys.exit(1)
print("terminating Daemon with Pid: {0}".format(pid))
os.kill(int(pid), signal.SIGTERM)
sys.stdout.write("Waiting...")
while os.path.isfile(self.pid):
sys.stdout.write(".")
sys.stdout.flush()
time.sleep(0.5)
print("Gone")
def reload(self, pidfile):
try:
pid = open(pidfile).readline()
except IOError:
print("Daemon not running, or pidfile was deleted manually")
sys.exit(1)
print("Sending SIGUSR1 to Daemon with Pid: {0}".format(pid))
os.kill(int(pid), signal.SIGUSR1)
sys.stdout.write("Ok")
def start(app):
app.config = app.readConfig(app.config_file)
app.daemon = DaemonContext(pidfile=PidFile(app.pid)
, signal_map={signal.SIGTERM: app.program_cleanup,
signal.SIGHUP: app.terminate,
signal.SIGUSR1: app.reload_program_config}
# ,files_preserve=(sys.stdout)
, stdout=open("/tmp/daemon_stdout.log", 'w')
, stderr=open("/tmp/daemon_stderr.log", 'w')
, gid=app.config["daemon"]["groupid"])
print("daemon created")
if app.nodaemon:
print("no daemon")
app.daemon.detach_process = False
else:
app.daemon.detach_process = True
try:
print("before daemon")
app.daemon.open()
print("after daemon")
app.createLogger()
app.logger.debug('After open')
app.run()
except:
print("Unexpected error:", sys.exc_info()[0])
raise
| 35.66129 | 99 | 0.502035 |
402bd8c64dfcf6dc81c4a8f215d5e462112b9046 | 4,542 | py | Python | tools/sysupdate/qmfmlib/dfu.py | dalessan/qm-bootloader | 2743fa8128792d73f447bfa5079fca144df6ce7c | [
"BSD-3-Clause"
] | 15 | 2016-08-11T23:17:10.000Z | 2019-04-30T01:12:52.000Z | tools/sysupdate/qmfmlib/dfu.py | dalessan/qm-bootloader | 2743fa8128792d73f447bfa5079fca144df6ce7c | [
"BSD-3-Clause"
] | 6 | 2016-08-12T14:11:21.000Z | 2017-03-31T18:48:33.000Z | tools/sysupdate/qmfmlib/dfu.py | quark-mcu/qm-bootloader | 0b8ce494885666dda7bd88fc5a117cc5df403f48 | [
"BSD-3-Clause"
] | 13 | 2016-08-11T20:32:36.000Z | 2021-10-18T14:54:58.000Z | #!/usr/bin/python -tt
# -*- coding: utf-8 -*-
# Copyright (c) 2017, Intel Corporation
# 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 Intel Corporation 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 INTEL CORPORATION 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.
""" Quark Microcontroller Firmware Update DFU Module
This module provides classes to add and DFU compliance to firmware images for
Quark Microcontrollers.
"""
from __future__ import print_function, division, absolute_import
import struct
import binascii
_ENDIAN = "<" # Defines the endian for struct packing. ('<'=little, '>'=big)
class DFUException(Exception):
""" DFU Exception """
def __init__(self, message):
super(DFUException, self).__init__(message)
class DFUImage(object):
""" Creates a DFU compatible file from a binary file. """
suffix_crc = 0
dfu_spec = 0x0100 # DFU 1.0
length = 16
release = 0xFFFF
id_product = 0xFFFF
id_vendor = 0xFFFF
_suffix_struct = struct.Struct("%sHHHH3cBI" % _ENDIAN)
def __init__(self):
pass
@property
def _pack_suffix_tuple(self):
""" Tuple containing the suffix information in a defined order. """
return (
self.release,
self.id_product,
self.id_vendor,
self.dfu_spec,
'U', 'F', 'D',
self.length,
self.suffix_crc,
)
@property
def packed_dfu_suffix(self):
""" Binary representation DFU suffix. """
ret = self._suffix_struct.pack(*self._pack_suffix_tuple)
return ret
def crc(self, data, return_type=str):
""" Calculate CRC.
CRC32 as binary string or as defined with `format` of image file
ignoring the last 4 bytes. These 4 bytes are space-holder for the
resulting CRC32.
Args:
data (string): Binary content. (Must have 4 bytes CRC32 appended)
return_type (type): The return type of CRC value. (int or str)
Returns:
Formatted CRC value.
Raises:
QFUException: In case of an invalid return_type or missing content.
"""
if len(data) < 4:
raise DFUException("no content available")
crc = binascii.crc32(data[:-4])
# NOTE: DFU-Util expects ~CRC
crc = ~crc & 0xffffffff
if return_type == int:
return crc
if return_type == str:
return struct.Struct("%sI" % _ENDIAN).pack(crc)
raise DFUException("unknown return type: %s" % return_type)
def add_suffix(self, data, id_product=0xFFFF, id_vendor=0xFFFF):
""" Adds DFU Suffix and the binary data.
Args:
data (string): Content of the binary file as a binary string.
id_product (int): USB / DFU Product ID.
id_vendor (int): USB / DFU Vendor ID.
Returns:
Binary data with attached DFU suffix.
"""
self.id_vendor = id_vendor
self.id_product = id_product
# Set DFU suffix.
data += self.packed_dfu_suffix
# Compute suffix CRC.
self.suffix_crc = self.crc(data, str)
return data[:-4] + self.suffix_crc
| 33.397059 | 79 | 0.666446 |
9357f3e059a0fa1d597f7db18628192f1479de26 | 2,216 | rs | Rust | archived/src/voxel_data/chunk_compressor.rs | cs2dsb/feldspar | 6071bd0d21ad4f341ceda4529c1e82845044b8ac | [
"MIT"
] | 45 | 2021-06-21T08:12:07.000Z | 2022-03-26T08:22:15.000Z | archived/src/voxel_data/chunk_compressor.rs | cs2dsb/feldspar | 6071bd0d21ad4f341ceda4529c1e82845044b8ac | [
"MIT"
] | 2 | 2021-11-17T13:33:51.000Z | 2022-01-10T20:14:44.000Z | archived/src/voxel_data/chunk_compressor.rs | cs2dsb/feldspar | 6071bd0d21ad4f341ceda4529c1e82845044b8ac | [
"MIT"
] | 8 | 2021-06-23T01:51:25.000Z | 2022-03-04T17:04:37.000Z | use crate::prelude::{SdfArrayCompression, SdfVoxelMap};
use bevy::{prelude::*, tasks::ComputeTaskPool};
use building_blocks::prelude::{Compression, FromBytesCompression, Lz4};
use serde::Deserialize;
#[derive(Clone, Copy, Deserialize)]
pub struct ChunkCacheConfig {
// These constants should be correlated with the size of a chunk.
pub max_cached_chunks: usize,
pub max_chunks_compressed_per_frame_per_thread: usize,
}
impl Default for ChunkCacheConfig {
fn default() -> Self {
Self {
// Assuming 8192-byte chunks, we'll reserve a little under a gigabyte for the cache.
max_cached_chunks: 100000,
// Avoid high latency from compressing too many chunks in one frame. 8192-byte chunk
// compression latency is around 0.01 ms.
max_chunks_compressed_per_frame_per_thread: 50,
}
}
}
/// A system that evicts and compresses the least recently used voxel chunks when the cache gets too
/// big.
pub fn chunk_compressor_system(
cache_config: Res<ChunkCacheConfig>,
pool: Res<ComputeTaskPool>,
mut voxel_map: ResMut<SdfVoxelMap>,
) {
let num_cached = voxel_map.voxels.storage().len_cached();
if num_cached < cache_config.max_cached_chunks {
return;
}
let overgrowth = num_cached - cache_config.max_cached_chunks;
let num_to_compress =
overgrowth.min(pool.thread_num() * cache_config.max_chunks_compressed_per_frame_per_thread);
let mut chunks_to_compress = Vec::new();
for _ in 0..num_to_compress {
if let Some(key_and_chunk) = voxel_map.voxels.storage_mut().remove_lru() {
chunks_to_compress.push(key_and_chunk);
} else {
break;
}
}
let compression = SdfArrayCompression::from_bytes_compression(Lz4 { level: 10 });
let compressed_chunks = pool.scope(|s| {
for (key, chunk) in chunks_to_compress.into_iter() {
s.spawn(async move { (key, compression.compress(&chunk)) });
}
});
for (key, compressed_chunk) in compressed_chunks.into_iter() {
voxel_map
.voxels
.storage_mut()
.insert_compressed(key, compressed_chunk);
}
}
| 33.575758 | 100 | 0.672383 |
13a6cbf84dff1f98fa0d546a491abfa5d8a3a680 | 728 | swift | Swift | Source/String+SwiftRegex.swift | maxadamski/SwiftyRegex | d5697ee47fcbc32d44cba68175b1e40874d81504 | [
"MIT"
] | 46 | 2015-09-20T22:43:53.000Z | 2021-06-21T07:19:27.000Z | Source/String+SwiftRegex.swift | maxadamski/SwiftyRegex | d5697ee47fcbc32d44cba68175b1e40874d81504 | [
"MIT"
] | 2 | 2016-04-27T11:36:24.000Z | 2019-02-08T12:39:53.000Z | Source/String+SwiftRegex.swift | maxadamski/SwiftyRegex | d5697ee47fcbc32d44cba68175b1e40874d81504 | [
"MIT"
] | 5 | 2015-09-20T22:44:06.000Z | 2017-01-23T16:26:44.000Z |
extension String
{
init(bytes: [UInt8])
{
self = bytes.reduce("") {
$0 + String(UnicodeScalar($1))
}
}
init(bytes: [Int8])
{
let uBytes = bytes.map { UInt8($0) }
self = String(bytes: uBytes)
}
mutating func replaceRange(range: Range<Int>, with sub: String)
{
let s = startIndex.advancedBy(range.startIndex)
let e = startIndex.advancedBy(range.endIndex)
replaceRange(s..<e, with: sub)
}
func substringWithRange(range: Range<Int>) -> String
{
let s = startIndex.advancedBy(range.startIndex)
let e = startIndex.advancedBy(range.endIndex)
return substringWithRange(s..<e)
}
}
| 23.483871 | 67 | 0.565934 |
0b7d1f1e2fd547f10391c4be9766498485799dc7 | 1,581 | py | Python | grid_search/mlp_gridsearch.py | RiboswitchClassifier/RiboswitchClassification | 4a4ab0590aa50aa765638b2bd8aa0cfd84054ac7 | [
"MIT"
] | 2 | 2019-12-16T13:08:28.000Z | 2021-02-23T03:03:18.000Z | grid_search/mlp_gridsearch.py | RiboswitchClassifier/RiboswitchClassification | 4a4ab0590aa50aa765638b2bd8aa0cfd84054ac7 | [
"MIT"
] | null | null | null | grid_search/mlp_gridsearch.py | RiboswitchClassifier/RiboswitchClassification | 4a4ab0590aa50aa765638b2bd8aa0cfd84054ac7 | [
"MIT"
] | 3 | 2019-01-01T06:00:20.000Z | 2020-01-28T13:57:49.000Z |
from sklearn.model_selection import cross_val_score, GridSearchCV, cross_validate, train_test_split
from sklearn.metrics import accuracy_score, classification_report
from sklearn.neural_network import MLPClassifier
import pandas as pd
import csv
from sklearn.preprocessing import label_binarize
from sklearn.preprocessing import StandardScaler
import numpy as np
data = pd.read_csv('processed_datasets/final_32classes.csv')
# Separate out the x_data and y_data.
x_data = data.loc[:, data.columns != "Type"]
x_data = x_data.loc[:,x_data.columns != "Sequence"]
y_data = data.loc[:, "Type"]
random_state = 100
x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.7, random_state=100,stratify=y_data)
scaler = StandardScaler()
scaler.fit(x_train)
x_train = scaler.transform(x_train)
x_test = scaler.transform(x_test)
mlp = MLPClassifier()
mlp.fit(x_train, y_train)
y_pred_train = mlp.predict(x_train)
y_pred_test = mlp.predict(x_test)
print("classifier", mlp)
print ("Accuracy on Train Set")
print (mlp.score(x_train, y_train))
print ("MLP Classifier")
print ("Accuracy on Test Set")
print (mlp.score(x_test, y_test))
print ("Report")
print (classification_report(y_test,mlp.predict(x_test)))
param_grid = {
'activation': ['tanh', 'relu'],
'solver': ['sgd', 'adam'],
'alpha': [0.0001,0.01, 0.05,0.1,1.0],
'learning_rate': ['constant','adaptive'],
}
#,2000
#,70
grid_search = GridSearchCV(mlp, param_grid=param_grid,n_jobs=-1,cv=10)
grid_search.fit(x_train,y_train)
print(grid_search.best_params_)
print(grid_search.best_score_)
| 27.258621 | 116 | 0.759646 |
1ffb6d6b447feb2542d449bbe97020ec1ecb7ff5 | 755 | css | CSS | css/ie8.css | kgardnr/kgardnr.github.io | 3b27f7eb1e4d709fcdb458cdcabab03fb7acea89 | [
"CC-BY-3.0"
] | null | null | null | css/ie8.css | kgardnr/kgardnr.github.io | 3b27f7eb1e4d709fcdb458cdcabab03fb7acea89 | [
"CC-BY-3.0"
] | null | null | null | css/ie8.css | kgardnr/kgardnr.github.io | 3b27f7eb1e4d709fcdb458cdcabab03fb7acea89 | [
"CC-BY-3.0"
] | null | null | null | /*
Miniport 1.0 by HTML5 Up!
html5up.net | @n33co
Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
*/
/*********************************************************************************/
/* Basic */
/*********************************************************************************/
.box
{
border: solid 1px #ddd;
}
/*********************************************************************************/
/* Wrappers */
/*********************************************************************************/
.wrapper
{
border-top: solid 1px #ddd;
} | 32.826087 | 86 | 0.21457 |